Ejemplo n.º 1
0
    def __init__(self, pdata):
        """
        Constructor
        @param pdata vtkPolyData instance
        """
        self.polydata = pdata

        # save the points and point data as separate class members
        # so as not to pollute pdata
        self.points = vtk.vtkPoints()
        self.points.DeepCopy(pdata.GetPoints())

        self.pointData = {}
        pd = pdata.GetPointData()
        for i in range(pd.GetNumberOfArrays()):
            arr = pd.GetArray(i)
            name = arr.GetName()
            self.pointData[name] = vtk.vtkDoubleArray()
            self.pointData[name].DeepCopy(arr)

        self.cellData = {}
        cd = pdata.GetCellData()
        for i in range(cd.GetNumberOfArrays()):
            name = cd.GetArray(i).GetName()
            self.cellData[name] = vtk.vtkDoubleArray()
            self.cellData[name].SetName(name)
Ejemplo n.º 2
0
def initializearray(polydata, arrayname, isscalar=True, ispointdata=True):
    """Initialize a data array. Choose pointdata or celldata and scalar or
    vector. Array values are initialized with 0.0 or [0.0, 0.0, 0.0]."""
    if ispointdata:  # add array to pointdata
        numberofpoints = polydata.GetNumberOfPoints()
        array = vtk.vtkDoubleArray()
        array.SetName(arrayname)
        if isscalar:  # array holds scalars
            array.SetNumberOfValues(numberofpoints)
            array.FillComponent(0, 0.0)
            polydata.GetPointData().AddArray(array)
        else:  # array holds vectors
            array.SetNumberOfComponents(3)
            array.SetNumberOfTuples(numberofpoints)
            for j in range(3):
                array.FillComponent(j, 0.0)
            polydata.GetPointData().AddArray(array)
    else:  # add array to celldata
        numberofcells = polydata.GetNumberOfCells()
        array = vtk.vtkDoubleArray()
        array.SetName(arrayname)
        if isscalar:  # array holds scalars
            array.SetNumberOfValues(numberofcells)
            array.FillComponent(0, 0.0)
            polydata.GetCellData().AddArray(array)
        else:  # array holds vectors
            array.SetNumberOfComponents(3)
            array.SetNumberOfTuples(numberofcells)
            for j in range(3):
                array.FillComponent(j, 0.0)
            polydata.GetCellData().AddArray(array)
    return array
Ejemplo n.º 3
0
    def initVTK(self, key):
        print "initializing VTK objects"
        self.__setMinMaxRange(key)
        self.__normalize(key)

        # Create our Data object
        vtk.vtkStructuredGrid()
        self.vtkStructuredGrid = vtk.vtkStructuredGrid()
        self.vtkStructuredGrid.SetDimensions([128]*3)

        # Set up Points
        self.vtkPoints = vtk.vtkPoints()
        self.vtkPoints.Allocate(128*3)

        # Set up Cells
        # self.vtkCells = vtk.vtkCellArray()

        # Setup the velocity vectors
        self.vtkVectors = vtk.vtkDoubleArray()
        self.vtkVectors.SetNumberOfComponents(3)
        self.vtkVectors.SetNumberOfTuples(self.sdfIdent.size)

        # Setup the Scalars
        self.vtkScalars = vtk.vtkDoubleArray()
        self.vtkScalars.SetName(key)

        # Allocate points, cells, scalars, and vector fields
        self.AllocateData(self.sdfIdent.size, key)

        # Now attach newly allocated objects to the grid
        self.vtkStructuredGrid.SetPoints(self.vtkPoints)
        # self.vtkStructuredGrid.SetVerts(self.vtkCells)
        self.vtkStructuredGrid.GetPointData().SetVectors(self.vtkVectors)
        self.vtkStructuredGrid.GetPointData().SetScalars(self.vtkScalars)
        self.vtkStructuredGrid.GetPointData().SetActiveScalars(key)
def SetVtkGrid(x,y,z):
    """Set up the vtk rectilinear grid using x, y, z data.
    
    Parameters:
        x, y, z -- the points in the x, y and z directions respectively
    Returns:
        grid -- a vtkRectilinearGrid object
    """
    grid = vtkRectilinearGrid();
    grid.SetDimensions(len(x),len(y),len(z));
     
    xArray = vtkDoubleArray();
    for xCoord in x: xArray.InsertNextValue(xCoord)
     
    yArray = vtkDoubleArray();
    for yCoord in y: yArray.InsertNextValue(yCoord)
    
    zArray = vtkDoubleArray();
    for zCoord in z: zArray.InsertNextValue(zCoord)
     
    grid.SetXCoordinates(xArray);
    grid.SetYCoordinates(yArray);
    grid.SetZCoordinates(zArray);
    
    print "There are " + str(grid.GetNumberOfPoints()) + " points.";
    print "There are " + str(grid.GetNumberOfCells()) + " cells.";

    return grid
Ejemplo n.º 5
0
def cell_average(model, bucket):
    """ Calculate a volume fraction estimate at the level of the grid."""

    ugrid = vtk.vtkUnstructuredGrid()
    ugrid.DeepCopy(model)

    locator = vtk.vtkCellLocator()
    locator.SetDataSet(ugrid)
    locator.BuildLocator()

    volfrac = numpy.zeros(ugrid.GetNumberOfCells())
    volume = numpy.zeros(ugrid.GetNumberOfCells())
    temperature = numpy.zeros(ugrid.GetNumberOfCells())
    velocity = numpy.zeros((ugrid.GetNumberOfCells(),3))

    for particle in bucket.particles:
        cell_id = locator.FindCell(particle.pos)
        volume[cell_id] += particle.volume
        velocity[cell_id, :] += particle.volume*particle.vel

    for _ in range(ugrid.GetNumberOfCells()):
        if volume[_] >1.0e-12:
            velocity[_, :] /= volume[_]
        volfrac[_] = volume[_] / get_measure(ugrid.GetCell(_))

    for particle in bucket.particles:
        cell_id = locator.FindCell(particle.pos)
        temperature[cell_id] += particle.volume*distance2(particle.vel,velocity[cell_id, :])

    for _ in range(ugrid.GetNumberOfCells()):
         if volume[_] >1.0e-12:
             temperature[_] /= volume[_]
        
    data = [vtk.vtkDoubleArray()]
    data[0].SetName('SolidVolumeFraction')
    data.append(vtk.vtkDoubleArray())
    data[1].SetName('SolidVolumeVelocity')
    data[1].SetNumberOfComponents(3)
    data.append(vtk.vtkDoubleArray())
    data[2].SetName('GranularTemperature')
#    data.append(vtk.vtkDoubleArray())
#    data[3].SetName('SolidPressure')

    for _ in range(ugrid.GetNumberOfCells()):
        data[0].InsertNextValue(volume[_])
        data[1].InsertNextTuple3(*(velocity[_]))
        data[2].InsertNextValue(temperature[_])
#        data[3].InsertNextValue(solid_pressure[_])

    pdata = vtk.vtkDoubleArray()
    pdata.SetName('Time')
    
    for _ in range(ugrid.GetNumberOfPoints()):
        pdata.InsertNextValue(bucket.time)

    for _ in data:
        ugrid.GetCellData().AddArray(_)
    ugrid.GetPointData().AddArray(pdata)
        
    return ugrid
Ejemplo n.º 6
0
    def __init__(self):

        pypes.pypeScript.__init__(self)

        self.Surface = None
        self.DeformedSurface = None
        self.SourcePoints = vtk.vtkPoints()
        self.TargetPoints = vtk.vtkPoints()
        self.DisplacementNorms = vtk.vtkDoubleArray()
        self.Displacements = vtk.vtkDoubleArray()
        self.Displacements.SetNumberOfComponents(3)
        self.SourceSpheres = vtk.vtkPolyData()
        self.TargetSpheres = vtk.vtkPolyData()
        self.SourceSpheres.SetPoints(self.SourcePoints)
        self.TargetSpheres.SetPoints(self.TargetPoints)
        self.SourceSpheres.GetPointData().SetScalars(self.DisplacementNorms)
        self.SourceSpheres.GetPointData().SetVectors(self.Displacements)
        self.vmtkRenderer = None
        self.OwnRenderer = 0
        self.DisplayDeformed = False
        self.SurfaceMapper = None
        self.Opacity = 1.0
        self.SourceSpheresActor = None
        self.TargetSpheresActor = None

        self.SetScriptName("vmtkthinplatesplinedeformation")
        self.SetInputMembers(
            [
                ["Surface", "i", "vtkPolyData", 1, "", "the input surface", "vmtksurfacereader"],
                ["Opacity", "opacity", "float", 1, "(0.0,1.0)", "object opacities in the scene"],
                ["vmtkRenderer", "renderer", "vmtkRenderer", 1, "", "external renderer"],
            ]
        )
        self.SetOutputMembers([["DeformedSurface", "o", "vtkPolyData", 1, "", "", "vmtksurfacewriter"]])
Ejemplo n.º 7
0
def Gather(c, arr, root):
    vtkArr = vtk.vtkDoubleArray()
    count = len(arr)
    vtkArr.SetNumberOfTuples(count)
    for i in range(count):
        vtkArr.SetValue(i, arr[i])
    vtkResult = vtk.vtkDoubleArray()
    c.Gather(vtkArr, vtkResult, root)
    result = [vtkResult.GetValue(i) for i in range(vtkResult.GetNumberOfTuples())]
    return [ tuple(result[i : i + count]) \
                for i in range(0, vtkResult.GetNumberOfTuples(), count) ]
Ejemplo n.º 8
0
def make_unstructured_grid(mesh, velocity, pressure, time, outfile=None):
    """Given a mesh (in Gmsh format), velocity and pressure fields, and a
    time level, store the data in a vtkUnstructuredGridFormat."""

    pnts = vtk.vtkPoints()
    pnts.Allocate(len(mesh.nodes))

    node2id = {}
    for k, point in mesh.nodes.items():
        node2id[k] = pnts.InsertNextPoint(point)

    ugrid = vtk.vtkUnstructuredGrid()
    ugrid.SetPoints(pnts)

    for element in mesh.elements.values():
        id_list = vtk.vtkIdList()
        for node in element[2]:
            id_list.InsertNextId(node2id[node])

        ugrid.InsertNextCell(TYPE_DICT[element[0]], id_list)

    data = []
    data.append(vtk.vtkDoubleArray())
    data[0].SetNumberOfComponents(3)
    data[0].Allocate(3*pnts.GetNumberOfPoints())
    data[0].SetName('Velocity')

    data.append(vtk.vtkDoubleArray())
    data[1].Allocate(pnts.GetNumberOfPoints())
    data[1].SetName('Pressure')

    data.append(vtk.vtkDoubleArray())
    data[2].Allocate(pnts.GetNumberOfPoints())
    data[2].SetName('Time')

    for k in range(len(mesh.nodes)):
        if hasattr(velocity, '__call__'):
            data[0].InsertNextTuple3(*velocity(ugrid.GetPoints().GetPoint(k)))
        else:
            data[0].InsertNextTuple3(*velocity[k, :])
        if hasattr(pressure, '__call__'):
            data[1].InsertNextValue(pressure(ugrid.GetPoints().GetPoint(k)))
        else:
            data[1].InsertNextValue(pressure[k])
        data[2].InsertNextValue(time)


    for _ in data:
        ugrid.GetPointData().AddArray(_)

    if outfile:
        write_to_file(ugrid, outfile)

    return ugrid
def CreateParentArteryPatches(parentCenterlines, clipPoints):
    numberOfDaughterPatches = parentCenterlines.GetNumberOfCells()

    patchedCenterlines = vtk.vtkPolyData()
    patchedCenterlinesPoints = vtk.vtkPoints()
    patchedCenterlinesCellArray = vtk.vtkCellArray()
    patchedRadiusArray = vtk.vtkDoubleArray()

    clipIds, numberOfPatchedCenterlinesPoints = ExtractPatchesIds(parentCenterlines, clipPoints)
    print "Clipping Point Ids ", clipIds

    radiusArray = vtk.vtkDoubleArray()
    radiusArray.SetNumberOfComponents(1)
    radiusArray.SetName(radiusArrayName)
    radiusArray.SetNumberOfTuples(numberOfPatchedCenterlinesPoints)
    radiusArray.FillComponent(0, 0.0)

    numberOfCommonPatch = clipIds[0] + 1
    patchedCenterlinesCellArray.InsertNextCell(numberOfCommonPatch)

    count = 0
    for i in range(0, numberOfCommonPatch):
        patchedCenterlinesPoints.InsertNextPoint(parentCenterlines.GetPoint(i))
        patchedCenterlinesCellArray.InsertCellPoint(i)
        radiusArray.SetTuple1(i, parentCenterlines.GetPointData().GetArray(radiusArrayName).GetTuple1(i))
        count += 1

    for j in range(numberOfDaughterPatches):
        cell = vtk.vtkGenericCell()
        parentCenterlines.GetCell(j, cell)

        numberOfCellPoints = cell.GetNumberOfPoints()
        startId = clipIds[j + 1]
        patchNumberOfPoints = numberOfCellPoints - startId
        patchedCenterlinesCellArray.InsertNextCell(patchNumberOfPoints)

        for i in range(startId, cell.GetNumberOfPoints()):
            point = cell.GetPoints().GetPoint(i)
            patchedCenterlinesPoints.InsertNextPoint(point)
            patchedCenterlinesCellArray.InsertCellPoint(count)
            radiusArray.SetTuple1(
                count, parentCenterlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell.GetPointId(i))
            )
            count += 1

    patchedCenterlines.SetPoints(patchedCenterlinesPoints)
    patchedCenterlines.SetLines(patchedCenterlinesCellArray)
    patchedCenterlines.GetPointData().AddArray(radiusArray)

    return patchedCenterlines
Ejemplo n.º 10
0
def vtkbasis(mesh, etob, fname, coeffs):
    ''' Find the directions from a (non-uniform) plane wave basis and output a VTK-compatible file
    
        It's possible that this needs to be updated to work with recent changes to ElementToBasis
    '''
    try:
        import vtk
        
        points = vtk.vtkPoints()
        vectors = vtk.vtkDoubleArray()
        vectors.SetNumberOfComponents(3)
        scalars = vtk.vtkDoubleArray()
        
        nc = 0
        for e in range(mesh.nelements):
            c = paa.origin(mesh, e)
            bs = etob[e]
            cc = np.zeros(3)
            cc[:len(c)] = c
            nondir = 0
            ndir = 0
            for b in bs:
                if hasattr(b, "directions"):
                    for d in b.directions.transpose():
                        dd = np.zeros(3)
                        dd[:len(d)] = d
                        if coeffs is not None: dd *= abs(coeffs[nc])
                        points.InsertNextPoint(*cc)
                        vectors.InsertNextTuple3(*dd)
                        ndir+=1
                        nc+=1
                else:
                    nondir += np.sqrt(np.sum(coeffs[nc:nc+b.n]**2))
                    nc += b.n
            for _ in range(ndir): scalars.InsertNextValue(nondir)
                    
        g = vtk.vtkUnstructuredGrid()
        g.SetPoints(points)
        gpd = g.GetPointData()
        gpd.SetVectors(vectors)
        gpd.SetScalars(scalars)
        writer = vtk.vtkXMLUnstructuredGridWriter()
        writer.SetFileName(fname)
        writer.SetInput(g)
        writer.Write()
    except ImportError as e:
        print "Unable to write basis to file: ",e
                
                
Ejemplo n.º 11
0
 def addVectorToCell(self,fieldValues,name):
     datas = vtk.vtkDoubleArray()
     datas.SetNumberOfComponents(3)
     datas.SetName(name)
     for value in fieldValues:
         datas.InsertNextTuple3(value[0],value[1],value[2])
     self._resultsCell.append(datas)
Ejemplo n.º 12
0
 def setSourceFromExpression(self, expression):
     """
     Set the source from expression
     @param expression expression of x, y, and z
     """
     from math import sqrt, pi, sin, cos, tan, log, exp
     
     n = self.pdata.GetNumberOfPolys()
     sourceData = vtk.vtkDoubleArray()
     sourceData.SetNumberOfComponents(1)
     sourceData.SetNumberOfTuples(n)
     sourceData.SetName(self.sourceName)
     midPoint = numpy.zeros((3,), numpy.float64)
     ptIds = vtk.vtkIdList()
     cells = self.pdata.GetPolys()
     cells.InitTraversal()
     for i in range(n):
         cell = cells.GetNextCell(ptIds)
         npts = ptIds.GetNumberOfIds()
         midPoint *= 0 # reset
         for j in range(npts):
             midPoint += self.points.GetPoint(ptIds.GetId(j))
         midPoint /= float(npts)
         x, y, z = midPoint
         v = eval(expression)
         sourceData.SetTuple(i, [v])
     self.pdata.GetCellData().AddArray(sourceData)
Ejemplo n.º 13
0
 def addVectorToNode(self,fieldValues,name):
     datas = vtk.vtkDoubleArray()
     datas.SetNumberOfComponents(3)
     datas.SetName(name)
     for value in fieldValues:
         datas.InsertNextTuple3(value[0],value[1],value[2])
     self._hexs.GetPointData().AddArray(datas)
def ExtractSingleLine(centerlines,id):
   cell = vtk.vtkGenericCell()
   centerlines.GetCell(id,cell) 

   line = vtk.vtkPolyData()
   points = vtk.vtkPoints()
   cellArray = vtk.vtkCellArray()
   cellArray.InsertNextCell(cell.GetNumberOfPoints())

   radiusArray = vtk.vtkDoubleArray()
   radiusArray.SetName(radiusArrayName)
   radiusArray.SetNumberOfComponents(1)
   radiusArray.SetNumberOfTuples(cell.GetNumberOfPoints())
   radiusArray.FillComponent(0,0.0)

   for i in range(cell.GetNumberOfPoints()):
      point = [0.0,0.0,0.0]
      point = cell.GetPoints().GetPoint(i)

      points.InsertNextPoint(point)
      cellArray.InsertCellPoint(i)
      radius = centerlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell.GetPointId(i))
      radiusArray.SetTuple1(i,radius)

   line.SetPoints(points)   
   line.SetLines(cellArray)
   line.GetPointData().AddArray(radiusArray)

   return line 
def createTrail(ts):
    Points = vtk.vtkPoints()
    id_array = vtk.vtkIntArray()
    #id_array.SetNumberofComponents(1)
    id_array.SetName("haloid")
    
    phi_array = vtk.vtkDoubleArray()
    phi_array.SetName("phi")
    for i in range(0,ts+1):
        px,py,pz,phid,pphi = readParticle(i)
        for j in range(0,len(px)):
            Points.InsertNextPoint(px[j],py[j],pz[j])
            id_array.InsertNextTuple1(phid[j])
            phi_array.InsertNextTuple1(pphi[j])
    
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(Points)
    polydata.GetPointData().AddArray(id_array)
    polydata.GetPointData().AddArray(phi_array)
    
    if vtk.VTK_MAJOR_VERSION <= 5:
        polydata.Update()
        
    
    outputFile = "/home/subhashis/VisData/merger_trees/particleTrail/time" + str(ts) + ".vtp" 
        
    writer = vtk.vtkXMLPolyDataWriter();
    writer.SetFileName(outputFile);
    if vtk.VTK_MAJOR_VERSION <= 5:
        writer.SetInput(polydata)
    else:
        writer.SetInputData(polydata)
    writer.Write()
    print "Done generating output for time %d" %ts
def SaveParentArtery(centerlines):
   numberOfCells = centerlines.GetNumberOfCells()

   cell0 = centerlines.GetCell(0)
   numberOfArteryPoints = centerlines.GetNumberOfPoints()-cell0.GetNumberOfPoints()
  
   artery = vtk.vtkPolyData()
   arteryPoints = vtk.vtkPoints()
   arteryCellArray = vtk.vtkCellArray()

   radiusArray = vtk.vtkDoubleArray()
   radiusArray.SetName(radiusArrayName)
   radiusArray.SetNumberOfComponents(1)
   radiusArray.SetNumberOfTuples(numberOfArteryPoints)
   radiusArray.FillComponent(0,0.0)

   count = 0
   for i in range(1,numberOfCells): # cell0 is the one that goes to the aneurysm dome
      cell = vtk.vtkGenericCell()
      centerlines.GetCell(i,cell)
   
      arteryCellArray.InsertNextCell(cell.GetNumberOfPoints())
   
      for j in range(cell.GetNumberOfPoints()):
         arteryPoints.InsertNextPoint(cell.GetPoints().GetPoint(j))
         radiusArray.SetTuple1(count,centerlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell.GetPointId(j)))
         arteryCellArray.InsertCellPoint(count)
         count+=1
         
   artery.SetPoints(arteryPoints)
   artery.SetLines(arteryCellArray)
   artery.GetPointData().AddArray(radiusArray)
   return artery 
    def Execute(self):

        if self.Surface == None:
            self.PrintError("Error: No input surface.")

        if self.PolyBall == None:
            self.PrintError("Error: No input polyball.")

        evaluationArray = vtk.vtkDoubleArray()
        evaluationArray.SetName(self.EvaluationArrayName)
        evaluationArray.SetNumberOfComponents(1)
        evaluationArray.SetNumberOfTuples(self.Surface.GetNumberOfPoints())

        polyball = None
        if self.Type == "polyball":
            polyball = vtkvmtk.vtkvmtkPolyBall()
        elif self.Type == "tubes":
            polyball = vtkvmtk.vtkvmtkPolyBallLine()
        polyball.SetInputData(self.PolyBall)
        polyball.SetPolyBallRadiusArrayName(self.RadiusArrayName)

        for i in xrange(self.Surface.GetNumberOfPoints()):
            point = self.Surface.GetPoint(i)
            value = polyball.EvaluateFunction(point)
            evaluationArray.SetValue(i, value)

        self.Surface.GetPointData().AddArray(evaluationArray)
Ejemplo n.º 18
0
    def GridSurface(self):
        #----------------------------------------------------------------------
        # ELECTRODE CONTACT DELAUNAY TRIANGULATION ----------------------------
        deln = vtk.vtkDelaunay3D()
        deln.SetInput(self.electrodePolyData)
        deln.SetTolerance(0.01)
        tmapper = vtk.vtkTextureMapToSphere()
        tmapper.SetInputConnection(deln.GetOutputPort())
        #tmapper.PreventSeamOn()
        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputConnection(tmapper.GetOutputPort())

        # TEST TEXTURE PART
        atext = vtk.vtkOpenGLTexture()

        self.contactScalarData = vtk.vtkDoubleArray()
        self.contactScalarData.SetNumberOfComponents(1)
        for tupleID in range(self.electrodePolyData.GetNumberOfPoints()):
            self.contactScalarData.InsertNextValue(random.uniform(0, 1))

        self.UpdateGridSurface()
        atext.SetInput(self.electrodePolyData)
        self.triangulation = vtk.vtkOpenGLActor()
        self.triangulation.SetMapper(mapper)
        self.triangulation.SetTexture(atext)
        self.triangulation.GetProperty().SetOpacity(1)
Ejemplo n.º 19
0
def simpleVtkDiGraph():
    g = vtk.vtkMutableDirectedGraph()

    # Create 3 vertices
    v1 = g.AddVertex()
    v2 = g.AddVertex()
    v3 = g.AddVertex()

    # Create a fully connected graph
    g.AddGraphEdge(v1, v2)
    g.AddGraphEdge(v2, v3)
    g.AddGraphEdge(v1, v3)

    # Create the edge weight array
    weights = vtk.vtkDoubleArray()
    weights.SetNumberOfComponents(1)
    weights.SetName("Weights")

    # Set the edge weights
    weights.InsertNextValue(1.0)
    weights.InsertNextValue(1.0)
    weights.InsertNextValue(2.0)

    # Add the edge weight array to the graph
    g.GetEdgeData().AddArray(weights)

    return g
Ejemplo n.º 20
0
 def addVectorToNode(self,fieldValues,name):
     datas = vtk.vtkDoubleArray()
     datas.SetNumberOfComponents(2)
     datas.SetName(name)
     for value in fieldValues:
         datas.InsertNextTuple2(value[0],value[1])
     self._resultsPoint.append(datas)
Ejemplo n.º 21
0
def make_pData_periodic (np, x, a, lattice):
    pos = vtk.vtkPoints()
    diameter = vtk.vtkDoubleArray()
    diameter.SetNumberOfComponents(1)
    # primary cell
    for i in range(np):
        pos.InsertNextPoint(x[i*3], x[i*3+1], x[i*3+2])
        if a != []:
            diameter.InsertNextTuple1(2.0*a[i])
        else:
            diameter.InsertNextTuple1(2.0)
    # image cells
    for ix in range(-1,2):
        for iy in range(-1,2):
            for iz in range(-1,2):
                if ix == 0 and iy == 0 and iz == 0: continue
                for i in range(np):
                    pos.InsertNextPoint(x[i*3  ]+float(ix)*lattice[0],
                                        x[i*3+1]+float(iy)*lattice[1],
                                        x[i*3+2]+float(iz)*lattice[2])
                    if a != []:
                        diameter.InsertNextTuple1(2.0*a[i])
                    else:
                        diameter.InsertNextTuple1(2.0)

    # first make pData containing particle coordinates
    pData = vtk.vtkPolyData()
    pData.SetPoints(pos)
    pData.GetPointData().SetScalars(diameter)

    return pData
Ejemplo n.º 22
0
 def convertArray2vtkImage(self, nparray, t_ImagedataVTK, npImagesandMask): 
     """ Takes a numpy.ndarray and converts it to a vtkimageData. require npImagesandMask to pass on image info """
     # Create vtk object
     size_array = npImagesandMask['dims'][0]*npImagesandMask['dims'][1]*npImagesandMask['dims'][2]
     flatim = nparray.transpose(2,1,0)
     flatim = flatim.flatten()
     
     # create vtk image
     vtk_image = vtk.vtkImageData()
     vtk_image.DeepCopy(t_ImagedataVTK)
     vtk_image.SetNumberOfScalarComponents(1)
     vtk_image.SetScalarTypeToDouble()
     vtk_image.AllocateScalars()
     
     # Get scalars from numpy
     image_array = vtk.vtkDoubleArray() 
     image_array.SetNumberOfValues(size_array)
     image_array.SetNumberOfComponents(1) 
     
     # not too efficient convertion of np.array to vtk. Far from ideal
     for k in range(size_array):
         image_array.InsertTuple1(k,flatim[k])
         
     vtk_image.GetPointData().SetScalars(image_array) 
     vtk_image.Update()
       
     return vtk_image   
Ejemplo n.º 23
0
    def compute(self):
        a = self.getInputFromPort("Array")
        ds = self.getInputFromPort("VTK Data")
        scalar_name = ''
        if self.hasInputFromPort("Scalar Name"):
            scalar_name = self.getInputFromPort("Scalar Name")
        else:
            scalar_name = 'scalars'
        
        s_ar = a.get_array().flatten()
        np = ds.vtkInstance.GetNumberOfPoints()
#        if s_ar.size != np:
#            raise ModuleError("Could not assign scalars to VTK dataset with different number of elements")

        pd = ds.vtkInstance.GetPointData()
        vtk_ar = vtk.vtkDoubleArray()
        vtk_ar.SetNumberOfValues(np)
        for i in xrange(np):
            vtk_ar.SetValue(i, s_ar[i])

        vtk_ar.SetName(scalar_name)
        ds.vtkInstance.GetPointData().AddArray(vtk_ar)
#        ds.vtkinstance.GetPointData().SetActiveScalars(scalar_name)
        ds.vtkInstance.GetPointData().SetScalars(vtk_ar)
        self.setResult("Output", ds)
Ejemplo n.º 24
0
def make_sphereActor (x, r, rgb, opacity):
    points = vtk.vtkPoints()
    points.InsertNextPoint(x[0], x[1], x[2])

    diameter = vtk.vtkDoubleArray()
    diameter.SetNumberOfComponents(1)
    diameter.InsertNextTuple1(2.0*r)

    pData = vtk.vtkPolyData()
    pData.SetPoints(points)
    pData.GetPointData().SetScalars(diameter)

    pSource = vtk.vtkSphereSource()
    pSource.SetPhiResolution(16)
    pSource.SetThetaResolution(16)

    pGlyph = vtk.vtkGlyph3D()
    pGlyph.SetSource(pSource.GetOutput())
    pGlyph.SetInput(pData)
    pGlyph.ScalingOn()
    pGlyph.SetScaleModeToScaleByScalar()

    pMapper = vtk.vtkPolyDataMapper()
    pMapper.ScalarVisibilityOff()
    pMapper.SetInput(pGlyph.GetOutput())

    pActor = vtk.vtkActor()
    pActor.SetMapper(pMapper)
    pActor.GetProperty().SetColor(rgb[0], rgb[1], rgb[2])
    pActor.GetProperty().SetOpacity(opacity)

    return pActor
Ejemplo n.º 25
0
def createPolyData(faces, vtList, verts, tcoords):

    points = vtk.vtkPoints()
    points.SetDataTypeToDouble()
    points.SetNumberOfPoints(len(vtList))

    tcoordArray = vtk.vtkDoubleArray()
    tcoordArray.SetName('tcoords')
    tcoordArray.SetNumberOfComponents(2)
    tcoordArray.SetNumberOfTuples(len(vtList))

    for i, vt in enumerate(vtList):
        vi, ti = vt
        xyz = verts[vi]
        uv = tcoords[ti]

        points.SetPoint(i, xyz)
        tcoordArray.SetTuple2(i, uv[0], uv[1])

    cells = vtk.vtkCellArray()

    for i, face in enumerate(faces):
        tri = vtk.vtkTriangle()
        tri.GetPointIds().SetId(0, face[0])
        tri.GetPointIds().SetId(1, face[1])
        tri.GetPointIds().SetId(2, face[2])
        cells.InsertNextCell(tri)

    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)
    polyData.SetPolys(cells)
    polyData.GetPointData().SetTCoords(tcoordArray)
    return polyData
Ejemplo n.º 26
0
def array_to_vtk(array_in, dtype=None):
    """Get vtkFloatArray/vtkDoubleArray from the input numpy array."""
    if dtype == None:
        dtype = _numpy.dtype(array_in.dtype)
    else:
        dtype = _numpy.dtype(dtype)
    if dtype == _numpy.float32:
        float_array = _vtk.vtkFloatArray()
    elif dtype == _numpy.float64:
        float_array = _vtk.vtkDoubleArray()
    elif dtype == _numpy.uint8:
        float_array = _vtk.vtkUnsignedCharArray()
    elif dtype == _numpy.int8:
        float_array = _vtk.vtkCharArray()
    else:
        raise ValueError("Wrong format of input array, must be float32 or float64")
    if len(array_in.shape) != 1 and len(array_in.shape) != 2:
        raise ValueError("Wrong shape: array must be 1D or 2D.")
    #float_array.SetNumberOfComponents(_numpy.product(array_in.shape))
    # if len(array_in.shape) == 2:
    #     float_array.SetNumberOfComponents(array_in.shape[1])
    # elif len(array_in.shape) == 1:
    #     float_array.SetNumberOfComponents(1)
    float_array.SetNumberOfComponents(1)
    array_contiguous = _numpy.ascontiguousarray(array_in, dtype)
    float_array.SetVoidArray(array_contiguous, _numpy.product(array_in.shape), 1)
    float_array._contiguous_array = array_contiguous  # Hack to keep the array of being garbage collected
    # if len(array_in.shape) == 2:
    #     print "set tuple to {0}".format(array_in.shape[1])
    #     #float_array.SetNumberOfTuples(array_in.shape[1])
    #     float_array.Resize(array_in.shape[1])
    #     float_array.Squeeze()
    return float_array
Ejemplo n.º 27
0
 def ReadTetrIniFile(self,filename,arrayname):
     self.PrintLog('Reading '+filename+'.')
     if (self.Compressed == 1):
         f=gzip.open(filename, 'r')
     else:
         f=open(filename, 'r')
     line = f.readline()
     while (line!='$vel_old1'):
         line = f.readline()
     line = f.readline()
     line = f.readline()
     numberOfTuples = int(line)
     outputArray = vtk.vtkDoubleArray()
     outputArray.SetName(arrayname)
     outputArray.SetNumberOfComponents(3)
     outputArray.SetNumberOfTuples(numberOfTuples)
     for i in range(numberOfTuples):
         line = f.readline()
         splitline = line.split(' ')
         value0 = float(splitline[0])
         value1 = float(splitline[1])
         value2 = float(splitline[2])
         outputArray.SetComponent(i,0,value0)
         outputArray.SetComponent(i,1,value1)
         outputArray.SetComponent(i,2,value2)
     self.Mesh.GetPointData().AddArray(outputArray)
Ejemplo n.º 28
0
 def ReadTetrVelFile(self,filename,arrayname):
     self.PrintLog('Reading '+filename+'.')
     if self.UnNormalize == 1:
         self.ReadTetrInDimensionalParameters()
     if (self.Compressed == 1):
         f=gzip.open(filename, 'r')
     else:
         f=open(filename, 'r')
     lines = f.readlines()
     line = lines[0]
     lineoffset = 1
     splitline = line.split(' ')
     numberOfTuples = int(splitline[0])
     iteration = float(splitline[1])
     outputArray = vtk.vtkDoubleArray()
     outputArray.SetName(arrayname)
     outputArray.SetNumberOfComponents(3)
     outputArray.SetNumberOfTuples(numberOfTuples)
     velocityUnNormalizationFactor = self.ReD / (2.0 * self.Radius) * self.Viscosity / self.Density 
     for i in range(numberOfTuples):
         line = lines[i+lineoffset]
         splitline = line.split(' ')
         value0 = float(splitline[0])
         value1 = float(splitline[1])
         value2 = float(splitline[2])
         if self.UnNormalize ==1:
             value0 *= velocityUnNormalizationFactor
             value1 *= velocityUnNormalizationFactor
             value2 *= velocityUnNormalizationFactor
         outputArray.SetComponent(i,0,value0)
         outputArray.SetComponent(i,1,value1)
         outputArray.SetComponent(i,2,value2)
     self.Mesh.GetPointData().AddArray(outputArray)
Ejemplo n.º 29
0
def buildATPMesh(polydata, filename):
    
    centroidFilter = vtk.vtkCellCenters()
    centroidFilter.VertexCellsOn()
    centroidFilter.SetInputData(polydata)
    
    newPolydata = vtk.vtkPolyData()
    newPolydata = centroidFilter.GetOutput()
    centroidFilter.Update()
    
    ATPValues = vtk.vtkDoubleArray()
    ATPValues.SetName("initialATP")
    
    _, _, yMin, yMax, _, _ = polydata.GetBounds()
    yRange = yMax - yMin
    
    for pointId in range(0, newPolydata.GetNumberOfPoints()):
        _, y, _ = newPolydata.GetPoint(pointId)
        ATPValue = y / (yRange * 1.0)
        ATPValues.InsertNextValue(ATPValue)
        
    newPolydata.GetCellData().SetScalars(ATPValues)
    
    polyDataWriter = vtk.vtkXMLPolyDataWriter()
    polyDataWriter.SetFileName(filename)
    polyDataWriter.SetInputData(newPolydata)    
    polyDataWriter.Write()
Ejemplo n.º 30
0
    def compute(self):
        ds = self.getInputFromPort("VTK Data")
        ar = self.getInputFromPort("Scalars")
        v_name = self.forceGetInputFromPort("Array Name")
        if v_name == None:
            v_name = 'scalars'
        num_times = ds.vtkInstance.GetNumberOfTimeSteps()
        ar_ = ar.get_array()
        if ar_.shape[0] != num_times:
            raise ModuleError("Cannot process array with num timesteps = " +
                              str(ar_.shape[0]) +
                              " and vtkdata with " +
                              str(num_times) + " timesteps")
        
        for i in range(num_times):
            self.update_progress(i, num_times)
            s_ar = ar_[i,::].squeeze().flatten()
            vtk_ar = vtk.vtkDoubleArray()
            vtk_ar.SetNumberOfValues(s_ar.size)
            vtk_ar.SetName(v_name)
            for j in range(s_ar.size):
                vtk_ar.InsertNextValue(s_ar[j])
            
            ds.vtkInstance.GetTimeStep(i).GetPointData().AddArray(vtk_ar)
            ds.vtkInstance.GetTimeStep(i).GetPointData().SetScalars(vtk_ar)

        self.setResult("Output", ds)
Ejemplo n.º 31
0
def saveTrajectory(sols, outputFile):
    """
    Save the trajectory to VTK file
    @param sols list of return values of odeint
    @param filename
    """

    # number of contours
    nContours = len(sols)

    # number of points for each contour
    nptsContour = [sol.shape[0] for sol in sols]

    # total number of points
    npts = functools.reduce(lambda x, y: x + y, nptsContour)

    # total number of segments
    nSegs = functools.reduce(lambda x, y: x + y,
                             [nps - 1 for nps in nptsContour])

    # number of space dimensions
    ndims = 3

    pvals = numpy.zeros((npts, 3), numpy.float64)
    tarr = vtk.vtkDoubleArray()
    tpts = vtk.vtkPoints()
    tgrid = vtk.vtkUnstructuredGrid()

    tarr.SetNumberOfComponents(ndims)
    tarr.SetNumberOfTuples(npts)
    tpts.SetNumberOfPoints(npts)

    ptIds = vtk.vtkIdList()
    ptIds.SetNumberOfIds(2)

    tgrid.Allocate(nSegs, 1)

    # create the points and the unstructured grid that goes with it
    offset1 = 0
    offset2 = 0
    for iContour in range(nContours):

        ns = nptsContour[iContour]

        # store points
        for i in range(ns):
            pvals[i + offset1, :] = sols[iContour][i]
            pvals[i + offset1, 0] = max(0., min(360., pvals[i + offset1, 0]))
            pvals[i + offset1, 1] = max(-90., min(90., pvals[i + offset1, 1]))
        offset1 += ns

        # create new cells/segments
        for i in range(ns - 1):
            ptIds.SetId(0, i + offset2)
            ptIds.SetId(1, i + 1 + offset2)
            tgrid.InsertNextCell(vtk.VTK_LINE, ptIds)
        offset2 += ns

    # connect
    tpts.SetData(tarr)
    tgrid.SetPoints(tpts)
    tarr.SetVoidArray(pvals, npts * 3, 1)

    # save
    writer = vtk.vtkUnstructuredGridWriter()
    writer.SetFileName(outputFile)
    writer.SetInputData(tgrid)
    writer.Update()
Ejemplo n.º 32
0
    def setup(self):
        # Instantiate and connect widgets ...
        ScriptedLoadableModuleWidget.setup(self)

        # if self.developerMode:
        #     #
        #     # Reload and Test area
        #     #
        #     reloadCollapsibleButton = ctk.ctkCollapsibleButton()
        #     reloadCollapsibleButton.text = "Reload && Test"
        #     self.layout.addWidget(reloadCollapsibleButton)
        #     reloadFormLayout = qt.QFormLayout(reloadCollapsibleButton)
        #
        #     # reload button
        #     # (use this during development, but remove it when delivering
        #     #  your module to users)
        #     self.reloadButton = qt.QPushButton("Reload")
        #     self.reloadButton.toolTip = "Reload this module."
        #     self.reloadButton.name = "VolumeProbe Reload"
        #     reloadFormLayout.addWidget(self.reloadButton)
        #     self.reloadButton.connect('clicked()', self.onReload)
        #
        #     # reload and test button
        #     # (use this during development, but remove it when delivering
        #     #  your module to users)
        #     self.reloadAndTestButton = qt.QPushButton("Reload and Test All")
        #     self.reloadAndTestButton.toolTip = "Reload this module and then run the self tests."
        #     reloadFormLayout.addWidget(self.reloadAndTestButton)
        #     self.reloadAndTestButton.connect('clicked()', self.onReloadAndTest)
        #
        #     # reload and run specific tests
        #     scenarios = ("Three Volume", "View Watcher", "ROIManager",)
        #     for scenario in scenarios:
        #         button = qt.QPushButton("Reload and Test %s" % scenario)
        #         self.reloadAndTestButton.toolTip = "Reload this module and then run the %s self test." % scenario
        #         reloadFormLayout.addWidget(button)
        #         button.connect('clicked()', lambda s=scenario: self.onReloadAndTest(scenario=s))

        #
        # Parameters Area
        #
        parametersCollapsibleButton = ctk.ctkCollapsibleButton()
        parametersCollapsibleButton.text = "Parameters"
        self.layout.addWidget(parametersCollapsibleButton)

        # Layout within the dummy collapsible button
        parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)
        """
        #
        # target volume selector
        #
        self.inputSelector = slicer.qMRMLNodeComboBox()
        self.inputSelector.nodeTypes = ( ("vtkMRMLVolumeNode"), "" )
        self.inputSelector.selectNodeUponCreation = True
        self.inputSelector.addEnabled = False
        self.inputSelector.removeEnabled = False
        self.inputSelector.noneEnabled = False
        self.inputSelector.showHidden = False
        self.inputSelector.showChildNodeTypes = True
        self.inputSelector.setMRMLScene( slicer.mrmlScene )
        self.inputSelector.setToolTip( "Pick the input to the algorithm." )
        parametersFormLayout.addRow("Target Volume: ", self.inputSelector)
        """

        #
        # Add ROI
        #
        self.drawROICheck = qt.QCheckBox()
        parametersFormLayout.addRow("Draw ROI", self.drawROICheck)
        self.drawROICheck.connect("toggled(bool)", self.onDrawROIToggled)

        self.ROIRadiusSlider = ctk.ctkSliderWidget()
        # self.ROIRadiusSlider.setMinimum(1)
        # self.ROIRadiusSlider.setMaximum(100)
        self.ROIRadiusSlider.setValue(self.ROIRadius)
        parametersFormLayout.addRow("ROI Radius", self.ROIRadiusSlider)
        self.ROIRadiusSlider.connect("valueChanged(double)",
                                     self.onROIRadiusChanged)

        #
        # Add Histogram
        self.numBins = qt.QSpinBox()
        self.numBins.setRange(0, 200)
        self.numBins.setEnabled(1)
        self.numBins.setValue(20)
        parametersFormLayout.addRow("Number of Bins", self.numBins)

        self.histogramArray = vtk.vtkDoubleArray()
        self.histogramArray.SetNumberOfComponents(1)
        self.histogramArray.SetNumberOfTuples(0)

        self.histogram = ctk.ctkVTKHistogram()
        self.histogram.setDataArray(self.histogramArray)
        self.histogram.numberOfBins = self.numBins.value

        self.histogramView = ctk.ctkTransferFunctionView()
        self.histogramItem = ctk.ctkTransferFunctionBarsItem(self.histogram)
        self.histogramItem.barWidth = 0.7

        self.histogramView.scene().addItem(self.histogramItem)
        parametersFormLayout.addRow("Histogram", self.histogramView)
        self.histogramView.show()

        self.minField = qt.QSpinBox()
        self.minField.setRange(-100000, 100000)
        self.minField.setEnabled(0)
        parametersFormLayout.addRow("Min Value", self.minField)

        self.maxField = qt.QSpinBox()
        self.maxField.setRange(-100000, 100000)
        self.maxField.setEnabled(0)
        parametersFormLayout.addRow("Max Value", self.maxField)

        self.meanField = qt.QSpinBox()
        self.meanField.setRange(-100000, 100000)
        self.meanField.setEnabled(0)
        parametersFormLayout.addRow("Mean Value", self.meanField)

        self.medianField = qt.QSpinBox()
        self.medianField.setRange(-100000, 100000)
        self.medianField.setEnabled(0)
        parametersFormLayout.addRow("Median Value", self.medianField)

        self.stdField = qt.QSpinBox()
        self.stdField.setRange(-100000, 100000)
        self.stdField.setEnabled(0)
        parametersFormLayout.addRow("STD Value", self.stdField)

        # Add vertical spacer
        self.layout.addStretch(1)
Ejemplo n.º 33
0
 def display_tube(self, gfx, caller):
     if gfx.ps != None:
         gfx.renderer.RemoveActor(gfx.ps.acteur)
     if self.c != '' and self.T != '' and self.U != '' and self.henttype == 'cTU':  #CTU CASE
         ptype = 'delta'
         self.enttype = 'cTU'
         deltaz = (self.c / self.U)
         deltaphi = (self.T * 360.0) / self.U
         self.dphi = deltaphi
         self.dz = deltaz
     elif self.dphi != '' and self.dz != '' and self.henttype == 'Elm-Hel':  #DELTA CASE
         ptype = 'delta'
         self.enttype = 'Elm-Hel'
         deltaphi = self.dphi
         deltaz = self.dz
     else:
         MB.showwarning('Info', 'Configure symmetry setting')
         return
     try:
         zmax = gfx.map[0].box.GetBounds()[5]
         zmin = gfx.map[0].box.GetBounds()[4]
         z = zmax - zmin
     except:
         z = 4 * 360 * abs(self.dz / self.dphi)
     #ici exeption 'fit' calcule de dz avec ratio !!!
     if 'fit' in caller:
         self.c = self.c * gfx.map[0].ratio
         self.dz = self.dz * gfx.map[0].ratio
         deltaz = self.dz
     numPts = int(z / deltaz)
     self.numpts = numPts  #definition du nombre de sm
     self.cptsymops_tube(
         ptype, numPts
     )  #ptype est tjs = a delta on calcule toujours de la même maniere dans symmetry
     #parameter definition :
     shifta = radians(deltaphi)
     phizero = radians(self.phizero)
     ###definition des boules selon les parametres
     pdo = vtk.vtkPolyData()
     newPts = vtk.vtkPoints()  #This will store the points for the Helix
     vals = vtk.vtkDoubleArray()
     for i in range(0, numPts):
         try:
             x = self.radius * gfx.map[0].scale * cos(i * shifta + phizero)
             y = self.radius * gfx.map[0].scale * sin(i * shifta + phizero)
             z = zmin + i * deltaz
         except:
             x = self.radius * cos(i * shifta + phizero)
             y = self.radius * sin(i * shifta + phizero)
             z = i * deltaz
         newPts.InsertPoint(i, x, y, z)
         vals.InsertNextValue(i)
     pdo.SetPoints(newPts)
     pdo.GetPointData().SetScalars(vals)
     sphere = vtk.vtkSphereSource()
     sphere.SetCenter(0, 0, 0)
     try:
         sphere.SetRadius(self.radius * gfx.map[0].scale / 5.0)
     except:
         sphere.SetRadius(self.radius * (1 / 5.))
     sphere.SetThetaResolution(8)
     sphere.SetStartTheta(0)
     sphere.SetEndTheta(360)
     sphere.SetPhiResolution(8)
     sphere.SetStartPhi(0)
     sphere.SetEndPhi(180)
     glyph = vtk.vtkGlyph3D()
     glyph.SetInput(pdo)
     glyph.SetColorMode(1)
     glyph.ScalingOn()
     glyph.SetScaleMode(2)
     glyph.SetScaleFactor(0.25)
     glyph.SetSource(sphere.GetOutput())
     self.spheremapper = vtk.vtkPolyDataMapper()
     self.spheremapper.SetInputConnection(glyph.GetOutputPort())
     self.spheremapper.UseLookupTableScalarRangeOff()
     self.spheremapper.SetScalarVisibility(0)
     self.sphact = vtk.vtkActor()
     self.sphact.PickableOff()
     self.sphact.DragableOff()
     self.sphact.SetMapper(self.spheremapper)
     self.sphact.GetProperty().SetRepresentationToSurface()
     self.sphact.GetProperty().SetInterpolationToGouraud()
     self.sphact.GetProperty().SetAmbient(0.15)
     self.sphact.GetProperty().SetDiffuse(0.85)
     self.sphact.GetProperty().SetSpecular(0.1)
     self.sphact.GetProperty().SetSpecularPower(100)
     self.sphact.GetProperty().SetSpecularColor(1, 1, 1)
     self.sphact.GetProperty().SetColor(1, 1, 1)
     ###definition de l helice continue
     enhance = 100
     hlxpdo = vtk.vtkPolyData()
     hlxnewPts = vtk.vtkPoints()  #This will store the points for the Helix
     hlxvals = vtk.vtkDoubleArray()
     hlxnumPts = int(numPts * enhance)
     for i in range(0, hlxnumPts):
         try:
             x = self.radius * gfx.map[0].scale * cos(i * shifta / enhance +
                                                      phizero)
             y = self.radius * gfx.map[0].scale * sin(i * shifta / enhance +
                                                      phizero)
             z = zmin + i * deltaz / enhance
         except:
             x = self.radius * cos(i * shifta / enhance + phizero)
             y = self.radius * sin(i * shifta / enhance + phizero)
             z = i * deltaz / enhance
         hlxnewPts.InsertPoint(i, x, y, z)
         hlxvals.InsertNextValue(i)
     hlxpdo.SetPoints(hlxnewPts)
     hlxpdo.GetPointData().SetScalars(hlxvals)
     aPolyLine = vtk.vtkPolyLine()
     aPolyLine.GetPointIds().SetNumberOfIds(hlxnumPts)
     for i in range(0, hlxnumPts):
         aPolyLine.GetPointIds().SetId(i, i)
     hlxpdo.Allocate(1, 1)
     hlxpdo.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds())
     self.mapper = vtk.vtkPolyDataMapper()
     self.mapper.SetScalarVisibility(0)
     self.mapper.SetInput(hlxpdo)
     self.helact = vtk.vtkActor()
     self.helact.PickableOff()
     self.helact.DragableOff()
     self.helact.GetProperty().SetColor(1, 1, 1)
     self.helact.GetProperty().SetRepresentationToWireframe()
     self.helact.GetProperty().SetLineWidth(5)
     self.helact.GetProperty().SetLineWidth(1)
     self.helact.GetProperty().SetSpecular(.4)
     self.helact.GetProperty().SetSpecularPower(10)
     self.helact.SetMapper(self.mapper)
     assembly = vtk.vtkAssembly()
     assembly.AddPart(self.sphact)
     assembly.AddPart(self.helact)
     helcol = [(1, 1, 1), (1, 0, 0.3), (0.3, 0, 1), (0, 1, 0.3)]
     for i in range(1, self.s + 1):
         if i == 1:
             continue
         else:
             tmp_sphact = vtk.vtkActor()
             tmp_helact = vtk.vtkActor()
             tmp_sphact.ShallowCopy(self.sphact)
             tmp_helact.ShallowCopy(self.helact)
             ps = vtk.vtkProperty()
             ph = vtk.vtkProperty()
             ps.SetColor(helcol[(i - 1) % 4])
             ph.SetColor(helcol[(i - 1) % 4])
             tmp_sphact.SetProperty(ps)
             tmp_helact.SetProperty(ph)
             tmp_sphact.RotateWXYZ((360 / self.s) * (i - 1), 0, 0, 1)
             tmp_helact.RotateWXYZ((360 / self.s) * (i - 1), 0, 0, 1)
             assembly.AddPart(tmp_sphact)
             assembly.AddPart(tmp_helact)
     self.acteur = assembly
     gfx.renderer.AddActor(self.acteur)
     gfx.renwin.Render()
     gfx.ps = self
     return ptype
Ejemplo n.º 34
0
    def examineFilesIPPAcqTime(self, files):
        """
    This strategy first orders files into lists, where each list is
    indexed by ImagePositionPatient (IPP). Next, files within each
    list are ordered by AcquisitionTime attribute. Finally, loadable
    frames are indexed by AcquisitionTime, and files within each
    frame are ordered by IPP.
    This strategy was required to handle DSC MRI data collected on
    Siemens, tested with a DSC sequence obtained using software
    version "syngo MR B15"
    """

        loadables = []
        subseriesLists = {}
        orderedFiles = []

        desc = slicer.dicomDatabase.fileValue(
            files[0], self.tags['seriesDescription'])  # SeriesDescription

        minTime = self.tm2ms(
            slicer.dicomDatabase.fileValue(files[0],
                                           self.tags['AcquisitionTime']))
        for file in files:
            ipp = slicer.dicomDatabase.fileValue(file, self.tags['position'])
            time = self.tm2ms(
                slicer.dicomDatabase.fileValue(file,
                                               self.tags['AcquisitionTime']))
            if time < minTime:
                minTime = time
            if not subseriesLists.has_key(ipp):
                subseriesLists[ipp] = {}
            subseriesLists[ipp][time] = file

        nSlicesEqual = True
        allIPPs = subseriesLists.keys()
        for ipp in subseriesLists.keys():
            if len(subseriesLists[allIPPs[0]].keys()) != len(
                    subseriesLists[ipp].keys()):
                nSlicesEqual = False
                break

        if len(subseriesLists[allIPPs[0]].keys()) < 2 or not nSlicesEqual:
            return []

        if nSlicesEqual:
            nFrames = len(subseriesLists[allIPPs[0]].keys())
            nSlices = len(allIPPs)

            orderedFiles = [0] * nFrames * nSlices

            frameLabelsStr = ""
            frameFileListStr = ""
            frameLabelsArray = vtk.vtkDoubleArray()

            ippPositionCnt = 0
            for ipp in subseriesLists.keys():
                timesSorted = subseriesLists[ipp].keys()
                timesSorted.sort()
                timeCnt = 0
                for time in timesSorted:
                    orderedFiles[timeCnt * nSlices +
                                 ippPositionCnt] = subseriesLists[ipp][time]
                    timeCnt = timeCnt + 1
                    if ippPositionCnt == 0:
                        frameLabelsStr = frameLabelsStr + str(time -
                                                              minTime) + ','
                        frameLabelsArray.InsertNextValue(time - minTime)
                ippPositionCnt = ippPositionCnt + 1

            scalarVolumePlugin = slicer.modules.dicomPlugins[
                'DICOMScalarVolumePlugin']()
            firstFrameTime = 0
            for f in range(nFrames):
                frameFileList = orderedFiles[f * nSlices:(f + 1) * nSlices]
                svs = scalarVolumePlugin.examine([frameFileList])
                if len(svs) == 0:
                    print(
                        'Failed to parse one of the multivolume frames as scalar volume!'
                    )
                    break
                time = self.tm2ms(
                    slicer.dicomDatabase.fileValue(
                        svs[0].files[0], self.tags['AcquisitionTime']))
                if f == 0:
                    frameLabelsStr = '0,'
                    frameLabelsArray.InsertNextValue(0)
                    firstFrameTime = time
                else:
                    frameLabelsStr = frameLabelsStr + str(time -
                                                          firstFrameTime) + ','
                    frameLabelsArray.InsertNextValue(time)

            for file in orderedFiles:
                frameFileListStr = frameFileListStr + str(file) + ','

            frameLabelsStr = frameLabelsStr[:-1]
            frameFileListStr = frameFileListStr[:-1]

            mvNode = slicer.mrmlScene.CreateNodeByClass(
                'vtkMRMLMultiVolumeNode')
            mvNode.SetReferenceCount(mvNode.GetReferenceCount() - 1)
            mvNode.SetScene(slicer.mrmlScene)
            mvNode.SetAttribute("MultiVolume.FrameLabels", frameLabelsStr)
            mvNode.SetAttribute("MultiVolume.FrameIdentifyingDICOMTagName",
                                "AcquisitionTime")
            mvNode.SetAttribute("MultiVolume.ParseStrategy",
                                "AcquisitionTime+ImagePositionPatient")
            mvNode.SetAttribute('MultiVolume.NumberOfFrames', str(nFrames))
            mvNode.SetAttribute('MultiVolume.FrameIdentifyingDICOMTagUnits',
                                "ms")
            # keep the files in the order by the detected tag
            # files are not ordered within the individual frames -- this will be
            # done by ScalarVolumePlugin later
            mvNode.SetAttribute('MultiVolume.FrameFileList', frameFileListStr)

            self.addAcquisitionAttributes(mvNode, frameFileList)

            mvNode.SetNumberOfFrames(nFrames)
            mvNode.SetLabelName("AcquisitionTime")
            mvNode.SetLabelArray(frameLabelsArray)

            loadable = DICOMLib.DICOMLoadable()
            loadable.files = orderedFiles
            loadable.name = desc + ' - as a ' + str(
                nFrames
            ) + ' frames MultiVolume by ImagePositionPatient+AcquisitionTime'
            mvNode.SetName(desc)
            loadable.tooltip = loadable.name
            loadable.selected = True
            loadable.multivolume = mvNode
            loadable.confidence = 1.
            loadables.append(loadable)

        return loadables
Ejemplo n.º 35
0
def getIntegratedQOI(model, sorted_region_nodes, quantities_to_integrate,
                     output_filename, vprint):
    # Integrated quantities
    output_collection = []
    # Point Averaged quantities
    output2_collection = []
    for i_region in xrange(0, len(sorted_region_nodes)):
        for j_region in xrange(0, len(sorted_region_nodes[i_region])):
            print('Working on Region ' + str(i_region + 1) + '_' +
                  str(j_region + 1) + '...')
            region = extractRegion(model,
                                   sorted_region_nodes[i_region][j_region],
                                   vprint)
            writeVTU(region, 'test.vtu', vprint)
            numPts = region.GetNumberOfPoints()
            numCells = region.GetNumberOfCells()

            # Read in your quantities of interest from the .vtp file
            QOI = []
            for i in xrange(0, len(quantities_to_integrate)):
                QOI.append(vtk.vtkDoubleArray())
                QOI[i] = model.GetPointData().GetArray(
                    quantities_to_integrate[i])

        # Initialize data structures to store area, point total, and point counts
            total_area = 0.0
            integrated_variables = []
            for i in xrange(0, len(quantities_to_integrate)):
                integrated_variables.append(0.0)

            point_totals = []
            point_counts = []
            point_averages = []
            for iq in xrange(0, len(quantities_to_integrate)):
                point_totals.append(0.0)
                point_counts.append(0)
                point_averages.append(0.0)

            for pointID in xrange(0, numPts):
                # Get the region coordinate
                pointCoordinate = region.GetPoint(pointID)
                for iq in xrange(0, len(quantities_to_integrate)):
                    # Find the region coordinate in the model
                    vector = QOI[iq].GetTuple(model.FindPoint(pointCoordinate))
                    mag = 0
                    for i in xrange(0, len(vector)):
                        mag = mag + float(vector[i])**2
                        mag = mag**(.5)
                        # Ignore 0 value points
                        if (mag > 0):
                            point_totals[iq] = point_totals[iq] + mag
                            point_counts[iq] = point_counts[iq] + 1

            # Calculate point averaged QOIs
            for iq in xrange(0, len(quantities_to_integrate)):
                if (point_counts[iq] > 0):
                    point_averages[iq] = point_totals[iq] / point_counts[iq]

        # Now loop over the cells and add in contribution to the integrated_variable
        # that is equal to the average of all the cell nodal values multiplied by
        # the area of the cell
            for icell in xrange(0, numCells):

                temp_cell = region.GetCell(icell)
                pts_cell = temp_cell.GetPointIds()

                # First, get the area of this cell
                vtkpt = temp_cell.GetPoints()
                p0 = vtkpt.GetPoint(0)
                p1 = vtkpt.GetPoint(1)
                p2 = vtkpt.GetPoint(2)
                temp_area = vtk.vtkTriangle().TriangleArea(p0, p1, p2)
                total_area = total_area + temp_area

                # Now, sum up the values of the quantities of interest at the cell
                # vertices
                averages = []
                for iq in xrange(0, len(quantities_to_integrate)):
                    averages.append(0.0)

                for ipt in xrange(0, pts_cell.GetNumberOfIds()):
                    iid = pts_cell.GetId(ipt)
                    pointCoordinate = region.GetPoint(iid)
                    for iq in xrange(0, len(quantities_to_integrate)):
                        vector = QOI[iq].GetTuple(
                            model.FindPoint(pointCoordinate))
                        mag = 0
                        for i in xrange(0, len(vector)):
                            mag = mag + float(vector[i])**2
                        mag = mag**(.5)
                        averages[iq] = averages[iq] + mag

        # To complete the trapezoidal rule integration, multiply each summed quantity
        # by the area of the cell, then divide by the number of vertices
                for iq in xrange(0, len(quantities_to_integrate)):
                    integrated_variables[iq] = integrated_variables[iq] + \
                    averages[iq] * temp_area / float(pts_cell.GetNumberOfIds())

        # Now that we have integrated the variables of interest, it is time to save
        # the results to a list for outputting later
            temp_collection = [total_area]
            for iq in xrange(0, len(quantities_to_integrate)):
                temp_collection.append(integrated_variables[iq])

            temp2_collection = []
            for iq in xrange(0, len(quantities_to_integrate)):
                temp2_collection.append(point_averages[iq])
        # Stores the integrated values
            output_collection.append(temp_collection)
            # Stores the point averaged values
            output2_collection.append(temp2_collection)

    # Now that we have looped over all our .vtp files of interest and integrated
    # the variables, it is time to save them to the output file. We also print
    # out the integrated quantities divided by the surface area for post-processing
    # convenience

    outfile = open(output_filename, 'w')

    # First print a header that tells what each integrated quantity of interest is
    out_string = 'Region, Surface area, '
    for iq in xrange(0, len(quantities_to_integrate)):
        out_string = out_string + quantities_to_integrate[iq] + ', '
        out_string = out_string + quantities_to_integrate[iq] + "/Area, "
    out_string = out_string + '\n'
    outfile.write(out_string)
    # Print data
    counter = 0
    for i in xrange(0, len(sorted_region_nodes)):
        for j in xrange(0, len(sorted_region_nodes[i])):
            out_string = str(i) + '_' + str(j) + ',' + str(
                output_collection[counter][0])
            for iq in xrange(1, len(quantities_to_integrate) + 1):
                out_string = out_string + ', ' + str(
                    output_collection[counter][iq])
                out_string = out_string + ', ' + str(
                    output_collection[counter][iq] / output_collection[i][0])
            counter += 1

            out_string = out_string + '\n'
            outfile.write(out_string)

    outfile.write('\n')

    # Second print a header point averaged quantity of interests
    out_string = 'Region, '
    for iq in xrange(0, len(quantities_to_integrate)):
        out_string = out_string + quantities_to_integrate[iq] + ', '
    out_string = out_string + '\n'
    outfile.write(out_string)
    # Print data
    counter = 0
    for i in xrange(0, len(sorted_region_nodes)):
        for j in xrange(0, len(sorted_region_nodes[i])):
            out_string = str(i) + '_' + str(j) + ',' + str(
                output_collection[counter][0])
            for iq in xrange(0, len(quantities_to_integrate)):
                out_string = out_string + ', ' + str(
                    output2_collection[counter][iq])
            counter += 1

            out_string = out_string + '\n'
            outfile.write(out_string)

    outfile.close()
    def clipSurfaceAtEndPoints(self, networkPolyData, surfacePolyData):
        '''
        Clips the surfacePolyData on the endpoints identified using the networkPolyData.

        Returns a tupel of the form [clippedPolyData, endpointsPoints]
        '''
        # import the vmtk libraries
        try:
            import vtkvmtkComputationalGeometryPython as vtkvmtkComputationalGeometry
            import vtkvmtkMiscPython as vtkvmtkMisc
        except ImportError:
            logging.error("Unable to import the SlicerVmtk libraries")

        cleaner = vtk.vtkCleanPolyData()
        cleaner.SetInputData(networkPolyData)
        cleaner.Update()
        network = cleaner.GetOutput()
        network.BuildCells()
        network.BuildLinks(0)
        endpointIds = vtk.vtkIdList()

        radiusArray = network.GetPointData().GetArray('Radius')

        endpoints = vtk.vtkPolyData()
        endpointsPoints = vtk.vtkPoints()
        endpointsRadius = vtk.vtkDoubleArray()
        endpointsRadius.SetName('Radius')
        endpoints.SetPoints(endpointsPoints)
        endpoints.GetPointData().AddArray(endpointsRadius)

        radiusFactor = 1.2
        minRadius = 0.01

        for i in range(network.GetNumberOfCells()):
            numberOfCellPoints = network.GetCell(i).GetNumberOfPoints()
            pointId0 = network.GetCell(i).GetPointId(0)
            pointId1 = network.GetCell(i).GetPointId(numberOfCellPoints - 1)

            pointCells = vtk.vtkIdList()
            network.GetPointCells(pointId0, pointCells)
            numberOfEndpoints = endpointIds.GetNumberOfIds()
            if pointCells.GetNumberOfIds() == 1:
                pointId = endpointIds.InsertUniqueId(pointId0)
                if pointId == numberOfEndpoints:
                    point = network.GetPoint(pointId0)
                    radius = radiusArray.GetValue(pointId0)
                    radius = max(radius, minRadius)
                    endpointsPoints.InsertNextPoint(point)
                    endpointsRadius.InsertNextValue(radiusFactor * radius)

            pointCells = vtk.vtkIdList()
            network.GetPointCells(pointId1, pointCells)
            numberOfEndpoints = endpointIds.GetNumberOfIds()
            if pointCells.GetNumberOfIds() == 1:
                pointId = endpointIds.InsertUniqueId(pointId1)
                if pointId == numberOfEndpoints:
                    point = network.GetPoint(pointId1)
                    radius = radiusArray.GetValue(pointId1)
                    radius = max(radius, minRadius)
                    endpointsPoints.InsertNextPoint(point)
                    endpointsRadius.InsertNextValue(radiusFactor * radius)

        polyBall = vtkvmtkComputationalGeometry.vtkvmtkPolyBall()
        #polyBall.SetInputData(endpoints)
        polyBall.SetInput(endpoints)
        polyBall.SetPolyBallRadiusArrayName('Radius')

        clipper = vtk.vtkClipPolyData()
        clipper.SetInputData(surfacePolyData)
        clipper.SetClipFunction(polyBall)
        clipper.Update()

        connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
        connectivityFilter.SetInputData(clipper.GetOutput())
        connectivityFilter.ColorRegionsOff()
        connectivityFilter.SetExtractionModeToLargestRegion()
        connectivityFilter.Update()

        clippedSurface = connectivityFilter.GetOutput()

        outPolyData = vtk.vtkPolyData()
        outPolyData.DeepCopy(clippedSurface)

        return [outPolyData, endpointsPoints]
Ejemplo n.º 37
0
v1=vtk.vtkSelectEnclosedPoints()
v1.SetInputConnection(reader.GetOutputPort())
v1.SetSurfaceConnection(rodReader.GetOutputPort())
v1.CheckSurfaceOn ()
v1.InsideOutOff ()
v1.SetTolerance (1.0e-6)
v1.Update()
v1insideArray = v1.GetOutput().GetPointData().GetArray("SelectedPoints");
particleId=[]
for x in range(v1insideArray.GetNumberOfTuples()):
    particleId.append(v1insideArray.GetTuple1(x))
poly=vtk.vtkPolyData()
points=vtk.vtkPoints()
cells=vtk.vtkCellArray()

particle_id=vtk.vtkDoubleArray()
particle_id.SetName("ID")
particle_id.SetNumberOfComponents(1)
radius=vtk.vtkDoubleArray()
radius.SetName("RADIUS")
radius.SetNumberOfComponents(1)
bonds=vtk.vtkIntArray()
bonds.SetName("BONDS_ID")
bonds.SetNumberOfComponents(1)
data=reader.GetOutput()
for x in range(data.GetNumberOfPoints()):
    points.InsertNextPoint(data.GetPoint(x))
    radius.InsertNextTuple1(data.GetPointData().GetArray("radius").GetTuple1(x))
    particle_id.InsertNextTuple1(particleId[x])
for x in range(data.GetNumberOfCells()):
    cell=data.GetCell(x)
Ejemplo n.º 38
0
#a handy point iterator, calls action() on each point
def forEachPoint(xlim,ylim,zlim, action):
    for z in range(0,zlim+1):
        for y in range(0,ylim+1):
            for x in range(0,xlim+1):
                 action((x,y,z))

#make geometry
points = vtk.vtkPoints()
def makeCoordinate(pt):
    points.InsertNextPoint(pt)
forEachPoint(xlim,ylim,zlim, makeCoordinate)
sg.SetPoints(points)

#make a scalar array
scalars = vtk.vtkDoubleArray()
scalars.SetNumberOfComponents(1)
scalars.SetName("Xcoord")
def makeScalar(pt):
    scalars.InsertNextValue(pt[0]+pt[1]+pt[2])
forEachPoint(xlim,ylim,zlim, makeScalar)
sg.GetPointData().SetScalars(scalars)

#blank some arbitrarily chosen cells
numcells = sg.GetNumberOfCells()
if 11 < numcells:
    sg.BlankCell(11)
if 64 < numcells:
    sg.BlankCell(64)
if 164 < numcells:
    sg.BlankCell(164)
Ejemplo n.º 39
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)
Ejemplo n.º 40
0
 def creaEstrucDatosDiagrama(self):
     # Crea las estructuras de datos necesarias para crear el diagrama.
     self.initializeMinMax()
     self.points = vtk.vtkPoints()
     self.escalares = vtk.vtkDoubleArray()
     self.cells = vtk.vtkCellArray()
Ejemplo n.º 41
0
def main():
    points = vtk.vtkPoints()
    points.InsertNextPoint(0.0, 0.0, 0.0)
    points.InsertNextPoint(1.0, 0.0, 0.0)
    points.InsertNextPoint(2.0, 0.0, 0.0)
    points.InsertNextPoint(3.0, 0.0, 0.0)
    points.InsertNextPoint(4.0, 0.0, 0.0)

    lines = vtk.vtkCellArray()
    line = vtk.vtkLine()
    line.GetPointIds().SetId(0, 0)
    line.GetPointIds().SetId(1, 1)
    lines.InsertNextCell(line)
    line.GetPointIds().SetId(0, 1)
    line.GetPointIds().SetId(1, 2)
    lines.InsertNextCell(line)
    line.GetPointIds().SetId(0, 2)
    line.GetPointIds().SetId(1, 3)
    lines.InsertNextCell(line)
    line.GetPointIds().SetId(0, 3)
    line.GetPointIds().SetId(1, 4)
    lines.InsertNextCell(line)

    warpData = vtk.vtkDoubleArray()
    warpData.SetNumberOfComponents(3)
    warpData.SetName("warpData")
    warp = [0.0, 0.0, 0.0]
    warp[1] = 0.0
    warpData.InsertNextTuple(warp)
    warp[1] = 0.1
    warpData.InsertNextTuple(warp)
    warp[1] = 0.3
    warpData.InsertNextTuple(warp)
    warp[1] = 0.0
    warpData.InsertNextTuple(warp)
    warp[1] = 0.1
    warpData.InsertNextTuple(warp)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetLines(lines)
    polydata.GetPointData().AddArray(warpData)
    polydata.GetPointData().SetActiveVectors(warpData.GetName())

    # WarpVector will use the array marked as active vector in polydata
    # it has to be a 3 component array
    # with the same number of tuples as points in polydata
    warpVector = vtk.vtkWarpVector()
    if VTK_MAJOR_VERSION <= 5:
        warpVector.SetInput(polydata)
    else:
        warpVector.SetInputData(polydata)
    warpVector.Update()

    mapper = vtk.vtkPolyDataMapper()
    if VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(warpVector.GetPolyDataOutput())
    else:
        mapper.SetInputData(warpVector.GetPolyDataOutput())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    renderer.SetBackground(.3, .6, .3)

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderWindow.Render()
    renderWindowInteractor.Start()

    return
Ejemplo n.º 42
0
            pts.SetPoint(count,xy_new[i,j,k],yx_new[i,j,k],zx_new[i,j,k])
            count = count +1
print("Endding of Point creation")
#Create UNstructured grid and add the points
ug = vtk.vtkUnstructuredGrid()
ug.SetPoints(pts)
#Probe filter to extract image pixel intensities in specific coordinates
probe = vtk.vtkProbeFilter()
probe.SetInputData(ug)
probe.SetSourceData(t)
probe.Update()
samples = probe.GetOutput()
samples = samples.GetPointData()
samples = samples.GetScalars()
#Create array with all pixel intensities extracted
w = vtk.vtkDoubleArray()
w.SetNumberOfTuples(samples.GetNumberOfTuples())
for i in range(samples.GetNumberOfTuples()):
    w.SetTuple1(i,samples.GetTuple1(i))
#Check paraview
ug.GetPointData().AddArray(w)
wr = vtk.vtkXMLUnstructuredGridWriter()
wr.SetInputData(ug)
wr.SetFileName("test.vtu")
wr.EncodeAppendedDataOff()
wr.Write()
#Create Image
output = vtk.vtkImageData()
output.SetDimensions(xy_new.shape)
output.AllocateScalars(vtk.VTK_DOUBLE,0)
# output.SetDirectionMatrix(R[0,0],R[0,1],R[0,2],R[1,0],R[1,1],R[1,2],R[2,0],R[2,1],R[2,2])
file_handle = open(outPrefix + '/header.xml', 'w')
file_handle.write(prettify(root))
file_handle.close()

# medial points and polygons first
medial_points = vtk.vtkPoints()
medial_points.SetDataTypeToDouble(
)  # important, this fix the bug that new srep has different precision with legacy one, you can find it by runningapplyTps2NewSrep program
medial_polys = vtk.vtkCellArray()

# This will be curves
crest_points = vtk.vtkPoints()
crest_polys = vtk.vtkCellArray()
#
up_spoke_directions = vtk.vtkDoubleArray()
up_spoke_directions.SetNumberOfComponents(3)
up_spoke_directions.SetName("spokeDirection")

up_spoke_lengths = vtk.vtkDoubleArray()
up_spoke_lengths.SetNumberOfComponents(1)
up_spoke_lengths.SetName("spokeLength")

down_spoke_directions = vtk.vtkDoubleArray()
down_spoke_directions.SetNumberOfComponents(3)
down_spoke_directions.SetName("spokeDirection")

down_spoke_lengths = vtk.vtkDoubleArray()
down_spoke_lengths.SetNumberOfComponents(1)
down_spoke_lengths.SetName("spokeLength")
Ejemplo n.º 44
0
      idList.InsertNextId(xyzToNode[i+1][j+1][k])
      idList.InsertNextId(xyzToNode[i+1][j+1][k+1])
      idList.InsertNextId(xyzToNode[i+1][j][k+1])
      ugrid.InsertNextCell(VTK_HEXAHEDRON, idList)

# Add the fields
pointdata = ugrid.GetPointData()

# NOTE: we cache the grid to speed up the conversion - not valid with variable meshes

for f in files:

  f3d = Spherical_3D_multi(f)

  for index, vals in f3d.vals.items():
    data = vtk.vtkDoubleArray()
    data.SetNumberOfValues(len(vals))
    data.SetName('f'+index)
    for i, v in enumerate(vals):
      data.SetValue(i, v)
    pointdata.AddArray(data)
    pointdata.SetActiveScalars('f'+index)

  gridwriter = vtk.vtkXMLUnstructuredGridWriter()
  gridwriter.SetFileName(os.path.join("Spherical_3D", "full3d_"+f3d.basefilename+".vtu"))
  if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
    gridwriter.SetInput(ugrid)
  else:
    gridwriter.SetInputData(ugrid)

  gridwriter.Write()
Ejemplo n.º 45
0
    def Execute(self):

        if not self.Network:
            self.Network = vtk.vtkPolyData()
            networkPoints = vtk.vtkPoints()
            networkLines = vtk.vtkCellArray()
            radiusArray = vtk.vtkDoubleArray()
            radiusArray.SetName(self.RadiusArrayName)
            self.Network.SetPoints(networkPoints)
            self.Network.SetLines(networkLines)
            self.Network.GetPointData().AddArray(radiusArray)

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.ExitAfterTextInputMode = False
        self.vmtkRenderer.RegisterScript(self)

        if self.Image and (not self.PlaneWidgetX or not self.PlaneWidgetY or not self.PlaneWidgetZ):
            imageViewer = vmtkimageviewer.vmtkImageViewer()
            imageViewer.Image = self.Image
            imageViewer.vmtkRenderer = self.vmtkRenderer
            imageViewer.Display = 0
            imageViewer.Execute()
            self.PlaneWidgetX = imageViewer.PlaneWidgetX
            self.PlaneWidgetY = imageViewer.PlaneWidgetY
            self.PlaneWidgetZ = imageViewer.PlaneWidgetZ

        if self.Image:
            spacing = self.Image.GetSpacing()
            self.CurrentRadius = min(spacing)

        if self.UseActiveTubes and not self.FeatureImage:
            imageFeatures = vmtkimagefeatures.vmtkImageFeatures()
            imageFeatures.Image = self.Image
            imageFeatures.FeatureImageType = 'vtkgradient'
            imageFeatures.Execute()
            self.FeatureImage = imageFeatures.FeatureImage

        self.NetworkRadiusArray = self.Network.GetPointData().GetArray(self.RadiusArrayName)

        self.Network.GetPointData().SetActiveScalars(self.RadiusArrayName)

        networkMapper = vtk.vtkPolyDataMapper()
        networkMapper.SetInputData(self.Network)
        networkMapper.SetScalarModeToUseCellData()

        self.NetworkActor = vtk.vtkActor()
        self.NetworkActor.SetMapper(networkMapper)
        self.vmtkRenderer.Renderer.AddActor(self.NetworkActor)

        self.NetworkTube = vtk.vtkTubeFilter()
        self.NetworkTube.SetInputData(self.Network)
        self.NetworkTube.SetVaryRadiusToVaryRadiusByAbsoluteScalar()
        self.NetworkTube.SetNumberOfSides(20)
        networkTubeMapper = vtk.vtkPolyDataMapper()
        networkTubeMapper.SetInputConnection(self.NetworkTube.GetOutputPort())
        networkTubeMapper.ScalarVisibilityOff()
        networkTubeActor = vtk.vtkActor()
        networkTubeActor.SetMapper(networkTubeMapper)
        networkTubeActor.PickableOff()
        networkTubeActor.GetProperty().SetOpacity(0.2)
        self.vmtkRenderer.Renderer.AddActor(networkTubeActor)

        self.Selection = vtk.vtkPolyData()
        self.SelectionPoints = vtk.vtkPoints()
        self.SelectionRadiusArray = vtk.vtkDoubleArray()
        self.SelectionRadiusArray.SetName(self.RadiusArrayName)
        self.Selection.SetPoints(self.SelectionPoints)
        self.Selection.GetPointData().AddArray(self.SelectionRadiusArray)
        self.Selection.GetPointData().SetActiveScalars(self.RadiusArrayName)

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphSource.SetRadius(1.0)
        glyphSource.SetThetaResolution(20)
        glyphSource.SetPhiResolution(20)
        glyphs.SetInputData(self.Selection)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToScaleByScalar()
        glyphs.SetScaleFactor(1.0)

        selectionMapper = vtk.vtkPolyDataMapper()
        selectionMapper.SetInputConnection(glyphs.GetOutputPort())

        self.SelectionActor = vtk.vtkActor()
        self.SelectionActor.SetMapper(selectionMapper)
        self.SelectionActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.SelectionActor.GetProperty().SetOpacity(0.5)
        self.SelectionActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SelectionActor)

        self.ActiveSegmentSeeds = vtk.vtkPolyData()
        self.ActiveSegmentSeedsPoints = vtk.vtkPoints()
        self.ActiveSegmentSeedsRadiusArray = vtk.vtkDoubleArray()
        self.ActiveSegmentSeedsRadiusArray.SetName(self.RadiusArrayName)
        self.ActiveSegmentSeeds.SetPoints(self.ActiveSegmentSeedsPoints)
        self.ActiveSegmentSeeds.GetPointData().AddArray(self.ActiveSegmentSeedsRadiusArray)
        self.ActiveSegmentSeeds.GetPointData().SetActiveScalars(self.RadiusArrayName)

        activeSegmentSeedsGlyphs = vtk.vtkGlyph3D()
        activeSegmentSeedsGlyphSource = vtk.vtkSphereSource()
        activeSegmentSeedsGlyphSource.SetRadius(1.0)
        activeSegmentSeedsGlyphSource.SetThetaResolution(20)
        activeSegmentSeedsGlyphSource.SetPhiResolution(20)
        activeSegmentSeedsGlyphs.SetInputData(self.ActiveSegmentSeeds)
        activeSegmentSeedsGlyphs.SetSourceConnection(activeSegmentSeedsGlyphSource.GetOutputPort())
        activeSegmentSeedsGlyphs.SetScaleModeToScaleByScalar()
        activeSegmentSeedsGlyphs.SetScaleFactor(1.0)

        activeSegmentSeedsMapper = vtk.vtkPolyDataMapper()
        activeSegmentSeedsMapper.SetInputConnection(activeSegmentSeedsGlyphs.GetOutputPort())
        activeSegmentSeedsMapper.ScalarVisibilityOff()

        self.ActiveSegmentSeedsActor = vtk.vtkActor()
        self.ActiveSegmentSeedsActor.SetMapper(activeSegmentSeedsMapper)
        self.ActiveSegmentSeedsActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.ActiveSegmentSeedsActor.GetProperty().SetOpacity(0.5)
        self.ActiveSegmentSeedsActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.ActiveSegmentSeedsActor)

        self.ActiveSegment = vtk.vtkPolyData()
        self.ActiveSegmentPoints = vtk.vtkPoints()
        self.ActiveSegmentCellArray = vtk.vtkCellArray()
        self.ActiveSegmentRadiusArray = vtk.vtkDoubleArray()
        self.ActiveSegmentRadiusArray.SetName(self.RadiusArrayName)
        self.ActiveSegment.SetPoints(self.ActiveSegmentPoints)
        self.ActiveSegment.SetLines(self.ActiveSegmentCellArray)
        self.ActiveSegment.GetPointData().AddArray(self.ActiveSegmentRadiusArray)
        self.ActiveSegment.GetPointData().SetActiveScalars(self.RadiusArrayName)

        activeSegmentMapper = vtk.vtkPolyDataMapper()
        activeSegmentMapper.ScalarVisibilityOff()
        if self.SplineInterpolation and self.Image != None:
            splineFilter = vtk.vtkSplineFilter()
            splineFilter.SetInputData(self.ActiveSegment)
            splineFilter.SetSubdivideToLength()
            splineFilter.SetLength(2.0*min(self.Image.GetSpacing()))
            activeSegmentMapper.SetInputConnection(splineFilter.GetOutputPort())
        else:
            activeSegmentMapper.SetInputData(self.ActiveSegment)

        self.ActiveSegmentActor = vtk.vtkActor()
        self.ActiveSegmentActor.SetMapper(activeSegmentMapper)
        self.ActiveSegmentActor.GetProperty().SetColor(1.0,1.0,1.0)
        self.ActiveSegmentActor.GetProperty().SetLineWidth(3.0)
        self.ActiveSegmentActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.ActiveSegmentActor)

        activeTube = vtk.vtkTubeFilter()
        activeTube.SetInputData(activeSegmentMapper.GetInput())
        activeTube.SetVaryRadiusToVaryRadiusByAbsoluteScalar()
        activeTube.SetNumberOfSides(20)
        activeTubeMapper = vtk.vtkPolyDataMapper()
        activeTubeMapper.SetInputConnection(activeTube.GetOutputPort())
        activeTubeMapper.ScalarVisibilityOff()
        activeTubeActor = vtk.vtkActor()
        activeTubeActor.SetMapper(activeTubeMapper)
        activeTubeActor.PickableOff()
        activeTubeActor.GetProperty().SetOpacity(0.6)
        self.vmtkRenderer.Renderer.AddActor(activeTubeActor)

        self.NetworkLabelsArray = vtk.vtkStringArray.SafeDownCast(self.Network.GetCellData().GetAbstractArray(self.LabelsArrayName))
        if not self.NetworkLabelsArray:
            self.NetworkLabelsArray = vtk.vtkStringArray()
            self.NetworkLabelsArray.SetName(self.LabelsArrayName)
            self.NetworkLabelsArray.SetNumberOfValues(self.Network.GetNumberOfCells())
            for i in range(self.Network.GetNumberOfCells()):
                self.NetworkLabelsArray.SetValue(i,'')
            self.Network.GetCellData().AddArray(self.NetworkLabelsArray)
        self.CellCenters = vtk.vtkCellCenters()
        self.CellCenters.SetInputData(self.Network)
        self.CellCenters.VertexCellsOff()
        self.CellCenters.Update()

        labeledMapper = vtk.vtkLabeledDataMapper()
        labeledMapper.SetInputConnection(self.CellCenters.GetOutputPort())
        labeledMapper.SetLabelModeToLabelFieldData()
        labeledMapper.SetFieldDataName(self.LabelsArrayName)
        labeledMapper.GetLabelTextProperty().SetFontFamilyToArial()
        labeledMapper.GetLabelTextProperty().BoldOff()
        labeledMapper.GetLabelTextProperty().ItalicOff()
        labeledMapper.GetLabelTextProperty().ShadowOff()

        self.LabelsActor = vtk.vtkActor2D()
        self.LabelsActor.SetMapper(labeledMapper)
        self.LabelsActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.LabelsActor)

        self.CellPicker = vtk.vtkCellPicker()
        self.CellPicker.SetTolerance(1E-2)
        self.CellPicker.InitializePickList()
        self.CellPicker.AddPickList(self.NetworkActor)
        self.CellPicker.PickFromListOn()

        self.vmtkRenderer.AddKeyBinding('a','Add mode.',self.AddCallback)
        self.vmtkRenderer.AddKeyBinding('d','Delete mode.',self.DeleteCallback)
        self.vmtkRenderer.AddKeyBinding('m','Merge mode.',self.MergeCallback)
        self.vmtkRenderer.AddKeyBinding('s','Split mode.',self.SplitCallback)
        self.vmtkRenderer.AddKeyBinding('l','Label mode.',self.LabelCallback)
        self.vmtkRenderer.AddKeyBinding('Tab','Show labels.',self.ShowLabelCallback)
        self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyReleaseEvent", self.KeyReleaseCallback)
        self.vmtkRenderer.RenderWindowInteractor.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback)
        self.vmtkRenderer.RenderWindowInteractor.AddObserver("MouseMoveEvent", self.MouseMoveCallback)

        if self.PlaneWidgetX:
            self.PlaneWidgetX.UseContinuousCursorOn()
            self.PlaneWidgetX.AddObserver("StartInteractionEvent", self.PlaneStartInteractionCallback)
        if self.PlaneWidgetY:
            self.PlaneWidgetY.UseContinuousCursorOn()
            self.PlaneWidgetY.AddObserver("StartInteractionEvent", self.PlaneStartInteractionCallback)
        if self.PlaneWidgetZ:
            self.PlaneWidgetZ.UseContinuousCursorOn()
            self.PlaneWidgetZ.AddObserver("StartInteractionEvent", self.PlaneStartInteractionCallback)

        self.FirstRender()

        self.Surface = self.NetworkTube.GetOutput()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Ejemplo n.º 46
0
    def export2vtk(self, filename):
        """This method call saves existing fields into a vtk file for visualization in e.g Paraview.
        This function has a dependency on VTK and the Python bindings vtk."""
        logging.info('exporting network to VTK format...')
        try:
            import vtk
            from vtk.util import numpy_support
        except ImportError:
            logging.warning(
                'Package VTK cannot be found, abort export to VTK format.')
            return
        self.clean_network()

        points = vtk.vtkPoints()  # node-based quantities
        for n, node in enumerate(self.nodes):
            points.InsertPoint(n, node.x, node.y, node.z)
        if self.heads is not None:
            head = numpy_support.numpy_to_vtk(num_array=self.heads.ravel(),
                                              deep=True,
                                              array_type=vtk.VTK_FLOAT)
            head.SetName("h (m)")
        if self.node_throughflows is not None:
            throughflows = numpy_support.numpy_to_vtk(
                self.node_throughflows.ravel(), True, array_type=vtk.VTK_FLOAT)
            throughflows.SetName("Node throughflows (m**3/s)")
        if self.boundary_flows is not None:
            boundary_flows = numpy_support.numpy_to_vtk(
                self.boundary_flows.ravel(), True, array_type=vtk.VTK_FLOAT)
            boundary_flows.SetName("Local boundary flows (m**3/s)")
        if self.components is not None:
            components = numpy_support.numpy_to_vtk(self.components.ravel(),
                                                    True,
                                                    array_type=vtk.VTK_INT)
            components.SetName("Connected components (id)")

        lines = vtk.vtkCellArray()  # channel-based quantities
        conductances, lengths, widths = vtk.vtkDoubleArray(
        ), vtk.vtkDoubleArray(), vtk.vtkDoubleArray()
        apertures, flows = vtk.vtkDoubleArray(), vtk.vtkDoubleArray()
        conductances.SetName("C (m**2/s)")
        lengths.SetName("L (m)")
        widths.SetName("W (m)")
        apertures.SetName("b (m)")
        flows.SetName("Q (m**3/s)")
        for k, v in self.channels.items():
            lines.InsertNextCell(2)
            lines.InsertCellPoint(k[0])
            lines.InsertCellPoint(k[1])
            conductances.InsertNextValue(v.conductance)
            lengths.InsertNextValue(v.length)
            widths.InsertNextValue(v.width)
            apertures.InsertNextValue(v.aperture)
            flows.InsertNextValue(v.flow)

        profile = vtk.vtkPolyData()
        profile.SetPoints(points)  # node-based data
        if self.heads is not None:
            profile.GetPointData().AddArray(head)
        if self.node_throughflows is not None:
            profile.GetPointData().AddArray(throughflows)
        if self.boundary_flows is not None:
            profile.GetPointData().AddArray(boundary_flows)
        if self.components is not None:
            profile.GetPointData().SetScalars(components)
        profile.SetLines(lines)  # channel-based data
        profile.GetCellData().SetScalars(conductances)
        profile.GetCellData().AddArray(lengths)
        profile.GetCellData().AddArray(widths)
        profile.GetCellData().AddArray(apertures)
        profile.GetCellData().AddArray(flows)

        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetFileName(filename + ".vtp")
        try:
            writer.SetInputData(profile)
        except AttributeError:
            writer.SetInput(profile)
        writer.Write()
        logging.info('...done')
Ejemplo n.º 47
0
def meshgrid_slice(meshgrid, x0, x1, y0, y1, main):

    #Data Parameter
    ndata = len(meshgrid[:, 0])
    nx = len(np.unique(meshgrid[:, 0]))
    ny = len(np.unique(meshgrid[:, 1]))
    nz = int(ndata / nx / ny)

    minx = min(meshgrid[:, 0])
    miny = min(meshgrid[:, 1])

    delx = meshgrid[nz, 0] - meshgrid[nz - 1, 0]
    dely = meshgrid[nz * nx, 1] - meshgrid[nz * nx - 1, 1]

    #Mesh Creation
    d = (delx + dely) / 2
    r = ((x1 - x0)**2 + (y1 - y0)**2)**0.5
    dr = r / (int(r / d))

    mesh = np.zeros((4, 4))
    nsec = int(r / d) + 1
    section = np.zeros((nsec * nz, 4))

    for i in range(nsec):
        x = x0 + dr * i * (x1 - x0) / r
        y = y0 + dr * i * (y1 - y0) / r

        nmx = int((x0 + d * i * (x1 - x0) / r - minx) / delx)
        nmy = int((y0 + d * i * (y1 - y0) / r - miny) / dely)

        #--Interpolasi Liniar

        for h in range(nz):
            section[i * nz + h, 0] = x
            section[i * nz + h, 1] = y

            #Neighbors
            mesh[0, :] = meshgrid[(nx * (nmy + 0) + nmx + 0) * nz + h, :]
            mesh[1, :] = meshgrid[(nx * (nmy + 0) + nmx + 1) * nz + h, :]
            mesh[2, :] = meshgrid[(nx * (nmy + 1) + nmx + 0) * nz + h, :]
            mesh[3, :] = meshgrid[(nx * (nmy + 1) + nmx + 1) * nz + h, :]

            #Elevation Interpolation
            a0 = ((mesh[1, 2] - mesh[0, 2]) / (mesh[1, 0] - mesh[0, 0]) *
                  (section[i * nz + h, 0] - mesh[0, 0])) + mesh[0, 2]
            b0 = ((mesh[3, 2] - mesh[2, 2]) / (mesh[3, 0] - mesh[2, 0]) *
                  (section[i * nz + h, 0] - mesh[2, 0])) + mesh[2, 2]
            section[i * nz + h,
                    2] = ((b0 - a0) / (mesh[2, 1] - mesh[0, 1]) *
                          (section[i * nz + h, 1] - mesh[0, 1])) + a0

            a0 = ((mesh[1, 3] - mesh[0, 3]) / (mesh[1, 0] - mesh[0, 0]) *
                  (section[i * nz + h, 0] - mesh[0, 0])) + mesh[0, 3]
            b0 = ((mesh[3, 3] - mesh[2, 3]) / (mesh[3, 0] - mesh[2, 0]) *
                  (section[i * nz + h, 0] - mesh[2, 0])) + mesh[2, 3]
            section[i * nz + h,
                    3] = np.log10(((b0 - a0) / (mesh[2, 1] - mesh[0, 1]) *
                                   (section[i * nz + h, 1] - mesh[0, 1])) + a0)

    #--Creating Vtk Object
    #Create Polygon
    points = vtk.vtkPoints()
    mesh = vtk.vtkUnstructuredGrid()
    scalar = vtk.vtkDoubleArray()

    #Filling Points
    for i in range(nsec * nz):
        points.InsertNextPoint(section[i, 0], section[i, 1], section[i, 2])

    #Insert Cells
    quad = vtk.vtkQuad()

    for i in range(nsec - 1):
        for h in range(nz - 1):
            quad.GetPointIds().SetId(0, nz * i + 0)
            quad.GetPointIds().SetId(1, nz * i + 1)
            quad.GetPointIds().SetId(2, nz * (i + 1) + 1)
            quad.GetPointIds().SetId(3, nz * (i + 1) + 0)

            mesh.InsertNextCell(quad.GetCellType(), quad.GetPointIds())

            #Cell Scalar Value
            value = (section[nz * i + 0, 3] + section[nz * i + 1, 3] +
                     section[nz *
                             (i + 1) + 1, 3] + section[nz *
                                                       (i + 1) + 0, 3]) / 4
            scalar.InsertNextTuple([np.log10(value) * 0.5])

    mesh.SetPoints(points)
    mesh.GetCellData().SetScalars(scalar)
    main.mesh_renderer(mesh)

    return section


#point = np.array([[795727, 9197285, 0, 0], [795727, 9197285, 0, 0]])
#data  = np.loadtxt("D:\WORK\MODEL_WNI\data\mesh_adj.txt")

#a = xyzv_krigging(data, point)
Ejemplo n.º 48
0
    def test_array2vtk(self):
        """Test Numeric array to VTK array conversion and vice-versa."""
        # Put all the test arrays here.
        t_z = []

        # Test the different types of arrays.
        t_z.append(numpy.array([-128, 0, 127], numpy.int8))

        # FIXME: character arrays are a problem since there is no
        # unique mapping to a VTK data type and back.
        #t_z.append(numpy.array([-128, 0, 127], numpy.character))
        t_z.append(numpy.array([-32768, 0, 32767], numpy.int16))
        t_z.append(numpy.array([-2147483648, 0, 2147483647], numpy.int32))
        t_z.append(numpy.array([0, 255], numpy.uint8))
        t_z.append(numpy.array([0, 65535], numpy.uint16))
        t_z.append(numpy.array([0, 4294967295L], numpy.uint32))
        t_z.append(numpy.array([-1.0e38, 0, 1.0e38], 'f'))
        t_z.append(numpy.array([-1.0e299, 0, 1.0e299], 'd'))

        # Check multi-component arrays.
        t_z.append(numpy.array([[1], [2], [300]], 'd'))
        t_z.append(numpy.array([[1, 20], [300, 4000]], 'd'))
        t_z.append(numpy.array([[1, 2, 3], [4, 5, 6]], 'f'))
        t_z.append(numpy.array([[1, 2, 3], [4, 5, 6]], 'd'))
        t_z.append(numpy.array([[1, 2, 3, 400], [4, 5, 6, 700]], 'd'))
        t_z.append(numpy.array([range(9), range(10, 19)], 'f'))

        # Test if a Python list also works.
        t_z.append(numpy.array([[1., 2., 3., 400.], [4, 5, 6, 700]], 'd'))

        # Test if arrays with number of components not in [1,2,3,4,9] work.
        t_z.append(
            numpy.array([[1, 2, 3, 400, 5000], [4, 5, 6, 700, 8000]], 'd'))
        t_z.append(numpy.array([range(10), range(10, 20)], 'd'))

        for z in t_z:
            vtk_arr = array_handler.array2vtk(z)
            # Test for memory leaks.
            self.assertEqual(vtk_arr.GetReferenceCount(),
                             array_handler.BASE_REFERENCE_COUNT)
            self._check_arrays(z, vtk_arr)
            z1 = array_handler.vtk2array(vtk_arr)
            if len(z.shape) == 1:
                self.assertEqual(len(z1.shape), 1)
            if z.dtype.char != 'c':
                #print z1
                self.assertEqual(sum(numpy.ravel(z) - numpy.ravel(z1)), 0)
            else:
                #print z1.astype('c')
                self.assertEqual(z, z1.astype('c'))

        # Check if type conversion works correctly.
        z = numpy.array([-128, 0, 127], numpy.int8)
        vtk_arr = vtk.vtkDoubleArray()
        ident = id(vtk_arr)
        vtk_arr = array_handler.array2vtk(z, vtk_arr)
        # Make sure this is the same array!
        self.assertEqual(ident, id(vtk_arr))
        self._check_arrays(z, vtk_arr)

        # Check the vtkBitArray.
        vtk_arr = vtk.vtkBitArray()
        vtk_arr.InsertNextValue(0)
        vtk_arr.InsertNextValue(1)
        vtk_arr.InsertNextValue(0)
        vtk_arr.InsertNextValue(1)
        arr = array_handler.vtk2array(vtk_arr)
        self.assertEqual(numpy.sum(arr - [0, 1, 0, 1]), 0)
        vtk_arr = array_handler.array2vtk(arr, vtk_arr)
        self.assertEqual(vtk_arr.GetValue(0), 0)
        self.assertEqual(vtk_arr.GetValue(1), 1)
        self.assertEqual(vtk_arr.GetValue(2), 0)
        self.assertEqual(vtk_arr.GetValue(3), 1)

        # ----------------------------------------
        # Test if the array is copied or not.
        a = numpy.array([[1, 2, 3], [4, 5, 6]], 'd')
        vtk_arr = array_handler.array2vtk(a)
        # Change the numpy array and see if the changes are
        # reflected in the VTK array.
        a[0] = [10.0, 20.0, 30.0]
        self.assertEqual(vtk_arr.GetTuple3(0), (10., 20., 30.))

        # Make sure the cache is doing its job.
        key = vtk_arr.__this__
        z = array_handler._array_cache.get(vtk_arr)
        self.assertEqual(numpy.sum(z - numpy.ravel(a)), 0.0)

        l1 = len(array_handler._array_cache)
        # del the Numeric array and see if this still works.
        del a
        self.assertEqual(vtk_arr.GetTuple3(0), (10., 20., 30.))
        # Check the cache -- just making sure.
        self.assertEqual(len(array_handler._array_cache), l1)

        # Delete the VTK array and see if the cache is cleared.
        del vtk_arr
        self.assertEqual(len(array_handler._array_cache), l1 - 1)
        self.assertEqual(array_handler._array_cache._cache.has_key(key), False)

        # Make sure bit arrays are copied.
        vtk_arr = vtk.vtkBitArray()
        a = numpy.array([0, 1, 0, 1], numpy.int32)
        vtk_arr = array_handler.array2vtk(a, vtk_arr)
        del a
        self.assertEqual(vtk_arr.GetValue(0), 0)
        self.assertEqual(vtk_arr.GetValue(1), 1)
        self.assertEqual(vtk_arr.GetValue(2), 0)
        self.assertEqual(vtk_arr.GetValue(3), 1)

        # Make sure the code at least runs for all the non-complex
        # numerical dtypes in numpy.
        for dtype in (numpy.sctypes['int'] + numpy.sctypes['uint'] +
                      numpy.sctypes['float']):
            array_handler.array2vtk(numpy.zeros((1, ), dtype=dtype))
Ejemplo n.º 49
0
    def exportToTable(self, table, nonEmptyKeysOnly=True):
        """
    Export statistics to table node
    """
        tableWasModified = table.StartModify()
        table.RemoveAllColumns()

        keys = self.getNonEmptyKeys() if nonEmptyKeysOnly else self.keys
        columnHeaderNames, uniqueColumnHeaderNames = self.getHeaderNames(
            nonEmptyKeysOnly)

        # Define table columns
        statistics = self.getStatistics()
        for key in keys:
            # create table column appropriate for data type; currently supported: float, int, long, string
            measurements = [
                statistics[segmentID, key]
                for segmentID in statistics["SegmentIDs"]
                if statistics.has_key((segmentID, key))
            ]
            if len(
                    measurements
            ) == 0:  # there were not measurements and therefore use the default "string" representation
                col = table.AddColumn()
            elif type(measurements[0]) in [int, long]:
                col = table.AddColumn(vtk.vtkLongArray())
            elif type(measurements[0]) is float:
                col = table.AddColumn(vtk.vtkDoubleArray())
            else:  # default
                col = table.AddColumn()
            plugin = self.getPluginByKey(key)
            columnName = uniqueColumnHeaderNames[key]
            longColumnName = columnHeaderNames[key]
            col.SetName(columnName)
            if plugin:
                table.SetColumnProperty(columnName, "Plugin", plugin.name)
                longColumnName += '<br>Computed by ' + plugin.name + ' Statistics plugin'
            table.SetColumnLongName(columnName, longColumnName)
            measurementInfo = statistics["MeasurementInfo"][
                key] if key in statistics["MeasurementInfo"] else {}
            if measurementInfo:
                for mik, miv in measurementInfo.iteritems():
                    if mik == 'description':
                        table.SetColumnDescription(columnName, str(miv))
                    elif mik == 'units':
                        table.SetColumnUnitLabel(columnName, str(miv))
                    else:
                        table.SetColumnProperty(columnName, str(mik), str(miv))

        # Fill columns
        for segmentID in statistics["SegmentIDs"]:
            rowIndex = table.AddEmptyRow()
            columnIndex = 0
            for key in keys:
                value = statistics[segmentID, key] if statistics.has_key(
                    (segmentID, key)) else None
                if value is None and key != 'Segment':
                    value = float('nan')
                table.GetTable().GetColumn(columnIndex).SetValue(
                    rowIndex, value)
                columnIndex += 1

        table.Modified()
        table.EndModify(tableWasModified)
    def __get_contour_data_vtk(self, x_grid, y_grid, z_grid, isovalue=[0]):
        """
        wrapper for vtk marching squares function. Extracting contour information into bokeh compatible data type.
        Less comfortable (no text labels, no coloring) but faster then __get_contour_data_mpl
        :param x_grid:
        :param y_grid:
        :param z_grid:
        :param isovalue:
        :return:
        """
        nx, ny = x_grid.shape

        xmin = self._plot.x_range.start
        xmax = self._plot.x_range.end
        ymin = self._plot.y_range.start
        ymax = self._plot.y_range.end

        hx = (xmax - xmin) / (nx - 1)
        hy = (ymax - ymin) / (ny - 1)

        image = vtk.vtkImageData()
        image.SetDimensions(nx, ny, 1)
        image.SetOrigin(xmin, ymin, 0)
        image.SetSpacing(hx, hy, 0)

        data = vtk.vtkDoubleArray()
        data.SetNumberOfComponents(1)
        data.SetNumberOfTuples(image.GetNumberOfPoints())
        data.SetName("Values")

        # we load the z_data into vtk datatypes
        vtk_data_array = numpy_support.numpy_to_vtk(z_grid.ravel(),
                                                    deep=True,
                                                    array_type=vtk.VTK_DOUBLE)
        image.AllocateScalars(vtk.VTK_DOUBLE, 1)
        image.GetPointData().SetScalars(vtk_data_array)

        # apply marchign squares
        ms = vtk.vtkMarchingSquares()
        ms.SetInputData(image)
        for i in range(isovalue.__len__()):  # set isovalues
            ms.SetValue(i, isovalue[i])
        ms.SetImageRange(0,
                         image.GetDimensions()[0], 0,
                         image.GetDimensions()[1], 0, 0)
        ms.Update()

        # read output
        poly = ms.GetOutput()
        points = poly.GetPoints()
        lines = poly.GetLines()

        pts = numpy_support.vtk_to_numpy(points.GetData())  # get points
        line_idx = numpy_support.vtk_to_numpy(lines.GetData())  # get lines

        # lines are encoded as [nVerticesLine1, firstId, secondId, ... , nVerticesLine2...]
        # We always have 2 vertices per line. This justifies the stride 3 pattern below
        even_idx = line_idx[1::3]
        odd_idx = line_idx[2::3]

        x0 = pts[odd_idx, 0]
        y0 = pts[odd_idx, 1]
        x1 = pts[even_idx, 0]
        y1 = pts[even_idx, 1]

        data_contour = {'x0': x0, 'x1': x1, 'y0': y0, 'y1': y1}
        data_contour_label = {}
        return data_contour, data_contour_label
Ejemplo n.º 51
0
        x0, y0, z0 = points.GetPoint(ptId0)
        x1, y1, z1 = points.GetPoint(ptId1)

        # retreat by a tiny bit in order to capture multivalued jumps 
        #x1 = x0 + (x1 - x0)*(1. - EPS)
        #y1 = y0 + (y1 - y0)*(1. - EPS)
        #z1 = z0 + (z1 - z0)*(1. - EPS)

        lam0, the0 = getLambdaTheta(x0, y0, z0)
        lam1, the1 = getLambdaTheta(x1, y1, z1)

        divVal += getCosThetaDLambda(lam0, the0, lam1, the1)
        divVal -= 0.5 * alpha * getSinTwoThetaDLambda(lam0, the0, lam1, the1)


    divData[cellId] = divVal

# attach cell centred values to the grid
dataArray = vtk.vtkDoubleArray()
dataArray.SetNumberOfComponents(1)
dataArray.SetNumberOfTuples(numCells)
save = 1
dataArray.SetVoidArray(divData, numCells, save)

grid.GetCellData().SetScalars(dataArray)

# save/show
cs.save('divLatLon1.vtk')
cs.show()
Ejemplo n.º 52
0
    def initMultiVolumes(self, files, prescribedTags=None):
        tag2ValueFileList = {}
        multivolumes = []

        if prescribedTags == None:
            consideredTags = self.multiVolumeTags.keys()
        else:
            consideredTags = prescribedTags

        # iterate over all files
        for file in files:

            # iterate over the tags that can be used to separate individual frames
            for frameTag in consideredTags:
                try:
                    tagValue2FileList = tag2ValueFileList[frameTag]
                except:
                    tagValue2FileList = {}
                    tag2ValueFileList[frameTag] = tagValue2FileList

                tagValueStr = slicer.dicomDatabase.fileValue(
                    file, self.tags[frameTag])
                if tagValueStr == '':
                    # not found?
                    continue

                if frameTag == 'AcquisitionTime' or frameTag == 'SeriesTime' or frameTag == 'ContentTime':
                    # extra parsing is needed to convert from DICOM TM VR into ms
                    tagValue = self.tm2ms(tagValueStr)  # convert to ms
                elif frameTag == "GE.B-value":
                    try:
                        # Parse this:
                        # (0043,1039) IS [1000001250\8\0\0] #  16, 4 Unknown Tag & Data
                        # GE Discovery w750
                        tagValue = float(
                            int(tagValueStr.split('\\')[0]) % 100000)
                    except:
                        continue
                elif frameTag == "CardiacCycle":
                    try:
                        # Parse this:
                        #  TP0PC0965, PULSTART_P0020PC, PULSEND_P0080PC...
                        #  TP10PC0965, PULSTART_P0020PC, PULSEND_P0080PC...
                        #  TP30PC0965, PULSTART_P0020PC, PULSEND_P0080PC...
                        cardiacPhaseInfo = tagValueStr.split('\\')[
                            0]  # TP0PC0965
                        matched = re.search("TP(\d+)PC(\d+)", cardiacPhaseInfo)
                        tagValue = float(matched.groups()[0])
                    except:
                        continue
                else:
                    try:
                        tagValue = float(tagValueStr)
                    except:
                        continue

                try:
                    tagValue2FileList[tagValue].append(file)
                except:
                    tagValue2FileList[tagValue] = [file]

        # iterate over the parsed items and decide which ones can qualify as mv
        for frameTag in self.multiVolumeTags.keys():

            try:
                tagValue2FileList = tag2ValueFileList[frameTag]
            except:
                # didn't find the tag
                continue

            if len(tagValue2FileList) < 2:
                # not enough frames for this tag to be a multivolume
                continue

            tagValues = tagValue2FileList.keys()
            # sort the frames
            tagValues.sort()
            firstFrameSize = len(tagValue2FileList[tagValues[0]])
            frameInvalid = False
            for tagValue in tagValues:
                if len(tagValue2FileList[tagValue]) != firstFrameSize:
                    # number of frames does not match

                    frameInvalid = True
            if frameInvalid == True:
                continue

            # TODO: add a check to confirm individual frames have the same geometry
            # (check pixel dimensions, orientation, position)

            # now this looks like a serious mv!

            # initialize the needed attributes for a new mvNode
            frameFileListStr = ""
            frameLabelsStr = ""
            frameLabelsArray = vtk.vtkDoubleArray()
            tagValue0 = tagValues[0]
            for tagValue in tagValues:
                frameFileList = tagValue2FileList[tagValue]
                for file in frameFileList:
                    frameFileListStr = frameFileListStr + file + ','

                # if mv was parsed by series time, probably makes sense to start from 0
                if frameTag == 'SeriesTime' or frameTag == 'AcquisitionTime' or frameTag == 'ContentTime':
                    frameLabelsArray.InsertNextValue(tagValue - tagValue0)
                    frameLabelsStr = frameLabelsStr + str(tagValue -
                                                          tagValue0) + ','
                else:
                    frameLabelsArray.InsertNextValue(tagValue)
                    frameLabelsStr = frameLabelsStr + str(tagValue) + ','

            frameFileListStr = frameFileListStr[:-1]
            frameLabelsStr = frameLabelsStr[:-1]

            mvNode = slicer.mrmlScene.CreateNodeByClass(
                'vtkMRMLMultiVolumeNode')
            mvNode.UnRegister(None)
            mvNode.SetAttribute("MultiVolume.FrameLabels", frameLabelsStr)
            mvNode.SetAttribute("MultiVolume.FrameIdentifyingDICOMTagName",
                                frameTag)
            mvNode.SetAttribute('MultiVolume.NumberOfFrames',
                                str(len(tagValue2FileList)))
            mvNode.SetAttribute('MultiVolume.FrameIdentifyingDICOMTagUnits',
                                self.multiVolumeTagsUnits[frameTag])
            # keep the files in the order by the detected tag
            # files are not ordered within the individual frames -- this will be
            # done by ScalarVolumePlugin later
            mvNode.SetAttribute('MultiVolume.FrameFileList', frameFileListStr)

            mvNode.SetNumberOfFrames(len(tagValue2FileList))
            mvNode.SetLabelName(self.multiVolumeTagsUnits[frameTag])
            mvNode.SetLabelArray(frameLabelsArray)

            self.addAcquisitionAttributes(mvNode, frameFileList)

            # add the node
            multivolumes.append(mvNode)

        return multivolumes
Ejemplo n.º 53
0
if len(z) == 0:
    z = [0]
if len(t) == 0:
    t = [0]

# need to check for repeated values as i haven't
# considered them below
if len(x) != len(set(x)) or len(y) != len(set(y)) or len(z) != len(set(z)):
    sys.stderr.write(
        "griddeddata_to_vtk cannot handle repeated X, Y or Z values\n")
    sys.exit(4)

if opts.verbose:
    sys.stdout.write("Creating the VTR base grid\n")
# create the vtr grid
xArray = vtk.vtkDoubleArray()
for val in sorted(x):
    xArray.InsertNextValue(val)

yArray = vtk.vtkDoubleArray()
for val in sorted(y):
    yArray.InsertNextValue(val)

zArray = vtk.vtkDoubleArray()
for val in sorted(z):
    zArray.InsertNextValue(val)

# create the vtkRectilinearGrid
grid = vtk.vtkRectilinearGrid()
grid.SetDimensions(xArray.GetNumberOfTuples(), yArray.GetNumberOfTuples(),
                   zArray.GetNumberOfTuples())
Ejemplo n.º 54
0
                lateralunit = pieces[3]
            if pieces[1] == 'Height:':
                height = float(pieces[2])
                lateralunit = pieces[3]
            if pieces[1] == 'Value' and pieces[2] == 'units:':
                elevationunit = pieces[3]

        if options.scaling == 0.0:
            options.scaling = scalingFactor[lateralunit][elevationunit]

        elevation = np.loadtxt(file) * options.scaling

        grid = vtk.vtkRectilinearGrid()
        grid.SetDimensions(elevation.shape[1], elevation.shape[0], 1)

        xCoords = vtk.vtkDoubleArray()
        for x in np.arange(0.0, width, width / elevation.shape[1], 'd'):
            xCoords.InsertNextValue(x)
        yCoords = vtk.vtkDoubleArray()
        for y in np.arange(0.0, height, height / elevation.shape[0], 'd'):
            yCoords.InsertNextValue(y)
        zCoords = vtk.vtkDoubleArray()
        zCoords.InsertNextValue(0.0)

        grid.SetXCoordinates(xCoords)
        grid.SetYCoordinates(yCoords)
        grid.SetZCoordinates(zCoords)

        vector = vtk.vtkFloatArray()
        vector.SetName("elevation")
        vector.SetNumberOfComponents(3)
Ejemplo n.º 55
0
def GenerateParticles():
    (mesh, minPoint, maxPoint) = STLMESH("particles.stl")
    mntable = MNTable3D(minPoint, maxPoint, 2.0 * RMAX, 1)
    taskai = []

    for x in range(len(taskai)):
        S = Sphere(
            Vector3(float(taskai[x][0]), float(taskai[x][1]),
                    float(taskai[x][2])), float(taskai[x][3]))
        mntable.insert(S, 0)
        yra = 1

    packer = InsertGenerator3D(R, R, 100, 1000, 1.0e-9, True)

    packer.generatePacking(mesh, mntable, 0, 1)
    mntable.write("tempas.vtu", 2)
    reader = vtk.vtkXMLUnstructuredGridReader()
    reader.SetFileName("tempas.vtu")
    reader.Update()
    poly = vtk.vtkPolyData()
    poly.SetPoints(reader.GetOutput().GetPoints())
    KIEKIS = poly.GetNumberOfPoints()
    rad_seg = vtk.vtkDoubleArray()
    rad_seg.SetName("UNIQUE_RADIUS")
    rad_seg.SetNumberOfComponents(1)
    rad_seg.SetNumberOfTuples(2)
    rad_seg.SetTuple1(0, R)
    rad_seg.SetTuple1(1, R_KLIUTIS)

    rad = vtk.vtkDoubleArray()
    rad.SetName("RADIUS")
    rad.SetNumberOfComponents(1)
    rad.SetNumberOfTuples(KIEKIS)
    vel = vtk.vtkDoubleArray()
    vel.SetName("VELOCITY")
    vel.SetNumberOfComponents(3)
    vel.SetNumberOfTuples(KIEKIS)

    part_type = vtk.vtkIntArray()
    part_type.SetName("PARTICLE_TYPE")
    part_type.SetNumberOfComponents(1)
    part_type.SetNumberOfTuples(KIEKIS)

    part_material = vtk.vtkIntArray()
    part_material.SetName("PARTICLE_MATERIAL")
    part_material.SetNumberOfComponents(1)
    part_material.SetNumberOfTuples(KIEKIS)

    part_fix = vtk.vtkIntArray()
    part_fix.SetName("PARTICLE_FIX")
    part_fix.SetNumberOfComponents(1)
    part_fix.SetNumberOfTuples(KIEKIS)

    reader.GetOutput().GetPointData().GetArray("radius").SetName("RADIUS")
    poly.GetPointData().SetScalars(
        reader.GetOutput().GetPointData().GetArray("RADIUS"))
    verts = vtk.vtkCellArray()
    for x in range(poly.GetNumberOfPoints()):
        vel.SetTuple3(x, 0, 0, 0)

        part_material.SetTuple1(x, 0)
        tag = reader.GetOutput().GetPointData().GetArray(
            "particleTag").GetTuple1(x)

        if (tag == 0):
            part_type.SetTuple1(x, 1)
            part_fix.SetTuple1(x, 1)
            print(tag)
        else:
            part_type.SetTuple1(x, 0)
            part_fix.SetTuple1(x, 0)
        verts.InsertNextCell(1)
        verts.InsertCellPoint(x)
    poly.SetVerts(verts)
    poly.GetPointData().AddArray(part_fix)
    poly.GetPointData().AddArray(part_material)
    poly.GetPointData().AddArray(vel)
    poly.GetPointData().AddArray(part_type)
    poly.GetFieldData().AddArray(rad_seg)
    www = vtk.vtkXMLPolyDataWriter()
    www.SetInputData(poly)
    www.SetFileName("input.vtp")
    www.Write()
#!/usr/bin/env python
import vtk

htg = vtk.vtkUniformHyperTreeGrid()
htg.Initialize()

scalarArray = vtk.vtkDoubleArray()
scalarArray.SetName('scalar')
scalarArray.SetNumberOfValues(0)
htg.GetPointData().AddArray(scalarArray)
htg.GetPointData().SetActiveScalars('scalar')

htg.SetDimensions([4, 3, 1])
htg.SetBranchFactor(2)
htg.SetOrigin([-1, -1, 0])
htg.SetGridScale([1, 1, 1])

# Let's split the various trees
cursor = vtk.vtkHyperTreeGridNonOrientedCursor()
offsetIndex = 0

# ROOT CELL 0
htg.InitializeNonOrientedCursor(cursor, 0, True)
cursor.SetGlobalIndexStart(offsetIndex)

idx = cursor.GetGlobalNodeIndex()
scalarArray.InsertTuple1(idx, 10)

cursor.SubdivideLeaf()

# ROOT CELL 0/[0-3]
Ejemplo n.º 57
0
import sys
import vtk
import math

# Default branch angle if the angle per branch is not specified.
branchAngle = math.pi / 4.0
scaling = 1.0
step = 0.1
radiusBase = 1.0
# If sphereRadius is set to None, the centreline is generated in the XY plane.
# Otherwise the centreline is wrapped on a sphere of the specified radius.
sphereRadius = None

points = vtk.vtkPoints()
lines = vtk.vtkCellArray()
radii = vtk.vtkDoubleArray()
radii.SetName("radiiScalars")
centreline = vtk.vtkPolyData()


def BuildCentreline(segmentList,
                    firstId=0,
                    firstPt=(0.0, 0.0, 0.0),
                    direction=0.0):
    print("Processing centreline:", segmentList)

    domain = None

    try:
        domain = segmentList[0]
    except IndexError:
Ejemplo n.º 58
0
 def display_Xn(self, gfx):
     if gfx.ps != None:
         gfx.renderer.RemoveActor(gfx.ps.acteur)
     try:
         zmax = gfx.map[0].box.GetBounds()[5]
         zmin = gfx.map[0].box.GetBounds()[4]
         ymax = gfx.map[0].box.GetBounds()[3]
         ymin = gfx.map[0].box.GetBounds()[2]
         c = (zmax - zmin) / 2.
         b = (ymax - ymin) / 2.
     except:
         b = c = self.radius
     dist = self.radius
     phizero = radians(self.phizero)
     if self.solidtype == 'Cn':
         numPts = self.cnn
         shifta = radians(360. / numPts)
         pdo = vtk.vtkPolyData()
         cirpdo = vtk.vtkPolyData()
         newPts = vtk.vtkPoints()
         vals = vtk.vtkDoubleArray()
         for i in range(0, numPts):
             try:
                 if self.axe == 'Z':
                     x = dist * gfx.map[0].scale * cos(i * shifta + phizero)
                     y = dist * gfx.map[0].scale * sin(i * shifta + phizero)
                     z = 0
                 elif self.axe == 'Y':
                     x = dist * gfx.map[0].scale * cos(i * shifta + phizero)
                     y = 0
                     z = dist * gfx.map[0].scale * sin(i * shifta + phizero)
                 elif self.axe == 'X':
                     x = 0
                     y = dist * gfx.map[0].scale * cos(i * shifta + phizero)
                     z = dist * gfx.map[0].scale * sin(i * shifta + phizero)
             except:
                 if self.axe == 'Z':
                     x = dist * cos(i * shifta + phizero)
                     y = dist * sin(i * shifta + phizero)
                     z = 0
                 elif self.axe == 'Y':
                     x = dist * cos(i * shifta + phizero)
                     y = 0
                     z = dist * sin(i * shifta + phizero)
                 elif self.axe == 'X':
                     x = 0
                     y = dist * cos(i * shifta + phizero)
                     z = dist * sin(i * shifta + phizero)
             newPts.InsertPoint(i, x, y, z)
             vals.InsertNextValue(i)
         pdo.SetPoints(newPts)
         pdo.GetPointData().SetScalars(vals)
         cirpdo.SetPoints(newPts)
         cirpdo.GetPointData().SetScalars(vals)
         aPolyLine = vtk.vtkPolyLine()
         aPolyLine.GetPointIds().SetNumberOfIds(numPts + 1)
         for i in range(0, numPts):
             aPolyLine.GetPointIds().SetId(i, i)
         aPolyLine.GetPointIds().SetId(numPts, 0)
         cirpdo.Allocate(1, 1)
         cirpdo.InsertNextCell(aPolyLine.GetCellType(),
                               aPolyLine.GetPointIds())
         sphere = vtk.vtkSphereSource()
         sphere.SetCenter(0, 0, 0)
         try:
             sphere.SetRadius(self.radius * gfx.map[0].scale / 5.0)
         except:
             sphere.SetRadius(self.radius / 5.0)
         sphere.SetThetaResolution(8)
         sphere.SetStartTheta(0)
         sphere.SetEndTheta(360)
         sphere.SetPhiResolution(8)
         sphere.SetStartPhi(0)
         sphere.SetEndPhi(180)
         glyph = vtk.vtkGlyph3D()
         glyph.SetInput(pdo)
         glyph.SetColorMode(1)
         glyph.ScalingOn()
         glyph.SetScaleMode(2)
         glyph.SetScaleFactor(0.25)
         glyph.SetSource(sphere.GetOutput())
         self.spheremapper = vtk.vtkPolyDataMapper()
         self.spheremapper.SetInputConnection(glyph.GetOutputPort())
         self.spheremapper.UseLookupTableScalarRangeOff()
         self.spheremapper.SetScalarVisibility(0)
         self.sphact = vtk.vtkActor()
         self.sphact.PickableOff()
         self.sphact.DragableOff()
         self.sphact.SetMapper(self.spheremapper)
         self.sphact.GetProperty().SetRepresentationToSurface()
         self.sphact.GetProperty().SetInterpolationToGouraud()
         self.sphact.GetProperty().SetAmbient(0.15)
         self.sphact.GetProperty().SetDiffuse(0.85)
         self.sphact.GetProperty().SetSpecular(0.1)
         self.sphact.GetProperty().SetSpecularPower(100)
         self.sphact.GetProperty().SetSpecularColor(1, 1, 1)
         self.sphact.GetProperty().SetColor(1, 1, 1)
         self.mapper = vtk.vtkPolyDataMapper()
         self.mapper.SetScalarVisibility(0)
         self.mapper.SetInput(cirpdo)
         self.helact = vtk.vtkActor()
         self.helact.PickableOff()
         self.helact.DragableOff()
         self.helact.GetProperty().SetColor(1, 1, 1)
         self.helact.GetProperty().SetRepresentationToWireframe()
         self.helact.GetProperty().SetLineWidth(5)
         self.helact.GetProperty().SetLineWidth(1)
         self.helact.GetProperty().SetSpecular(.4)
         self.helact.GetProperty().SetSpecularPower(10)
         self.helact.SetMapper(self.mapper)
         assembly = vtk.vtkAssembly()
         assembly.AddPart(self.sphact)
         assembly.AddPart(self.helact)
         self.acteur = assembly
         gfx.renderer.AddActor(self.acteur)
         gfx.renwin.Render()
         gfx.ps = self
     elif self.solidtype == 'Dn':
         numPts = self.dnn
         shifta = radians(360. / numPts)
         cirpdo = vtk.vtkPolyData()
         pdo = vtk.vtkPolyData()
         newPts = vtk.vtkPoints()
         vals = vtk.vtkDoubleArray()
         for i in range(0, numPts):
             try:
                 x = dist * gfx.map[0].scale * cos(i * shifta)
                 y = dist * gfx.map[0].scale * sin(i * shifta)
                 z = 0
             except:
                 x = dist * cos(i * shifta)
                 y = dist * sin(i * shifta)
                 z = 0
             newPts.InsertPoint(i, x, y, z)
             vals.InsertNextValue(i)
         pdo.SetPoints(newPts)
         pdo.GetPointData().SetScalars(vals)
         cirpdo.SetPoints(newPts)
         cirpdo.GetPointData().SetScalars(vals)
         aPolyLine = vtk.vtkPolyLine()
         aPolyLine.GetPointIds().SetNumberOfIds(numPts + 1)
         for i in range(0, numPts):
             aPolyLine.GetPointIds().SetId(i, i)
         aPolyLine.GetPointIds().SetId(numPts, 0)
         cirpdo.Allocate(1, 1)
         cirpdo.InsertNextCell(aPolyLine.GetCellType(),
                               aPolyLine.GetPointIds())
         sphere = vtk.vtkSphereSource()
         sphere.SetCenter(0, 0, 0)
         try:
             sphere.SetRadius(self.radius * gfx.map[0].scale / 5.0)
         except:
             sphere.SetRadius(self.radius / 5.0)
         sphere.SetThetaResolution(8)
         sphere.SetStartTheta(0)
         sphere.SetEndTheta(360)
         sphere.SetPhiResolution(8)
         sphere.SetStartPhi(0)
         sphere.SetEndPhi(180)
         glyph = vtk.vtkGlyph3D()
         glyph.SetInput(pdo)
         glyph.SetColorMode(1)
         glyph.ScalingOn()
         glyph.SetScaleMode(2)
         glyph.SetScaleFactor(0.25)
         glyph.SetSource(sphere.GetOutput())
         self.spheremapper = vtk.vtkPolyDataMapper()
         self.spheremapper.SetInputConnection(glyph.GetOutputPort())
         self.spheremapper.UseLookupTableScalarRangeOff()
         self.spheremapper.SetScalarVisibility(0)
         self.sphact = vtk.vtkActor()
         self.sphact.PickableOff()
         self.sphact.DragableOff()
         self.sphact.SetMapper(self.spheremapper)
         self.sphact.GetProperty().SetRepresentationToSurface()
         self.sphact.GetProperty().SetInterpolationToGouraud()
         self.sphact.GetProperty().SetAmbient(0.15)
         self.sphact.GetProperty().SetDiffuse(0.85)
         self.sphact.GetProperty().SetSpecular(0.1)
         self.sphact.GetProperty().SetSpecularPower(100)
         self.sphact.GetProperty().SetSpecularColor(1, 1, 1)
         self.sphact.GetProperty().SetColor(1, 1, 1)
         self.mapper = vtk.vtkPolyDataMapper()
         self.mapper.SetScalarVisibility(0)
         self.mapper.SetInput(cirpdo)
         self.helact = vtk.vtkActor()
         self.helact.PickableOff()
         self.helact.DragableOff()
         self.helact.GetProperty().SetColor(1, 1, 1)
         self.helact.GetProperty().SetRepresentationToWireframe()
         self.helact.GetProperty().SetLineWidth(5)
         self.helact.GetProperty().SetLineWidth(1)
         self.helact.GetProperty().SetSpecular(.4)
         self.helact.GetProperty().SetSpecularPower(10)
         self.helact.SetMapper(self.mapper)
         sphact2 = vtk.vtkActor()
         helact2 = vtk.vtkActor()
         sphact2.ShallowCopy(self.sphact)
         helact2.ShallowCopy(self.helact)
         self.sphact.AddPosition(0, 0, dist * c / b)
         self.helact.AddPosition(0, 0, dist * c / b)
         sphact2.AddPosition(0, 0, -dist * c / b)
         helact2.AddPosition(0, 0, -dist * c / b)
         assembly = vtk.vtkAssembly()
         assembly.AddPart(self.sphact)
         assembly.AddPart(self.helact)
         assembly.AddPart(sphact2)
         assembly.AddPart(helact2)
         self.acteur = assembly
         gfx.renderer.AddActor(self.acteur)
         gfx.renwin.Render()
         gfx.ps = self
def main():

    angle_num = 1

    for angle in range(60, 120, 10):

        print 'Processing angle', angle, '...'
        # Read the EC mesh.
        ecFileName = os.path.join(str(angle), 'quadMeshFullECc4080.vtp')
        ecMeshReader = vtk.vtkXMLPolyDataReader()
        ecMeshReader.SetFileName(ecFileName)
        ecMeshReader.Update()

        # Remember the EC mesh.
        ecMesh = ecMeshReader.GetOutput()

        # Get EC centres.
        cellCentresFilter = vtk.vtkCellCenters()
        cellCentresFilter.VertexCellsOn()
        cellCentresFilter.SetInput(ecMesh)
        cellCentresFilter.Update()

        ecMeshCentres = cellCentresFilter.GetOutput()
        pointsPerBranch = ecMeshCentres.GetNumberOfPoints() / 3

        # Find three saddle points.
        # The first point is 3/4th of the EC row away from the end of the parent branch.
        # The second point is 1/4th of the EC row away from the end of the parent branch.
        # The third point is 3/4th of the way from the start of the first sibling branch.
        saddle_ids = [
            pointsPerBranch - (numQuadsPerRing / 4) * (numECsAx * numECsCirc),
            pointsPerBranch - ((numQuadsPerRing / 4) * 3) *
            (numECsAx * numECsCirc), pointsPerBranch +
            ((numQuadsPerRing / 4) * 3) * (numECsAx * numECsCirc)
        ]

        saddle_points = [ecMeshCentres.GetPoint(sId) for sId in saddle_ids]

        atpArray = vtk.vtkDoubleArray()
        atpArray.SetName("initialATP")

        # Loop through each centre point.
        for cId in range(pointsPerBranch * 3):
            # If it falls within one of the three spheres, map it to ATP.
            point = ecMeshCentres.GetPoints().GetPoint(cId)

            # Find closest saddle point to work with.
            # List of distances to all three saddle points.
            dist2_list = [
                vtk.vtkMath.Distance2BetweenPoints(point, saddle_point)
                for saddle_point in saddle_points
            ]

            # Position of the closest saddle point.
            saddle_id = dist2_list.index(min(dist2_list))

            sphere_rad = sphere_rads[saddle_id]
            max_atp = atp_max[saddle_id]

            # Decrement radius if on the first one; this is the changing angle for bifurcation outer curve.
            if saddle_id == 0:
                sphere_rad -= (angle_num * rad_dec) * sphere_rad

            # Increment radius if on the third one; this is the neck of the bifurcation.
            if saddle_id == 2:
                sphere_rad += (angle_num * rad_inc) * sphere_rad

            # Increase intensity if on the third one.
            if saddle_id == 2:
                max_atp += ((angle_num - 1) * atp_inc)

            # Does dist2 fall into sphere_rad2?
            if dist2_list[saddle_id] <= sphere_rad**2:

                # Map to parametric distance in the range [0, 1].
                par_dist = math.sqrt(dist2_list[saddle_id]) / sphere_rad

                # Map to ATP range, depending on the saddle id.
                if par_dist <= inner_rad:
                    # The centre is atp_max.
                    atp_val = max_atp
                else:
                    # Discard the inner radius from our parametric distance.
                    x0 = par_dist - inner_rad

                    # Map distance to sigmoind domain min to max range.
                    x1 = x0 * scaling_to_sigmoid_domain
                    x2 = x1 + sigmoind_domain_min

                    # Calculate sigmoid value and subtract the min sigmoid value for this domain.
                    s = sigmoid(x2)
                    s1 = s

                    # Scale to atp range.
                    atp_range = max_atp - atp_base
                    atp_val = atp_base + s1 * atp_range

            # Outside the sphere_rad2.
            else:
                atp_val = atp_base

            # Remember the ATP value.
            atpArray.InsertNextValue(atp_val)

        ecMeshCentres.GetCellData().SetScalars(atpArray)
        angle_num += 1

        ecMesh.GetCellData().SetScalars(atpArray)

        atpFileName = os.path.join(str(angle), 'quadMeshFullATPc4080.vtp')
        # atpFileName = 'quadMeshFullATPc4080_' + str(angle) + '.vtp'
        print 'Writing', atpFileName, '...'

        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetFileName(atpFileName)
        writer.SetInput(ecMeshCentres)
        # writer.SetInput(ecMesh)
        writer.Update()
Ejemplo n.º 60
0
def write_vtp(vtp_filename,
              points,
              fieldData_list,
              flagVerboseLevel=0,
              flagFieldDataMode=None):
    ambient_num_dim = 3
    # assumed data is embedded in R^3

    if flagFieldDataMode == None:
        if isinstance(fieldData_list, list) == True:
            flagFieldDataMode = 'list'
        elif isinstance(fieldData_list, dict) == True:
            flagFieldDataMode = 'dict'

    # Check parameter types are correct given the flags
    flagFieldTypeErr = False
    if (flagFieldDataMode == 'list') and (isinstance(fieldData_list, list)
                                          == False):
        flagFieldTypeErr = True
        type_str = str(list)
    elif (flagFieldDataMode == 'dict') and (isinstance(fieldData_list, dict)
                                            == False):
        flagFieldTypeErr = True
        type_str = str(dict)

    if flagFieldTypeErr == True:
        err_s = ""
        err_s += "Expected that the fieldData_list is of type '%s'. \n" % type_str
        err_s += "May need to adjust and set the flagFieldDataMode. \n"
        err_s += "flagFieldDataMode = %s\n" % str(flagFieldDataMode)
        err_s += "type(fieldData_list) = %s\n" % str(type(fieldData_list))
        raise Exception(err_s)

    # Output a VTP file with the fields
    #
    # record the data for output
    #N_list = np.shape(ptsX)[0];
    vtpData = vtk.vtkPolyData()

    # check format of the points array
    #n1 = np.size(points_data,0);
    #if (n1 == 0): # we assume array already flat
    #  # nothing to do
    #else:
    #  points = points_data.T.flatten();

    # setup the points data
    Points = vtk.vtkPoints()
    #numPoints = int(len(points)/ambient_num_dim);
    numPoints = np.size(points, 1)
    for I in range(numPoints):
        Points.InsertNextPoint(points[0, I], points[1, I], points[2, I])
    vtpData.SetPoints(Points)

    # Get data from the vtu object
    #print("Getting data from the vtu object.");
    #nodes_vtk_array = vtuData.GetPoints().GetData();
    #ptsX            = vtk_to_numpy(nodes_vtk_array);

    # -- setup data arrays
    if fieldData_list != None:  # if we have field data

        numFields = len(fieldData_list)
        if flagVerboseLevel == 1:
            print("numFields = " + str(numFields))

        if flagFieldDataMode == 'list':
            f_list = fieldData_list
        elif flagFieldDataMode == 'dict':
            # convert dictionary to a list
            f_list = []
            for k, v in fieldData_list.items():
                f_list.append(v)

        for fieldData in f_list:
            #print("fieldData = " + str(fieldData));
            fieldName = fieldData['fieldName']
            if flagVerboseLevel == 1:
                print("fieldName = " + str(fieldName))
            fieldValues = fieldData['fieldValues']
            NumberOfComponents = fieldData['NumberOfComponents']

            if (NumberOfComponents == 1):
                N_list = len(fieldValues)
                if flagVerboseLevel == 1:
                    print("N_list = " + str(N_list))
                atzDataPhi = vtk.vtkDoubleArray()
                atzDataPhi.SetNumberOfComponents(1)
                atzDataPhi.SetName(fieldName)
                #print("fieldName = "+str(fieldName))
                atzDataPhi.SetNumberOfTuples(N_list)
                for I in np.arange(0, N_list):
                    #print("I = "+str(I)+", fieldValues[I] = "+str(fieldValues[I]))
                    atzDataPhi.SetValue(I, fieldValues[I])
                #vtpData.GetPointData().SetScalars(atzDataPhi);
                vtpData.GetPointData().AddArray(atzDataPhi)
            elif (NumberOfComponents == 3):
                #print(fieldValues);
                #print(fieldValues.shape);
                N_list = fieldValues.shape[1]
                if flagVerboseLevel == 1:
                    print("N_list = " + str(N_list))
                atzDataV = vtk.vtkDoubleArray()
                atzDataV.SetNumberOfComponents(3)
                atzDataV.SetName(fieldName)
                atzDataV.SetNumberOfTuples(N_list)
                for I in np.arange(0, N_list):
                    atzDataV.SetValue(I * ambient_num_dim + 0, fieldValues[0,
                                                                           I])
                    atzDataV.SetValue(I * ambient_num_dim + 1, fieldValues[1,
                                                                           I])
                    atzDataV.SetValue(I * ambient_num_dim + 2, fieldValues[2,
                                                                           I])
                #vtpData.GetPointData().SetVectors(atzDataV);
                vtpData.GetPointData().AddArray(atzDataV)

            else:
                #print("ERROR: " + error_code_file + ":" + error_func);
                s = ""
                s += "NumberOfComponents invalid. \n"
                s += "NumberOfComponents = " + str(NumberOfComponents)
                raise Exception(s)

                #exit(1);

    #vtuData.GetPointData().SetVectors(atzDataVec);
    #vtuData.GetPointData().AddArray(atzDataScalar1);
    #vtuData.GetPointData().AddArray(atzDataScalar2);
    #vtuData.GetPointData().AddArray(atzDataVec1);
    #vtuData.GetPointData().AddArray(atzDataVec2);

    # write the XML file
    writerVTP = vtk.vtkXMLPolyDataWriter()
    writerVTP.SetFileName(vtp_filename)
    writerVTP.SetInputData(vtpData)
    writerVTP.SetCompressorTypeToNone()
    # help ensure ascii output (as opposed to binary)
    writerVTP.SetDataModeToAscii()
    # help ensure ascii output (as opposed to binary)
    writerVTP.Write()