Ejemplo n.º 1
0
 def __init__(self, pos, radius, rgb=[0.62, 0, 0.77]):
     self.source = vtk.vtkCubeSource()
     self.mapper = vtk.vtkPolyDataMapper()
     
     # length of sides
     self.source.SetXLength(radius)
     self.source.SetYLength(radius)
     self.source.SetZLength(radius)
     
     # centre
     self.source.SetCenter(pos)
     
     # edges filter
     edges = vtk.vtkExtractEdges()
     edges.SetInputConnection(self.source.GetOutputPort())
     
     # tube filter
     tubes = vtk.vtkTubeFilter()
     tubes.SetInputConnection(edges.GetOutputPort())
     tubes.SetRadius(0.15)
     tubes.SetNumberOfSides(5)
     tubes.UseDefaultNormalOn()
     tubes.SetDefaultNormal(.577, .577, .577)
     
     # mapper
     self.mapper.SetInputConnection(tubes.GetOutputPort())
     
     # actor
     self.SetMapper(self.mapper)
     self.GetProperty().SetColor(rgb)
def make_sphere():
    global renderer
    # ---------------------------------------------------------------
    # The following code is identical to render_demo.py...
    # ---------------------------------------------------------------
    # create a sphere
    sphere_src = vtk.vtkSphereSource()
    sphere_src.SetRadius(1.0)
    sphere_src.SetCenter(0.0, 0.0, 0.0)
    sphere_src.SetThetaResolution(20)
    sphere_src.SetPhiResolution(20)
    # extract the edges
    edge_extractor = vtk.vtkExtractEdges()
    edge_extractor.SetInputConnection(sphere_src.GetOutputPort())
    # map sphere and edges separately
    sphere_mapper = vtk.vtkPolyDataMapper()
    sphere_mapper.SetInputConnection(sphere_src.GetOutputPort())
    edge_mapper = vtk.vtkPolyDataMapper()
    edge_mapper.SetInputConnection(edge_extractor.GetOutputPort())
    # define different rendering styles for sphere and edges
    sphere_actor = vtk.vtkActor()
    sphere_actor.SetMapper(sphere_mapper)
    sphere_actor.GetProperty().SetColor(1, 0.5, 0)
    edge_actor = vtk.vtkActor()
    edge_actor.SetMapper(edge_mapper)
    edge_actor.GetProperty().SetColor(0, 0.5, 0)
    edge_actor.GetProperty().SetLineWidth(3)
    # add resulting primitives to renderer
    renderer.AddActor(sphere_actor)
    renderer.AddActor(edge_actor)
Ejemplo n.º 3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkExtractEdges(), 'Processing.',
         ('vtkDataSet',), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Ejemplo n.º 4
0
    def render(self, pointsData, scalarsArray, radiusArray, nspecies, colouringOptions, atomScaleFactor, lut):
        """
        Render the given antisites (wire frame).
        
        """
        self._logger.debug("Rendering antisites: colour by '%s'", colouringOptions.colourBy)

        # points
        points = vtk.vtkPoints()
        points.SetData(pointsData.getVTK())

        # poly data
        polydata = vtk.vtkPolyData()
        polydata.SetPoints(points)
        polydata.GetPointData().AddArray(scalarsArray.getVTK())
        polydata.GetPointData().SetScalars(radiusArray.getVTK())

        # source
        cubeSource = vtk.vtkCubeSource()
        edges = vtk.vtkExtractEdges()
        edges.SetInputConnection(cubeSource.GetOutputPort())
        glyphSource = vtk.vtkTubeFilter()
        glyphSource.SetInputConnection(edges.GetOutputPort())
        glyphSource.SetRadius(0.05)
        glyphSource.SetVaryRadius(0)
        glyphSource.SetNumberOfSides(5)
        glyphSource.UseDefaultNormalOn()
        glyphSource.SetDefaultNormal(0.577, 0.577, 0.577)

        # glyph
        glyph = vtk.vtkGlyph3D()
        if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
            glyph.SetSource(glyphSource.GetOutput())
            glyph.SetInput(polydata)
        else:
            glyph.SetSourceConnection(glyphSource.GetOutputPort())
            glyph.SetInputData(polydata)
        glyph.SetScaleFactor(atomScaleFactor * 2.0)
        glyph.SetScaleModeToScaleByScalar()
        glyph.ClampingOff()

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(glyph.GetOutputPort())
        mapper.SetLookupTable(lut)
        mapper.SetScalarModeToUsePointFieldData()
        mapper.SelectColorArray("colours")
        utils.setMapperScalarRange(mapper, colouringOptions, nspecies)

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

        # store attributes
        self._actor = utils.ActorObject(actor)
        self._data["Points"] = pointsData
        self._data["Scalars"] = scalarsArray
        self._data["Radius"] = radiusArray
        self._data["LUT"] = lut
        self._data["Scale factor"] = atomScaleFactor
Ejemplo n.º 5
0
 def __init__(self, **kwargs):
     self.hull = vtk.vtkHull()
     self.poly_data = vtk.vtkPolyData()
     self.extractor = vtk.vtkExtractEdges()
     self.extractor.SetInput(self.poly_data)
     self.mapper = vtk.vtkPolyDataMapper()
     self.mapper.SetInputConnection(self.extractor.GetOutputPort())
     self.actor = vtk.vtkActor()
     self.actor.SetMapper(self.mapper)
     self._process_kwargs(**kwargs)
Ejemplo n.º 6
0
    def get_edges(self):
        edges = vtk.vtkExtractEdges()
        edges.SetInput(self.grid)
        self.edgeMapper.SetInput(edges.GetOutput())

        self.edgeActor.SetMapper(self.edgeMapper)
        self.edgeActor.GetProperty().SetColor(0, 0, 0)

        prop = self.edgeActor.GetProperty()
        self.edgeActor.SetVisibility(self.is_edges)
        self.rend.AddActor(self.edgeActor)
def compute_info_mesh(mesh):
    vertices= mesh.GetNumberOfPoints()
    triangles= mesh.GetNumberOfCells()
    extractEdges = vtk.vtkExtractEdges()
    extractEdges.SetInputData(mesh)
    extractEdges.Update()
    lines=extractEdges.GetOutput()
    edges=lines.GetNumberOfCells()
    print "triangles: ",triangles
    print "vertices: ",vertices
    print "edges: ",edges

    return vertices,triangles
Ejemplo n.º 8
0
def vtkpoints(points, color=None, radius=None):
    # Create a polydata with the points we just created.
    profile = vtk.vtkPolyData()
    profile.SetPoints(points)

    # Perform a 2D Delaunay triangulation on them.
    delny = vtk.vtkDelaunay2D()
    delny.SetInput(profile)
    delny.SetTolerance(0.001)
    mapMesh = vtk.vtkPolyDataMapper()
    mapMesh.SetInputConnection(delny.GetOutputPort())
    meshActor = vtk.vtkActor()
    meshActor.SetMapper(mapMesh)
    meshActor.GetProperty().SetColor(0.1, 0.2, 0.1)

    # We will now create a nice looking mesh by wrapping the edges in tubes,
    # and putting fat spheres at the points.
    extract = vtk.vtkExtractEdges()
    extract.SetInputConnection(delny.GetOutputPort())

    ball = vtk.vtkSphereSource()

    if radius == None:
        rad = 0.002
    else:
        rad = radius
    print rad
    ball.SetRadius(rad)
    ball.SetThetaResolution(50)
    ball.SetPhiResolution(5)
    balls = vtk.vtkGlyph3D()
    balls.SetInputConnection(delny.GetOutputPort())
    balls.SetSourceConnection(ball.GetOutputPort())
    mapBalls = vtk.vtkPolyDataMapper()
    mapBalls.SetInputConnection(balls.GetOutputPort())
    ballActor = vtk.vtkActor()
    ballActor.SetMapper(mapBalls)
    if color == None:
        ballcolor = red
    else:
        ballcolor = color
    print "setting ball color to...", ballcolor
    ballActor.GetProperty().SetColor(ballcolor)
    ballActor.GetProperty().SetSpecularColor(0, 0, 0)
    ballActor.GetProperty().SetSpecular(0.3)
    ballActor.GetProperty().SetSpecularPower(500)
    ballActor.GetProperty().SetAmbient(0.2)
    ballActor.GetProperty().SetDiffuse(0.8)
    return ballActor, profile
    def CreateWirePolyData(self):
        '''
        @rtype: None
        '''
        if self.getWirePolyData():
            return
        if not self.GetPolyData():
            return
        
        extractor = vtk.vtkExtractEdges()
        extractor.SetInput(self.GetPolyData())
        extractor.Update()
        self.setWirePolyData(extractor.GetOutput())
        
#        del extractor
        self.Modified()
Ejemplo n.º 10
0
def unstructedGridToWireframe(grid,bkgdColor=[255,255,255],color=[0,0,0],renderer=None):
	
	"""Extracts mesh as wireframe plot from unstructured grid and adds it to renderer.
	
	.. note:: Will create new renderer if none is given.
	
	Keyword Args:
		fnVTK (str): Path to input vtk file.
		bkgdColor (list): Background color in RGB values.
		color (list): Color of mesh in RGB values.
		renderer (vtk.vtkRenderer): Some renderer.
		
	Returns:
		vtk.vtkRenderer: Renderer object.
	
	"""
	
	#Extract Edges 
	edges=vtk.vtkExtractEdges()
	edges.SetInput(grid) 
	
	#Make edges into tubes
	tubes = vtk.vtkTubeFilter()
	tubes.SetInput(edges.GetOutput())
	tubes.SetRadius(0.5)
	tubes.SetNumberOfSides(3)

	#Genereate wireframe mapper
	wireFrameMapper=vtk.vtkPolyDataMapper()
	wireFrameMapper.SetInput(tubes.GetOutput())
	wireFrameMapper.SetScalarVisibility(0)
	
	#Make Actor
	wireFrameActor=vtk.vtkActor()
	wireFrameActor.SetMapper(wireFrameMapper)
	wireFrameActor.GetProperty().SetColor(color[0],color[1],color[2])
	wireFrameActor.SetPickable(0)

	#Create the Renderer
	if renderer==None:
		renderer = vtk.vtkRenderer()
		
	# Add to renderer	
	renderer.AddActor(wireFrameActor)
	renderer.SetBackground(bkgdColor[0], bkgdColor[1], bkgdColor[2]) 
	
	return renderer
Ejemplo n.º 11
0
def taubin_smooth(poly, l, m, steps):
    edgesfilter = vtk.vtkExtractEdges()
    edgesfilter.SetInput(poly)
    edgesfilter.Update()

    edges = edgesfilter.GetOutput()

    new_poly = vtk.vtkPolyData()
    new_poly.DeepCopy(poly)

    print edges.GetNumberOfPoints()
    print poly.GetNumberOfPoints()

    points = new_poly.GetPoints()
    for s in xrange(steps):
        D = {}
        for i in xrange(edges.GetNumberOfPoints()):
            D[i] = calculate_d(edges, new_poly, i)
        for i in xrange(poly.GetNumberOfPoints()):
            p = np.array(points.GetPoint(i))
            pl = p + l*D[i]
            nx, ny, nz = pl
            points.SetPoint(i, nx, ny, nz)

        D = {}
        for i in xrange(edges.GetNumberOfPoints()):
            D[i] = calculate_d(edges, new_poly, i)
        for i in xrange(poly.GetNumberOfPoints()):
            p = np.array(points.GetPoint(i))
            pl = p + m*D[i]
            nx, ny, nz = pl
            points.SetPoint(i, nx, ny, nz)

        #D = {}
        #for i in xrange(edges.GetNumberOfPoints()):
            #D[i] = calculate_d(edges, i)
        #for i in xrange(poly.GetNumberOfPoints()):
            #x, y, z = points.GetPoint(i)
            #nx = x + m*D[i][0]
            #ny = y + m*D[i][1]
            #nz = z + m*D[i][2]
            #points.SetPoint(i, nx, ny, nz)

    #new_poly.SetPoints(points)
    return new_poly
Ejemplo n.º 12
0
    def getEdges(self):
        edges = vtk.vtkExtractEdges()
        edges.SetInput(self.grid)
        self.edgeMapper = vtk.vtkPolyDataMapper()
        self.edgeMapper.SetInput(edges.GetOutput())
        #self.edgeMapper.EdgeVisibilityOff()

        self.edgeActor = vtk.vtkActor()
        self.edgeActor.SetMapper(self.edgeMapper)
        self.edgeActor.GetProperty().SetColor(0, 0, 0)
        prop = self.edgeActor.GetProperty()
        #prop.SetLineWidth(0.0)
        if self.isEdges:
            prop.EdgeVisibilityOn()
        else:
            prop.EdgeVisibilityOff()

        self.rend.AddActor(self.edgeActor)

        vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset()
        print "visible = ", prop.GetEdgeVisibility()
Ejemplo n.º 13
0
def Edges(cm,
          cl=khaki):

    Edges = vtk.vtkExtractEdges()
    Edges.SetInputConnection(cm.GetOutputPort())
    Tubes = vtk.vtkTubeFilter()
    Tubes.SetInputConnection(Edges.GetOutputPort())
    Tubes.SetRadius(.01)
    Tubes.SetNumberOfSides(6)
    Tubes.UseDefaultNormalOn()
    Tubes.SetDefaultNormal(.577, .577, .577)
    # Create the mapper and actor to display the cube edges.
    TubeMapper = vtk.vtkPolyDataMapper()
    TubeMapper.SetInputConnection(Tubes.GetOutputPort())
    CubeEdges = vtk.vtkActor()
    CubeEdges.SetMapper(TubeMapper)
    CubeEdges.GetProperty().SetDiffuseColor(cl)
    CubeEdges.GetProperty().SetSpecular(.4)
    CubeEdges.GetProperty().SetSpecularPower(10)

    return CubeEdges
Ejemplo n.º 14
0
    def getEdges(self):
        edges = vtk.vtkExtractEdges()

        edges.SetInput(self.grid)
        self.edgeMapper = vtk.vtkPolyDataMapper()
        self.edgeMapper.SetInput(edges.GetOutput())
        #edges.GetOutput().ReleaseDataFlagOn()
        #self.edgeMapper.EdgeVisibilityOff()

        self.edgeActor = vtk.vtkActor()
        self.edgeActor.SetMapper(self.edgeMapper)
        self.edgeActor.GetProperty().SetColor(0, 0, 0)
        prop = self.edgeActor.GetProperty()
        #prop.SetLineWidth(0.0)
        if self.isEdges:
            prop.EdgeVisibilityOn()
        else:
            prop.EdgeVisibilityOff()

        self.rend.AddActor(self.edgeActor)

        print("visible = %s" % (prop.GetEdgeVisibility()))
Ejemplo n.º 15
0
def make_cubeActor (lattice, radius=0.1):
    CubeModel = vtk.vtkCubeSource()
    CubeModel.SetXLength(lattice[0])
    CubeModel.SetYLength(lattice[1])
    CubeModel.SetZLength(lattice[2])
    CubeModel.SetCenter(.5*lattice[0], .5*lattice[1], .5*lattice[2])
    Edges = vtk.vtkExtractEdges()
    Edges.SetInput(CubeModel.GetOutput())
    Tubes = vtk.vtkTubeFilter()
    Tubes.SetInput(Edges.GetOutput())
    Tubes.SetRadius(radius)
    Tubes.SetNumberOfSides(6)
    Tubes.UseDefaultNormalOn()
    Tubes.SetDefaultNormal(.577, .577, .577)
    # Create the mapper and actor to display the cube edges.
    TubeMapper = vtk.vtkPolyDataMapper()
    TubeMapper.SetInput(Tubes.GetOutput())
    CubeEdges = vtk.vtkActor()
    CubeEdges.SetMapper(TubeMapper)
    CubeEdges.GetProperty().SetDiffuseColor(khaki)
    CubeEdges.GetProperty().SetSpecular(.4)
    CubeEdges.GetProperty().SetSpecularPower(10)
    #ren.AddActor(CubeEdges)
    return(CubeEdges)
Ejemplo n.º 16
0
def get_vtk_edges(vtkdata):
    """
    Get mesh edges.

    Parameters
    ----------
    vtkdata : VTK object
        Mesh, scalar, vector and tensor data.

    Returns
    -------
    edges : VTK object
        Mesh, scalar, vector and tensor data.
    """
    edges = vtk.vtkExtractEdges()
    if vtk_version < 6:
        edges.SetInput(vtkdata)

    else:
        edges.SetInputData(vtkdata)

    edges.Update()

    return edges.GetOutput()
Ejemplo n.º 17
0
    def GetActor(self):
        planeCnt = 3
        planeSources = []
        for createSources in range(planeCnt):
            planeSources.append(vtk.vtkPlaneSource())

        self.planeSources = planeSources

        endPts = ((0, 0, 0), (1, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 0),
                  (0, 0, 0), (0, 1, 0), (0, 0, 0), (0, 1, 1))

        box = self.box

        planeSources[0].SetOrigin(box[0][0], box[0][1], box[0][2])
        planeSources[0].SetPoint1(box[1][0], box[0][1], box[0][2])
        planeSources[0].SetPoint2(box[0][0], box[0][1], box[1][2])
        planeSources[1].SetOrigin(box[0][0], box[1][1], box[0][2])
        planeSources[1].SetPoint1(box[1][0], box[1][1], box[0][2])
        planeSources[1].SetPoint2(box[0][0], box[0][1], box[0][2])
        planeSources[2].SetOrigin(box[0][0], box[1][1], box[0][2])
        planeSources[2].SetPoint1(box[0][0], box[0][1], box[0][2])
        planeSources[2].SetPoint2(box[0][0], box[1][1], box[1][2])

        planeSources[0].SetXResolution(5)
        planeSources[0].SetYResolution(5)
        planeSources[1].SetXResolution(5)
        planeSources[1].SetYResolution(5)
        planeSources[2].SetXResolution(5)
        planeSources[2].SetYResolution(5)

        self.Properties.append(
            IntProperty("plane resolution", self.SetResolution,
                        self.GetResolution))

        appendPolyData = vtk.vtkAppendPolyData()
        for appendIdx in range(planeCnt):
            appendPolyData.AddInput(planeSources[appendIdx].GetOutput())

        self.tubeFilter = []
        collectTubes = vtk.vtkAppendPolyData()
        for tubeIdx in range(planeCnt):
            edgeFilter = vtk.vtkExtractEdges()
            edgeFilter.SetInput(planeSources[tubeIdx].GetOutput())
            tubeFilter = vtk.vtkTubeFilter()
            tubeFilter.SetInput(edgeFilter.GetOutput())
            tubeFilter.SetRadius(0.05)
            tubeFilter.SetNumberOfSides(12)
            self.tubeFilter.append(tubeFilter)
            collectTubes.AddInput(tubeFilter.GetOutput())
        self.Properties.append(
            FloatProperty("grid thickness", self.SetTubeThickness,
                          self.GetTubeThickness))

        tubeMap = vtk.vtkPolyDataMapper()
        tubeMap.SetInput(collectTubes.GetOutput())
        tubeActor = vtk.vtkActor()
        tubeActor.SetMapper(tubeMap)
        tubeActor.GetProperty().SetColor(0.1, 0.1, 0.1)
        self.Properties.append(
            ColorProperty("grid color",
                          tubeActor.GetProperty().SetColor,
                          tubeActor.GetProperty().GetColor))
        self.Properties.append(
            FloatProperty("grid opacity",
                          tubeActor.GetProperty().SetOpacity,
                          tubeActor.GetProperty().GetOpacity))
        self.Properties.append(
            ChoiceProperty("grid visible", tubeActor.SetVisibility,
                           tubeActor.GetVisibility))

        map = vtk.vtkPolyDataMapper()
        map.SetInput(appendPolyData.GetOutput())

        planeActor = vtk.vtkActor()
        planeActor.SetMapper(map)
        planeActor.GetProperty().SetColor(.2, .2, .2)
        self.Properties.append(
            ColorProperty("plane color",
                          planeActor.GetProperty().SetColor,
                          planeActor.GetProperty().GetColor))
        self.Properties.append(
            FloatProperty("plane opacity",
                          planeActor.GetProperty().SetOpacity,
                          planeActor.GetProperty().GetOpacity))
        self.Properties.append(
            ChoiceProperty("plane visible", planeActor.SetVisibility,
                           planeActor.GetVisibility))
        return [planeActor, tubeActor]
def CreateVoxelizedTubeFilter(polydataMesh,voxelNumbers,fiberRadius):
    """ Creates an image putting cylinders around the edges of a mesh
    (see paraview tube filter to get an idea of what it's doing).
    :param: polydataMesh : mesh, used as the skeleton of the image (vtk polydata object)
    :param: voxelNumbers: virtual image size
    :param: fiberRadius : cylinder raidus (in voxel unit)
    
    :return: image (numpy array)
    
    :example:
    
    """
    
    
    print('Create FibersOnMesh')
    beginTime=time.time()
    
    #Prepare the structure image
    image=np.zeros(voxelNumbers,dtype=np.bool)
    
    imageBounds = polydataMesh.GetBounds()
    margin=fiberRadius    
    
    gridX=np.linspace(imageBounds[0]-margin,imageBounds[1]+margin,voxelNumbers[0]+1)
    gridY=np.linspace(imageBounds[2]-margin,imageBounds[3]+margin,voxelNumbers[1]+1)
    gridZ=np.linspace(imageBounds[4]-margin,imageBounds[5]+margin,voxelNumbers[2]+1)
    
    #Extract lines and points
    
    edgeExtractor = vtk.vtkExtractEdges()    
    
    if vtk.vtkVersion.GetVTKMajorVersion()==6:
        edgeExtractor.SetInputData(polydataMesh)
    else:
        edgeExtractor.SetInput(polydataMesh)
    edgeExtractor.Update()
    
    
    points = edgeExtractor.GetOutput().GetPoints()
    nVertice = int(points.GetNumberOfPoints())
    vertices=[(float(points.GetPoint(iPoint)[0]),
               float(points.GetPoint(iPoint)[1]),
               float(points.GetPoint(iPoint)[2]))
                   for iPoint in range(nVertice)]
    
    output = edgeExtractor.GetOutput()
    nFibre = int(output.GetNumberOfCells())
    fibres = [ [int(output.GetCell(iFibre).GetPointId(0)),
                int(output.GetCell(iFibre).GetPointId(1))]
                for iFibre in range(nFibre)]

    #Add cylinders and balls to the structure image
    print(str(nFibre)+' fibers')
    print(str(nVertice)+' vertices')
    
    for iFibre in range(nFibre):
        print iFibre,         
        iPoint1=fibres[iFibre][0]
        iPoint2=fibres[iFibre][1]
        origin=np.array(vertices[iPoint1])
        end=np.array(vertices[iPoint2])
        height=np.linalg.norm(end-origin)
        axis=end-origin
        center=tuple((end+origin)/2)
        mesh = BasicShapes.CreateCylinder(center,axis,fiberRadius,height)
        objImage=Voxelization.Voxelize(mesh,gridX,gridY,gridZ,raydirection='xz')
        image=np.logical_or(image,objImage)
      
      
    #spherical capings of cylinders      
    for iVertice in range(nVertice):
        print iVertice,
        center = vertices[iVertice]
        
        mesh = BasicShapes.CreateBall(tuple(center),fiberRadius)
        objImage=Voxelization.Voxelize(mesh,gridX,gridY,gridZ,raydirection='xz')
        image=np.logical_or(image,objImage)

    #image = InsertSubimageInImage(image,voxelNumbers,gridRelativePosition)
    
    endTime=time.time()
    print("Time spent : {} s".format(endTime-beginTime))
    
    return image
Ejemplo n.º 19
0
    def Execute(self):

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

        if (self.Surface.GetPointData().GetArray(
                self.SurfaceArrayName) == None):
            self.PrintError('Error: no array with name specified')
        else:
            array = self.Surface.GetPointData().GetArray(self.SurfaceArrayName)

        surface = self.Surface
        extractEdges = vtk.vtkExtractEdges()
        extractEdges.SetInputData(surface)
        extractEdges.Update()
        surfEdges = extractEdges.GetOutput()

        if self.Connexity == 1:
            for n in range(self.Iterations):
                for i in range(surfEdges.GetNumberOfPoints()):
                    cells = vtk.vtkIdList()
                    surfEdges.GetPointCells(i, cells)
                    vval = 0
                    ddd = 0
                    d = 0
                    N = 0
                    for j in range(cells.GetNumberOfIds()):
                        points = vtk.vtkIdList()
                        surfEdges.GetCellPoints(cells.GetId(j), points)
                        for k in range(points.GetNumberOfIds()):
                            if points.GetId(k) != i:
                                d = math.sqrt(
                                    vtk.vtkMath.Distance2BetweenPoints(
                                        surface.GetPoint(i),
                                        surface.GetPoint(points.GetId(k))))
                                dd = 1 / d
                                val = array.GetComponent(points.GetId(k),
                                                         0)  #*dd
                                N = N + 1
                                vval = vval + val
                                ddd = ddd + dd
                    val = array.GetComponent(i, 0)
                    vval = vval / (N)
                    newval = self.Relaxation * vval + (1 -
                                                       self.Relaxation) * val
                    array.SetTuple1(i, newval)
        elif self.Connexity == 2:
            for n in range(self.Iterations):
                for i in range(surfEdges.GetNumberOfPoints()):
                    cells = vtk.vtkIdList()
                    surfEdges.GetPointCells(i, cells)
                    pointlist = vtk.vtkIdList()
                    vval = 0
                    ddd = 0
                    d = 0
                    N = 0
                    for j in range(cells.GetNumberOfIds()):
                        points = vtk.vtkIdList()
                        surfEdges.GetCellPoints(cells.GetId(j), points)
                        for k in range(points.GetNumberOfIds()):
                            if points.GetId(k) != i:
                                pointlist.InsertUniqueId(points.GetId(k))
                                cells2 = vtk.vtkIdList()
                                surfEdges.GetPointCells(i, cells2)
                                for p in range(cells2.GetNumberOfIds()):
                                    points2 = vtk.vtkIdList()
                                    surfEdges.GetCellPoints(
                                        cells2.GetId(j), points2)
                                    for q in range(points2.GetNumberOfIds()):
                                        if points2.GetId(k) != i:
                                            pointlist.InsertUniqueId(
                                                points2.GetId(k))
                    N = pointlist.GetNumberOfIds()
                    for j in range(pointlist.GetNumberOfIds()):
                        d = math.sqrt(
                            vtk.vtkMath.Distance2BetweenPoints(
                                surface.GetPoint(i),
                                surface.GetPoint(pointlist.GetId(j))))
                        dd = 1 / d
                        val = array.GetComponent(pointlist.GetId(j), 0)
                        vval = vval + val
                        ddd = ddd + dd
                    val = array.GetComponent(i, 0)
                    vval = vval / (N)
                    newval = self.Relaxation * vval + (1 -
                                                       self.Relaxation) * val
                    array.SetTuple1(i, newval)
        else:
            self.PrintError('Error: wrong connexity')

        self.Surface = surface
Ejemplo n.º 20
0
    def load_vtk_legacy_file(self, file):
        """
		Loads the vtk mesh and displays the scalar data in a color map.
		Allows further postprocessing to be done, such as grayscale and contour plots.
		"""

        if hasattr(self, "mesh_actor"):
            self.ren.RemoveActor(self.mesh_actor)
            self.ren.RemoveActor(self.sbActor)

        if file is None:
            file, _ = get_file("*.vtk")

        self.ui.statLabel.setText("Reading %s for mesh . . ." % file)
        mesh_source = vtk.vtkUnstructuredGridReader()
        mesh_source.SetFileName(file)

        # read scalar to vtk
        mesh_source.SetScalarsName("S33")
        mesh_source.Update()
        mesh_reader_output = mesh_source.GetOutput()

        # bounds for axis
        bounds = mesh_reader_output.GetBounds()

        # show element edges
        edges = vtk.vtkExtractEdges()
        edges.SetInputConnection(mesh_source.GetOutputPort())
        edges.Update()

        # lookup table and scalar range for a vtk file
        mesh_lookup_table = vtk.vtkLookupTable()

        # make scalar red = max; blue = min
        self.ui.statLabel.setText("Building lookup table . . .")
        self.draw_color_range(mesh_lookup_table)
        mesh_lookup_table.Build()
        scalar_range = mesh_reader_output.GetScalarRange()

        # mesh data set
        self.mesh_mapper = vtk.vtkDataSetMapper()
        self.mesh_mapper.SetInputData(mesh_reader_output)
        self.mesh_mapper.SetScalarRange(scalar_range)
        self.mesh_mapper.SetLookupTable(mesh_lookup_table)

        #define actors
        self.mesh_actor = vtk.vtkActor()
        # self.sbActor = vtk.vtkScalarBarActor()

        # #the scalar bar widget is associated with the qt interactor box
        scalar_bar_widget = vtk.vtkScalarBarWidget()
        scalar_bar_widget.SetInteractor(self.iren)
        # scalar_bar_widget.SetCurrentRenderer(self.ren.GetRenderer())
        # scalar_bar_widget.SetDefaultRenderer(self.ren.GetRenderer())
        scalar_bar_widget.SetEnabled(True)
        scalar_bar_widget.RepositionableOn()
        scalar_bar_widget.On()

        # define scalar bar actor
        self.sbActor = scalar_bar_widget.GetScalarBarActor()
        # self.sbActor.SetOrientationToVertical()
        self.sbActor.SetLookupTable(mesh_lookup_table)
        self.sbActor.SetTitle("S33")

        scalarBarRep = scalar_bar_widget.GetRepresentation()
        scalarBarRep.GetPositionCoordinate().SetValue(0.01, 0.01)
        scalarBarRep.GetPosition2Coordinate().SetValue(0.09, 0.9)

        #attempt to change scalebar properties [ineffective]
        propT = vtk.vtkTextProperty()
        propL = vtk.vtkTextProperty()
        propT.SetFontFamilyToArial()
        # propT.ItalicOff()
        propT.BoldOn()
        propL.BoldOff()
        propL.SetFontSize(1)
        propT.SetFontSize(2)
        self.sbActor.SetTitleTextProperty(propT)
        self.sbActor.SetLabelTextProperty(propL)
        self.sbActor.GetLabelTextProperty().SetFontSize(7)
        self.sbActor.GetTitleTextProperty().SetFontSize(7)
        self.sbActor.SetLabelFormat("%.1f")

        #define the mesh actor properties
        self.mesh_actor.SetMapper(self.mesh_mapper)
        self.mesh_actor.GetProperty().SetLineWidth(1)
        self.mesh_actor.GetProperty().EdgeVisibilityOn()

        #display the actors
        self.ren.AddActor(self.mesh_actor)
        self.ren.AddActor(self.sbActor)

        #get boundary of mesh
        self.limits = mesh_reader_output.GetBounds()

        self.ui.vtkWidget.setFocus()
        self.AddAxis(self.limits, 1)
        xyview_post(self.ren, self.ren.GetActiveCamera(), self.cp,
                    self.fp)  #sorts out the camera issue
        self.ui.vtkWidget.update()
        self.ui.statLabel.setText("Loaded results. Idle.")
        QtWidgets.QApplication.processEvents()
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

### SetUp the pipeline
FormMesh = vtk.vtkRectilinearGridToTetrahedra()
FormMesh.SetInput(4,2,2,1,1,1,0.001)
FormMesh.RememberVoxelIdOn()
TetraEdges = vtk.vtkExtractEdges()
TetraEdges.SetInputConnection(FormMesh.GetOutputPort())
tubes = vtk.vtkTubeFilter()
tubes.SetInputConnection(TetraEdges.GetOutputPort())
tubes.SetRadius(0.05)
tubes.SetNumberOfSides(6)
### Run the pipeline 3 times, with different conversions to TetMesh
Tubes1 = vtk.vtkPolyData()
FormMesh.SetTetraPerCellTo5()
tubes.Update()
Tubes1.DeepCopy(tubes.GetOutput())
Tubes2 = vtk.vtkPolyData()
FormMesh.SetTetraPerCellTo6()
tubes.Update()
Tubes2.DeepCopy(tubes.GetOutput())
Tubes3 = vtk.vtkPolyData()
FormMesh.SetTetraPerCellTo12()
tubes.Update()
Tubes3.DeepCopy(tubes.GetOutput())
### Run the pipeline once more, this time converting some cells to
### 5 and some data to 12 TetMesh
Ejemplo n.º 22
0
def extractedges(surface):
    """Extract edges of a surface mesh, i.e. the edges of all mesh elements."""
    extractor = vtk.vtkExtractEdges()
    extractor.SetInput(surface)
    extractor.Update()
    return extractor.GetOutput()
Ejemplo n.º 23
0
def main():
    colors = vtk.vtkNamedColors()

    # PART 1 Make some Data.
    # Make a tree.
    root = vtk.vtkMultiBlockDataSet()

    branch = vtk.vtkMultiBlockDataSet()
    root.SetBlock(0, branch)

    # Make some leaves.
    leaf1 = vtk.vtkSphereSource()
    leaf1.SetCenter(0, 0, 0)
    leaf1.Update()
    branch.SetBlock(0, leaf1.GetOutput())

    leaf2 = vtk.vtkSphereSource()
    leaf2.SetCenter(1.75, 2.5, 0)
    leaf2.SetRadius(1.5)
    leaf2.Update()
    branch.SetBlock(1, leaf2.GetOutput())

    leaf3 = vtk.vtkSphereSource()
    leaf3.SetCenter(4, 0, 0)
    leaf3.SetRadius(2)
    leaf3.Update()
    root.SetBlock(1, leaf3.GetOutput())

    # PART 2 Do something with the data
    # a non composite aware filter, the pipeline will iterate
    edges = vtk.vtkExtractEdges()
    edges.SetInputData(root)

    # PART 3 Show the data
    # also demonstrate a composite aware filter
    # this filter aggregates all blocks into one polydata
    # this is handy for display, although fairly limited
    # see vtkCompositePolyDataMapper2 for something better
    polydata = vtk.vtkCompositeDataGeometryFilter()
    polydata.SetInputConnection(edges.GetOutputPort())

    # Create the Renderer, RenderWindow, and RenderWindowInteractor.
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(0, polydata.GetOutputPort(0))
    actor = vtk.vtkActor()
    actor.GetProperty().SetColor(colors.GetColor3d('Yellow'))
    actor.GetProperty().SetLineWidth(2)
    actor.SetMapper(mapper)

    # Enable user interface interactor.
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('CornflowerBlue'))
    renderWindow.SetWindowName('MultiBlockDataSet')
    renderWindow.Render()
    renderWindowInteractor.Start()
Ejemplo n.º 24
0
Ids.InsertNextId(5)

grid = vtk.vtkUnstructuredGrid()
grid.Allocate(10, 10)
grid.InsertNextCell(13, Ids)
grid.SetPoints(Points)
grid.GetPointData().SetScalars(Scalars)

# Clip the wedge
clipper = vtk.vtkClipDataSet()
clipper.SetInputData(grid)
clipper.SetValue(0.5)

# build tubes for the triangle edges
#
wedgeEdges = vtk.vtkExtractEdges()
wedgeEdges.SetInputConnection(clipper.GetOutputPort())
wedgeEdgeTubes = vtk.vtkTubeFilter()
wedgeEdgeTubes.SetInputConnection(wedgeEdges.GetOutputPort())
wedgeEdgeTubes.SetRadius(.005)
wedgeEdgeTubes.SetNumberOfSides(6)
wedgeEdgeMapper = vtk.vtkPolyDataMapper()
wedgeEdgeMapper.SetInputConnection(wedgeEdgeTubes.GetOutputPort())
wedgeEdgeMapper.ScalarVisibilityOff()
wedgeEdgeActor = vtk.vtkActor()
wedgeEdgeActor.SetMapper(wedgeEdgeMapper)
wedgeEdgeActor.GetProperty().SetDiffuseColor(GetRGBColor('lamp_black'))
wedgeEdgeActor.GetProperty().SetSpecular(.4)
wedgeEdgeActor.GetProperty().SetSpecularPower(10)

# shrink the triangles so we can see each one
Ejemplo n.º 25
0
def vtksetup(points, color=None, radius=None):
    # Create a polydata with the points we just created.
    profile = vtk.vtkPolyData()
    profile.SetPoints(points)

    # Perform a 2D Delaunay triangulation on them.
    delny = vtk.vtkDelaunay2D()
    delny.SetInput(profile)
    delny.SetTolerance(0.001)
    mapMesh = vtk.vtkPolyDataMapper()
    mapMesh.SetInputConnection(delny.GetOutputPort())
    meshActor = vtk.vtkActor()
    meshActor.SetMapper(mapMesh)
    meshActor.GetProperty().SetColor(.1, .2, .1)
    
    # Construct the surface and create isosurface.
    #surf = vtk.vtkSurfaceReconstructionFilter()
    #surf.SetInput(pointSource.GetPolyDataOutput())
    cf = vtk.vtkPolyData()
    
    #cf = vtk.vtkContourFilter()
    cf.SetPoints(points)
    #cf.SetInput(surf.GetOutput())
    #cf.SetValue(0, 0.0)
    
##    map = vtk.vtkPolyDataMapper()
##    map.SetInput(reverse.GetOutput())
##    map.ScalarVisibilityOff()

    surfaceActor = vtk.vtkActor()
    surfaceActor.SetMapper(map)
    surfaceActor.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784)
    surfaceActor.GetProperty().SetSpecularColor(1, 1, 1)
    surfaceActor.GetProperty().SetSpecular(.4)
    surfaceActor.GetProperty().SetSpecularPower(50)

    # We will now create a nice looking mesh by wrapping the edges in tubes,
    # and putting fat spheres at the points.
    extract = vtk.vtkExtractEdges()
    extract.SetInputConnection(delny.GetOutputPort())

    ball = vtk.vtkSphereSource()
    
    if radius == None:
        rad = .002
    else:
        rad = radius
    
    ball.SetRadius(rad)
    ball.SetThetaResolution(5)
    ball.SetPhiResolution(5)
    balls = vtk.vtkGlyph3D()
    balls.SetInputConnection(delny.GetOutputPort())
    balls.SetSourceConnection(ball.GetOutputPort())
    mapBalls = vtk.vtkPolyDataMapper()
    mapBalls.SetInputConnection(balls.GetOutputPort())
    ballActor = vtk.vtkActor()
    ballActor.SetMapper(mapBalls)
    if color == None:
        ballcolor = red
    else:
        ballcolor = color
    ballActor.GetProperty().SetColor(ballcolor)
    ballActor.GetProperty().SetSpecularColor(0, 0, 0)
    ballActor.GetProperty().SetSpecular(0.3)
    ballActor.GetProperty().SetSpecularPower(100)
    ballActor.GetProperty().SetAmbient(0.2)
    ballActor.GetProperty().SetDiffuse(0.8)
    return ballActor
Ejemplo n.º 26
0
def extractedges(surface):
    """Extract edges of a surface mesh, i.e. the edges of all mesh elements."""
    extractor = vtk.vtkExtractEdges()
    extractor.SetInput(surface)
    extractor.Update()
    return extractor.GetOutput()
Ejemplo n.º 27
0
def marching_cubes(mcCases):
    color = vtk.vtkNamedColors()

    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(640, 480)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    renderers = list()
    gridSize = ((len(mcCases) + 3) // 4) * 4
    if len(mcCases) < 4:
        gridSize = len(mcCases)
    print("gridSize:", gridSize)
    for i in range(0, gridSize):
        # Create the Renderer
        renderer = vtk.vtkRenderer()
        renderers.append(renderer)
        renWin.AddRenderer(renderer)

    for i in range(0, len(mcCases)):
        # Define a Single Cube
        Scalars = vtk.vtkFloatArray()
        Scalars.InsertNextValue(1.0)
        Scalars.InsertNextValue(0.0)
        Scalars.InsertNextValue(0.0)
        Scalars.InsertNextValue(1.0)
        Scalars.InsertNextValue(0.0)
        Scalars.InsertNextValue(0.0)
        Scalars.InsertNextValue(0.0)
        Scalars.InsertNextValue(0.0)

        Points = vtk.vtkPoints()
        Points.InsertNextPoint(0, 0, 0)
        Points.InsertNextPoint(1, 0, 0)
        Points.InsertNextPoint(1, 1, 0)
        Points.InsertNextPoint(0, 1, 0)
        Points.InsertNextPoint(0, 0, 1)
        Points.InsertNextPoint(1, 0, 1)
        Points.InsertNextPoint(1, 1, 1)
        Points.InsertNextPoint(0, 1, 1)

        Ids = vtk.vtkIdList()
        Ids.InsertNextId(0)
        Ids.InsertNextId(1)
        Ids.InsertNextId(2)
        Ids.InsertNextId(3)
        Ids.InsertNextId(4)
        Ids.InsertNextId(5)
        Ids.InsertNextId(6)
        Ids.InsertNextId(7)

        Grid = vtk.vtkUnstructuredGrid()
        Grid.Allocate(10, 10)
        Grid.InsertNextCell(12, Ids)
        Grid.SetPoints(Points)
        Grid.GetPointData().SetScalars(Scalars)

        # Find the triangles that lie along the 0.5 contour in this cube.
        Marching = vtk.vtkContourFilter()
        Marching.SetInputData(Grid)
        Marching.SetValue(0, 0.5)
        Marching.Update()

        # Extract the edges of the triangles just found.
        triangleEdges = vtk.vtkExtractEdges()
        triangleEdges.SetInputConnection(Marching.GetOutputPort())

        # Draw the edges as tubes instead of lines.  Also create the associated
        # mapper and actor to display the tubes.
        triangleEdgeTubes = vtk.vtkTubeFilter()
        triangleEdgeTubes.SetInputConnection(triangleEdges.GetOutputPort())
        triangleEdgeTubes.SetRadius(.005)
        triangleEdgeTubes.SetNumberOfSides(6)
        triangleEdgeTubes.UseDefaultNormalOn()
        triangleEdgeTubes.SetDefaultNormal(.577, .577, .577)

        triangleEdgeMapper = vtk.vtkPolyDataMapper()
        triangleEdgeMapper.SetInputConnection(
            triangleEdgeTubes.GetOutputPort())
        triangleEdgeMapper.ScalarVisibilityOff()

        triangleEdgeActor = vtk.vtkActor()
        triangleEdgeActor.SetMapper(triangleEdgeMapper)
        triangleEdgeActor.GetProperty().SetDiffuseColor(
            color.GetColor3d("lamp_black"))
        triangleEdgeActor.GetProperty().SetSpecular(.4)
        triangleEdgeActor.GetProperty().SetSpecularPower(10)

        # Shrink the triangles we found earlier.  Create the associated mapper
        # and actor.  Set the opacity of the shrunken triangles.
        aShrinker = vtk.vtkShrinkPolyData()
        aShrinker.SetShrinkFactor(1)
        aShrinker.SetInputConnection(Marching.GetOutputPort())

        aMapper = vtk.vtkPolyDataMapper()
        aMapper.ScalarVisibilityOff()
        aMapper.SetInputConnection(aShrinker.GetOutputPort())

        Triangles = vtk.vtkActor()
        Triangles.SetMapper(aMapper)
        Triangles.GetProperty().SetDiffuseColor(color.GetColor3d("banana"))
        Triangles.GetProperty().SetOpacity(.6)

        # Draw a cube the same size and at the same position as the one
        # created previously.  Extract the edges because we only want to see
        # the outline of the cube.  Pass the edges through a vtkTubeFilter so
        # they are displayed as tubes rather than lines.
        CubeModel = vtk.vtkCubeSource()
        CubeModel.SetCenter(.5, .5, .5)

        Edges = vtk.vtkExtractEdges()
        Edges.SetInputConnection(CubeModel.GetOutputPort())

        Tubes = vtk.vtkTubeFilter()
        Tubes.SetInputConnection(Edges.GetOutputPort())
        Tubes.SetRadius(.01)
        Tubes.SetNumberOfSides(6)
        Tubes.UseDefaultNormalOn()
        Tubes.SetDefaultNormal(.577, .577, .577)
        # Create the mapper and actor to display the cube edges.
        TubeMapper = vtk.vtkPolyDataMapper()
        TubeMapper.SetInputConnection(Tubes.GetOutputPort())
        CubeEdges = vtk.vtkActor()
        CubeEdges.SetMapper(TubeMapper)
        CubeEdges.GetProperty().SetDiffuseColor(color.GetColor3d("khaki"))
        CubeEdges.GetProperty().SetSpecular(.4)
        CubeEdges.GetProperty().SetSpecularPower(10)

        # Create a sphere to use as a glyph source for vtkGlyph3D.
        Sphere = vtk.vtkSphereSource()
        Sphere.SetRadius(0.04)
        Sphere.SetPhiResolution(20)
        Sphere.SetThetaResolution(20)
        # Remove the part of the cube with data values below 0.5.
        ThresholdIn = vtk.vtkThresholdPoints()
        ThresholdIn.SetInputData(Grid)
        ThresholdIn.ThresholdByUpper(.5)
        # Display spheres at the vertices remaining in the cube data set after
        # it was passed through vtkThresholdPoints.
        Vertices = vtk.vtkGlyph3D()
        Vertices.SetInputConnection(ThresholdIn.GetOutputPort())
        Vertices.SetSourceConnection(Sphere.GetOutputPort())
        # Create a mapper and actor to display the glyphs.
        SphereMapper = vtk.vtkPolyDataMapper()
        SphereMapper.SetInputConnection(Vertices.GetOutputPort())
        SphereMapper.ScalarVisibilityOff()

        CubeVertices = vtk.vtkActor()
        CubeVertices.SetMapper(SphereMapper)
        CubeVertices.GetProperty().SetDiffuseColor(color.GetColor3d("tomato"))

        # Define the text for the label
        caseLabel = vtk.vtkVectorText()
        caseLabel.SetText("Case 1")

        # Set up a transform to move the label to a new position.
        aLabelTransform = vtk.vtkTransform()
        aLabelTransform.Identity()
        aLabelTransform.Translate(-0.2, 0, 1.25)
        aLabelTransform.Scale(.05, .05, .05)

        # Move the label to a new position.
        labelTransform = vtk.vtkTransformPolyDataFilter()
        labelTransform.SetTransform(aLabelTransform)
        labelTransform.SetInputConnection(caseLabel.GetOutputPort())

        # Create a mapper and actor to display the text.
        labelMapper = vtk.vtkPolyDataMapper()
        labelMapper.SetInputConnection(labelTransform.GetOutputPort())

        labelActor = vtk.vtkActor()
        labelActor.SetMapper(labelMapper)

        # Define the base that the cube sits on.  Create its associated mapper
        # and actor.  Set the position of the actor.
        baseModel = vtk.vtkCubeSource()
        baseModel.SetXLength(1.5)
        baseModel.SetYLength(.01)
        baseModel.SetZLength(1.5)

        baseMapper = vtk.vtkPolyDataMapper()
        baseMapper.SetInputConnection(baseModel.GetOutputPort())

        base = vtk.vtkActor()
        base.SetMapper(baseMapper)
        base.SetPosition(.5, -0.09, .5)

        # Set the scalar values for this case of marching cubes.
        # A negative case number will generate a complementary case
        mcCase = mcCases[i]
        if mcCase < 0:
            cases[-mcCase](Scalars, caseLabel, 0, 1)
        else:
            cases[mcCase](Scalars, caseLabel, 1, 0)
        # Force the grid to update.
        Grid.Modified()

        # Add the actors to the renderer
        renderers[i].AddActor(triangleEdgeActor)
        renderers[i].AddActor(base)
        renderers[i].AddActor(labelActor)
        renderers[i].AddActor(CubeEdges)
        renderers[i].AddActor(CubeVertices)
        renderers[i].AddActor(Triangles)
        # Set the background color.
        renderers[i].SetBackground(color.GetColor3d("slate_grey"))

        # Position the camera.
        renderers[i].GetActiveCamera().Dolly(1.2)
        renderers[i].GetActiveCamera().Azimuth(30)
        renderers[i].GetActiveCamera().Elevation(20)
        renderers[i].ResetCamera()
        renderers[i].ResetCameraClippingRange()
        if i > 0:
            renderers[i].SetActiveCamera(renderers[0].GetActiveCamera())

    # Setup viewports for the renderers
    rendererSize = 300
    xGridDimensions = 4
    if len(mcCases) < 4:
        xGridDimensions = len(mcCases)
    yGridDimensions = (len(mcCases) - 1) // 4 + 1
    print("x, y:", xGridDimensions, ",", yGridDimensions)
    renWin.SetSize(rendererSize * xGridDimensions,
                   rendererSize * yGridDimensions)
    for row in range(0, yGridDimensions):
        for col in range(0, xGridDimensions):
            index = row * xGridDimensions + col

            # (xmin, ymin, xmax, ymax)
            viewport = [
                float(col) / xGridDimensions,
                float(yGridDimensions - (row + 1)) / yGridDimensions,
                float(col + 1) / xGridDimensions,
                float(yGridDimensions - row) / yGridDimensions
            ]

            renderers[index].SetViewport(viewport)

    iren.Initialize()
    renWin.Render()
    iren.Start()
Ejemplo n.º 28
0
import vtk
from vtk.util.colors import *

cubeSource = vtk.vtkCubeSource()
cubeSource.SetBounds(-5, 5, -5, 5, -5, 5)

ee = vtk.vtkExtractEdges()
ee.SetInput(cubeSource.GetOutput())

cubeTube = vtk.vtkTubeFilter()
cubeTube.SetRadius(0.1)
cubeTube.SetNumberOfSides(20)
cubeTube.UseDefaultNormalOn()
cubeTube.SetDefaultNormal(.5, .5, .5)
cubeTube.SetInput(ee.GetOutput())

cubeMapper = vtk.vtkPolyDataMapper()
cubeMapper.SetInput(cubeTube.GetOutput())

cubeActor = vtk.vtkActor()
cubeActor.SetMapper(cubeMapper)
cubeActor.GetProperty().SetDiffuseColor(lamp_black)
cubeActor.GetProperty().SetSpecular(0.4)
cubeActor.GetProperty().SetSpecularPower(10)

cubeMapper2 = vtk.vtkPolyDataMapper()
cubeMapper2.SetInput(cubeSource.GetOutput())
cubeActor2 = vtk.vtkActor()
cubeActor2.SetMapper(cubeMapper2)
cubeActor2.GetProperty().SetDiffuseColor(banana)
#cubeActor2.GetProperty().SetOpacity(0.9)
def main():
    colors = vtk.vtkNamedColors()

    filename = get_program_parameters()

    # Create the reader for the data.
    print('Loading ', filename)
    reader = vtk.vtkUnstructuredGridReader()
    reader.SetFileName(filename)
    reader.Update()

    extractEdges = vtk.vtkExtractEdges()
    extractEdges.SetInputConnection(reader.GetOutputPort())

    legendValues = vtk.vtkVariantArray()
    it = reader.GetOutput().NewCellIterator()
    it.InitTraversal()
    while not it.IsDoneWithTraversal():
        cell = vtk.vtkGenericCell()
        it.GetCell(cell)
        cellName = vtk.vtkCellTypes.GetClassNameFromTypeId(cell.GetCellType())
        print(cellName, 'NumberOfPoints:', cell.GetNumberOfPoints(),
              'CellDimension:', cell.GetCellDimension())
        legendValues.InsertNextValue(cellName)
        it.GoToNextCell()

    # Tube the edges
    tubes = vtk.vtkTubeFilter()
    tubes.SetInputConnection(extractEdges.GetOutputPort())
    tubes.SetRadius(.05)
    tubes.SetNumberOfSides(21)

    edgeMapper = vtk.vtkPolyDataMapper()
    edgeMapper.SetInputConnection(tubes.GetOutputPort())
    edgeMapper.SetScalarRange(0, 26)

    edgeActor = vtk.vtkActor()
    edgeActor.SetMapper(edgeMapper)
    edgeActor.GetProperty().SetSpecular(0.6)
    edgeActor.GetProperty().SetSpecularPower(30)

    # Glyph the points
    sphere = vtk.vtkSphereSource()
    sphere.SetPhiResolution(21)
    sphere.SetThetaResolution(21)
    sphere.SetRadius(0.08)

    pointMapper = vtk.vtkGlyph3DMapper()
    pointMapper.SetInputConnection(reader.GetOutputPort())
    pointMapper.SetSourceConnection(sphere.GetOutputPort())
    pointMapper.ScalingOff()
    pointMapper.ScalarVisibilityOff()

    pointActor = vtk.vtkActor()
    pointActor.SetMapper(pointMapper)
    pointActor.GetProperty().SetDiffuseColor(colors.GetColor3d('Banana'))
    pointActor.GetProperty().SetSpecular(0.6)
    pointActor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0)
    pointActor.GetProperty().SetSpecularPower(100)

    # Label the points
    labelMapper = vtk.vtkLabeledDataMapper()
    labelMapper.SetInputConnection(reader.GetOutputPort())
    labelActor = vtk.vtkActor2D()
    labelActor.SetMapper(labelMapper)

    # The geometry
    geometryShrink = vtk.vtkShrinkFilter()
    geometryShrink.SetInputConnection(reader.GetOutputPort())
    geometryShrink.SetShrinkFactor(0.8)

    # NOTE: We must copy the originalLut because the CategoricalLegend
    # needs an indexed lookup table, but the geometryMapper uses a
    # non-index lookup table
    categoricalLut = vtk.vtkLookupTable()
    originalLut = reader.GetOutput().GetCellData().GetScalars().GetLookupTable(
    )

    categoricalLut.DeepCopy(originalLut)
    categoricalLut.IndexedLookupOn()

    geometryMapper = vtk.vtkDataSetMapper()
    geometryMapper.SetInputConnection(geometryShrink.GetOutputPort())
    geometryMapper.SetScalarModeToUseCellData()
    geometryMapper.SetScalarRange(0, 11)

    geometryActor = vtk.vtkActor()
    geometryActor.SetMapper(geometryMapper)
    geometryActor.GetProperty().SetLineWidth(3)
    geometryActor.GetProperty().EdgeVisibilityOn()
    geometryActor.GetProperty().SetEdgeColor(0, 0, 0)

    # Legend
    for v in range(0, legendValues.GetNumberOfTuples()):
        categoricalLut.SetAnnotation(legendValues.GetValue(v),
                                     legendValues.GetValue(v).ToString())
    legend = vtk.vtkCategoryLegend()
    legend.SetScalarsToColors(categoricalLut)
    legend.SetValues(legendValues)
    legend.SetTitle('Cell Type')
    legend.GetBrush().SetColor(colors.GetColor4ub('Silver'))

    placeLegend = vtk.vtkContextTransform()
    placeLegend.AddItem(legend)
    placeLegend.Translate(640 - 20, 480 - 12 * 16)

    contextView = vtk.vtkContextView()
    contextView.GetScene().AddItem(placeLegend)

    renderer = contextView.GetRenderer()

    renderWindow = contextView.GetRenderWindow()

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

    renderer.AddActor(geometryActor)
    renderer.AddActor(labelActor)
    renderer.AddActor(edgeActor)
    renderer.AddActor(pointActor)
    renderer.SetBackground(colors.GetColor3d('SlateGray'))

    aCamera = vtk.vtkCamera()
    aCamera.Azimuth(-40.0)
    aCamera.Elevation(50.0)

    renderer.SetActiveCamera(aCamera)
    renderer.ResetCamera()

    renderWindow.SetSize(640, 480)
    renderWindow.SetWindowName('ReadLegacyUnstructuredGrid')
    renderWindow.Render()

    renderWindowInteractor.Start()
lut.SetValueRange(0,1)
lut.SetNumberOfColors(len(clip_values)-1)

# Displays the contour bands
bands_mapper = vtk.vtkPolyDataMapper()
bands_mapper.SetInputDataObject(poly)
bands_mapper.ScalarVisibilityOn()
bands_mapper.SetScalarModeToUseCellData()
bands_mapper.SetScalarRange(out_scalars.GetRange())
bands_mapper.SetLookupTable(lut)
bands_mapper.UseLookupTableScalarRangeOn()
bands_actor = vtk.vtkActor()
bands_actor.SetMapper(bands_mapper)

# Displays the cell edges of the contour bands
band_cell_edges=vtk.vtkExtractEdges()
band_cell_edges.SetInputDataObject(poly)
band_cell_edges_mapper = vtk.vtkPolyDataMapper()
band_cell_edges_mapper.ScalarVisibilityOff()
band_cell_edges_mapper.SetInputConnection(band_cell_edges.GetOutputPort())
band_cell_edges_actor = vtk.vtkActor()
band_cell_edges_actor.SetMapper(band_cell_edges_mapper)
band_cell_edges_actor.GetProperty().SetColor(.4,.4,.4)

# Displays the contour edges generated by the BPDCF,
# somewhat thicker than the cell edges
band_edges_mapper = vtk.vtkPolyDataMapper()
band_edges_mapper.SetInputConnection(bands.GetOutputPort(1))
band_edges_actor = vtk.vtkActor()
band_edges_actor.SetMapper(band_edges_mapper)
band_edges_actor.GetProperty().SetColor(1,1,1)
Ejemplo n.º 31
0
def main():
    colors = vtk.vtkNamedColors()

    # Generate some "random" points.
    points = vtk.vtkPoints()
    randomSequence = vtk.vtkMinimalStandardRandomSequence()
    randomSequence.SetSeed(1)
    for i in range(0, 50):
        p1 = randomSequence.GetValue()
        randomSequence.Next()
        p2 = randomSequence.GetValue()
        randomSequence.Next()
        points.InsertPoint(i, p1, p2, 0.0)

    # Create a polydata with the points we just created.
    profile = vtk.vtkPolyData()
    profile.SetPoints(points)

    # Perform a 2D Delaunay triangulation on them.
    delny = vtk.vtkDelaunay2D()
    delny.SetInputData(profile)
    delny.SetTolerance(0.001)
    mapMesh = vtk.vtkPolyDataMapper()
    mapMesh.SetInputConnection(delny.GetOutputPort())
    meshActor = vtk.vtkActor()
    meshActor.SetMapper(mapMesh)
    meshActor.GetProperty().SetColor(colors.GetColor3d('MidnightBlue'))

    # We will now create a nice looking mesh by wrapping the edges in tubes,
    # and putting fat spheres at the points.
    extract = vtk.vtkExtractEdges()
    extract.SetInputConnection(delny.GetOutputPort())
    tubes = vtk.vtkTubeFilter()
    tubes.SetInputConnection(extract.GetOutputPort())
    tubes.SetRadius(0.01)
    tubes.SetNumberOfSides(6)
    mapEdges = vtk.vtkPolyDataMapper()
    mapEdges.SetInputConnection(tubes.GetOutputPort())
    edgeActor = vtk.vtkActor()
    edgeActor.SetMapper(mapEdges)
    edgeActor.GetProperty().SetColor(colors.GetColor3d('peacock'))
    edgeActor.GetProperty().SetSpecularColor(1, 1, 1)
    edgeActor.GetProperty().SetSpecular(0.3)
    edgeActor.GetProperty().SetSpecularPower(20)
    edgeActor.GetProperty().SetAmbient(0.2)
    edgeActor.GetProperty().SetDiffuse(0.8)

    ball = vtk.vtkSphereSource()
    ball.SetRadius(0.025)
    ball.SetThetaResolution(12)
    ball.SetPhiResolution(12)
    balls = vtk.vtkGlyph3D()
    balls.SetInputConnection(delny.GetOutputPort())
    balls.SetSourceConnection(ball.GetOutputPort())
    mapBalls = vtk.vtkPolyDataMapper()
    mapBalls.SetInputConnection(balls.GetOutputPort())
    ballActor = vtk.vtkActor()
    ballActor.SetMapper(mapBalls)
    ballActor.GetProperty().SetColor(colors.GetColor3d('hot_pink'))
    ballActor.GetProperty().SetSpecularColor(1, 1, 1)
    ballActor.GetProperty().SetSpecular(0.3)
    ballActor.GetProperty().SetSpecularPower(20)
    ballActor.GetProperty().SetAmbient(0.2)
    ballActor.GetProperty().SetDiffuse(0.8)

    # Create the rendering window, renderer, and interactive renderer.
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the actors to the renderer, set the background and size.
    ren.AddActor(ballActor)
    ren.AddActor(edgeActor)
    ren.SetBackground(colors.GetColor3d('AliceBlue'))
    renWin.SetSize(512, 512)
    renWin.SetWindowName('DelaunayMesh')

    ren.ResetCamera()
    ren.GetActiveCamera().Zoom(1.3)

    # Interact with the data.
    iren.Initialize()
    renWin.Render()
    iren.Start()
Ejemplo n.º 32
0
Ids.InsertNextId(5)

grid = vtk.vtkUnstructuredGrid()
grid.Allocate(10, 10)
grid.InsertNextCell(13, Ids)
grid.SetPoints(Points)
grid.GetPointData().SetScalars(Scalars)

# Clip the wedge
clipper = vtk.vtkClipDataSet()
clipper.SetInputData(grid)
clipper.SetValue(0.5)

# build tubes for the triangle edges
#
wedgeEdges = vtk.vtkExtractEdges()
wedgeEdges.SetInputConnection(clipper.GetOutputPort())
wedgeEdgeTubes = vtk.vtkTubeFilter()
wedgeEdgeTubes.SetInputConnection(wedgeEdges.GetOutputPort())
wedgeEdgeTubes.SetRadius(.005)
wedgeEdgeTubes.SetNumberOfSides(6)
wedgeEdgeMapper = vtk.vtkPolyDataMapper()
wedgeEdgeMapper.SetInputConnection(wedgeEdgeTubes.GetOutputPort())
wedgeEdgeMapper.ScalarVisibilityOff()
wedgeEdgeActor = vtk.vtkActor()
wedgeEdgeActor.SetMapper(wedgeEdgeMapper)
wedgeEdgeActor.GetProperty().SetDiffuseColor(GetRGBColor('lamp_black'))
wedgeEdgeActor.GetProperty().SetSpecular(.4)
wedgeEdgeActor.GetProperty().SetSpecularPower(10)

# shrink the triangles so we can see each one
Ejemplo n.º 33
0
model.SetMapper(dataMapper)
model.GetProperty().SetColor(1, 0, 0)

obb = vtk.vtkOBBTree()
obb.SetMaxLevel(10)
obb.SetNumberOfCellsPerNode(5)
obb.AutomaticOff()

boxes = vtk.vtkSpatialRepresentationFilter()
boxes.SetInputConnection(transPD.GetOutputPort())
boxes.SetSpatialRepresentation(obb)
boxes.SetGenerateLeaves(1)
boxes.Update()

output = boxes.GetOutput().GetBlock(boxes.GetMaximumLevel() + 1)
boxEdges = vtk.vtkExtractEdges()
boxEdges.SetInputData(output)

boxMapper = vtk.vtkPolyDataMapper()
boxMapper.SetInputConnection(boxEdges.GetOutputPort())
boxMapper.SetResolveCoincidentTopology(1)

boxActor = vtk.vtkActor()
boxActor.SetMapper(boxMapper)
boxActor.GetProperty().SetAmbient(1)
boxActor.GetProperty().SetDiffuse(0)
boxActor.GetProperty().SetRepresentationToWireframe()

ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
Ejemplo n.º 34
0
import vtk, os, sys
from vtk.test import Testing

ss = vtk.vtkSphereSource() #make mesh to test with

af = vtk.vtkElevationFilter() #add some attributes
af.SetInputConnection(ss.GetOutputPort())

ef = vtk.vtkExtractEdges() #make lines to test
ef.SetInputConnection(af.GetOutputPort())

gf = vtk.vtkGlyph3D() #make verts to test
pts = vtk.vtkPoints()
pts.InsertNextPoint(0,0,0)
verts = vtk.vtkCellArray()
avert = vtk.vtkVertex()
avert.GetPointIds().SetId(0, 0)
verts.InsertNextCell(avert)
onevertglyph = vtk.vtkPolyData()
onevertglyph.SetPoints(pts)
onevertglyph.SetVerts(verts)
gf.SetSourceData(onevertglyph)
gf.SetInputConnection(af.GetOutputPort())

testwrites = ["points","lines","mesh"]
failed = False
for datasetString in testwrites:
  if datasetString == "points":
    toshow=gf
  elif datasetString == "lines":
    toshow = ef
Ejemplo n.º 35
0
        def returnActors(slef, skel, mode):
            sx=skel.MS.size()[0]
            sy=skel.MS.size()[1]
            smax=sx
            if smax<sy:
                smax=sy

            points = vtk.vtkPoints()
            ndindex={}
            i=0
            for nd in skel.nodes:
                if mode==0:
                    points.InsertPoint(i,
                                       nd.position().x,
                                       nd.position().y,
                                       0)
                elif mode==1:
                    theta=2*vtk.vtkMath.Pi()*nd.position().x/sx
                    radius=sx/(2.0*vtk.vtkMath.Pi())
                    points.InsertPoint(i,
                                       radius*math.cos(theta),
                                       nd.position().y,
                                       radius*math.sin(theta))
                elif mode==2:
                    theta=2*vtk.vtkMath.Pi()*nd.position().y/sy
                    radius=sy/(2.0*vtk.vtkMath.Pi())
                    points.InsertPoint(i,
                                       nd.position().x,
                                       radius*math.cos(theta),
                                       radius*math.sin(theta))
                elif mode==3:
                    theta=2*vtk.vtkMath.Pi()*nd.position().y/sy
                    radius=sy/(2.0*vtk.vtkMath.Pi())
                    ry=radius*math.cos(theta)
                    R=sx/(2.0*vtk.vtkMath.Pi())+radius+ry
                    theta2=2*vtk.vtkMath.Pi()*nd.position().x/sx
                    points.InsertPoint(i,
                                       R*math.cos(theta2),
                                       R*math.sin(theta2),
                                       radius*math.sin(theta))
                ndindex[nd.getIndex()]=i
                i+=1
            strips = vtk.vtkCellArray()
            for el in skel.elements:
                strips.InsertNextCell(el.nnodes())
                if el.nnodes()==4:
                    strips.InsertCellPoint(ndindex[el.nodes[0].getIndex()])
                    strips.InsertCellPoint(ndindex[el.nodes[1].getIndex()])
                    strips.InsertCellPoint(ndindex[el.nodes[3].getIndex()])
                    strips.InsertCellPoint(ndindex[el.nodes[2].getIndex()])
                else:
                    for nd in el.nodes:
                        strips.InsertCellPoint(ndindex[nd.getIndex()])

            profile = vtk.vtkPolyData()
            profile.SetPoints(points)
            profile.SetStrips(strips)

            extract = vtk.vtkExtractEdges()
            extract.SetInput(profile)
            tubes = vtk.vtkTubeFilter()
            tubes.SetInputConnection(extract.GetOutputPort())
            tubes.SetRadius(0.01*smax)
            tubes.SetNumberOfSides(6)

            mapEdges = vtk.vtkPolyDataMapper()
            mapEdges.SetInputConnection(tubes.GetOutputPort())
            edgeActor = vtk.vtkActor()
            edgeActor.SetMapper(mapEdges)
            edgeActor.GetProperty().SetColor(peacock)
            edgeActor.GetProperty().SetSpecularColor(1, 1, 1)
            edgeActor.GetProperty().SetSpecular(0.3)
            edgeActor.GetProperty().SetSpecularPower(20)
            edgeActor.GetProperty().SetAmbient(0.2)
            edgeActor.GetProperty().SetDiffuse(0.8)

            ball = vtk.vtkSphereSource()
            ball.SetRadius(0.025*smax)
            ball.SetThetaResolution(12)
            ball.SetPhiResolution(12)
            balls = vtk.vtkGlyph3D()
            balls.SetInput(profile)
            balls.SetSourceConnection(ball.GetOutputPort())
            mapBalls = vtk.vtkPolyDataMapper()
            mapBalls.SetInputConnection(balls.GetOutputPort())
            ballActor = vtk.vtkActor()
            ballActor.SetMapper(mapBalls)
            ballActor.GetProperty().SetColor(hot_pink)
            ballActor.GetProperty().SetSpecularColor(1, 1, 1)
            ballActor.GetProperty().SetSpecular(0.3)
            ballActor.GetProperty().SetSpecularPower(20)
            ballActor.GetProperty().SetAmbient(0.2)
            ballActor.GetProperty().SetDiffuse(0.8)

            return ballActor, edgeActor
Ejemplo n.º 36
0
        def returnActors(slef, skel, mode):
            sx = skel.MS.size()[0]
            sy = skel.MS.size()[1]
            smax = sx
            if smax < sy:
                smax = sy

            points = vtk.vtkPoints()
            ndindex = {}
            i = 0
            for nd in skel.nodes:
                if mode == 0:
                    points.InsertPoint(i, nd.position().x, nd.position().y, 0)
                elif mode == 1:
                    theta = 2 * vtk.vtkMath.Pi() * nd.position().x / sx
                    radius = sx / (2.0 * vtk.vtkMath.Pi())
                    points.InsertPoint(i, radius * math.cos(theta),
                                       nd.position().y,
                                       radius * math.sin(theta))
                elif mode == 2:
                    theta = 2 * vtk.vtkMath.Pi() * nd.position().y / sy
                    radius = sy / (2.0 * vtk.vtkMath.Pi())
                    points.InsertPoint(i,
                                       nd.position().x,
                                       radius * math.cos(theta),
                                       radius * math.sin(theta))
                elif mode == 3:
                    theta = 2 * vtk.vtkMath.Pi() * nd.position().y / sy
                    radius = sy / (2.0 * vtk.vtkMath.Pi())
                    ry = radius * math.cos(theta)
                    R = sx / (2.0 * vtk.vtkMath.Pi()) + radius + ry
                    theta2 = 2 * vtk.vtkMath.Pi() * nd.position().x / sx
                    points.InsertPoint(i, R * math.cos(theta2),
                                       R * math.sin(theta2),
                                       radius * math.sin(theta))
                ndindex[nd.getIndex()] = i
                i += 1
            strips = vtk.vtkCellArray()
            for el in skel.elements:
                strips.InsertNextCell(el.nnodes())
                if el.nnodes() == 4:
                    strips.InsertCellPoint(ndindex[el.nodes[0].getIndex()])
                    strips.InsertCellPoint(ndindex[el.nodes[1].getIndex()])
                    strips.InsertCellPoint(ndindex[el.nodes[3].getIndex()])
                    strips.InsertCellPoint(ndindex[el.nodes[2].getIndex()])
                else:
                    for nd in el.nodes:
                        strips.InsertCellPoint(ndindex[nd.getIndex()])

            profile = vtk.vtkPolyData()
            profile.SetPoints(points)
            profile.SetStrips(strips)

            extract = vtk.vtkExtractEdges()
            extract.SetInput(profile)
            tubes = vtk.vtkTubeFilter()
            tubes.SetInputConnection(extract.GetOutputPort())
            tubes.SetRadius(0.01 * smax)
            tubes.SetNumberOfSides(6)

            mapEdges = vtk.vtkPolyDataMapper()
            mapEdges.SetInputConnection(tubes.GetOutputPort())
            edgeActor = vtk.vtkActor()
            edgeActor.SetMapper(mapEdges)
            edgeActor.GetProperty().SetColor(peacock)
            edgeActor.GetProperty().SetSpecularColor(1, 1, 1)
            edgeActor.GetProperty().SetSpecular(0.3)
            edgeActor.GetProperty().SetSpecularPower(20)
            edgeActor.GetProperty().SetAmbient(0.2)
            edgeActor.GetProperty().SetDiffuse(0.8)

            ball = vtk.vtkSphereSource()
            ball.SetRadius(0.025 * smax)
            ball.SetThetaResolution(12)
            ball.SetPhiResolution(12)
            balls = vtk.vtkGlyph3D()
            balls.SetInput(profile)
            balls.SetSourceConnection(ball.GetOutputPort())
            mapBalls = vtk.vtkPolyDataMapper()
            mapBalls.SetInputConnection(balls.GetOutputPort())
            ballActor = vtk.vtkActor()
            ballActor.SetMapper(mapBalls)
            ballActor.GetProperty().SetColor(hot_pink)
            ballActor.GetProperty().SetSpecularColor(1, 1, 1)
            ballActor.GetProperty().SetSpecular(0.3)
            ballActor.GetProperty().SetSpecularPower(20)
            ballActor.GetProperty().SetAmbient(0.2)
            ballActor.GetProperty().SetDiffuse(0.8)

            return ballActor, edgeActor
Ejemplo n.º 37
0
def createPipeline(srcLats, srcLons, dstLats, dstLons, nitersData, radius=1.0):
    # create the src grid pipeline
    srcN0, srcN1 = srcLats.shape
    srcNumPts = srcN0 * srcN1
    srcSg = vtk.vtkStructuredGrid()
    srcPt = vtk.vtkPoints()
    srcPt.SetNumberOfPoints(srcNumPts)
    k = 0
    for i1 in range(srcN1):
        for i0 in range(srcN0):
            r = radius * 1.05
            x = r * math.cos(srcLats[i0, i1] * math.pi / 180.) * math.cos(
                srcLons[i0, i1] * math.pi / 180.)
            y = r * math.cos(srcLats[i0, i1] * math.pi / 180.) * math.sin(
                srcLons[i0, i1] * math.pi / 180.)
            z = r * math.sin(srcLats[i0, i1] * math.pi / 180.)
            srcPt.SetPoint(k, x, y, z)
            k += 1
    srcSg.SetDimensions(1, srcN0, srcN1)
    srcSg.SetPoints(srcPt)

    srcEd = vtk.vtkExtractEdges()
    srcEt = vtk.vtkTubeFilter()
    srcEm = vtk.vtkPolyDataMapper()
    srcEa = vtk.vtkActor()
    srcEt.SetRadius(0.005)
    srcEd.SetInputData(srcSg)
    srcEt.SetInputConnection(srcEd.GetOutputPort())
    srcEm.SetInputConnection(srcEt.GetOutputPort())
    srcEa.SetMapper(srcEm)
    srcEa.GetProperty().SetColor(0., 1., 0.)
    #srcEa.GetProperty().SetOpacity(0.5)

    dstN0, dstN1 = dstLats.shape
    numPoints = dstN0 * dstN1
    sg = vtk.vtkStructuredGrid()
    pt = vtk.vtkPoints()
    pt.SetNumberOfPoints(numPoints)

    ar = vtk.vtkDoubleArray()
    numPts = nitersData.shape[0] * nitersData.shape[1]
    ar.SetNumberOfComponents(1)
    ar.SetNumberOfTuples(numPts)
    #ar.SetVoidArray(nitersData, 1, 1)

    k = 0
    for i1 in range(dstN1):
        for i0 in range(dstN0):
            elev = 0.0  #0.10 * math.log10(nitersData[i0, i1])
            r = radius * (1. + elev)
            x = r * math.cos(dstLats[i0, i1] * math.pi / 180.) * math.cos(
                dstLons[i0, i1] * math.pi / 180.)
            y = r * math.cos(dstLats[i0, i1] * math.pi / 180.) * math.sin(
                dstLons[i0, i1] * math.pi / 180.)
            z = r * math.sin(dstLats[i0, i1] * math.pi / 180.)
            pt.SetPoint(k, x, y, z)
            ar.SetTuple(k, (float(nitersData[i0, i1]), ))
            k += 1

    sg = vtk.vtkStructuredGrid()
    sg.SetDimensions(1, dstN0, dstN1)
    sg.SetPoints(pt)
    sg.GetPointData().SetScalars(ar)

    lu = vtk.vtkLookupTable()
    lu.SetScaleToLog10()
    #lu.SetTableRange(1, 10)
    lu.SetNumberOfColors(256)
    lu.SetHueRange(0.666, 0.)
    lu.Build()

    # add a scalar bar
    sb = vtk.vtkScalarBarActor()
    sb.SetLookupTable(lu)
    sb.SetTitle("Number of iters")
    sb.SetNumberOfLabels(4)

    # show the dst grid
    dstEd = vtk.vtkExtractEdges()
    dstEt = vtk.vtkTubeFilter()
    dstEm = vtk.vtkPolyDataMapper()
    dstEa = vtk.vtkActor()
    dstEt.SetRadius(0.005)
    dstEd.SetInputData(sg)
    dstEt.SetInputConnection(dstEd.GetOutputPort())
    dstEm.SetInputConnection(dstEt.GetOutputPort())
    dstEa.SetMapper(dstEm)
    dstEa.GetProperty().SetColor(1., 0., 0.)
    #dstEa.GetProperty().SetOpacity(0.5)

    # show number of iterations as a color plot
    mp = vtk.vtkDataSetMapper()
    mp.SetInputData(sg)
    mp.SetLookupTable(lu)
    mp.SetScalarRange(1, args.nitermax)
    ac = vtk.vtkActor()
    ac.SetMapper(mp)
    return {
        'actors': [
            ac,
            sb,
        ],
        'stuff': (sg, pt, mp, ar, lu, srcSg, srcPt, srcEd, srcEt, srcEm, dstEd,
                  dstEt, dstEm)
    }
Ejemplo n.º 38
0
model.SetMapper(dataMapper)
model.GetProperty().SetColor(1, 0, 0)

obb = vtk.vtkOBBTree()
obb.SetMaxLevel(10)
obb.SetNumberOfCellsPerNode(5)
obb.AutomaticOff()

boxes = vtk.vtkSpatialRepresentationFilter()
boxes.SetInputConnection(transPD.GetOutputPort())
boxes.SetSpatialRepresentation(obb)
boxes.SetGenerateLeaves(1)
boxes.Update()

output = boxes.GetOutput().GetBlock(boxes.GetMaximumLevel() + 1)
boxEdges = vtk.vtkExtractEdges()
boxEdges.SetInputData(output)

boxMapper = vtk.vtkPolyDataMapper()
boxMapper.SetInputConnection(boxEdges.GetOutputPort())
boxMapper.SetResolveCoincidentTopology(1)

boxActor = vtk.vtkActor()
boxActor.SetMapper(boxMapper)
boxActor.GetProperty().SetAmbient(1)
boxActor.GetProperty().SetDiffuse(0)
boxActor.GetProperty().SetRepresentationToWireframe()

ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
Ejemplo n.º 39
0
        kq_visible_only = vtk.vtkSelectVisiblePoints()
        kq_visible_only.SetRenderer(ren)
        kq_visible_only.SetInputConnection(kq_cell_centers.GetOutputPort())
        kq_labels = vtk.vtkLabeledDataMapper()
        kq_labels.SetInputConnection(kq_visible_only.GetOutputPort())
        kq_labels.SetLabelModeToLabelScalars()
        kq_labels.SetLabelFormat("%.0f")
        kq_labels.GetLabelTextProperty().SetJustificationToCentered()
        kq_labels.GetLabelTextProperty().SetVerticalJustificationToCentered()
        kq_labels_actor = vtk.vtkActor2D()
        kq_labels_actor.SetMapper(kq_labels)
        ren.AddActor(kq_labels_actor)

draw_edges = True
if draw_edges:
    lines = vtk.vtkExtractEdges()
    if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
        lines.SetInputData(edges)
    else:
        lines.SetInput(edges)
    tube = vtk.vtkTubeFilter()
    tube.SetInputConnection(lines.GetOutputPort())
    tube.SetRadius(0.005)
    tube.SetNumberOfSides(20)

    sphere = vtk.vtkSphereSource()
    sphere.SetRadius(0.005)
    sphere.SetPhiResolution(20)
    sphere.SetThetaResolution(20)
    vertices = vtk.vtkGlyph3D()
    if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
Ejemplo n.º 40
0
def render_demo():

    # Step 1. Data Source
    #   Create a sphere geometry
    sphere_src = vtk.vtkSphereSource()
    sphere_src.SetRadius(1.0)
    sphere_src.SetCenter(0.0, 0.0, 0.0)
    #   In reality, vtkSphereSource creates a polygonal approximation (a
    # triangulation) of a sphere. Set the resolution.
    sphere_src.SetThetaResolution(20)
    sphere_src.SetPhiResolution(20)

    # Step 2. Data Processing
    #   We will visualize the edges of the sphere that we just created. For
    #   that, we must first extract the edges from the sphere triangulation.
    #   VTK makes that easy.
    edge_extractor = vtk.vtkExtractEdges()
    #   Create a pipeline link between sphere source and edge extractor
    edge_extractor.SetInputConnection(sphere_src.GetOutputPort())
    #   Now our edge extractor acts as a second data source: it supplies the
    #   geometry of the edges of the sphere

    # Step 3. Mappers
    #   Create a set of graphical primitives to represent the sphere
    sphere_mapper = vtk.vtkPolyDataMapper()
    #   Create a pipeline link between sphere source and mapper
    sphere_mapper.SetInputConnection(sphere_src.GetOutputPort())
    #   Similarly, create a mapper for the edges of the sphere
    edge_mapper = vtk.vtkPolyDataMapper()
    edge_mapper.SetInputConnection(edge_extractor.GetOutputPort())

    # Step 4. Actors
    #   Insert the graphical primitives into the scene to be rendered
    sphere_actor = vtk.vtkActor()
    #   Assign sphere mapper to actor
    sphere_actor.SetMapper(sphere_mapper)
    #   The actor now controls the graphical properties of the sphere. We can
    #   access them to change the color of the sphere. The color is set in RGB
    #   mode using values from 0 to 1 for each of the three color channels.
    #   Here we set the color to orange.
    sphere_actor.GetProperty().SetColor(1, 0.5, 0)
    #   Same thing for the edges of the sphere
    edge_actor = vtk.vtkActor()
    edge_actor.SetMapper(edge_mapper)
    #   We want our edges to be drawn in dark green
    edge_actor.GetProperty().SetColor(0, 0.5, 0)
    #   We also want them to be shown as thick lines
    edge_actor.GetProperty().SetLineWidth(3)

    # Step 5. Renderer
    #   Render the scene to form an image that can be displayed
    my_renderer = vtk.vtkRenderer()
    #   Add all our actors to the renderer
    my_renderer.AddActor(sphere_actor)
    my_renderer.AddActor(edge_actor)
    my_renderer.SetBackground(0.1, 0.2, 0.4)

    # Step 6. Render Window
    #   Provides a window in which the rendered image can be displayed on the
    #   screen
    my_window = vtk.vtkRenderWindow()
    my_window.AddRenderer(my_renderer)
    #   The window size controls the resolution of the final image
    my_window.SetSize(600, 600)

    # Step 7. Interactor
    #   Create an interactor: the user will be able to control the
    #   visualization through mouse and keyboard interaction
    my_interactor = vtk.vtkRenderWindowInteractor()
    my_interactor.SetRenderWindow(my_window)
    #   IMPORTANT NOTE: always initialize the interactor before doing the
    #   rendering!
    my_interactor.Initialize()

    # Step 8. Actual Rendering
    #   Draw something on the screen (finally!)
    my_window.Render()

    # Step 9. Interaction Starts
    #   We are done: entering the interaction loop. The user is in charge
    my_interactor.Start()
Ejemplo n.º 41
0
    def Execute(self):

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

        if (self.Surface.GetPointData().GetArray(self.SurfaceArrayName) == None):
            self.PrintError('Error: no array with name specified')
        else:
            array = self.Surface.GetPointData().GetArray(self.SurfaceArrayName)

        surface = self.Surface
        extractEdges = vtk.vtkExtractEdges()
        extractEdges.SetInput(surface)
        extractEdges.Update()
        surfEdges = extractEdges.GetOutput()

        if self.Connexity == 1:
            for n in range (self.Iterations):
                for i in range (surfEdges.GetNumberOfPoints()):
                    cells = vtk.vtkIdList()
                    surfEdges.GetPointCells(i,cells)
                    vval = 0
                    ddd = 0
                    d = 0
                    N = 0
                    for j in range (cells.GetNumberOfIds()):
                        points = vtk.vtkIdList()
                        surfEdges.GetCellPoints(cells.GetId(j),points)
                        for k in range (points.GetNumberOfIds()):
                            if points.GetId(k) != i:
                                d = math.sqrt(vtk.vtkMath.Distance2BetweenPoints(surface.GetPoint(i),surface.GetPoint(points.GetId(k))))
                                dd = 1/d
                                val = array.GetComponent(points.GetId(k),0)#*dd
                                N = N+1
                                vval = vval + val
                                ddd = ddd + dd
                    val = array.GetComponent(i,0)
                    vval = vval / (N)
                    newval = self.Relaxation * vval + (1 - self.Relaxation) * val
                    array.SetTuple1(i,newval)
        elif self.Connexity == 2:
            for n in range (self.Iterations):
                for i in range (surfEdges.GetNumberOfPoints()):
                    cells = vtk.vtkIdList()
                    surfEdges.GetPointCells(i,cells)
                    pointlist = vtk.vtkIdList()
                    vval = 0
                    ddd = 0
                    d = 0
                    N = 0
                    for j in range (cells.GetNumberOfIds()):
                        points = vtk.vtkIdList()
                        surfEdges.GetCellPoints(cells.GetId(j),points)
                        for k in range (points.GetNumberOfIds()):
                            if points.GetId(k) != i:
                                pointlist.InsertUniqueId(points.GetId(k))
                                cells2 = vtk.vtkIdList()
                                surfEdges.GetPointCells(i,cells2)
                                for p in range (cells2.GetNumberOfIds()):
                                    points2 = vtk.vtkIdList()
                                    surfEdges.GetCellPoints(cells2.GetId(j),points2)
                                    for q in range (points2.GetNumberOfIds()):
                                        if points2.GetId(k) != i:
                                            pointlist.InsertUniqueId(points2.GetId(k))
                    N = pointlist.GetNumberOfIds()
                    for j in range (pointlist.GetNumberOfIds()):
                        d = math.sqrt(vtk.vtkMath.Distance2BetweenPoints(surface.GetPoint(i),surface.GetPoint(pointlist.GetId(j))))
                        dd = 1/d
                        val = array.GetComponent(pointlist.GetId(j),0)
                        vval = vval + val
                        ddd = ddd + dd
                    val = array.GetComponent(i,0)
                    vval = vval / (N)
                    newval = self.Relaxation * vval + (1 - self.Relaxation) * val
                    array.SetTuple1(i,newval)
        else:
            self.PrintError ('Error: wrong connexity')

        self.Surface = surface
Ejemplo n.º 42
0
    def _plotInternal(self):

        prepedContours = self._prepContours()
        tmpLevels = prepedContours["tmpLevels"]
        tmpIndices = prepedContours["tmpIndices"]
        tmpColors = prepedContours["tmpColors"]
        tmpOpacities = prepedContours["tmpOpacities"]

        style = self._gm.fillareastyle
        fareapixelspacing, fareapixelscale = self._patternSpacingAndScale()

        mappers = []
        luts = []
        geos = []
        wholeDataMin, wholeDataMax = vcs.minmax(self._data1)
        plotting_dataset_bounds = self.getPlottingBounds()
        x1, x2, y1, y2 = plotting_dataset_bounds
        # We need to do the convertion thing
        _convert = self._gm.yaxisconvert
        _func = vcs.utils.axisConvertFunctions[_convert]["forward"]
        y1 = _func(y1)
        y2 = _func(y2)
        _convert = self._gm.xaxisconvert
        _func = vcs.utils.axisConvertFunctions[_convert]["forward"]
        x1 = _func(x1)
        x2 = _func(x2)
        _colorMap = self.getColorMap()
        for i, l in enumerate(tmpLevels):
            # Ok here we are trying to group together levels can be, a join
            # will happen if: next set of levels contnues where one left off
            # AND pattern is identical
            # TODO this should really just be a single polydata that is
            # colored by scalars:
            for j, color in enumerate(tmpColors[i]):
                mapper = vtk.vtkPolyDataMapper()
                lut = vtk.vtkLookupTable()
                th = vtk.vtkThreshold()
                th.ThresholdBetween(l[j], l[j + 1])
                # th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
                th.SetInputData(self._vtkDataSetFittedToViewport)
                geoFilter2 = vtk.vtkDataSetSurfaceFilter()
                geoFilter2.SetInputConnection(th.GetOutputPort())
                # Make the polydata output available here for patterning later
                geoFilter2.Update()
                geos.append(geoFilter2)
                mapper.SetInputConnection(geoFilter2.GetOutputPort())
                lut.SetNumberOfTableValues(1)
                r, g, b, a = self.getColorIndexOrRGBA(_colorMap, color)
                if style == 'solid':
                    tmpOpacity = tmpOpacities[j]
                    if tmpOpacity is None:
                        tmpOpacity = a / 100.
                    else:
                        tmpOpacity = tmpOpacities[j] / 100.
                    lut.SetTableValue(0, r / 100., g / 100., b / 100.,
                                      tmpOpacity)
                else:
                    lut.SetTableValue(0, 1., 1., 1., 0.)
                mapper.SetLookupTable(lut)
                mapper.SetScalarRange(l[j], l[j + 1])
                luts.append([lut, [l[j], l[j + 1], True]])
                # Store the mapper only if it's worth it?
                # Need to do it with the whole slab min/max for animation
                # purposes
                if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax):
                    mappers.append(mapper)

        self._resultDict["vtk_backend_luts"] = luts
        if len(geos) > 0:
            self._resultDict["vtk_backend_geofilters"] = geos

        if self._maskedDataMapper is not None:
            # Note that this is different for meshfill -- others prepend.
            mappers.append(self._maskedDataMapper)

        wireColor = [0, 0, 0, 255]

        # Add a second mapper for wireframe meshfill:
        if self._gm.mesh:
            lineMappers = []
            for polyMapper in mappers:
                edgeFilter = vtk.vtkExtractEdges()
                edgeFilter.SetInputConnection(
                    polyMapper.GetInputConnection(0, 0))

                lineMapper = vtk.vtkPolyDataMapper()
                lineMapper.SetInputConnection(edgeFilter.GetOutputPort(0))

                lineMapper._useWireFrame = True

                lineMappers.append(lineMapper)
            mappers.extend(lineMappers)

        # And now we need actors to actually render this thing
        actors = []
        vp = self._resultDict.get('ratio_autot_viewport', [
            self._template.data.x1, self._template.data.x2,
            self._template.data.y1, self._template.data.y2
        ])
        cti = 0
        ctj = 0

        # view and interactive area
        view = self._context().contextView
        area = vtk.vtkInteractiveArea()
        view.GetScene().AddItem(area)

        adjusted_plotting_bounds = vcs2vtk.getProjectedBoundsForWorldCoords(
            plotting_dataset_bounds, self._gm.projection)
        drawAreaBounds = vcs2vtk.computeDrawAreaBounds(
            adjusted_plotting_bounds)

        [renWinWidth, renWinHeight] = self._context().renWin.GetSize()
        geom = vtk.vtkRecti(int(round(vp[0] * renWinWidth)),
                            int(round(vp[2] * renWinHeight)),
                            int(round((vp[1] - vp[0]) * renWinWidth)),
                            int(round((vp[3] - vp[2]) * renWinHeight)))

        vcs2vtk.configureContextArea(area, drawAreaBounds, geom)

        for mapper in mappers:
            act = vtk.vtkActor()
            act.SetMapper(mapper)
            mapper.Update()
            poly = mapper.GetInput()

            item = None

            wireframe = False
            if hasattr(mapper, "_useWireFrame"):
                wireframe = True

            if wireframe:
                item = vtk.vtkPolyDataItem()
                item.SetPolyData(poly)

                colorArray = vtk.vtkUnsignedCharArray()
                colorArray.SetNumberOfComponents(4)
                for i in range(poly.GetNumberOfCells()):
                    colorArray.InsertNextTypedTuple(wireColor)

                item.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_CELL_DATA)
                item.SetMappedColors(colorArray)
                area.GetDrawAreaItem().AddItem(item)
            elif style == "solid":
                if self._needsCellData:
                    attrs = poly.GetCellData()
                else:
                    attrs = poly.GetPointData()

                data = attrs.GetScalars()
                deleteColors = False

                if data:
                    lut = mapper.GetLookupTable()
                    scalarRange = mapper.GetScalarRange()
                    lut.SetRange(scalarRange)
                    mappedColors = lut.MapScalars(data,
                                                  vtk.VTK_COLOR_MODE_DEFAULT,
                                                  0)
                    deleteColors = True
                else:
                    loc = 'point'
                    numTuples = poly.GetNumberOfPoints()
                    if self._needsCellData:
                        loc = 'cell'
                        numTuples = poly.GetNumberOfCells()
                    msg = 'WARNING: meshfill pipeline: poly does not have Scalars '
                    msg = msg + 'array on {0} data, using solid color'.format(
                        loc)
                    print(msg)
                    color = [0, 0, 0, 255]
                    mappedColors = vcs2vtk.generateSolidColorArray(
                        numTuples, color)

                mappedColors.SetName('Colors')

                item = vtk.vtkPolyDataItem()
                item.SetPolyData(poly)

                if self._needsCellData:
                    item.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_CELL_DATA)
                else:
                    item.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_POINT_DATA)

                item.SetMappedColors(mappedColors)
                if deleteColors:
                    mappedColors.FastDelete()
                area.GetDrawAreaItem().AddItem(item)

            # TODO See comment in boxfill.
            if item is not None:
                if mapper is self._maskedDataMapper:
                    actors.append([
                        item, self._maskedDataMapper, plotting_dataset_bounds
                    ])
                else:
                    actors.append([item, plotting_dataset_bounds])

            if mapper is not self._maskedDataMapper:

                if not wireframe:
                    # Since pattern creation requires a single color, assuming the
                    # first
                    if ctj >= len(tmpColors[cti]):
                        ctj = 0
                        cti += 1
                    c = self.getColorIndexOrRGBA(_colorMap,
                                                 tmpColors[cti][ctj])

                    patact = fillareautils.make_patterned_polydata(
                        poly,
                        fillareastyle=style,
                        fillareaindex=tmpIndices[cti],
                        fillareacolors=c,
                        fillareaopacity=tmpOpacities[cti],
                        fillareapixelspacing=fareapixelspacing,
                        fillareapixelscale=fareapixelscale,
                        size=self._context().renWin.GetSize(),
                        screenGeom=self._context().renWin.GetSize())
                    ctj += 1

                    if patact is not None:
                        actors.append([patact, plotting_dataset_bounds])

                        patMapper = patact.GetMapper()
                        patMapper.Update()
                        patPoly = patMapper.GetInput()

                        patItem = vtk.vtkPolyDataItem()
                        patItem.SetPolyData(patPoly)

                        patItem.SetScalarMode(
                            vtk.VTK_SCALAR_MODE_USE_CELL_DATA)
                        colorArray = patPoly.GetCellData().GetArray('Colors')

                        patItem.SetMappedColors(colorArray)
                        area.GetDrawAreaItem().AddItem(patItem)

                        actors.append([patItem, plotting_dataset_bounds])

        z, t = self.getZandT()

        self._resultDict["vtk_backend_actors"] = actors
        kwargs = {
            "vtk_backend_grid":
            self._vtkDataSet,
            "dataset_bounds":
            self._vtkDataSetBounds,
            "plotting_dataset_bounds":
            plotting_dataset_bounds,
            "vtk_dataset_bounds_no_mask":
            self._vtkDataSetBoundsNoMask,
            "vtk_backend_geo":
            self._vtkGeoTransform,
            "vtk_backend_draw_area_bounds":
            drawAreaBounds,
            "vtk_backend_viewport_scale":
            [self._context_xScale, self._context_yScale]
        }
        if ("ratio_autot_viewport" in self._resultDict):
            kwargs["ratio_autot_viewport"] = vp
        self._resultDict.update(self._context().renderTemplate(
            self._template,
            self._data1,
            self._gm,
            t,
            z,
            X=numpy.arange(min(x1, x2),
                           max(x1, x2) * 1.1,
                           abs(x2 - x1) / 10.),
            Y=numpy.arange(min(y1, y2),
                           max(y1, y2) * 1.1,
                           abs(y2 - y1) / 10.),
            **kwargs))

        legend = getattr(self._gm, "legend", None)

        if self._gm.ext_1:
            if isinstance(self._contourLevels[0], list):
                if numpy.less(abs(self._contourLevels[0][0]), 1.e20):
                    # Ok we need to add the ext levels
                    self._contourLevels.insert(
                        0, [-1.e20, self._contourLevels[0][0]])
            else:
                if numpy.less(abs(self._contourLevels[0]), 1.e20):
                    # need to add an ext
                    self._contourLevels.insert(0, -1.e20)
        if self._gm.ext_2:
            if isinstance(self._contourLevels[-1], list):
                if numpy.less(abs(self._contourLevels[-1][1]), 1.e20):
                    # need ext
                    self._contourLevels.append(
                        [self._contourLevels[-1][1], 1.e20])
            else:
                if numpy.less(abs(self._contourLevels[-1]), 1.e20):
                    # need exts
                    self._contourLevels.append(1.e20)

        patternArgs = {}
        patternArgs['style'] = self._gm.fillareastyle
        patternArgs['index'] = self._gm.fillareaindices
        if patternArgs['index'] is None:
            patternArgs['index'] = [
                1,
            ]
        # Compensate for the different viewport size of the colorbar
        patternArgs['opacity'] = self._gm.fillareaopacity
        patternArgs['pixelspacing'] = [
            int(fareapixelspacing[0] / (vp[1] - vp[0])),
            int(fareapixelspacing[1] / (vp[3] - vp[2]))
        ]
        patternArgs['pixelscale'] = fareapixelscale / (vp[1] - vp[0])
        self._resultDict.update(self._context().renderColorBar(
            self._template, self._contourLevels, self._contourColors, legend,
            self.getColorMap(), **patternArgs))

        projection = vcs.elements["projection"][self._gm.projection]
        kwargs['xaxisconvert'] = self._gm.xaxisconvert
        kwargs['yaxisconvert'] = self._gm.yaxisconvert
        self._context().plotContinents(
            self._plot_kargs.get("continents", self._useContinents),
            plotting_dataset_bounds, projection, self._dataWrapModulo, vp,
            self._template.data.priority, **kwargs)
Ejemplo n.º 43
0
def main(filename):
    print("Loading", filename)
    reader = vtk.vtkUnstructuredGridReader()
    reader.SetFileName(filename)

    edges = vtk.vtkExtractEdges()
    edges.SetInputConnection(reader.GetOutputPort())

    tubes = vtk.vtkTubeFilter()
    tubes.SetInputConnection(edges.GetOutputPort())
    tubes.SetRadius(0.0625)
    tubes.SetVaryRadiusToVaryRadiusOff()
    tubes.SetNumberOfSides(32)

    tubesMapper = vtk.vtkPolyDataMapper()
    tubesMapper.SetInputConnection(tubes.GetOutputPort())
    tubesMapper.SetScalarRange(0.0, 26.0)

    tubesActor = vtk.vtkActor()
    tubesActor.SetMapper(tubesMapper)

    gradients = vtk.vtkGradientFilter()
    gradients.SetInputConnection(reader.GetOutputPort())

    vectors = vtk.vtkAssignAttribute()
    vectors.SetInputConnection(gradients.GetOutputPort())
    vectors.Assign("Gradients", vtk.vtkDataSetAttributes.VECTORS, \
        vtk.vtkAssignAttribute.POINT_DATA)

    arrow = vtk.vtkArrowSource()

    glyphs = vtk.vtkGlyph3D()
    glyphs.SetInputConnection(0, vectors.GetOutputPort())
    glyphs.SetInputConnection(1, arrow.GetOutputPort())
    glyphs.ScalingOn()
    glyphs.SetScaleModeToScaleByVector()
    glyphs.SetScaleFactor(0.25)
    glyphs.OrientOn()
    glyphs.ClampingOff()
    glyphs.SetVectorModeToUseVector()
    glyphs.SetIndexModeToOff()

    glyphMapper = vtk.vtkPolyDataMapper()
    glyphMapper.SetInputConnection(glyphs.GetOutputPort())
    glyphMapper.ScalarVisibilityOff()

    glyphActor = vtk.vtkActor()
    glyphActor.SetMapper(glyphMapper)

    renderer = vtk.vtkRenderer()
    renderer.AddActor(tubesActor)
    renderer.AddActor(glyphActor)
    renderer.SetBackground(0.328125, 0.347656, 0.425781)

    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(renderer)
    renwin.SetSize(350, 500)

    renderer.ResetCamera()
    camera = renderer.GetActiveCamera()
    camera.Elevation(-80.0)
    camera.OrthogonalizeViewUp()
    camera.Azimuth(135.0)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renwin)
    iren.Initialize()
    iren.Start()
    return 1
Ejemplo n.º 44
0
# Append the quadratic cells together
appendF = vtk.vtkAppendFilter()
appendF.AddInputData(BQuadGrid)
appendF.AddInputData(QLQuadGrid)
appendF.AddInputData(QLWedgeGrid)
appendF.AddInputData(aTriGrid)
appendF.AddInputData(aQuadGrid)
appendF.AddInputData(aTetGrid)
appendF.AddInputData(aHexGrid)
appendF.AddInputData(TQHexGrid)
appendF.AddInputData(BQHexGrid)
appendF.AddInputData(aWedgeGrid)
appendF.AddInputData(aPyraGrid)
appendF.AddInputData(BQWedgeGrid)
# Extract the edges
extract = vtk.vtkExtractEdges()
extract.SetInputConnection(appendF.GetOutputPort())
shrink = vtk.vtkShrinkPolyData()
shrink.SetInputConnection(extract.GetOutputPort())
shrink.SetShrinkFactor(0.90)
aMapper = vtk.vtkDataSetMapper()
aMapper.SetInputConnection(shrink.GetOutputPort())
#aMapper ScalarVisibilityOff
aActor = vtk.vtkActor()
aActor.SetMapper(aMapper)
aActor.GetProperty().SetRepresentationToWireframe()
# Create the rendering related stuff.
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
Ejemplo n.º 45
0
Ids.InsertNextId(1)
Ids.InsertNextId(2)
Ids.InsertNextId(3)
Ids.InsertNextId(4)
Grid = vtk.vtkUnstructuredGrid()
Grid.Allocate(10,10)
Grid.InsertNextCell(14,Ids)
Grid.SetPoints(Points)
Grid.GetPointData().SetScalars(Scalars)
#Clip the pyramid
clipper = vtk.vtkClipDataSet()
clipper.SetInputData(Grid)
clipper.SetValue(0.5)
# build tubes for the triangle edges
#
pyrEdges = vtk.vtkExtractEdges()
pyrEdges.SetInputConnection(clipper.GetOutputPort())
pyrEdgeTubes = vtk.vtkTubeFilter()
pyrEdgeTubes.SetInputConnection(pyrEdges.GetOutputPort())
pyrEdgeTubes.SetRadius(.005)
pyrEdgeTubes.SetNumberOfSides(6)
pyrEdgeMapper = vtk.vtkPolyDataMapper()
pyrEdgeMapper.SetInputConnection(pyrEdgeTubes.GetOutputPort())
pyrEdgeMapper.ScalarVisibilityOff()
pyrEdgeActor = vtk.vtkActor()
pyrEdgeActor.SetMapper(pyrEdgeMapper)
pyrEdgeActor.GetProperty().SetDiffuseColor(lamp_black)
pyrEdgeActor.GetProperty().SetSpecular(.4)
pyrEdgeActor.GetProperty().SetSpecularPower(10)
#shrink the triangles so we can see each one
aShrinker = vtk.vtkShrinkFilter()
Ejemplo n.º 46
0
    def serveVTKGeoJSON(self, datasetString):
        '''
        Deliver a geojson encoded serialized vtkpolydata file and render it
        over the canonical cpipe scene.
        '''

        if vtkOK == False:
            return """<html><head></head><body>VTK python bindings are not loadable, be sure VTK is installed on the server and its PATHS are set appropriately.</body><html>"""

        ss = vtk.vtkNetCDFCFReader() #get test data
        ss.SphericalCoordinatesOff()
        ss.SetOutputTypeToImage()
        datadir = cherrypy.request.app.config['/data']['tools.staticdir.dir']
        datadir = os.path.join(datadir, 'assets')
        datafile = os.path.join(datadir, 'clt.nc')
        ss.SetFileName(datafile)

        sf = vtk.vtkDataSetSurfaceFilter() #convert to polydata
        sf.SetInputConnection(ss.GetOutputPort())

        cf = vtk.vtkContourFilter() #add some attributes
        cf.SetInputConnection(sf.GetOutputPort())
        cf.SetInputArrayToProcess(0,0,0,"vtkDataObject::FIELD_ASSOCIATION_POINTS", "clt")
        cf.SetNumberOfContours(10)
        sf.Update()
        drange = sf.GetOutput().GetPointData().GetArray(0).GetRange()
        for x in range(0,10):
          cf.SetValue(x,x*0.1*(drange[1]-drange[0])+drange[0])
        cf.ComputeScalarsOn()

        ef = vtk.vtkExtractEdges() #make lines to test
        ef.SetInputConnection(sf.GetOutputPort())

        gf = vtk.vtkGlyph3D() #make verts to test
        pts = vtk.vtkPoints()
        pts.InsertNextPoint(0,0,0)
        verts = vtk.vtkCellArray()
        avert = vtk.vtkVertex()
        avert.GetPointIds().SetId(0, 0)
        verts.InsertNextCell(avert)
        onevertglyph = vtk.vtkPolyData()
        onevertglyph.SetPoints(pts)
        onevertglyph.SetVerts(verts)
        gf.SetSourceData(onevertglyph)
        gf.SetInputConnection(sf.GetOutputPort())

        if datasetString == "points":
            toshow = gf
        elif datasetString == "lines":
            toshow = ef
        elif datasetString == "contour":
            toshow = cf
        else:
            toshow = sf
        gw = vtk.vtkGeoJSONWriter()
        gw.SetInputConnection(toshow.GetOutputPort())
        gw.SetScalarFormat(2);
        if True:
            gw.SetFileName("/Source/CPIPES/buildogs/deploy/dataset.gj")
            gw.Write()
            f = file("/Source/CPIPES/buildogs/deploy/dataset.gj")
            gj = str(f.readlines())
        else:
            gw.WriteToOutputStringOn()
            gw.Write()
            gj = "['"+str(gw.RegisterAndGetOutputString()).replace('\n','')+"']"

        res = ("""
  <html>
    <head>
      <script type="text/javascript" src="/common/js/gl-matrix.js"></script>
      <script type="text/javascript" src="/lib/geoweb.min.js"></script>
      <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
      <script type="text/javascript">
      function makedata() {
        var datasetString = %(gjfile)s.join('\\n');

        var data = new ogs.vgl.geojsonReader().getPrimitives(datasetString);
        var geoms = data.geoms;

        var mapper = new ogs.vgl.mapper();
        mapper.setGeometryData(geoms[0]);
        """ +
        self.gjShader +
        """
        var actor = new ogs.vgl.actor();
        actor.setMapper(mapper);
        actor.setMaterial(mat);
        return actor;
      }
      </script>
      <script type="text/javascript">
      function main() {
        var mapOptions = {
          zoom : 1,
          center : ogs.geo.latlng(0.0, 0.0),
          source : '/data/assets/land_shallow_topo_2048.png'
        };
        var myMap = ogs.geo.map(document.getElementById("glcanvas"), mapOptions);

        var planeLayer = ogs.geo.featureLayer({
          "opacity" : 1,
          "showAttribution" : 1,
          "visible" : 1
         },
         makedata()
         );
        myMap.addLayer(planeLayer);
      }
      </script>

      <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
      <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
      <script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
    </head>
    <body onload="main()">
      <canvas id="glcanvas" width="800" height="600"></canvas>
    </body>
  </html>
""") % {'gjfile' :gj}

        return res
Ejemplo n.º 47
0
from __future__ import print_function

import vtk, os, sys
from vtk.test import Testing

ss = vtk.vtkSphereSource()  #make mesh to test with

af = vtk.vtkElevationFilter()  #add some attributes
af.SetInputConnection(ss.GetOutputPort())

ef = vtk.vtkExtractEdges()  #make lines to test
ef.SetInputConnection(af.GetOutputPort())

gf = vtk.vtkGlyph3D()  #make verts to test
pts = vtk.vtkPoints()
pts.InsertNextPoint(0, 0, 0)
verts = vtk.vtkCellArray()
avert = vtk.vtkVertex()
avert.GetPointIds().SetId(0, 0)
verts.InsertNextCell(avert)
onevertglyph = vtk.vtkPolyData()
onevertglyph.SetPoints(pts)
onevertglyph.SetVerts(verts)
gf.SetSourceData(onevertglyph)
gf.SetInputConnection(af.GetOutputPort())

testwrites = ["points", "lines", "mesh"]
failed = False
for datasetString in testwrites:
    if datasetString == "points":
        toshow = gf
Ejemplo n.º 48
0
Ids.InsertNextId(7)

Grid = vtk.vtkUnstructuredGrid()
Grid.Allocate(10, 10)
Grid.InsertNextCell(12, Ids)
Grid.SetPoints(Points)
Grid.GetPointData().SetScalars(Scalars)

# Find the triangles that lie along the 0.5 contour in this cube.
Marching = vtk.vtkContourFilter()
Marching.SetInput(Grid)
Marching.SetValue(0, 0.5)
Marching.Update()

# Extract the edges of the triangles just found.
triangleEdges = vtk.vtkExtractEdges()
triangleEdges.SetInputConnection(Marching.GetOutputPort())
# Draw the edges as tubes instead of lines.  Also create the associated
# mapper and actor to display the tubes.
triangleEdgeTubes = vtk.vtkTubeFilter()
triangleEdgeTubes.SetInputConnection(triangleEdges.GetOutputPort())
triangleEdgeTubes.SetRadius(.005)
triangleEdgeTubes.SetNumberOfSides(6)
triangleEdgeTubes.UseDefaultNormalOn()
triangleEdgeTubes.SetDefaultNormal(.577, .577, .577)
triangleEdgeMapper = vtk.vtkPolyDataMapper()
triangleEdgeMapper.SetInputConnection(triangleEdgeTubes.GetOutputPort())
triangleEdgeMapper.ScalarVisibilityOff()
triangleEdgeActor = vtk.vtkActor()
triangleEdgeActor.SetMapper(triangleEdgeMapper)
triangleEdgeActor.GetProperty().SetDiffuseColor(lamp_black)
Ejemplo n.º 49
0
    def render(self, pointsData, scalarsArray, radiusArray, nspecies,
               colouringOptions, atomScaleFactor, lut):
        """
        Render the given antisites (wire frame).
        
        """
        self._logger.debug("Rendering antisites: colour by '%s'",
                           colouringOptions.colourBy)

        # points
        points = vtk.vtkPoints()
        points.SetData(pointsData.getVTK())

        # poly data
        polydata = vtk.vtkPolyData()
        polydata.SetPoints(points)
        polydata.GetPointData().AddArray(scalarsArray.getVTK())
        polydata.GetPointData().SetScalars(radiusArray.getVTK())

        # source
        cubeSource = vtk.vtkCubeSource()
        edges = vtk.vtkExtractEdges()
        edges.SetInputConnection(cubeSource.GetOutputPort())
        glyphSource = vtk.vtkTubeFilter()
        glyphSource.SetInputConnection(edges.GetOutputPort())
        glyphSource.SetRadius(0.05)
        glyphSource.SetVaryRadius(0)
        glyphSource.SetNumberOfSides(5)
        glyphSource.UseDefaultNormalOn()
        glyphSource.SetDefaultNormal(.577, .577, .577)

        # glyph
        glyph = vtk.vtkGlyph3D()
        if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
            glyph.SetSource(glyphSource.GetOutput())
            glyph.SetInput(polydata)
        else:
            glyph.SetSourceConnection(glyphSource.GetOutputPort())
            glyph.SetInputData(polydata)
        glyph.SetScaleFactor(atomScaleFactor * 2.0)
        glyph.SetScaleModeToScaleByScalar()
        glyph.ClampingOff()

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(glyph.GetOutputPort())
        mapper.SetLookupTable(lut)
        mapper.SetScalarModeToUsePointFieldData()
        mapper.SelectColorArray("colours")
        utils.setMapperScalarRange(mapper, colouringOptions, nspecies)

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

        # store attributes
        self._actor = utils.ActorObject(actor)
        self._data["Points"] = pointsData
        self._data["Scalars"] = scalarsArray
        self._data["Radius"] = radiusArray
        self._data["LUT"] = lut
        self._data["Scale factor"] = atomScaleFactor
Ejemplo n.º 50
0
# is also the input to the Delaunay filter. The points of the
# vtkPolyData are used to generate the triangulation; the polygons are
# used to create a constraint region. The polygons are very carefully
# created and ordered in the right direction to indicate inside and
# outside of the polygon.
delny = vtk.vtkDelaunay2D()
delny.SetInputData(polyData)
delny.SetSourceData(polyData)
mapMesh = vtk.vtkPolyDataMapper()
mapMesh.SetInputConnection(delny.GetOutputPort())
meshActor = vtk.vtkActor()
meshActor.SetMapper(mapMesh)

# Now we just pretty the mesh up with tubed edges and balls at the
# vertices.
extract = vtk.vtkExtractEdges()
extract.SetInputConnection(delny.GetOutputPort())
tubes = vtk.vtkTubeFilter()
tubes.SetInputConnection(extract.GetOutputPort())
tubes.SetRadius(0.1)
tubes.SetNumberOfSides(6)
mapEdges = vtk.vtkPolyDataMapper()
mapEdges.SetInputConnection(tubes.GetOutputPort())
edgeActor = vtk.vtkActor()
edgeActor.SetMapper(mapEdges)
edgeActor.GetProperty().SetColor(peacock)
edgeActor.GetProperty().SetSpecularColor(1, 1, 1)
edgeActor.GetProperty().SetSpecular(0.3)
edgeActor.GetProperty().SetSpecularPower(20)
edgeActor.GetProperty().SetAmbient(0.2)
edgeActor.GetProperty().SetDiffuse(0.8)
Ejemplo n.º 51
0
    subdiv.SetNumberOfSubdivisions(4)
    if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
        subdiv.SetInputData(surface)
    else:
        subdiv.SetInput(surface)
    surfaceMapper = vtk.vtkPolyDataMapper()
    surfaceMapper.SetInputConnection(subdiv.GetOutputPort())
    surfaceMapper.SetScalarRange(0, 24)
    surfaceMapper.SetLookupTable(lut)
    surfaceActor = vtk.vtkActor()
    surfaceActor.SetMapper(surfaceMapper)
    ren.AddActor(surfaceActor)

draw_edges = False
if draw_edges:
    lines = vtk.vtkExtractEdges()
    if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
        lines.SetInputData(edges)
    else:
        lines.SetInput(edges)
    tube = vtk.vtkTubeFilter()
    tube.SetInputConnection(lines.GetOutputPort())
    tube.SetRadius(0.005)
    tube.SetNumberOfSides(20)

    sphere = vtk.vtkSphereSource()
    sphere.SetRadius(0.005)
    sphere.SetPhiResolution(20)
    sphere.SetThetaResolution(20)
    vertices = vtk.vtkGlyph3D()
    if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
Ejemplo n.º 52
0
    def populateTopologyDictionary(self):

        # Create vtk objects that will be used to clean the geometries

        firstValue = {
        }  # This will be used for checking consistent, inconsistent topologies

        for nodeName in self.testCaseDict.keys():
            # Topology table is a dictionary of dictionaries.
            self.topologyDict[nodeName] = {}
            self.polyDataDict[nodeName] = {}
            for segmentNum in range(self.labelRangeInCohort[0],
                                    self.labelRangeInCohort[1] + 1):
                # 0 label is assumed to be the background.
                if segmentNum == 0:
                    continue
                segmentId = str(segmentNum)
                polydata = self.segmentationDict[
                    nodeName].GetClosedSurfaceRepresentation(segmentId)
                if polydata == None:
                    print 'Ignoring segment id ' + segmentId + ' for case: ' + nodeName
                    continue

                polydataCleaner = vtk.vtkCleanPolyData()
                connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
                extractEdgeFilter = vtk.vtkExtractEdges()

                # clean up polydata
                polydataCleaner.SetInputData(polydata)
                polydataCleaner.Update()
                cleanData = polydataCleaner.GetOutput()

                # Get the largest connected component
                connectivityFilter.SetInputData(cleanData)
                connectivityFilter.SetExtractionModeToLargestRegion()
                connectivityFilter.SetScalarConnectivity(0)
                connectivityFilter.Update()
                largestComponent = connectivityFilter.GetOutput()

                # Clean the largest component to get rid of spurious points
                polydataCleaner.SetInputData(largestComponent)
                polydataCleaner.Update()
                cleanData = polydataCleaner.GetOutput()

                # run extract edge filter
                extractEdgeFilter.SetInputData(cleanData)
                extractEdgeFilter.Update()
                edges = extractEdgeFilter.GetOutput()

                # calculate the numbers
                topologyNumber = cleanData.GetNumberOfPoints() - edges.GetNumberOfLines()\
                                 + cleanData.GetNumberOfPolys()

                self.topologyDict[nodeName][segmentNum] = topologyNumber
                if self.saveCleanData:
                    self.polyDataDict[nodeName][segmentNum] = cleanData
                else:
                    self.polyDataDict[nodeName][segmentNum] = polydata

                del edges
                del largestComponent
                del cleanData

                # Check for consistency in the cohort for this segment label
                if segmentNum not in self.consistentTopologyDict.keys():
                    self.consistentTopologyDict[segmentNum] = 'Consistent'
                    firstValue[segmentNum] = self.topologyDict[nodeName][
                        segmentNum]
                    # print 'Adding segment num ' + segmentId + ' with top number: ' + str(topologyNumber) + ' For consistencies'
                elif firstValue[segmentNum] != self.topologyDict[nodeName][segmentNum] \
                        and self.consistentTopologyDict[segmentNum] is 'Consistent':
                    self.consistentTopologyDict[segmentNum] = 'InConsistent'
Ejemplo n.º 53
0
Ids.InsertNextId(1)
Ids.InsertNextId(2)
Ids.InsertNextId(3)
Ids.InsertNextId(4)
Grid = vtk.vtkUnstructuredGrid()
Grid.Allocate(10, 10)
Grid.InsertNextCell(14, Ids)
Grid.SetPoints(Points)
Grid.GetPointData().SetScalars(Scalars)
#Clip the pyramid
clipper = vtk.vtkClipDataSet()
clipper.SetInputData(Grid)
clipper.SetValue(0.5)
# build tubes for the triangle edges
#
pyrEdges = vtk.vtkExtractEdges()
pyrEdges.SetInputConnection(clipper.GetOutputPort())
pyrEdgeTubes = vtk.vtkTubeFilter()
pyrEdgeTubes.SetInputConnection(pyrEdges.GetOutputPort())
pyrEdgeTubes.SetRadius(.005)
pyrEdgeTubes.SetNumberOfSides(6)
pyrEdgeMapper = vtk.vtkPolyDataMapper()
pyrEdgeMapper.SetInputConnection(pyrEdgeTubes.GetOutputPort())
pyrEdgeMapper.ScalarVisibilityOff()
pyrEdgeActor = vtk.vtkActor()
pyrEdgeActor.SetMapper(pyrEdgeMapper)
pyrEdgeActor.GetProperty().SetDiffuseColor(lamp_black)
pyrEdgeActor.GetProperty().SetSpecular(.4)
pyrEdgeActor.GetProperty().SetSpecularPower(10)
#shrink the triangles so we can see each one
aShrinker = vtk.vtkShrinkFilter()
Ejemplo n.º 54
0
def test_mesh_elements():
    s = _generate_sphere()

    ee = vtk.vtkExtractEdges()
    ee.SetInputData(s.VTKObject)
    ee.Update()
    ee = wrap_vtk(ee.GetOutput())
    n_edges = ee.n_cells

    assert np.all(me.get_points(s) == s.Points)
    assert np.all(me.get_cells(s) == s.get_cells2D())
    assert me.get_extent(s).shape == (3, )

    pc = me.get_point2cell_connectivity(s)
    assert pc.shape == (s.n_points, s.n_cells)
    assert pc.dtype == np.uint8
    assert np.all(pc.sum(axis=0) == 3)

    cp = me.get_cell2point_connectivity(s)
    assert pc.dtype == np.uint8
    assert (pc - cp.T).nnz == 0

    adj = me.get_immediate_adjacency(s)
    assert adj.shape == (s.n_points, s.n_points)
    assert adj.dtype == np.uint8
    assert adj.nnz == (2 * n_edges + s.n_points)

    adj2 = me.get_immediate_adjacency(s, include_self=False)
    assert adj2.shape == (s.n_points, s.n_points)
    assert adj2.dtype == np.uint8
    assert adj2.nnz == (2 * n_edges)

    radj = me.get_ring_adjacency(s)
    assert radj.dtype == np.uint8
    assert (adj - radj).nnz == 0

    radj2 = me.get_ring_adjacency(s, include_self=False)
    assert radj2.dtype == np.uint8
    assert (adj2 - radj2).nnz == 0

    radj3 = me.get_ring_adjacency(s, n_ring=2, include_self=False)
    assert radj3.dtype == np.uint8
    assert (radj3 - adj2).nnz > 0

    d = me.get_immediate_distance(s)
    assert d.shape == (s.n_points, s.n_points)
    assert d.dtype == np.float
    assert d.nnz == adj2.nnz

    d2 = me.get_immediate_distance(s, metric='sqeuclidean')
    d_sq = d.copy()
    d_sq.data **= 2
    assert np.allclose(d_sq.A, d2.A)

    rd = me.get_ring_distance(s)
    assert rd.dtype == np.float
    assert np.allclose(d.A, rd.A)

    rd2 = me.get_ring_distance(s, n_ring=2)
    assert (rd2 - d).nnz > 0

    assert me.get_cell_neighbors(s).shape == (s.n_cells, s.n_cells)
    assert me.get_edges(s).shape == (n_edges, 2)
    assert me.get_edge_length(s).shape == (n_edges, )

    assert me.get_boundary_points(s).size == 0
    assert me.get_boundary_edges(s).size == 0
    assert me.get_boundary_cells(s).size == 0
Ejemplo n.º 55
0
Ids.InsertNextId(7)

Grid = vtk.vtkUnstructuredGrid()
Grid.Allocate(10, 10)
Grid.InsertNextCell(12, Ids)
Grid.SetPoints(Points)
Grid.GetPointData().SetScalars(Scalars)

# Find the triangles that lie along the 0.5 contour in this cube.
Marching = vtk.vtkContourFilter()
Marching.SetInput(Grid)
Marching.SetValue(0, 0.5)
Marching.Update()

# Extract the edges of the triangles just found.
triangleEdges = vtk.vtkExtractEdges()
triangleEdges.SetInputConnection(Marching.GetOutputPort())
# Draw the edges as tubes instead of lines.  Also create the associated
# mapper and actor to display the tubes.
triangleEdgeTubes = vtk.vtkTubeFilter()
triangleEdgeTubes.SetInputConnection(triangleEdges.GetOutputPort())
triangleEdgeTubes.SetRadius(.005)
triangleEdgeTubes.SetNumberOfSides(6)
triangleEdgeTubes.UseDefaultNormalOn()
triangleEdgeTubes.SetDefaultNormal(.577, .577, .577)
triangleEdgeMapper = vtk.vtkPolyDataMapper()
triangleEdgeMapper.SetInputConnection(triangleEdgeTubes.GetOutputPort())
triangleEdgeMapper.ScalarVisibilityOff()
triangleEdgeActor = vtk.vtkActor()
triangleEdgeActor.SetMapper(triangleEdgeMapper)
triangleEdgeActor.GetProperty().SetDiffuseColor(lamp_black)