Ejemplo n.º 1
0
def display(data, data2=None, data3=None):
    # Generate some random points

    math = vtk.vtkMath()
    points = vtk.vtkPoints()
    
    [data, scalefactor]=scaledata(data)
    for i in range(len(data)):
        points.InsertNextPoint( data[i,0],data[i,1], data[i,2]);
    ballActor = vtksetup(points, color=red, radius=.001)
    [ren,renWin,iren]=vtkwindow()
    ren.AddActor(ballActor) # Add the actors to the renderer, set the background and size
    
    if data2 != None:
        data=data2*scalefactor
        points = vtk.vtkPoints()
        for i in range(len(data)):
            points.InsertNextPoint( data[i,0],data[i,1], data[i,2]);
        ballActor = vtksetup(points, color=blue)
        ren.AddActor(ballActor)
    
    if data3 != None:
        data=data3*scalefactor
        points = vtk.vtkPoints()
        for i in range(len(data)):
            points.InsertNextPoint( data[i,0],data[i,1], data[i,2]);
        ballActor = vtksetup(points, color=green, radius=.007)
        ren.AddActor(ballActor)



    # Interact with the data.
    iren.Initialize()
    renWin.Render()
    iren.Start()
Ejemplo n.º 2
0
def latitude_create(
                arg_lat,
		arg_projection):

	if arg_projection == 'linear' :
		n_polypoints=2
        	polygonpoints=vtk.vtkPoints()
        	polygonpoints.SetNumberOfPoints(n_polypoints)
		polygonpoints.InsertPoint(0,-180,arg_lat,0)
		polygonpoints.InsertPoint(1,540,arg_lat,0)
	else:
        	n_polypoints=360
        	polygonpoints=vtk.vtkPoints()
        	polygonpoints.SetNumberOfPoints(n_polypoints)
        	deg2rad=numpy.pi/180.
        	for n in range(n_polypoints) :
                	theta=2*numpy.pi*n/(n_polypoints-1)
                	x=numpy.cos(arg_lat*deg2rad)*numpy.cos(theta)
                	y=numpy.cos(arg_lat*deg2rad)*numpy.sin(theta)
                	z=numpy.sin(arg_lat*deg2rad)
                	polygonpoints.InsertPoint(n,x,y,z)

        polygonlines=vtk.vtkCellArray()
        polygonlines.InsertNextCell(n_polypoints)
        for n in range(n_polypoints) :
                polygonlines.InsertCellPoint(n)
        latpolydata=vtk.vtkPolyData()
        latpolydata.SetPoints(polygonpoints)
        latpolydata.SetLines(polygonlines)

        return latpolydata
Ejemplo n.º 3
0
def getRigidTransform(fix, mov): # In real resolution
    LandmarkTransform = vtk.vtkLandmarkTransform()
    LandmarkTransform.SetModeToRigidBody()
    
    n = fix.shape[0]
    fix_point = vtk.vtkPoints()
    fix_point.SetNumberOfPoints(n)
    mov_point = vtk.vtkPoints()
    mov_point.SetNumberOfPoints(n)

    for i in range(n):
        fix_point.SetPoint(i, fix[i, 0], fix[i, 1], fix[i, 2])
        mov_point.SetPoint(i, mov[i, 0], mov[i, 1], mov[i, 2])

    LandmarkTransform.SetSourceLandmarks(mov_point)
    LandmarkTransform.SetTargetLandmarks(fix_point)
    LandmarkTransform.Update()

    matrix = LandmarkTransform.GetMatrix()
    T = ml.zeros([4, 4], dtype = npy.float32)
    for i in range(4):
        for j in range(4):
            T[i, j] = matrix.GetElement(j, i)

    p1 = mov[0, :].tolist()
    p2 = [0.0, 0, 0]
    LandmarkTransform.InternalTransformPoint(p1, p2)
    
    return T, npy.array(p2)
Ejemplo n.º 4
0
  def __init__(self, sliceWidget):

    # keep a flag since events such as sliceNode modified
    # may come during superclass construction, which will
    # invoke our processEvents method
    self.initialized = False

    super(DrawEffectTool,self).__init__(sliceWidget)

    # create a logic instance to do the non-gui work
    self.logic = DrawEffectLogic(self.sliceWidget.sliceLogic())

    # interaction state variables
    self.activeSlice = None
    self.lastInsertSLiceNodeMTime = None
    self.actionState = None

    # initialization
    self.xyPoints = vtk.vtkPoints()
    self.rasPoints = vtk.vtkPoints()
    self.polyData = self.createPolyData()

    self.mapper = vtk.vtkPolyDataMapper2D()
    self.actor = vtk.vtkActor2D()
    self.mapper.SetInputData(self.polyData)
    self.actor.SetMapper(self.mapper)
    property_ = self.actor.GetProperty()
    property_.SetColor(1,1,0)
    property_.SetLineWidth(1)
    self.renderer.AddActor2D( self.actor )
    self.actors.append( self.actor )

    self.initialized = True
Ejemplo n.º 5
0
  def __init__(self, sliceWidget):
    super(LevelTracingEffectTool,self).__init__(sliceWidget)

    # create a logic instance to do the non-gui work
    self.logic = LevelTracingEffectLogic(self.sliceWidget.sliceLogic())

    # instance variables
    self.actionState = ''

    # initialization
    self.xyPoints = vtk.vtkPoints()
    self.rasPoints = vtk.vtkPoints()
    self.polyData = vtk.vtkPolyData()

    self.tracingFilter = vtkITK.vtkITKLevelTracingImageFilter()
    self.ijkToXY = vtk.vtkGeneralTransform()

    self.mapper = vtk.vtkPolyDataMapper2D()
    self.actor = vtk.vtkActor2D()
    property_ = self.actor.GetProperty()
    property_.SetColor( 107/255., 190/255., 99/255. )
    property_.SetLineWidth( 1 )
    if vtk.VTK_MAJOR_VERSION <= 5:
      self.mapper.SetInput(self.polyData)
    else:
      self.mapper.SetInputData(self.polyData)
    self.actor.SetMapper(self.mapper)
    property_ = self.actor.GetProperty()
    property_.SetColor(1,1,0)
    property_.SetLineWidth(1)
    self.renderer.AddActor2D( self.actor )
    self.actors.append( self.actor )
Ejemplo n.º 6
0
def genTextActor(renderer,string=None,x=None,y=None,to='default',tt='default',cmap=None):
  if isinstance(to,str):
    to = vcs.elements["textorientation"][to]
  if isinstance(tt,str):
    tt = vcs.elements["texttable"][tt]
  if tt.priority==0:
    return []
  if string is None:
    string = tt.string
  if x is None:
    x = tt.x
  if y is None:
    y = tt.y
  if x is None or y is None or string in [['',],[]]:
    return []

  n = max(len(x),len(y),len(string))
  for a in [x,y,string]:
    while len(a)<n:
      a.append(a[-1])

  sz = renderer.GetRenderWindow().GetSize()
  actors=[]
  pts = vtk.vtkPoints()
  geo = None
  if vcs.elements["projection"][tt.projection].type!="linear":
      # Need to figure out new WC
      Npts = 20
      for i in range(Npts+1):
          X = tt.worldcoordinate[0]+float(i)/Npts*(tt.worldcoordinate[1]-tt.worldcoordinate[0])
          for j in range(Npts+1):
              Y = tt.worldcoordinate[2]+float(j)/Npts*(tt.worldcoordinate[3]-tt.worldcoordinate[2])
              pts.InsertNextPoint(X,Y,0.)
      geo,pts = project(pts,tt.projection,tt.worldcoordinate,geo=None)
      wc = pts.GetBounds()[:4]
      #renderer.SetViewport(tt.viewport[0],tt.viewport[2],tt.viewport[1],tt.viewport[3])
      renderer.SetWorldPoint(wc)


  for i in range(n):
    t = vtk.vtkTextActor()
    p=t.GetTextProperty()
    prepTextProperty(p,sz,to,tt,cmap)
    pts = vtk.vtkPoints()
    pts.InsertNextPoint(x[i],y[i],0.)
    if geo is not None:
        geo,pts = project(pts,tt.projection,tt.worldcoordinate,geo=geo)
        X,Y,tz=pts.GetPoint(0)
        X,Y = world2Renderer(renderer,X,Y,tt.viewport,wc)
    else:
        X,Y = world2Renderer(renderer,x[i],y[i],tt.viewport,tt.worldcoordinate)
    t.SetPosition(X,Y)
    t.SetInput(string[i])
    #T=vtk.vtkTransform()
    #T.Scale(1.,sz[1]/606.,1.)
    #T.RotateY(to.angle)
    #t.SetUserTransform(T)
    renderer.AddActor(t)
    actors.append(t)
  return actors
    def setPointHeights( self, ptheights ):
        try:
            if self.topo == PlotType.Planar:   
                self.np_points_data[2::3] =  ptheights
                vtk_points_data = numpy_support.numpy_to_vtk( self.np_points_data ) 
                vtk_points_data.SetNumberOfComponents( 3 )
                vtk_points_data.SetNumberOfTuples( len( self.np_points_data ) / 3 ) 
                self.vtk_planar_points.SetData( vtk_points_data )
                self.polydata.SetPoints( self.vtk_planar_points )  
                self.vtk_planar_points.Modified()
            elif self.topo == PlotType.Spherical:
                self.np_sp_grid_data[0::3] =  self.spherical_scaling * ptheights + self.earth_radius
                vtk_sp_grid_data = numpy_support.numpy_to_vtk( self.np_sp_grid_data ) 
                size = vtk_sp_grid_data.GetSize()                    
                vtk_sp_grid_data.SetNumberOfComponents( 3 )
                vtk_sp_grid_data.SetNumberOfTuples( size/3 )   
                vtk_sp_grid_points = vtk.vtkPoints()
                vtk_sp_grid_points.SetData( vtk_sp_grid_data )
                self.vtk_spherical_points = vtk.vtkPoints()
                self.shperical_to_xyz_trans.TransformPoints( vtk_sp_grid_points, self.vtk_spherical_points ) 
#                pt0 = self.vtk_spherical_points.GetPoint(0)
    #            print "VTK Set point Heights, samples: %s %s %s " % ( str( ptheights[0] ), str( self.np_sp_grid_data[0] ), str( pt0 ) )
                self.polydata.SetPoints( self.vtk_spherical_points ) 
                self.vtk_spherical_points.Modified()
            self.polydata.Modified()
        except Exception, err:
            self.printLogMessage( "Processing point heights: %s " % str( err ), error=True )
    def computeSphericalPoints( self, **args ):
        lon_data = self.np_points_data[0::3]
        lat_data = self.np_points_data[1::3]
        z_data = self.np_points_data[2::3]
        radian_scaling = math.pi / 180.0 
        theta =  ( 90.0 - lat_data ) * radian_scaling
        phi = lon_data * radian_scaling
        
        r = z_data * self.spherical_scaling + self.earth_radius
        self.np_sp_grid_data = numpy.dstack( ( r, theta, phi ) ).flatten()
        vtk_sp_grid_data = numpy_support.numpy_to_vtk( self.np_sp_grid_data ) 

#         if self.grid == PlotType.List:
# #             r = numpy.empty( lon_data.shape, lon_data.dtype )      
# #             r.fill(  self.earth_radius )
#             r = z_data * self.spherical_scaling + self.earth_radius
#             self.np_sp_grid_data = numpy.dstack( ( r, theta, phi ) ).flatten()
#             vtk_sp_grid_data = numpy_support.numpy_to_vtk( self.np_sp_grid_data ) 
#         elif self.grid == PlotType.Grid:
#             thetaB = theta.reshape( [ theta.shape[0], 1 ] )  
#             phiB = phi.reshape( [ 1, phi.shape[0] ] )
#             grid_data = numpy.array( [ ( self.earth_radius, t, p ) for (t,p) in numpy.broadcast(thetaB,phiB) ] )
#             self.np_sp_grid_data = grid_data.flatten() 
#             vtk_sp_grid_data = numpy_support.numpy_to_vtk( self.np_sp_grid_data ) 
#         else:
#             print>>sys.stderr, "Unrecognized grid type: %s " % str( self.grid )
#             return        
        size = vtk_sp_grid_data.GetSize()                    
        vtk_sp_grid_data.SetNumberOfComponents( 3 )
        vtk_sp_grid_data.SetNumberOfTuples( size/3 )   
        vtk_sp_grid_points = vtk.vtkPoints()
        vtk_sp_grid_points.SetData( vtk_sp_grid_data )
        self.vtk_spherical_points = vtk.vtkPoints()
        self.shperical_to_xyz_trans.TransformPoints( vtk_sp_grid_points, self.vtk_spherical_points ) 
Ejemplo n.º 9
0
    def __init__(self):

        pypes.pypeScript.__init__(self)

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

        self.SetScriptName("vmtkthinplatesplinedeformation")
        self.SetInputMembers(
            [
                ["Surface", "i", "vtkPolyData", 1, "", "the input surface", "vmtksurfacereader"],
                ["Opacity", "opacity", "float", 1, "(0.0,1.0)", "object opacities in the scene"],
                ["vmtkRenderer", "renderer", "vmtkRenderer", 1, "", "external renderer"],
            ]
        )
        self.SetOutputMembers([["DeformedSurface", "o", "vtkPolyData", 1, "", "", "vmtksurfacewriter"]])
Ejemplo n.º 10
0
    def DeleteCallback(self, obj):
        delId = -1
        sourceValid = False
        if self.CurrentSourcePointId != -1:
            delId = self.CurrentSourcePointId
            sourceValid = True
        elif self.CurrentTargetPointId != -1:
            delId = self.CurrentTargetPointId
        else:
            return
        savedSources = vtk.vtkPoints()
        savedSources.DeepCopy(self.SourcePoints)
        savedTargets = vtk.vtkPoints()
        savedTargets.DeepCopy(self.TargetPoints)
        self.InitializeSpheres()

        for i in range(savedSources.GetNumberOfPoints()):
            if i != delId:
                self.AddDisplacement(savedSources.GetPoint(i), savedTargets.GetPoint(i))

        nPoints = self.SourcePoints.GetNumberOfPoints()

        if nPoints == 0:
            self.SelectSource(-1)
        elif sourceValid:
            self.SelectSource((delId - 1) % nPoints)
        else:
            self.SelectTarget((delId - 1) % nPoints)

        self.SourceSpheres.Modified()
        self.TargetSpheres.Modified()

        self.vmtkRenderer.RenderWindow.Render()
Ejemplo n.º 11
0
        def method(self):

            # multiblock += contact points
            output_a = self._contact_source_a.GetPolyDataOutput()
            output_b = self._contact_source_b.GetPolyDataOutput()

            id_f = numpy.where(
                abs(self._data[:, 0] - self._time) < 1e-15)[0]

            self.cpa_export = self._data[
                id_f, 2:5].copy()

            self.cpb_export = self._data[
                id_f, 5:8].copy()

            self.cn_export = self._data[
                id_f, 8:11].copy()

            self.cf_export = self._data[
                id_f, 11:14].copy()

            self.cpa_ = numpy_support.numpy_to_vtk(
                self.cpa_export)
            self.cpa_.SetName('contact_positions_A')

            self.cpb_ = numpy_support.numpy_to_vtk(
                self.cpb_export)
            self.cpb_.SetName('contact_positions_B')

            self.cn_ = numpy_support.numpy_to_vtk(
                self.cn_export)
            self.cn_.SetName('contact_normals')

            self.cf_ = numpy_support.numpy_to_vtk(
                self.cf_export)
            self.cf_.SetName('contact_forces')

            output_a.Allocate(len(self.cpa_export), 1)

            cpa_points = vtk.vtkPoints()
            cpa_points.SetNumberOfPoints(len(self.cpa_export))
            cpa_points.SetData(self.cpa_)
            output_a.SetPoints(cpa_points)

            # normal and forces are attached to A points
            output_a.GetPointData().AddArray(self.cn_)
            output_a.GetPointData().AddArray(self.cf_)

            output_b.Allocate(len(self.cpb_export), 1)

            cpb_points = vtk.vtkPoints()
            cpb_points.SetNumberOfPoints(len(self.cpb_export))
            cpb_points.SetData(self.cpb_)

            output_b.SetPoints(cpb_points)
Ejemplo n.º 12
0
 def KeyPressCallback(self, obj, event):
     ch = self.window_interactor.GetKeySym()
     if ch == 'Return':
         trans = loadTransform()
         num = 0
         for transform in trans:
             self.point_data_result = applyTransform(self.tmp_data_move, transform)
             self.point_data_result[:, :3] /= self.tmp_space
             for cnt in range(3, 6):
                 point_result = self.point_data_result[npy.where(npy.round(self.point_data_result[:, -1]) == cnt - 3)]
                 point_move = self.point_data_move[npy.where(npy.round(self.point_data_move[:, -1]) == cnt - 3)]
                 if not point_result.shape[0]:
                     continue
                     
                 self.cells = vtk.vtkCellArray()
                 self.points = vtk.vtkPoints()
                 l = 0
                 for i in range(self.zmin, self.zmax + 1):
                     data = point_result[npy.where(npy.round(point_move[:, 2]) == i)]
                     if data is not None:
                         if data.shape[0] == 0:
                             continue
                         count = data.shape[0]
                         points = vtk.vtkPoints()
                         for j in range(count):
                             points.InsertPoint(j, data[j, 0], data[j, 1], data[j, 2])
                         
                         para_spline = vtk.vtkParametricSpline()
                         para_spline.SetXSpline(vtk.vtkKochanekSpline())
                         para_spline.SetYSpline(vtk.vtkKochanekSpline())
                         para_spline.SetZSpline(vtk.vtkKochanekSpline())
                         para_spline.SetPoints(points)
                         para_spline.ClosedOn()
                         
                         # The number of output points set to 10 times of input points
                         numberOfOutputPoints = count * 10
                         self.cells.InsertNextCell(numberOfOutputPoints)
                         for k in range(0, numberOfOutputPoints):
                             t = k * 1.0 / numberOfOutputPoints
                             pt = [0.0, 0.0, 0.0]
                             para_spline.Evaluate([t, t, t], pt, [0] * 9)
                             if pt[0] != pt[0]:
                                 print pt
                                 continue
                             self.points.InsertPoint(l, pt[0], pt[1], pt[2])
                             self.cells.InsertCellPoint(l)
                             l += 1
     
                 self.contours[cnt].SetPoints(self.points)
                 self.contours[cnt].SetPolys(self.cells)
                 self.contours[cnt].Update()
                 
             self.render_window.Render()
             saveGif(self.render_window, num)
             num += 1
Ejemplo n.º 13
0
def draw_lines(nodes, color):
    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    colors.SetName("Colors")
    cnt = 0
    noderange = 100
    mod = 1
    edges = nodes[0].getedges()
    points = vtk.vtkPoints()
    lines = vtk.vtkCellArray()
    nodecnt = 0

    while cnt < len(nodes):
        node = nodes[cnt]
        cnt += 1
        edges = node.getedges()
        for edge in edges:
            x0,y0,z0 = edge[0]
            x1,y1,z1 = edge[1]

            points.InsertNextPoint(edge[0])
            points.InsertNextPoint(edge[1])

            line = vtk.vtkLine()
            line.GetPointIds().SetId(0,nodecnt)
            line.GetPointIds().SetId(1,nodecnt+1)
            lines.InsertNextCell(line)
            nodecnt += 2
            colors.InsertNextTupleValue(color)

        if cnt % mod == 0:
            print "noderange", noderange, "cnt", cnt, "mod",mod
            # Create a polydata to store everything in
            linesPolyData = vtk.vtkPolyData()
            # Add the points to the dataset
            linesPolyData.SetPoints(points)
            # Add the lines to the dataset
            linesPolyData.SetLines(lines)
            linesPolyData.GetCellData().SetScalars(colors)

            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInput(linesPolyData)
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            renderer.AddActor(actor)
            points = vtk.vtkPoints()
            lines = vtk.vtkCellArray()
            nodecnt = 0    
            renderWindow.Render()
            camera = renderer.GetActiveCamera()
            camera.Azimuth(0.1)

    print "done!"
Ejemplo n.º 14
0
def vtk_ellipsoid_topomesh(ellipsoid_radius=50.0, ellipsoid_scales=[1,1,1], ellipsoid_axes=np.diag(np.ones(3)), ellipsoid_center=np.zeros(3)):
    """
    """      
    import vtk
    from openalea.cellcomplex.property_topomesh.utils.image_tools import vtk_polydata_to_triangular_mesh

    ico = vtk.vtkPlatonicSolidSource()
    ico.SetSolidTypeToIcosahedron()
    ico.Update()

    subdivide = vtk.vtkLoopSubdivisionFilter()
    subdivide.SetNumberOfSubdivisions(3)
    subdivide.SetInputConnection(ico.GetOutputPort())
    subdivide.Update()

    scale_transform = vtk.vtkTransform()
    scale_factor = ellipsoid_radius/(np.sqrt(2)/2.)
    scale_transform.Scale(scale_factor,scale_factor,scale_factor)

    ellipsoid_sphere = vtk.vtkTransformPolyDataFilter()
    ellipsoid_sphere.SetInput(subdivide.GetOutput())
    ellipsoid_sphere.SetTransform(scale_transform)
    ellipsoid_sphere.Update()

    ellipsoid_transform = vtk.vtkTransform()
    axes_transform = vtk.vtkLandmarkTransform()
    source_points = vtk.vtkPoints()
    source_points.InsertNextPoint([1,0,0])
    source_points.InsertNextPoint([0,1,0])
    source_points.InsertNextPoint([0,0,1])
    target_points = vtk.vtkPoints()
    target_points.InsertNextPoint(ellipsoid_axes[0])
    target_points.InsertNextPoint(ellipsoid_axes[1])
    target_points.InsertNextPoint(ellipsoid_axes[2])
    axes_transform.SetSourceLandmarks(source_points)
    axes_transform.SetTargetLandmarks(target_points)
    axes_transform.SetModeToRigidBody()
    axes_transform.Update()
    ellipsoid_transform.SetMatrix(axes_transform.GetMatrix())
    ellipsoid_transform.Scale(ellipsoid_scales[0],ellipsoid_scales[1],ellipsoid_scales[2])
    center_transform = vtk.vtkTransform()
    center_transform.Translate(ellipsoid_center[0],ellipsoid_center[1],ellipsoid_center[2])
    center_transform.Concatenate(ellipsoid_transform)
    ellipsoid_ellipsoid = vtk.vtkTransformPolyDataFilter()
    ellipsoid_ellipsoid.SetInput(ellipsoid_sphere.GetOutput())
    ellipsoid_ellipsoid.SetTransform(center_transform)
    ellipsoid_ellipsoid.Update()

    ellipsoid_mesh = vtk_polydata_to_triangular_mesh(ellipsoid_ellipsoid.GetOutput())

    topomesh = triangle_topomesh(ellipsoid_mesh.triangles.values(),ellipsoid_mesh.points)

    return topomesh
Ejemplo n.º 15
0
    def InitializeSeeds(self):
        if (self.InteractionMode==0):
	    self.SeedIds.Initialize()
	    self.SeedPoints.Initialize()
	    seedPoints = vtk.vtkPoints()
	    self.SeedPoints.SetPoints(seedPoints)
	else:
	    self.ExamineSpheres.Initialize()
	    spherePoints = vtk.vtkPoints()
	    self.ExamineSpheres.SetPoints(spherePoints)
	    self.ExamineSpheres.GetPointData().Initialize()
	    sphereRadii = vtk.vtkDoubleArray()
	    self.ExamineSpheres.GetPointData().SetScalars(sphereRadii)
Ejemplo n.º 16
0
  def onLandmarkMoved_NOT(self,state):
    """Perform the linear transform using the vtkLandmarkTransform class"""
    if state.transformed.GetTransformNodeID() != state.linearTransform.GetID():
      state.transformed.SetAndObserveTransformNodeID(state.linearTransform.GetID())

    self.linearMode = "Rigid"

    # try to use user selection, but fall back if not enough points are available
    landmarkTransform = vtk.vtkLandmarkTransform()
    if self.linearMode == 'Rigid':
      landmarkTransform.SetModeToRigidBody()
    if self.linearMode == 'Similarity':
      landmarkTransform.SetModeToSimilarity()
    if self.linearMode == 'Affine':
      landmarkTransform.SetModeToAffine()
    if state.fixedFiducials.GetNumberOfFiducials() < 3:
      landmarkTransform.SetModeToRigidBody()

    points = {}
    point = [0,]*3
    for volumeNode in (state.fixed,state.moving):
      points[volumeNode] = vtk.vtkPoints()
    indices = range(state.fixedFiducials.GetNumberOfFiducials())
    fiducialLists = (state.fixedFiducials,state.movingFiducials)
    volumeNodes = (state.fixed,state.moving)
    for fiducials,volumeNode in zip(fiducialLists,volumeNodes):
      for index in indices:
        fiducials.GetNthFiducialPosition(index,point)
        points[volumeNode].InsertNextPoint(point)
    landmarkTransform.SetSourceLandmarks(points[state.moving])
    landmarkTransform.SetTargetLandmarks(points[state.fixed])
    landmarkTransform.Update()
    t = state.linearTransform
    t.SetAndObserveMatrixTransformToParent(landmarkTransform.GetMatrix())
Ejemplo n.º 17
0
def make_cylinderActor (r, x0, x1, rgb, opacity):
    points = vtk.vtkPoints()
    lines  = vtk.vtkCellArray()
    lines.InsertNextCell(2)
    # point 0
    points.InsertNextPoint(x0[0], x0[1], x0[2])
    lines.InsertCellPoint(0)
    # point 1
    points.InsertNextPoint(x1[0], x1[1], x1[2])
    lines.InsertCellPoint(1)

    cData = vtk.vtkPolyData()
    cData.SetPoints(points)
    cData.SetLines(lines)

    c = vtk.vtkTubeFilter()
    c.SetNumberOfSides(8)
    c.SetInput(cData)
    c.SetRadius(r)

    cMapper = vtk.vtkPolyDataMapper()
    cMapper.SetInput(c.GetOutput())

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

    return cActor
Ejemplo n.º 18
0
def array2vtkPoints(num_array, vtk_points=None):
    """Converts a numpy array/Python list to a vtkPoints object.

    Unless a Python list/tuple or a non-contiguous array is given, no
    copy of the data is made.  Thus the function is very efficient.

    Parameters
    ----------

    - num_array : numpy array or Python list/tuple

      The input array must be 2D with `shape[1] == 3`.

    - vtk_points : `vtkPoints` (default: `None`)

      If an optional `vtkPoints` instance, is passed as an argument
      then a new array is not created and returned.  The passed array
      is itself modified and returned.

    """
    if vtk_points:
        points  = vtk_points
    else:
        points = vtk.vtkPoints()

    arr = numpy.asarray(num_array)
    assert len(arr.shape) == 2, "Points array must be 2 dimensional."
    assert arr.shape[1] == 3, "Incorrect shape: shape[1] must be 3."
    vtk_array = array2vtk(arr)
    points.SetData(vtk_array)
    return points
Ejemplo n.º 19
0
def make_sphereActor (x, r, rgb, opacity):
    points = vtk.vtkPoints()
    points.InsertNextPoint(x[0], x[1], x[2])

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

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

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

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

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

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

    return pActor
Ejemplo n.º 20
0
def testTwoTrianglesCoplanar():

    "Two triangles"

    # create set of points
    points = vtk.vtkPoints()
    points.SetNumberOfPoints(4)
    points.SetPoint(0, [0., 0., 0.])
    points.SetPoint(1, [1., 0., 0.])
    points.SetPoint(2, [0., 1., 0.])
    points.SetPoint(3, [1., 1., 0.])

    # create vtkPolyData object
    pdata = vtk.vtkPolyData()
    pdata.SetPoints(points)

    pdata.Allocate(2, 1)
    ptIds = vtk.vtkIdList()
    ptIds.SetNumberOfIds(3)

    ptIds.SetId(0, 0)
    ptIds.SetId(1, 1)
    ptIds.SetId(2, 2)
    pdata.InsertNextCell(vtk.VTK_POLYGON, ptIds)
    ptIds.SetId(0, 1)
    ptIds.SetId(1, 3)
    ptIds.SetId(2, 2)
    pdata.InsertNextCell(vtk.VTK_POLYGON, ptIds)

    for order in range(1, 6):
        lslm = PoissonSolver(pdata,
                             max_edge_length=1000.,
                             order=order)
        print('order = ', order)
        print('g matrix: ', lslm.getGreenMatrix())
Ejemplo n.º 21
0
def createPolyData(faces, vtList, verts, tcoords):

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

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

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

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

    cells = vtk.vtkCellArray()

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

    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)
    polyData.SetPolys(cells)
    polyData.GetPointData().SetTCoords(tcoordArray)
    return polyData
Ejemplo n.º 22
0
    def _update_vtk_objects(self):
        """When n is changed the thus the number of coordinates this function is needed
        to update the vtk objects with the new number of points."""
        # self._vtk_points.SetNumberOfPoints(len(self._points))
        # for i, c in enumerate(self._points):
        #     self._vtk_points.InsertPoint(i, c[0], c[1], c[2])
        self._vtk_points = _vtk.vtkPoints()
        for coordinates in self._points:
            self._vtk_points.InsertNextPoint(coordinates[0], coordinates[1], coordinates[2])

        self._vtk_polygons = _vtk.vtkCellArray()
        for polygon in self._polygons:
            vtk_polygon = _vtk.vtkPolygon()
            vtk_polygon.GetPointIds().SetNumberOfIds(3)
            for local_index, global_index in enumerate(polygon):
                vtk_polygon.GetPointIds().SetId(local_index, global_index)
            self._vtk_polygons.InsertNextCell(vtk_polygon)

        self._vtk_poly_data.SetPoints(self._vtk_points)
        self._vtk_poly_data.SetPolys(self._vtk_polygons)

        self._vtk_scalars = _vtk.vtkFloatArray()
        self._vtk_scalars.SetNumberOfValues(self._vtk_poly_data.GetPoints().GetNumberOfPoints())
        for i in range(self._vtk_scalars.GetNumberOfTuples()):
            self._vtk_scalars.SetValue(i, 0.)

        self._vtk_poly_data.GetPointData().SetScalars(self._vtk_scalars)
        self._vtk_poly_data.Modified()
Ejemplo n.º 23
0
def testSingleTriangle():

    "Single triangle"

    h = 0.1
    # create set of points
    points = vtk.vtkPoints()
    points.SetNumberOfPoints(3)
    points.SetPoint(0, [1., -1.*h/3., -1.*h/3.])
    points.SetPoint(1, [1., 2.*h/3., -1.*h/3.])
    points.SetPoint(2, [1., -1.*h/3., 2.*h/3.])

    # create vtkPolyData object
    pdata = vtk.vtkPolyData()
    pdata.SetPoints(points)
    ptIds = vtk.vtkIdList()
    ptIds.SetNumberOfIds(3)
    ptIds.SetId(0, 0)
    ptIds.SetId(1, 1)
    ptIds.SetId(2, 2)
    pdata.Allocate(1, 1)
    pdata.InsertNextCell(vtk.VTK_POLYGON, ptIds)

    for order in range(1, 6):
        lslm = PoissonSolver(pdata, max_edge_length=1000.)
        print('order = ', order)
        print('g matrix: ', lslm.getGreenMatrix())
Ejemplo n.º 24
0
def MakeHexagonalPrism():
    '''
      3D: hexagonal prism: a wedge with an hexagonal base.
      Be careful, the base face ordering is different from wedge.
    '''
 
    numberOfVertices = 12
 
    points = vtk.vtkPoints()
 
    points.InsertNextPoint(0.0, 0.0, 1.0)
    points.InsertNextPoint(1.0, 0.0, 1.0)
    points.InsertNextPoint(1.5, 0.5, 1.0)
    points.InsertNextPoint(1.0, 1.0, 1.0)
    points.InsertNextPoint(0.0, 1.0, 1.0)
    points.InsertNextPoint(-0.5, 0.5, 1.0)
 
    points.InsertNextPoint(0.0, 0.0, 0.0)
    points.InsertNextPoint(1.0, 0.0, 0.0)
    points.InsertNextPoint(1.5, 0.5, 0.0)
    points.InsertNextPoint(1.0, 1.0, 0.0)
    points.InsertNextPoint(0.0, 1.0, 0.0)
    points.InsertNextPoint(-0.5, 0.5, 0.0)
 
    hexagonalPrism = vtk.vtkHexagonalPrism()
    for i in range(0, numberOfVertices):
        hexagonalPrism.GetPointIds().SetId(i, i)
 
    ug = vtk.vtkUnstructuredGrid()
    ug.InsertNextCell(hexagonalPrism.GetCellType(),
                       hexagonalPrism.GetPointIds())
    ug.SetPoints(points)
 
    return ug
Ejemplo n.º 25
0
def MakePentagonalPrism():
 
    numberOfVertices = 10
 
    # Create the points
    points = vtk.vtkPoints()
    points.InsertNextPoint(11, 10, 10)
    points.InsertNextPoint(13, 10, 10)
    points.InsertNextPoint(14, 12, 10)
    points.InsertNextPoint(12, 14, 10)
    points.InsertNextPoint(10, 12, 10)
    points.InsertNextPoint(11, 10, 14)
    points.InsertNextPoint(13, 10, 14)
    points.InsertNextPoint(14, 12, 14)
    points.InsertNextPoint(12, 14, 14)
    points.InsertNextPoint(10, 12, 14)
 
    # Pentagonal Prism
    pentagonalPrism = vtk.vtkPentagonalPrism()
    for i in range(0, numberOfVertices):
        pentagonalPrism.GetPointIds().SetId(i, i)
 
    # Add the points and hexahedron to an unstructured grid
    uGrid = vtk.vtkUnstructuredGrid()
    uGrid.SetPoints(points)
    uGrid.InsertNextCell(pentagonalPrism.GetCellType(),
                          pentagonalPrism.GetPointIds())
 
    return uGrid
Ejemplo n.º 26
0
def MakeVoxel():
    '''
      A voxel is a representation of a regular grid in 3-D space.
    '''
    numberOfVertices = 8
 
    points = vtk.vtkPoints()
    points.InsertNextPoint(0, 0, 0)
    points.InsertNextPoint(1, 0, 0)
    points.InsertNextPoint(0, 1, 0)
    points.InsertNextPoint(1, 1, 0)
    points.InsertNextPoint(0, 0, 1)
    points.InsertNextPoint(1, 0, 1)
    points.InsertNextPoint(0, 1, 1)
    points.InsertNextPoint(1, 1, 1)
 
    voxel = vtk.vtkVoxel()
    for i in range(0, numberOfVertices):
        voxel.GetPointIds().SetId(i, i)
 
    ug = vtk.vtkUnstructuredGrid()
    ug.SetPoints(points)
    ug.InsertNextCell(voxel.GetCellType(), voxel.GetPointIds())
 
    return ug
Ejemplo n.º 27
0
def make_pData_periodic (np, x, a, lattice):
    pos = vtk.vtkPoints()
    diameter = vtk.vtkDoubleArray()
    diameter.SetNumberOfComponents(1)
    # primary cell
    for i in range(np):
        pos.InsertNextPoint(x[i*3], x[i*3+1], x[i*3+2])
        if a != []:
            diameter.InsertNextTuple1(2.0*a[i])
        else:
            diameter.InsertNextTuple1(2.0)
    # image cells
    for ix in range(-1,2):
        for iy in range(-1,2):
            for iz in range(-1,2):
                if ix == 0 and iy == 0 and iz == 0: continue
                for i in range(np):
                    pos.InsertNextPoint(x[i*3  ]+float(ix)*lattice[0],
                                        x[i*3+1]+float(iy)*lattice[1],
                                        x[i*3+2]+float(iz)*lattice[2])
                    if a != []:
                        diameter.InsertNextTuple1(2.0*a[i])
                    else:
                        diameter.InsertNextTuple1(2.0)

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

    return pData
Ejemplo n.º 28
0
def MakePyramid():
    '''
      Make a regular square pyramid.
    '''
    numberOfVertices = 5
 
    points = vtk.vtkPoints()
 
    p = [
         [1.0, 1.0, 0.0],
         [-1.0, 1.0, 0.0],
         [-1.0, -1.0, 0.0],
         [1.0, -1.0, 0.0],
         [0.0, 0.0, 1.0]
         ]
    for pt in p:
        points.InsertNextPoint(pt)
 
    pyramid = vtk.vtkPyramid()
    for i in range(0, numberOfVertices):
        pyramid.GetPointIds().SetId(i, i)
 
    ug = vtk.vtkUnstructuredGrid()
    ug.SetPoints(points)
    ug.InsertNextCell(pyramid.GetCellType(), pyramid.GetPointIds())
 
    return ug
Ejemplo n.º 29
0
  def copyFirstNLines(self, sourcePolyData, lineCount):
    """make a polydata with only the first N polylines"""

    polyData = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    polyData.SetPoints(points)

    lines = vtk.vtkCellArray()
    polyData.SetLines(lines)

    sourcePoints = sourcePolyData.GetPoints()
    sourceLines = sourcePolyData.GetLines()
    sourceIdList = vtk.vtkIdList()
    sourceLines.InitTraversal()
    while sourceLines.GetNextCell(sourceIdList):
        pointCount = sourceIdList.GetNumberOfIds()
        idList = vtk.vtkIdList()
        for idIndex in range(pointCount):
            sourceId = sourceIdList.GetId(idIndex)
            point = sourcePoints.GetPoint(sourceId)
            id = points.InsertNextPoint(point)
            idList.InsertNextId(id)
        lines.InsertNextCell(idList)
        if lines.GetNumberOfCells() > lineCount:
            break

    return polyData
Ejemplo n.º 30
0
def MakeWedge():
    '''
      A wedge consists of two triangular ends and three rectangular faces.
    '''
 
    numberOfVertices = 6
 
    points = vtk.vtkPoints()
 
    points.InsertNextPoint(0, 1, 0)
    points.InsertNextPoint(0, 0, 0)
    points.InsertNextPoint(0, .5, .5)
    points.InsertNextPoint(1, 1, 0)
    points.InsertNextPoint(1, 0.0, 0.0)
    points.InsertNextPoint(1, .5, .5)
 
    wedge = vtk.vtkWedge()
    for i in range(0, numberOfVertices):
        wedge.GetPointIds().SetId(i, i)
 
    ug = vtk.vtkUnstructuredGrid()
    ug.SetPoints(points)
    ug.InsertNextCell(wedge.GetCellType(), wedge.GetPointIds())
 
    return ug
Ejemplo n.º 31
0
    def _render_blurry_particles(self, particles_dataset):
        particles_per_species = dict(
            (k, vtk.vtkPoints()) for k in self._species_idmap.iterkeys())

        scaling = self.settings.scaling

        position_idx = particles_dataset.dtype.names.index('position')
        species_id_idx = particles_dataset.dtype.names.index('species_id')
        for p in particles_dataset:
            pos = p[position_idx]
            display_species_id = self._species_idmap.get(p[species_id_idx])
            if display_species_id is None:
                continue
            particles_per_species[display_species_id].InsertNextPoint(
                pos * scaling / self._world_size)

        nx = ny = nz = self.settings.fluorimetry_axial_voxel_number

        for display_species_id, points in particles_per_species.iteritems():
            poly_data = vtk.vtkPolyData()
            poly_data.SetPoints(points)
            poly_data.ComputeBounds()

            pattr = self._pattrs[display_species_id]
            # Calc standard deviation of gauss distribution function
            wave_length = pattr['fluorimetry_wave_length']
            sigma = scaling * 0.5 * wave_length / self._world_size

            # Create guassian splatter
            gs = vtk.vtkGaussianSplatter()
            gs.SetInput(poly_data)
            gs.SetSampleDimensions(nx, ny, nz)
            gs.SetRadius(sigma)
            gs.SetExponentFactor(-.5)
            gs.ScalarWarpingOff()
            gs.SetModelBounds([-sigma, scaling + sigma] * 3)
            gs.SetAccumulationModeToMax()

            # Create filter for volume rendering
            filter = vtk.vtkImageShiftScale()
            # Scales to unsigned char
            filter.SetScale(255. * pattr['fluorimetry_brightness'])
            filter.ClampOverflowOn()
            filter.SetOutputScalarTypeToUnsignedChar()
            filter.SetInputConnection(gs.GetOutputPort())

            mapper = vtk.vtkFixedPointVolumeRayCastMapper()
            mapper.SetInputConnection(filter.GetOutputPort())

            volume = vtk.vtkVolume()
            property = volume.GetProperty()  # vtk.vtkVolumeProperty()
            color = pattr['fluorimetry_luminescence_color']
            color_tfunc = vtk.vtkColorTransferFunction()
            color_tfunc.AddRGBPoint(0, color[0], color[1], color[2])
            property.SetColor(color_tfunc)
            opacity_tfunc = vtk.vtkPiecewiseFunction()
            opacity_tfunc.AddPoint(0, 0.0)
            opacity_tfunc.AddPoint(255., 1.0)
            property.SetScalarOpacity(opacity_tfunc)
            property.SetInterpolationTypeToLinear()

            if self.settings.fluorimetry_shadow_display:
                property.ShadeOn()
            else:
                property.ShadeOff()

            volume.SetMapper(mapper)

            self.renderer.AddVolume(volume)
Ejemplo n.º 32
0
    def run(self, baseMeshNode, baseLMNode, semiLMNode, meshDirectory,
            lmDirectory, ouputDirectory, outputExtension, scaleProjection):
        SLLogic = CreateSemiLMPatches.CreateSemiLMPatchesLogic()
        targetPoints = vtk.vtkPoints()
        point = [0, 0, 0]
        # estimate a sample size usingn semi-landmark spacing
        sampleArray = np.zeros(shape=(25, 3))
        for i in range(25):
            semiLMNode.GetMarkupPoint(0, i, point)
            sampleArray[i, :] = point
        sampleDistances = self.distanceMatrix(sampleArray)
        minimumMeshSpacing = sampleDistances[sampleDistances.nonzero()].min(
            axis=0)
        rayLength = minimumMeshSpacing * (scaleProjection)

        for i in range(baseLMNode.GetNumberOfFiducials()):
            baseLMNode.GetMarkupPoint(0, i, point)
            targetPoints.InsertNextPoint(point)

        for meshFileName in os.listdir(meshDirectory):
            if (not meshFileName.startswith(".")):
                print(meshFileName)
                lmFileList = os.listdir(lmDirectory)
                meshFilePath = os.path.join(meshDirectory, meshFileName)
                regex = re.compile(r'\d+')
                subjectID = [int(x) for x in regex.findall(meshFileName)][0]
                for lmFileName in lmFileList:
                    if str(subjectID) in lmFileName:
                        # if mesh and lm file with same subject id exist, load into scene
                        currentMeshNode = slicer.util.loadModel(meshFilePath)
                        lmFilePath = os.path.join(lmDirectory, lmFileName)
                        success, currentLMNode = slicer.util.loadMarkupsFiducialList(
                            lmFilePath)

                        # set up transform between base lms and current lms
                        sourcePoints = vtk.vtkPoints()
                        for i in range(currentLMNode.GetNumberOfMarkups()):
                            currentLMNode.GetMarkupPoint(0, i, point)
                            sourcePoints.InsertNextPoint(point)

                        transform = vtk.vtkThinPlateSplineTransform()
                        transform.SetSourceLandmarks(sourcePoints)
                        transform.SetTargetLandmarks(targetPoints)
                        transform.SetBasisToR()  # for 3D transform

                        transformNode = slicer.mrmlScene.AddNewNodeByClass(
                            "vtkMRMLTransformNode", "TPS")
                        transformNode.SetAndObserveTransformToParent(transform)

                        # apply transform to the current surface mesh
                        currentMeshNode.SetAndObserveTransformNodeID(
                            transformNode.GetID())
                        slicer.vtkSlicerTransformLogic().hardenTransform(
                            currentMeshNode)

                        # project semi-landmarks
                        resampledLandmarkNode = slicer.mrmlScene.AddNewNodeByClass(
                            'vtkMRMLMarkupsFiducialNode',
                            meshFileName + '_SL_warped')
                        success = SLLogic.projectPoints(
                            baseMeshNode, currentMeshNode, semiLMNode,
                            resampledLandmarkNode, rayLength)

                        transformNode.Inverse()
                        resampledLandmarkNode.SetAndObserveTransformNodeID(
                            transformNode.GetID())
                        slicer.vtkSlicerTransformLogic().hardenTransform(
                            resampledLandmarkNode)

                        # transfer point data
                        for index in range(
                                semiLMNode.GetNumberOfControlPoints()):
                            fiducialLabel = semiLMNode.GetNthControlPointLabel(
                                index)
                            fiducialDescription = semiLMNode.GetNthControlPointDescription(
                                index)
                            resampledLandmarkNode.SetNthControlPointLabel(
                                index, fiducialLabel)
                            resampledLandmarkNode.SetNthControlPointDescription(
                                index, fiducialDescription)

                        # save output file
                        outputFileName = meshFileName + '_SL_warped' + outputExtension
                        outputFilePath = os.path.join(ouputDirectory,
                                                      outputFileName)
                        slicer.util.saveNode(resampledLandmarkNode,
                                             outputFilePath)

                        # clean up
                        slicer.mrmlScene.RemoveNode(resampledLandmarkNode)
                        slicer.mrmlScene.RemoveNode(currentLMNode)
                        slicer.mrmlScene.RemoveNode(currentMeshNode)
                        slicer.mrmlScene.RemoveNode(transformNode)
Ejemplo n.º 33
0
def readpoints(filename):

    points = vtk.vtkPoints()
    file = open(filename, "r")
    xdim = int(raw_input("Please Enter the X-Dimension: "))
    ydim = int(raw_input("Please Enter the Y-Dimension: "))
    zdim = int(raw_input("Please Enter the Z-Dimension: "))
    m = 0
    a = 0
    while file:
        line = file.readline()
        if line == "":
            break
        line = str.rstrip(line)
        cols = line.split('	')

        if len(cols) < 3:
            if line.find('-') == 0:
                print "Treating as options: ", line
                processOption(line)
            else:
                print "Omitting line: ", line
                continue

        x = cols[1]
        y = cols[2]
        z = cols[3]

        p = float(z)
        if m == 0:
            zmin = p

        if m >= 1:
            zmax = p
            p = (round(zmin) >= (zdim - 2)) and (round(zmax) <= 1)
            if p == 1:
                d = m - 1
                a = a + 1
                if a == 1:
                    t = d

            zmin = zmax

        points.InsertNextPoint(float(x), float(y), float(z))
        #print m
        m = m + 1

#Define Scalar and vectors
    scalars = vtk.vtkFloatArray()
    scalars.SetNumberOfTuples(m)

    vector = vtk.vtkFloatArray()
    vector.SetNumberOfComponents(3)
    vector.SetNumberOfTuples(m)

    pdata = vtk.vtkPolyData()
    pline = vtk.vtkCellArray()

    pline.InsertNextCell(t)
    for i in range(0, t):
        pline.InsertCellPoint(i)

    pline.InsertNextCell(d - t - 1)
    for i in range(t + 1, d):
        pline.InsertCellPoint(i)

    pline.InsertNextCell(m - d - 1)
    for i in range(d + 1, m):
        pline.InsertCellPoint(i)

    pdata.SetPoints(points)
    pdata.SetLines(pline)
    pdata.GetPointData().SetVectors(vector)

    profileTubes = vtk.vtkTubeFilter()
    profileTubes.SetNumberOfSides(4)
    profileTubes.SetInput(pdata)
    profileTubes.SetRadius(0.75)

    slineGrid = vtk.vtkStructuredGrid()
    #slineGrid.Allocate(10,10)
    #slineGrid.InsertNextCell(12,Idlist)
    slineGrid.GetPointData().SetScalars(scalars)
    slineGrid.GetPointData().SetVectors(vector)
    slineGrid.GetPointData().AddArray
    slineGrid.SetPoints(points)

    map = vtk.vtkDataSetMapper()
    map.SetInputConnection(profileTubes.GetOutputPort())

    triangulation = vtk.vtkActor()
    triangulation.SetMapper(map)
    triangulation.GetProperty().SetColor(1, 0, 0)

    ren.AddActor(triangulation)
    ren.SetBackground(1, 1, 1)
Ejemplo n.º 34
0
        def surf_fill_vtk(vertices, polys, mat, shape):
            """

            :param vertices:
            :param polys:
            :param mat:
            :param shape:
            :return:
            """
            import vtk
            from vtk.util import numpy_support

            voxverts = nibabel.affines.apply_affine(numpy.linalg.inv(mat),
                                                    vertices)
            points = vtk.vtkPoints()
            points.SetNumberOfPoints(len(voxverts))
            for i, pt in enumerate(voxverts):
                points.InsertPoint(i, pt)

            tris = vtk.vtkCellArray()
            for vert in polys:
                tris.InsertNextCell(len(vert))
                for v in vert:
                    tris.InsertCellPoint(v)

            pd = vtk.vtkPolyData()
            pd.SetPoints(points)
            pd.SetPolys(tris)
            del points, tris

            whiteimg = vtk.vtkImageData()
            whiteimg.SetDimensions(shape)
            if vtk.VTK_MAJOR_VERSION <= 5:
                whiteimg.SetScalarType(vtk.VTK_UNSIGNED_CHAR)
            else:
                info = vtk.vtkInformation()
                whiteimg.SetPointDataActiveScalarInfo(info,
                                                      vtk.VTK_UNSIGNED_CHAR, 1)

            ones = numpy.ones(numpy.prod(shape), dtype=numpy.uint8)
            whiteimg.GetPointData().SetScalars(
                numpy_support.numpy_to_vtk(ones))

            pdtis = vtk.vtkPolyDataToImageStencil()
            if vtk.VTK_MAJOR_VERSION <= 5:
                pdtis.SetInput(pd)
            else:
                pdtis.SetInputData(pd)

            pdtis.SetOutputWholeExtent(whiteimg.GetExtent())
            pdtis.Update()

            imgstenc = vtk.vtkImageStencil()
            if vtk.VTK_MAJOR_VERSION <= 5:
                imgstenc.SetInput(whiteimg)
                imgstenc.SetStencil(pdtis.GetOutput())
            else:
                imgstenc.SetInputData(whiteimg)
                imgstenc.SetStencilConnection(pdtis.GetOutputPort())
            imgstenc.SetBackgroundValue(0)

            imgstenc.Update()

            data = numpy_support.vtk_to_numpy(
                imgstenc.GetOutput().GetPointData().GetScalars()).reshape(
                    shape).transpose(2, 1, 0)
            del pd, voxverts, whiteimg, pdtis, imgstenc
            return data
Ejemplo n.º 35
0
def main():
    colors = vtk.vtkNamedColors()

    aren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(aren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Create single splat point
    pts = vtk.vtkPoints()
    verts = vtk.vtkCellArray()
    norms = vtk.vtkDoubleArray()
    scalars = vtk.vtkDoubleArray()

    x = [0.0] * 3
    pts.InsertNextPoint(x)
    norms.SetNumberOfTuples(1)
    norms.SetNumberOfComponents(3)
    n = [0] * 3
    n[0] = 0.707
    n[1] = 0.707
    n[2] = 0.0
    norms.InsertTuple(0, n)
    scalars.SetNumberOfTuples(1)
    scalars.SetNumberOfComponents(1)
    scalars.InsertTuple1(0, 1.0)

    verts.InsertNextCell(1)
    verts.InsertCellPoint(0)

    pData = vtk.vtkPolyData()
    pData.SetPoints(pts)
    pData.SetVerts(verts)
    pData.GetPointData().SetNormals(norms)
    pData.GetPointData().SetScalars(scalars)

    # Splat point and generate isosurface.
    splat = vtk.vtkGaussianSplatter()
    splat.SetInputData(pData)
    splat.SetModelBounds(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
    splat.SetSampleDimensions(75, 75, 75)
    splat.SetRadius(0.5)
    splat.SetEccentricity(5.0)
    splat.SetExponentFactor(-3.25)
    contour = vtk.vtkContourFilter()
    contour.SetInputConnection(splat.GetOutputPort())
    contour.SetValue(0, 0.9)
    splatMapper = vtk.vtkPolyDataMapper()
    splatMapper.SetInputConnection(contour.GetOutputPort())
    splatActor = vtk.vtkActor()
    splatActor.SetMapper(splatMapper)

    # Create outline.
    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(splat.GetOutputPort())
    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())
    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(colors.GetColor3d('Brown'))

    # Create cone to indicate direction.
    cone = vtk.vtkConeSource()
    cone.SetResolution(24)
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)
    coneActor.SetScale(0.75, 0.75, 0.75)
    coneActor.RotateZ(45.0)
    coneActor.AddPosition(0.50, 0.50, 0.0)
    coneActor.GetProperty().SetColor(colors.GetColor3d('DeepPink'))
    #
    # Rendering stuff.
    #
    aren.SetBackground(colors.GetColor3d('Beige'))
    aren.AddActor(splatActor)
    aren.AddActor(outlineActor)
    aren.AddActor(coneActor)

    renWin.SetSize(640, 640)
    renWin.SetWindowName('SingleSplat')
    renWin.Render()

    # Interact with the data.
    iren.Start()
Ejemplo n.º 36
0
def main():
    angle, step, radius, uncapped, show_line = get_program_parameters()
    angle = math.radians(abs(angle))
    step = math.radians(abs(step))
    radius = abs(radius)
    # With default settings set this to 45 and you get a bowl with a flat bottom.
    start = math.radians(90)

    pts = get_line(angle, step, radius, uncapped, start)

    # Setup points and lines
    points = vtk.vtkPoints()
    lines = vtk.vtkCellArray()
    for pt in pts:
        pt_id = points.InsertNextPoint(pt)
        if pt_id < len(pts) - 1:
            line = vtk.vtkLine()
            line.GetPointIds().SetId(0, pt_id)
            line.GetPointIds().SetId(1, pt_id + 1)
            lines.InsertNextCell(line)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetLines(lines)

    # Extrude the profile to make the capped sphere
    extrude = vtk.vtkRotationalExtrusionFilter()
    extrude.SetInputData(polydata)
    extrude.SetResolution(60)

    #  Visualize
    colors = vtk.vtkNamedColors()

    # To see the line
    lineMapper = vtk.vtkPolyDataMapper()
    lineMapper.SetInputData(polydata)

    lineActor = vtk.vtkActor()
    lineActor.SetMapper(lineMapper)
    lineActor.GetProperty().SetLineWidth(4)
    lineActor.GetProperty().SetColor(colors.GetColor3d("Red"))

    # To see the surface
    surfaceMapper = vtk.vtkPolyDataMapper()
    surfaceMapper.SetInputConnection(extrude.GetOutputPort())

    surfaceActor = vtk.vtkActor()
    surfaceActor.SetMapper(surfaceMapper)
    surfaceActor.GetProperty().SetColor(colors.GetColor3d('Khaki'))

    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    ren.AddActor(surfaceActor)
    if show_line:
        ren.AddActor(lineActor)
    ren.SetBackground(colors.GetColor3d('LightSlateGray'))

    ren.ResetCamera()
    ren.GetActiveCamera().Azimuth(0)
    ren.GetActiveCamera().Elevation(60)
    ren.ResetCameraClippingRange()

    renWin.SetSize(600, 600)
    renWin.Render()
    renWin.SetWindowName('CappedSphere')
    iren.Start()
Ejemplo n.º 37
0
def decimate(points,
             faces,
             reduction=0.75,
             smooth_steps=25,
             scalars=[],
             save_vtk=False,
             output_vtk=''):
    """
    Decimate vtk triangular mesh with vtk.vtkDecimatePro.

    Parameters
    ----------
    points : list of lists of floats
        each element is a list of 3-D coordinates of a vertex on a surface mesh
    faces : list of lists of integers
        each element is list of 3 indices of vertices that form a face
        on a surface mesh
    reduction : float
        fraction of mesh faces to remove
    smooth_steps : integer
        number of smoothing steps
    scalars : list of integers or floats
        optional scalars for output VTK file
    save_vtk : bool
        output decimated vtk file?
    output_vtk : string
        output decimated vtk file name

    Returns
    -------
    points : list of lists of floats
        decimated points
    faces : list of lists of integers
        decimated faces
    scalars : list of integers or floats
        scalars for output VTK file
    output_vtk : string
        output decimated vtk file

    Examples
    --------
    >>> # Example: Twins-2-1 left postcentral pial surface, 0.75 decimation:
    >>> from mindboggle.guts.mesh import decimate
    >>> from mindboggle.mio.vtks import read_vtk
    >>> from mindboggle.mio.fetch_data import prep_tests
    >>> urls, fetch_data = prep_tests()
    >>> input_vtk = fetch_data(urls['left_freesurfer_labels'])
    >>> points, f1, f2, faces, scalars, f3, f4, f5 = read_vtk(input_vtk)
    >>> reduction = 0.5
    >>> smooth_steps = 25
    >>> save_vtk = True
    >>> output_vtk = ''
    >>> points2, faces2, scalars, output_vtk = decimate(points, faces,
    ...     reduction, smooth_steps, scalars, save_vtk, output_vtk)
    >>> (len(points), len(points2))
    (145069, 72535)
    >>> (len(faces), len(faces2))
    (290134, 145066)

    View decimated surface (skip test):

    >>> from mindboggle.mio.plots import plot_surfaces
    >>> plot_surfaces('decimated.vtk') # doctest: +SKIP

    """
    import os
    import vtk

    #-------------------------------------------------------------------------
    # vtk points:
    #-------------------------------------------------------------------------
    vtk_points = vtk.vtkPoints()
    [vtk_points.InsertPoint(i, x[0], x[1], x[2]) for i, x in enumerate(points)]

    #-------------------------------------------------------------------------
    # vtk faces:
    #-------------------------------------------------------------------------
    vtk_faces = vtk.vtkCellArray()
    for face in faces:
        vtk_face = vtk.vtkPolygon()
        vtk_face.GetPointIds().SetNumberOfIds(3)
        vtk_face.GetPointIds().SetId(0, face[0])
        vtk_face.GetPointIds().SetId(1, face[1])
        vtk_face.GetPointIds().SetId(2, face[2])
        vtk_faces.InsertNextCell(vtk_face)

    #-------------------------------------------------------------------------
    # vtk scalars:
    #-------------------------------------------------------------------------
    if scalars:
        vtk_scalars = vtk.vtkFloatArray()
        vtk_scalars.SetName("scalars")
        for scalar in scalars:
            vtk_scalars.InsertNextValue(scalar)

    #-------------------------------------------------------------------------
    # vtkPolyData:
    #-------------------------------------------------------------------------
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(vtk_points)
    polydata.SetPolys(vtk_faces)
    if scalars:
        polydata.GetPointData().SetScalars(vtk_scalars)

    #-------------------------------------------------------------------------
    # Decimate:
    #-------------------------------------------------------------------------
    # We want to preserve topology (not let any cracks form).
    # This may limit the total reduction possible.
    decimate = vtk.vtkDecimatePro()

    # Migrate to VTK6:
    # http://www.vtk.org/Wiki/VTK/VTK_6_Migration/Replacement_of_SetInput
    # Old: decimate.SetInput(polydata)
    decimate.SetInputData(polydata)

    decimate.SetTargetReduction(reduction)
    decimate.PreserveTopologyOn()

    #-------------------------------------------------------------------------
    # Smooth:
    #-------------------------------------------------------------------------
    if save_vtk:
        if not output_vtk:
            output_vtk = os.path.join(os.getcwd(), 'decimated.vtk')
        exporter = vtk.vtkPolyDataWriter()
    else:
        output_vtk = None
    if smooth_steps > 0:
        smoother = vtk.vtkSmoothPolyDataFilter()

        # Migrate to VTK6:
        # http://www.vtk.org/Wiki/VTK/VTK_6_Migration/Replacement_of_SetInput
        # Old: smoother.SetInput(decimate.GetOutput())
        smoother.SetInputConnection(decimate.GetOutputPort())

        smoother.SetNumberOfIterations(smooth_steps)
        smoother.Update()
        out = smoother.GetOutput()

        # Migrate to VTK6:
        # http://www.vtk.org/Wiki/VTK/VTK_6_Migration/Replacement_of_SetInput
        # Old: exporter.SetInput(smoother.GetOutput())
        exporter.SetInputConnection(smoother.GetOutputPort())

    else:
        decimate.Update()
        out = decimate.GetOutput()
        if save_vtk:
            # Migrate to VTK6:
            # http://www.vtk.org/Wiki/VTK/VTK_6_Migration/Replacement_of_SetInput
            # http://stackoverflow.com/questions/29020740/
            #        what-is-the-difference-in-setinputconnection-and-setinput
            # Old: exporter.SetInput(decimate.GetOutput())
            exporter.SetInputConnection(decimate.GetOutputPort())

    #-------------------------------------------------------------------------
    # Export output:
    #-------------------------------------------------------------------------
    if save_vtk:
        exporter.SetFileName(output_vtk)
        exporter.Write()
        if not os.path.exists(output_vtk):
            raise IOError(output_vtk + " not found")

    #-------------------------------------------------------------------------
    # Extract decimated points, faces, and scalars:
    #-------------------------------------------------------------------------
    points = [
        list(out.GetPoint(point_id))
        for point_id in range(out.GetNumberOfPoints())
    ]
    if out.GetNumberOfPolys() > 0:
        polys = out.GetPolys()
        pt_data = out.GetPointData()
        faces = [[
            int(polys.GetData().GetValue(j))
            for j in range(i * 4 + 1, i * 4 + 4)
        ] for i in range(polys.GetNumberOfCells())]
        if scalars:
            scalars = [
                pt_data.GetScalars().GetValue(i) for i in range(len(points))
            ]
    else:
        faces = []
        scalars = []

    return points, faces, scalars, output_vtk
Ejemplo n.º 38
0
    def writeVTK(self, fileName, models=None):
        """Function to write a VTU file from a TreeMesh and model."""
        import vtk
        from vtk import vtkXMLUnstructuredGridWriter as Writer, VTK_VERSION
        from vtk.util.numpy_support import numpy_to_vtk, numpy_to_vtkIdTypeArray

        # Make the data parts for the vtu object
        # Points
        #mesh.number()
        if (type(mesh) is TreeMesh):
            ptshMat = mesh.gridhN
            ptsMat = np.vstack((mesh.gridN, mesh.gridhN))
        else:
            ptsMat = mesh._gridN + mesh.x0

        vtkPts = vtk.vtkPoints()
        vtkPts.SetData(numpy_to_vtk(ptsMat, deep=True))
        # Cells
        cellConn = np.array([c.nodes for c in mesh], dtype=np.int64)

        cellsMat = np.concatenate((np.ones(
            (cellConn.shape[0], 1), dtype=np.int64) * cellConn.shape[1],
                                   cellConn),
                                  axis=1).ravel()
        cellsArr = vtk.vtkCellArray()
        cellsArr.SetNumberOfCells(cellConn.shape[0])
        cellsArr.SetCells(cellConn.shape[0],
                          numpy_to_vtkIdTypeArray(cellsMat, deep=True))

        # Make the object
        vtuObj = vtk.vtkUnstructuredGrid()
        vtuObj.SetPoints(vtkPts)
        vtuObj.SetCells(vtk.VTK_VOXEL, cellsArr)
        # Add the level of refinement as a cell array
        cellSides = np.array([
            np.array(vtuObj.GetCell(i).GetBounds()).reshape(
                (3, 2)).dot(np.array([-1, 1]))
            for i in np.arange(vtuObj.GetNumberOfCells())
        ])
        uniqueLevel, indLevel = np.unique(np.prod(cellSides, axis=1),
                                          return_inverse=True)
        refineLevelArr = numpy_to_vtk(indLevel.max() - indLevel, deep=1)
        refineLevelArr.SetName('octreeLevel')
        vtuObj.GetCellData().AddArray(refineLevelArr)
        # Assign the model('s) to the object
        if models is not None:
            for item in six.iteritems(models):
                # Convert numpy array
                vtkDoubleArr = numpy_to_vtk(item[1], deep=1)
                vtkDoubleArr.SetName(item[0])
                vtuObj.GetCellData().AddArray(vtkDoubleArr)

        # Make the writer
        vtuWriteFilter = Writer()
        if float(VTK_VERSION.split('.')[0]) >= 6:
            vtuWriteFilter.SetInputData(vtuObj)
        else:
            vtuWriteFilter.SetInput(vtuObj)
        vtuWriteFilter.SetFileName(fileName)
        # Write the file
        vtuWriteFilter.Update()
Ejemplo n.º 39
0
def Cull(in0, out0):
    """
  Create BTPolygon from points in input, Compute Original Area

  Error = 0
  while Error < MaxError
    foreach vertex in input
      Create Polygon from input, minus this vertex
      Compute area
      subtract area from original area
    endfor
    find minimum error vertex, remove it
    Error = minimum error
  """
    """
  Do an initial point count reduction based on
  curvature through vertices of the polygons
  """
    in2 = vtk.vtkPolyData()
    ReducePolyData2D(in0, in2, 1)
    print("Number of points after reduction: %d\n" % in2.GetNumberOfPoints())
    originalArea = PolyDataArea(in2)
    print("Original area: %f" % (originalArea))
    #
    # SWAG numbers -- accept
    # area change of 0.5%,
    # regard 0.005% as the same as zero
    maxError = originalArea * 0.005
    errEpsilon = maxError * 0.001
    curPoints = vtk.vtkPoints()
    curPoints.DeepCopy(in2.GetPoints())
    PointCount = curPoints.GetNumberOfPoints()

    ids = vtk.vtkIdList()
    ids.SetNumberOfIds(PointCount - 1)
    minErrorPointID = -1

    while (True):
        minError = 10000000.0
        for i in range(PointCount):
            IdsMinusThisPoint(ids, PointCount, i)
            normal = (0.0, 0.0, 0.0)
            curArea = vtk.vtkPolygon.ComputeArea(curPoints, PointCount - 1,
                                                 ids, normal)
            thisError = math.fabs(originalArea - curArea)
            if (thisError < minError):
                minError = thisError
                minErrorPointID = i
                if (thisError < errEpsilon):
                    break

        # if we have a new winner for least important point
        if (minError <= maxError):
            newPoints = vtk.vtkPoints()
            for i in range(PointCount):
                if (i == minErrorPointID):
                    continue
                point = curPoints.GetPoint(i)
                newPoints.InsertNextPoint(point)
            curPoints.Delete()
            curPoints = newPoints
            PointCount = PointCount - 1
        else:
            break

    out0 = ConvertPointSequenceToPolyData(curPoints, 1)
    curPoints.Delete()
    in2.Delete()
Ejemplo n.º 40
0
colors.InsertComponent(0,1,99)
colors.InsertComponent(0,2,71)
colors.InsertComponent(1,0,125)
colors.InsertComponent(1,1,255)
colors.InsertComponent(1,2,0)
colors.InsertComponent(2,0,226)
colors.InsertComponent(2,1,207)
colors.InsertComponent(2,2,87)
sizes = vtk.vtkUnsignedCharArray()
sizes.SetName("Sizes")
sizes.SetNumberOfComponents(1)
sizes.SetNumberOfTuples(3)
sizes.SetValue(0,1)
sizes.SetValue(1,2)
sizes.SetValue(2,3)
polyVertexPoints = vtk.vtkPoints()
polyVertexPoints.SetNumberOfPoints(3)
polyVertexPoints.InsertPoint(0,0.0,0.0,0.0)
polyVertexPoints.InsertPoint(1,2.5,0.0,0.0)
polyVertexPoints.InsertPoint(2,5.0,0.0,0.0)
aPolyVertex = vtk.vtkPolyVertex()
aPolyVertex.GetPointIds().SetNumberOfIds(3)
aPolyVertex.GetPointIds().SetId(0,0)
aPolyVertex.GetPointIds().SetId(1,1)
aPolyVertex.GetPointIds().SetId(2,2)
aPolyVertexGrid = vtk.vtkUnstructuredGrid()
aPolyVertexGrid.Allocate(1,1)
aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(),aPolyVertex.GetPointIds())
aPolyVertexGrid.SetPoints(polyVertexPoints)
aPolyVertexGrid.GetPointData().SetScalars(sizes)
aPolyVertexGrid.GetPointData().AddArray(colors)
Ejemplo n.º 41
0
https://vtk.org/doc/nightly/html/classvtkSelectPolyData.html
"""

import vtk
import random

renderer = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(renderer)
renWin.SetSize(1500, 1500)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())

#Make Control Point
landmark = vtk.vtkPoints()
landmark.InsertNextPoint(
    [random.randrange(0, 10) / 10,
     random.randrange(0, 10) / 10, 0.0])
landmark.InsertNextPoint(
    [random.randrange(0, 10) / 10,
     random.randrange(0, 10) / 10, 0.0])
landmark.InsertNextPoint(
    [random.randrange(0, 10) / 10,
     random.randrange(0, 10) / 10, 0.0])
# landmark.InsertNextPoint([random.randrange(0, 10)/10, random.randrange(0, 10)/10, 0.0])
# landmark.InsertNextPoint([random.randrange(0, 10)/10, random.randrange(0, 10)/10, 0.0])
# landmark.InsertNextPoint([random.randrange(0, 10)/10, random.randrange(0, 10)/10, 0.0])
landmarkActor = vtk.vtkActor()
pickedPoint = -1
Ejemplo n.º 42
0
                  math.cos(delta)*math.cos(gam)*(2*3.14159265)/lam )

        vectorarr = vtk.vtkDoubleArray()
        vectorarr.SetNumberOfComponents(3)
        vectorarr.SetNumberOfTuples(3)
        vectorarr.SetComponent(0, 0, Qlabcenter1)
        vectorarr.SetComponent(0, 1, Qlabcenter2)
        vectorarr.SetComponent(0, 2, Qlabcenter3)
        vectorarr.SetComponent(1, 0, ki[0])
        vectorarr.SetComponent(1, 1, ki[1])
        vectorarr.SetComponent(1, 2, ki[2])
        vectorarr.SetComponent(2, 0, kf[0])
        vectorarr.SetComponent(2, 1, kf[1])
        vectorarr.SetComponent(2, 2, kf[2])

        vectorpoints = vtk.vtkPoints()
        vectorpoints.SetDataTypeToDouble()
        vectorpoints.SetNumberOfPoints(3)
        vectorpoints.SetPoint(0, (0.0, 0.0, 0.0))
        vectorpoints.SetPoint(1, (0.0, 0.0, 0.0))
        vectorpoints.SetPoint(2, (0.0, 0.0, 0.0))

        vectorgrid = vtk.vtkUnstructuredGrid()
        vectorgrid.SetPoints(vectorpoints)
        vectorgrid.GetPointData().SetVectors(vectorarr)

        usgridwriter = vtk.vtkUnstructuredGridWriter()
        usgridwriter.SetFileName('Qvector.vtk')
        usgridwriter.SetFileTypeToASCII()
        usgridwriter.SetInput(vectorgrid)
        usgridwriter.Write()
Ejemplo n.º 43
0
 def build_vtk(self):
     '''Build a vtkUnstructuredGrid instance corresponding to the mesh.
     
     This method creates a new vtkUnstructuredGrid object, set the nodes and the elements.
     
     :returns: the vtkUnstructuredGrid object.
     '''
     print('building vtk stuff for FE_Mesh')
     vtk_mesh = vtk.vtkUnstructuredGrid()
     # take care of nodes
     nodes = vtk.vtkPoints()
     nodes.SetNumberOfPoints(self.get_number_of_nodes());
     for i in range(self.get_number_of_nodes()):
         (x, y, z) = self._nodes[i]._x, self._nodes[i]._y, self._nodes[i]._z
         nodes.InsertPoint(i, x, y, z)  # here i == self._nodes[i].give_rank()
     vtk_mesh.SetPoints(nodes)
     # take care of elements
     for i in range(self.get_number_of_elements()):
         el = self._elements[i]
         vtk_type = FE_Mesh.to_vtk_element_type(el._type)
         # allocate memory for this element type
         # vtk_mesh.Allocate(vtk_type, numpy.shape(el_list)[0])
         if el._type in ['c2d3', 's3d3', 'c3d4', 'c3d6', 'c3d8', 'c3d13']:
             Ids = vtk.vtkIdList()
             for j in range(len(el._nodelist)):
                 Ids.InsertNextId(el._nodelist[j].give_rank())
             vtk_mesh.InsertNextCell(vtk_type, Ids)
         elif el._type.startswith('c3d10'):
             Ids = vtk.vtkIdList()
             Ids.InsertNextId(el._nodelist[0].give_rank())
             Ids.InsertNextId(el._nodelist[2].give_rank())
             Ids.InsertNextId(el._nodelist[1].give_rank())
             Ids.InsertNextId(el._nodelist[9].give_rank())
             Ids.InsertNextId(el._nodelist[5].give_rank())
             Ids.InsertNextId(el._nodelist[4].give_rank())
             Ids.InsertNextId(el._nodelist[3].give_rank())
             Ids.InsertNextId(el._nodelist[6].give_rank())
             Ids.InsertNextId(el._nodelist[8].give_rank())
             Ids.InsertNextId(el._nodelist[7].give_rank())
             vtk_mesh.InsertNextCell(vtk_type, Ids)
         elif el._type.startswith('c3d15'):
             Ids = vtk.vtkIdList()
             Ids.InsertNextId(el._nodelist[0].give_rank())
             Ids.InsertNextId(el._nodelist[2].give_rank())
             Ids.InsertNextId(el._nodelist[4].give_rank())
             Ids.InsertNextId(el._nodelist[9].give_rank())
             Ids.InsertNextId(el._nodelist[11].give_rank())
             Ids.InsertNextId(el._nodelist[13].give_rank())
             Ids.InsertNextId(el._nodelist[1].give_rank())
             Ids.InsertNextId(el._nodelist[3].give_rank())
             Ids.InsertNextId(el._nodelist[5].give_rank())
             Ids.InsertNextId(el._nodelist[10].give_rank())
             Ids.InsertNextId(el._nodelist[12].give_rank())
             Ids.InsertNextId(el._nodelist[14].give_rank())
             Ids.InsertNextId(el._nodelist[6].give_rank())
             Ids.InsertNextId(el._nodelist[7].give_rank())
             Ids.InsertNextId(el._nodelist[8].give_rank())
             vtk_mesh.InsertNextCell(vtk_type, Ids)
         elif el._type.startswith('c3d20'):
             Ids = vtk.vtkIdList()
             Ids.InsertNextId(el._nodelist[0].give_rank())
             Ids.InsertNextId(el._nodelist[6].give_rank())
             Ids.InsertNextId(el._nodelist[4].give_rank())
             Ids.InsertNextId(el._nodelist[2].give_rank())
             Ids.InsertNextId(el._nodelist[12].give_rank())
             Ids.InsertNextId(el._nodelist[18].give_rank())
             Ids.InsertNextId(el._nodelist[16].give_rank())
             Ids.InsertNextId(el._nodelist[14].give_rank())
             Ids.InsertNextId(el._nodelist[7].give_rank())
             Ids.InsertNextId(el._nodelist[5].give_rank())
             Ids.InsertNextId(el._nodelist[3].give_rank())
             Ids.InsertNextId(el._nodelist[1].give_rank())
             Ids.InsertNextId(el._nodelist[19].give_rank())
             Ids.InsertNextId(el._nodelist[17].give_rank())
             Ids.InsertNextId(el._nodelist[15].give_rank())
             Ids.InsertNextId(el._nodelist[13].give_rank())
             Ids.InsertNextId(el._nodelist[8].give_rank())
             Ids.InsertNextId(el._nodelist[11].give_rank())
             Ids.InsertNextId(el._nodelist[10].give_rank())
             Ids.InsertNextId(el._nodelist[9].give_rank())
             vtk_mesh.InsertNextCell(vtk_type, Ids)
         elif el._type.startswith('c2d4') or el._type.startswith('s3d4'):
             Ids = vtk.vtkIdList()
             for j in range(len(el._nodelist)):
                 Ids.InsertNextId(el._nodelist[j].give_rank())
             vtk_mesh.InsertNextCell(vtk_type, Ids)
         elif el._type.startswith('c2d8') or el._type.startswith('s3d8'):
             Ids = vtk.vtkIdList()
             Ids.InsertNextId(el._nodelist[0].give_rank())
             Ids.InsertNextId(el._nodelist[2].give_rank())
             Ids.InsertNextId(el._nodelist[4].give_rank())
             Ids.InsertNextId(el._nodelist[6].give_rank())
             Ids.InsertNextId(el._nodelist[1].give_rank())
             Ids.InsertNextId(el._nodelist[3].give_rank())
             Ids.InsertNextId(el._nodelist[5].give_rank())
             Ids.InsertNextId(el._nodelist[7].give_rank())
             vtk_mesh.InsertNextCell(vtk_type, Ids)
     return vtk_mesh
Ejemplo n.º 44
0
import vtk

# create a rendering window and renderer
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)

# create a renderwindowinteractor
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

# Create the points fot the lines.
points = vtk.vtkPoints()
points.InsertPoint(0, 0, 0, 1)
points.InsertPoint(1, 1, 0, 0)
points.InsertPoint(2, 0, 1, 0)
points.InsertPoint(3, 1, 1, 1)

# Create line1
line1 = vtk.vtkLine()
line1.GetPointIds().SetId(0, 0)
line1.GetPointIds().SetId(1, 1)

# Create line2
line2 = vtk.vtkLine()
line2.GetPointIds().SetId(0, 2)
line2.GetPointIds().SetId(1, 3)

# Create a cellArray containing the lines
lines = vtk.vtkCellArray()
lines.InsertNextCell(line1)
Ejemplo n.º 45
0
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Prevent .pyc files being created.
# Stops the vtk source being polluted
# by .pyc files.
sys.dont_write_bytecode = True

import backdrop

# Contour every quadratic cell type
# Create a scene with one of each cell type.
# QuadraticEdge
edgePoints = vtk.vtkPoints()
edgePoints.SetNumberOfPoints(3)
edgePoints.InsertPoint(0, 0, 0, 0)
edgePoints.InsertPoint(1, 1.0, 0, 0)
edgePoints.InsertPoint(2, 0.5, 0.25, 0)
edgeScalars = vtk.vtkFloatArray()
edgeScalars.SetNumberOfTuples(3)
edgeScalars.InsertValue(0, 0.0)
edgeScalars.InsertValue(1, 0.0)
edgeScalars.InsertValue(2, 0.9)
aEdge = vtk.vtkQuadraticEdge()
aEdge.GetPointIds().SetId(0, 0)
aEdge.GetPointIds().SetId(1, 1)
aEdge.GetPointIds().SetId(2, 2)
aEdgeGrid = vtk.vtkUnstructuredGrid()
aEdgeGrid.Allocate(1, 1)
Ejemplo n.º 46
0
def cap_polydata_openings(poly, size):
    """
    Cap the PolyData openings  with acceptable mesh quality

    Args:
        poly: VTK PolyData to cap
        size: edge size of the cap mesh
    Returns:
        poly: capped VTK PolyData
    """
    # TRY NOT USE TO USE THE POINT IDS, START FROM FEATURE EDGE DIRECTLY SINCE IT REQUIRES THE BOUNDARY POLYDATA
    #import matplotlib.pyplot as plt
    from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
    import os

    def _plot_points(points):
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        ax.scatter(points[:, 0], points[:, 1], points[:, 2])
        plt.show()

    def _add_nodes_to_cap(vtkPts, size):
        """
        Add uniformed points to cap
        """
        points = vtk_to_numpy(vtkPts.GetData())
        num = points.shape[0]
        #_plot_points(points)
        ctr = np.mean(points, axis=0)
        length = np.mean(np.linalg.norm(points - ctr, axis=1))
        r = np.linspace(0.5 * size / length, (length - size * 0.8) / length,
                        int(np.floor(length / size)))
        addedPts = vtk.vtkPoints()
        for rf in r:
            newPts = vtk.vtkPoints()
            newPts.SetData(numpy_to_vtk((points - ctr) * rf + ctr))
            addedPts.InsertPoints(addedPts.GetNumberOfPoints(),
                                  newPts.GetNumberOfPoints(), 0, newPts)
        ptsPly = vtk.vtkPolyData()
        ptsPly.SetPoints(addedPts)
        vertexFilter = vtk.vtkVertexGlyphFilter()
        vertexFilter.SetInputData(ptsPly)
        vertexFilter.Update()
        ptsPly = vertexFilter.GetOutput()
        cleanedPts = clean_polydata(ptsPly, size * 0.01)

        vtkPts.InsertPoints(vtkPts.GetNumberOfPoints(),
                            cleanedPts.GetNumberOfPoints(), 0,
                            cleanedPts.GetPoints())

        #_plot_points(vtk_to_numpy(vtkPts.GetData()))
        return vtkPts

    def _delaunay_2d(vtkPts, boundary):
        """
        Delaunay 2D on input points
        """
        vtkPtsPly = vtk.vtkPolyData()
        vtkPtsPly.SetPoints(vtkPts)

        ids, pt_list = oriented_pointset_on_boundary(boundary)

        polygon = vtk.vtkCellArray()
        polygon.InsertNextCell(len(ids))
        for i in ids:
            polygon.InsertCellPoint(i)
        vtkPtsPly.SetPolys(polygon)
        delaunay = vtk.vtkDelaunay2D()
        delaunay.SetInputData(vtkPtsPly)
        delaunay.SetSourceData(vtkPtsPly)
        delaunay.SetTolerance(0.002)
        delaunay.Update()
        return delaunay.GetOutput()

    #tag polydata
    tag_id = 1
    poly = tag_polydata(poly, tag_id)

    edges = find_boundary_edges(poly)
    components = separate_disconnected_polydata(edges)
    id_lists = [None] * len(components)
    pt_lists = [None] * len(components)
    for i in range(len(id_lists)):
        id_lists[i] = find_point_correspondence(poly,
                                                components[i].GetPoints())
        pt_lists[i] = vtk.vtkPoints()
        pt_lists[i].DeepCopy(components[i].GetPoints())
        print('Found %d points for boundary %d\n' % (len(id_lists[i]), i))

    cap_pts_list = list()
    for boundary, ids, pts in zip(components, id_lists, pt_lists):
        cap_pts = _add_nodes_to_cap(pts, size)
        cap_pts_list.append(cap_pts)
        cap = _delaunay_2d(cap_pts, boundary)
        #cap = cutSurfaceWithPolygon(cap, boundary)
        #tag the caps
        tag_id += 1
        cap = tag_polydata(cap, tag_id)
        poly = append_polydata(poly, cap)

    #cap_pts_ids = list()
    #for cap_pts in cap_pts_list:
    #    cap_pts_ids.append(find_point_correspondence(poly,cap_pts))
    poly = fix_polydata_normals(poly)
    return poly
Ejemplo n.º 47
0
def create_surface():
    path_directory = 'PATH2D/'
    #elevation_data = np.loadtxt(path_directory + 'Ground_Rock2D.txt', delimiter = ',')
    topography = np.loadtxt(path_directory + 'Ground_Rock2D_2.txt')
#    topography *= 10
    #elevation_data = elevation_data[:,1]
    #elevation_data *= 100
    #width = elevation_data.shape[0]
    #width = 30
    
    #topography = np.repeat(elevation_data, width).reshape((width, elevation_data.shape[0]))
    
    m = topography.shape[0]
    n = topography.shape[1]
    
    # Define points, triangles and colors
    points = vtk.vtkPoints()
    triangles = vtk.vtkCellArray()
    
    # Build the meshgrid manually
    count = 0
    for i in range(m-1):
        for j in range(n-1):
    
            z1 = topography[i][j]
            z2 = topography[i][j+1]
            z3 = topography[i+1][j]
    
            # Triangle 1
            points.InsertNextPoint(i, j, z1)
            points.InsertNextPoint(i, (j+1), z2)
            points.InsertNextPoint((i+1), j, z3)
    
            triangle = vtk.vtkTriangle()
            triangle.GetPointIds().SetId(0, count)
            triangle.GetPointIds().SetId(1, count + 1)
            triangle.GetPointIds().SetId(2, count + 2)
    
            triangles.InsertNextCell(triangle)
    
            z1 = topography[i][j+1]
            z2 = topography[i+1][j+1]
            z3 = topography[i+1][j]
    
            # Triangle 2
            points.InsertNextPoint(i, (j+1), z1)
            points.InsertNextPoint((i+1), (j+1), z2)
            points.InsertNextPoint((i+1), j, z3)
    
            triangle = vtk.vtkTriangle()
            triangle.GetPointIds().SetId(0, count + 3)
            triangle.GetPointIds().SetId(1, count + 4)
            triangle.GetPointIds().SetId(2, count + 5)
    
            count += 6
    
            triangles.InsertNextCell(triangle)
    
    # Create a polydata object
    trianglePolyData = vtk.vtkPolyData()
    
    # Add the geometry and topology to the polydata
    trianglePolyData.SetPoints(points)
    #trianglePolyData.GetPointData().SetScalars(colors)
    trianglePolyData.SetPolys(triangles)
    
    # Clean the polydata so that the edges are shared !
    cleanPolyData = vtk.vtkCleanPolyData()
    cleanPolyData.SetInputData(trianglePolyData)
    
    # Use a filter to smooth the data (will add triangles and smooth)
    smooth_loop = vtk.vtkLoopSubdivisionFilter()
    smooth_loop.SetNumberOfSubdivisions(3)
    smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort())
    
    # Create a mapper and actor for smoothed dataset
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(smooth_loop.GetOutputPort())
    actor_loop = vtk.vtkActor()
    actor_loop.SetMapper(mapper)
    actor_loop.GetProperty().SetInterpolationToFlat()
    
    # Update the pipeline so that vtkCellLocator finds cells !
    smooth_loop.Update()
    
    # Define a cellLocator to be able to compute intersections between lines
    # and the surface
    locator = vtk.vtkCellLocator()
    locator.SetDataSet(smooth_loop.GetOutput())
    locator.BuildLocator()
    
    transform = vtk.vtkTransform()
    transform.Scale((0.06, 1, 1))
    transformFilter = vtk.vtkTransformPolyDataFilter()
    transformFilter.SetTransform(transform)
    actor_loop.SetUserTransform(transform)

    # Visualize
#    renderer = vtk.vtkRenderer()
#    renderWindow = vtk.vtkRenderWindow()
#    renderWindow.AddRenderer(renderer)
#    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
#    renderWindowInteractor.SetRenderWindow(renderWindow)
    
    return actor_loop
    # Add actors and render
#    renderer.AddActor(actor_loop)
#    
#    renderer.SetBackground(1, 1, 1)  # Background color white
#    renderWindow.SetSize(800, 800)
#    renderWindow.Render()
#    renderWindowInteractor.Start()
Ejemplo n.º 48
0
def visualizeTracks(tracker, seed):
    # Input the seed to the tracker object
    tracker.set_seeds(seed)

    # Run the tracker
    # This step will create N tracks if seed is a 3xN matrix
    tractogram = tracker.run()

    # Convert the first track to a vtkActor, i.e., tractogram[0] is the track
    # computed for the first seed
    # return trk2vtkActor(tractogram[0])

    # renderer.AddActor(trkActor)

    # convert trk to vtkPolyData
    trk = np.transpose(np.asarray(tractogram[0]))
    numberOfPoints = trk.shape[0]

    points = vtk.vtkPoints()
    lines = vtk.vtkCellArray()

    colors = vtk.vtkFloatArray()
    colors.SetNumberOfComponents(4)
    colors.SetName("tangents")

    k = 0
    lines.InsertNextCell(numberOfPoints)
    for j in range(numberOfPoints):
        points.InsertNextPoint(trk[j, :])
        lines.InsertCellPoint(k)
        k = k + 1

        if j < (numberOfPoints - 1):
            direction = trk[j + 1, :] - trk[j, :]
            direction = direction / np.linalg.norm(direction)
            colors.InsertNextTuple(
                np.abs([direction[0], direction[1], direction[2], 1]))
        else:
            colors.InsertNextTuple(
                np.abs([direction[0], direction[1], direction[2], 1]))

    trkData = vtk.vtkPolyData()
    trkData.SetPoints(points)
    trkData.SetLines(lines)
    trkData.GetPointData().SetScalars(colors)

    # make it a tube
    trkTube = vtk.vtkTubeFilter()
    trkTube.SetRadius(0.1)
    trkTube.SetNumberOfSides(4)
    trkTube.SetInputData(trkData)
    trkTube.Update()

    # mapper
    trkMapper = vtk.vtkPolyDataMapper()
    trkMapper.SetInputData(trkTube.GetOutput())

    # actor
    trkActor = vtk.vtkActor()
    trkActor.SetMapper(trkMapper)

    return trkActor
Ejemplo n.º 49
0
        def write_data(self, deck, problem, ccm_class):
            num_nodes = deck.num_nodes
            for t in range(0, deck.time_steps, self.slice_length):
                writer = vtk.vtkXMLUnstructuredGridWriter()
                writer.SetFileName(self.path + "output_" + str(t) + ".vtu")
                grid = vtk.vtkUnstructuredGrid()
                points = vtk.vtkPoints()
                points.SetNumberOfPoints(num_nodes)
                points.SetDataTypeToDouble()
                for i in range(0, num_nodes):
                    act = problem.y
                    if deck.dim == 1:
                        points.InsertPoint(i, act[i][0][t], 0., 0.)
                    if deck.dim == 2:
                        points.InsertPoint(i, act[i][0][t], act[i][1][t], 0.)
                    if deck.dim == 3:
                        points.InsertPoint(i, act[i][0][t], act[i][1][t],
                                           act[i][2][t])
                    grid.SetPoints(points)

                dataOut = grid.GetPointData()

                for out_type in self.types:

                    if out_type == "Displacement":
                        array = vtk.vtkDoubleArray()
                        array.SetName("Displacement")
                        array.SetNumberOfComponents(deck.dim)
                        array.SetNumberOfTuples(num_nodes)

                        act = problem.y

                        for i in range(num_nodes):
                            if deck.dim == 1:
                                array.SetTuple1(
                                    i,
                                    act[i][0][t] - deck.geometry.nodes[i][0])
                            if deck.dim == 2:
                                array.SetTuple2(
                                    i,
                                    act[i][0][t] - deck.geometry.nodes[i][0],
                                    act[i][1][t] - deck.geometry.nodes[i][1])
                                array.SetComponentName(0, "d_x")
                                array.SetComponentName(1, "d_y")
                            dataOut.AddArray(array)

                    if out_type == "Neighbors":
                        array = vtk.vtkIntArray()
                        array.SetName("Neighbors")
                        array.SetNumberOfComponents(1)
                        array.SetNumberOfTuples(num_nodes)

                        for i in range(num_nodes):
                            array.SetTuple1(
                                i,
                                len(problem.neighbors.get_index_x_family(i)))
                        dataOut.AddArray(array)

                    if out_type == "Force":
                        array = vtk.vtkDoubleArray()
                        array.SetName("Volume_Force")
                        array.SetNumberOfComponents(deck.dim)
                        array.SetNumberOfTuples(num_nodes)

                        force = problem.force_int
                        #print force
                        for i in range(num_nodes):
                            if deck.dim == 1:
                                array.SetTuple1(i, force[i][0][t])
                            if deck.dim == 2:
                                array.SetTuple2(i, force[i][0][t],
                                                force[i][1][t])
                                array.SetComponentName(0, "f_x")
                                array.SetComponentName(1, "f_y")
                            dataOut.AddArray(array)

                    if out_type == "Conditions":

                        for con in deck.conditions:
                            array = vtk.vtkIntArray()
                            array.SetName("Condition_" + con.type + "_" +
                                          str(con.value) + "_" +
                                          str(con.direction))
                            array.SetNumberOfComponents(1)
                            array.SetNumberOfTuples(num_nodes)

                            for i in range(num_nodes):
                                if i not in con.id:
                                    array.SetTuple1(i, 0)
                                else:
                                    array.SetTuple1(i, 1)
                        dataOut.AddArray(array)

                    if out_type == "Volume_Force":

                        force = problem.force_int
                        for con in deck.conditions:
                            if con.type == "Force":
                                result_x = 0.
                                result_y = 0.
                                result_z = 0.
                                for i in con.id:
                                    index = int(i)

                                    if deck.dim >= 1:
                                        result_x += force[index][0][
                                            t] * deck.geometry.volumes[index]
                                    if deck.dim >= 2:
                                        result_y += force[index][1][
                                            t] * deck.geometry.volumes[index]
                                        array.SetComponentName(0, "f_x")
                                        array.SetComponentName(1, "f_y")
                                    if deck.dim >= 3:
                                        result_z += force[index][2][
                                            t] * deck.geometry.volumes[index]
                                        array.SetComponentName(2, "f_z")

                                array = vtk.vtkDoubleArray()
                                array.SetName("Volume_" + con.type + "_" +
                                              str(con.value) + "_" +
                                              str(con.direction))
                                array.SetNumberOfComponents(deck.dim)
                                array.SetNumberOfTuples(num_nodes)

                                for i in range(num_nodes):
                                    if i in con.id:
                                        if deck.dim == 1:
                                            array.SetTuple1(i, result_x)
                                        if deck.dim == 2:
                                            array.SetTuple2(
                                                i, result_x, result_y)
                                        if deck.dim == 3:
                                            array.SetTuple3(
                                                i, result_x, result_y,
                                                result_z)
                                    else:
                                        if deck.dim == 1:
                                            array.SetTuple1(i, 0.)
                                        if deck.dim == 2:
                                            array.SetTuple2(i, 0., 0.)
                                        if deck.dim == 3:
                                            array.SetTuple3(i, 0., 0., 0.)
                            dataOut.AddArray(array)

                    if out_type == "Strain":
                        array = vtk.vtkDoubleArray()
                        array.SetName("Strain")
                        if deck.dim == 1:
                            array.SetNumberOfComponents(1)
                        if deck.dim == 2:
                            array.SetNumberOfComponents(3)
                        if deck.dim == 3:
                            array.SetNumberOfComponents(6)
                        array.SetNumberOfTuples(num_nodes)

                        strain = ccm_class.global_strain[:, :, 1]

                        for i in range(num_nodes):
                            if deck.dim == 1:
                                array.SetComponentName(0, "epsil_xx")
                                array.SetTuple1(i, strain[i, 0])
                            if deck.dim == 2:
                                xx = strain[i * deck.dim, 0]
                                xy = strain[i * deck.dim, 1]
                                yy = strain[i * deck.dim + 1, 1]
                                array.SetTuple3(i, xx, yy, xy)
                                array.SetComponentName(0, "epsil_xx")
                                array.SetComponentName(1, "epsil_yy")
                                array.SetComponentName(2, "epsil_xy")
                            if deck.dim == 3:
                                xx = strain[i * deck.dim, 0]
                                xy = strain[i * deck.dim, 1]
                                yy = strain[i * deck.dim + 1, 1]
                                yz = strain[i * deck.dim + 1, 2]
                                xz = strain[i * deck.dim, 2]
                                zz = strain[i * deck.dim + 2, 2]
                                array.SetTuple6(i, xx, yy, zz, yz, xz, xy)
                                array.SetComponentName(0, "epsil_xx")
                                array.SetComponentName(1, "epsil_yy")
                                array.SetComponentName(2, "epsil_zz")
                                array.SetComponentName(3, "epsil_yz")
                                array.SetComponentName(4, "epsil_xz")
                                array.SetComponentName(5, "epsil_xy")
                        dataOut.AddArray(array)

                    if out_type == "Stress":
                        array = vtk.vtkDoubleArray()
                        array.SetName("Stress")
                        if deck.dim == 1:
                            array.SetNumberOfComponents(1)
                        if deck.dim == 2:
                            array.SetNumberOfComponents(3)
                        if deck.dim == 3:
                            array.SetNumberOfComponents(6)
                        array.SetNumberOfTuples(num_nodes)

                        stress = ccm_class.global_stress[:, :, 1]

                        for i in range(num_nodes):
                            if deck.dim == 1:
                                array.SetComponentName(0, "sigma_xx")
                                array.SetTuple1(i, strain[i, 0])
                            if deck.dim == 2:
                                xx = stress[i * deck.dim, 0]
                                xy = stress[i * deck.dim, 1]
                                yy = stress[i * deck.dim + 1, 1]
                                array.SetTuple3(i, xx, yy, xy)
                                array.SetComponentName(0, "sigma_xx")
                                array.SetComponentName(1, "sigma_yy")
                                array.SetComponentName(2, "sigma_xy")
                            if deck.dim == 3:
                                xx = stress[i * deck.dim, 0]
                                xy = stress[i * deck.dim, 1]
                                yy = stress[i * deck.dim + 1, 1]
                                yz = stress[i * deck.dim + 1, 2]
                                xz = stress[i * deck.dim, 2]
                                zz = stress[i * deck.dim + 2, 2]
                                array.SetTuple6(i, xx, yy, zz, yz, xz, xy)
                                array.SetComponentName(0, "sigma_xx")
                                array.SetComponentName(1, "sigma_yy")
                                array.SetComponentName(2, "sigma_zz")
                                array.SetComponentName(3, "sigma_yz")
                                array.SetComponentName(4, "sigma_xz")
                                array.SetComponentName(5, "sigma_xy")
                        dataOut.AddArray(array)

                    if out_type == "Strain_DIC":
                        array = vtk.vtkDoubleArray()
                        array.SetName("Strain_DIC")
                        array.SetNumberOfComponents(3)
                        array.SetNumberOfTuples(num_nodes)

                        for i in range(num_nodes):
                            xx = deck.geometry.strain[i][0]
                            xy = deck.geometry.strain[i][2]
                            yy = deck.geometry.strain[i][1]
                            array.SetTuple3(i, xx, yy, xy)
                            array.SetComponentName(0, "epsil_xx")
                            array.SetComponentName(1, "epsil_yy")
                            array.SetComponentName(2, "epsil_xy")
                        dataOut.AddArray(array)

                    if out_type == "Strain_Error":
                        array = vtk.vtkDoubleArray()
                        array.SetName("Strain_Error")
                        array.SetNumberOfComponents(3)
                        array.SetNumberOfTuples(num_nodes)

                        strain = ccm_class.global_strain[:, :, 1]

                        for i in range(num_nodes):
                            xx = abs(deck.geometry.strain[i][0] -
                                     strain[i * deck.dim, 0])
                            xy = abs(deck.geometry.strain[i][2] -
                                     strain[i * deck.dim, 1])
                            yy = abs(deck.geometry.strain[i][1] -
                                     strain[i * deck.dim + 1, 1])
                            array.SetTuple3(i, xx, yy, xy)
                            array.SetComponentName(0, "error_xx")
                            array.SetComponentName(1, "error_yy")
                            array.SetComponentName(2, "error_xy")
                        dataOut.AddArray(array)

                    if out_type == "Strain_Energy":
                        array = vtk.vtkDoubleArray()
                        array.SetName("Strain_Energy")
                        array.SetNumberOfComponents(1)
                        array.SetNumberOfTuples(num_nodes)

                        strain_energy = problem.strain_energy

                        for i in range(num_nodes):
                            array.SetTuple1(i, strain_energy[i])

                        dataOut.AddArray(array)

                writer.SetInputData(grid)

                writer.GetCompressor().SetCompressionLevel(0)
                writer.SetDataModeToAscii()
                writer.Write()
Ejemplo n.º 50
0
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# A script to test the vtkLassoStencilSource
reader = vtk.vtkPNGReader()
reader.SetDataSpacing(0.8,0.8,1.5)
reader.SetDataOrigin(0.0,0.0,0.0)
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/fullhead15.png")
reader.Update()
shiftScale = vtk.vtkImageShiftScale()
shiftScale.SetInputConnection(reader.GetOutputPort())
shiftScale.SetScale(0.2)
shiftScale.Update()
points1 = vtk.vtkPoints()
points1.InsertNextPoint(80,50,0)
points1.InsertNextPoint(100,90,0)
points1.InsertNextPoint(200,50,0)
points1.InsertNextPoint(230,100,0)
points1.InsertNextPoint(150,170,0)
points1.InsertNextPoint(110,170,0)
points1.InsertNextPoint(80,50,0)
points2 = vtk.vtkPoints()
points2.InsertNextPoint(80,50,0)
points2.InsertNextPoint(100,90,0)
points2.InsertNextPoint(200,50,0)
points2.InsertNextPoint(230,100,0)
points2.InsertNextPoint(150,170,0)
points2.InsertNextPoint(110,170,0)
roiStencil1 = vtk.vtkLassoStencilSource()
Ejemplo n.º 51
0
# Read in vtk file
ugrid = vtk_py.readUGrid(meshname + ".vtk")

# Rotate mesh so that z = 0 at base
ugridrot = vtk_py.rotateUGrid(ugrid,
                              rx=0.0,
                              ry=-90.0,
                              rz=0.0,
                              sx=1.0,
                              sy=1.0,
                              sz=1.0)
vtk_py.writeUGrid(ugridrot, meshname + "_rot.vtk")

# For some reason vtkPointLocator in extractFenicsBiVFacet will give error if precision is too high
newpts = vtk.vtkPoints()
for p in range(0, ugridrot.GetNumberOfPoints()):
    pt = [
        ugridrot.GetPoints().GetPoint(p)[0],
        ugridrot.GetPoints().GetPoint(p)[1],
        ugridrot.GetPoints().GetPoint(p)[2]
    ]
    newpts.InsertNextPoint([round(pt[k], 5) for k in range(0, 3)])
ugridrot.SetPoints(newpts)

# Extract fenics mesh
fenics_mesh_ref, fenics_facet_ref, fenics_edge_ref = vtk_py.extractFeNiCsBiVFacet(
    ugridrot)
dolfin.File("bivmesh.pvd") << fenics_mesh_ref
dolfin.File("bivfacet.pvd") << fenics_facet_ref
dolfin.File("bivedge.pvd") << fenics_edge_ref
Ejemplo n.º 52
0
def SWC_Processing(filename):
    print("Converting swc to vtp.")
    newname = filename[:-3] + "vtp"
    dataset = [text.split() for text in open(filename)]

    number = [int(line[0]) for line in dataset]
    colour = [int(line[1]) for line in dataset]
    positions = [[float(line[2]), float(line[3]), float(line[4])] for line in dataset]
    radius = [float(line[5]) for line in dataset]
    connection = [int(line[6]) for line in dataset]

    links = [[] for i in range(0, len(number))]
    for i in range(0, len(number)):
        if connection[i] > 0:
            nodenumber = number[i] - 1
            linkedto = connection[i] - 1
            links[nodenumber].append(linkedto)
            links[linkedto].append(nodenumber)

    nodes = [Node() for node in range(0, len(number))]
    [nodes[index].set_number(index) for index, rad in enumerate(radius)]
    [nodes[index].set_radius(rad) for index, rad in enumerate(radius)]
    [nodes[index].set_position(pos) for index, pos in enumerate(positions)]
    [nodes[index].set_ID(id) for index, id in enumerate(colour)]

    for index, link in enumerate(links):
        for con in link:
            nodes[index].add_connection(nodes[con])
            nodes[con].add_connection(nodes[index])

    outlets = [node for node in nodes if len(node.Connections) == 1]
    Vessels = []
    ProcessedNodes = []
    for BifurcationNode in outlets:
        # check connected vessels
        newvessels = list(set(BifurcationNode.Connections) - set(ProcessedNodes))
        for node in newvessels:
            vessel = []
            vessel.append(BifurcationNode)
            ProcessedNodes.append(BifurcationNode)
            currentnode = node
            while 1:
                numberconnection = len(currentnode.Connections)
                if numberconnection == 2:
                    vessel.append(currentnode)
                    ProcessedNodes.append(currentnode)
                    currentnode = list(set(currentnode.Connections) - set(vessel))[0]
                elif numberconnection == 1:
                    vessel.append(currentnode)
                    ProcessedNodes.append(currentnode)
                    Vessels.append(vessel)
                    break
                else:
                    vessel.append(currentnode)
                    ProcessedNodes.append(currentnode)
                    Vessels.append(vessel)
                    break

    nodesvtk = vtk.vtkPoints()  # pos
    vessels = vtk.vtkCellArray()  # lines
    radius = vtk.vtkFloatArray()  # radius
    nodeid = vtk.vtkIntArray()  # id

    radius.SetNumberOfComponents(1)
    radius.SetName("Radius")
    nodeid.SetNumberOfComponents(1)
    nodeid.SetName("ID")

    # Add radius and position to data array
    for i in nodes:
        nodesvtk.InsertNextPoint(i.Position)
        radius.InsertNextValue(i.Radius)
        nodeid.InsertNextValue(i.ID)

    # Add vessels to cell array
    for vessel in Vessels:
        line = vtk.vtkLine()
        line.GetPointIds().SetNumberOfIds(len(vessel))
        for i in range(0, len(vessel)):
            line.GetPointIds().SetId(i, vessel[i].Number)
        vessels.InsertNextCell(line)

    # Create a polydata to store everything in
    VesselsPolyData = vtk.vtkPolyData()

    # Add the nodes to the polydata
    VesselsPolyData.SetPoints(nodesvtk)

    # Add the vessels to the polydata
    VesselsPolyData.SetLines(vessels)

    # Assign radii and id to the nodes
    VesselsPolyData.GetPointData().SetScalars(radius)
    VesselsPolyData.GetPointData().AddArray(nodeid)

    # Write everything to a vtp file
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(newname)
    writer.SetInputData(VesselsPolyData)
    writer.Write()
Ejemplo n.º 53
0
    def setWidgetView(self, widget):
        super(CenterLineView, self).setWidgetView(widget)
        point_array = self.parent.getData().pointSet
        point_data = npy.array(point_array.getData('Centerline'))
        if point_data is None or not point_data.shape[0]:
            return

        #self.spacing = [1, 1, 1]
        self.spacing = self.parent.getData().getResolution().tolist()
        self.spacing = [float(x) / self.spacing[-1] for x in self.spacing]
        point_data[:, :2] *= self.spacing[:2]

        self.renderer = vtk.vtkRenderer()
        self.render_window = widget.GetRenderWindow()
        self.render_window.AddRenderer(self.renderer)
        self.window_interactor = vtk.vtkRenderWindowInteractor()
        self.render_window.SetInteractor(self.window_interactor)

        self.center = []
        self.center_mapper = []
        self.center_actor = []
        self.points = []
        self.para_spline = []
        self.spline_source = []

        for cnt in range(3):
            self.center.append(vtk.vtkPolyData())
            self.center_mapper.append(vtk.vtkPolyDataMapper())
            self.center_actor.append(vtk.vtkActor())
            self.points.append(vtk.vtkPoints())
            self.para_spline.append(vtk.vtkParametricSpline())
            self.spline_source.append(vtk.vtkParametricFunctionSource())

            point = point_data[npy.where(npy.round(point_data[:, -1]) == cnt)]
            point = point[point[:, 2].argsort(), :]
            count = point.shape[0]
            if not count:
                continue

            self.points[cnt].SetNumberOfPoints(count)
            for i in range(count):
                self.points[cnt].SetPoint(i, point[i, 0], point[i, 1],
                                          point[i, 2])

            self.para_spline[cnt].SetPoints(self.points[cnt])

            self.spline_source[cnt].SetParametricFunction(
                self.para_spline[cnt])
            numberOfOutputPoints = count * 10
            self.spline_source[cnt].SetUResolution(numberOfOutputPoints)

            self.center_mapper[cnt].SetInput(
                self.spline_source[cnt].GetOutput())
            self.center_mapper[cnt].ScalarVisibilityOff()

            self.center_actor[cnt].SetMapper(self.center_mapper[cnt])
            color = [0, 0, 0]
            color[cnt] = 1
            self.center_actor[cnt].GetProperty().SetColor(
                color[0], color[1], color[2])
            self.renderer.AddViewProp(self.center_actor[cnt])

        bound = npy.array(
            self.parent.getData().getData().shape)[::-1] * self.spacing
        outline_source = vtk.vtkOutlineSource()
        outline_source.SetBounds(0, bound[0], 0, bound[1], 0, bound[2])

        mapOutline = vtk.vtkPolyDataMapper()
        mapOutline.SetInputConnection(outline_source.GetOutputPort())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(mapOutline)
        outlineActor.GetProperty().SetColor(1, 1, 1)
        self.renderer.AddViewProp(outlineActor)

        self.renderer.ResetCamera()
        point = self.renderer.GetActiveCamera().GetFocalPoint()
        dis = self.renderer.GetActiveCamera().GetDistance()
        self.renderer.GetActiveCamera().SetViewUp(0, 0, 1)
        self.renderer.GetActiveCamera().SetPosition(point[0], point[1] - dis,
                                                    point[2])
        self.renderer.ResetCameraClippingRange()
        self.render_window.Render()

        # Manually set to trackball style
        self.window_interactor.SetKeyCode('t')
        self.window_interactor.CharEvent()
        self.window_interactor.GetInteractorStyle().AddObserver(
            "KeyPressEvent", self.KeyPressCallback)
        self.window_interactor.GetInteractorStyle().AddObserver(
            "CharEvent", self.KeyPressCallback)
Ejemplo n.º 54
0
def convertQuadScalarDataToVTK(mesh, Fspace, data, filename=[]):

    nsubspace = Fspace.num_sub_spaces()
    assert (nsubspace == 0), 'Only scalar space works'

    dim = mesh.geometry().dim()
    coord = Fspace.tabulate_dof_coordinates().reshape((-1, dim))
    npts = int(len(coord))

    my_first, my_last = Fspace.dofmap().ownership_range()

    x_dofs = np.arange(0, my_last - my_first)
    coord_dofs = np.arange(0, (my_last - my_first))

    coord_reduce = coord[x_dofs]

    if (not isinstance(data, list)):

        points = vtk.vtkPoints()
        scalar = vtk.vtkFloatArray()
        scalar.SetNumberOfComponents(1)
        scalar.SetName("scalar")

        for x_dof, coord_dof in zip(x_dofs, coord_dofs):
            points.InsertNextPoint(coord_reduce[int(coord_dof)])
            scalar.InsertNextValue(data.vector().array()[x_dof])

        pdata = vtk.vtkPolyData()
        pdata.SetPoints(points)
        pdata.GetPointData().AddArray(scalar)

        glyphfilter = vtk.vtkVertexGlyphFilter()
        glyphfilter.AddInputData(pdata)
        glyphfilter.Update()

    else:

        points = vtk.vtkPoints()

        scalar_array = []
        for p in range(0, len(data)):
            scalar_array.append(vtk.vtkFloatArray())
            scalar_array[p].SetNumberOfComponents(3)
            scalar_array[p].SetName("scalar" + str(p))

        for x_dof, coord_dof in zip(x_dofs, coord_dofs):
            points.InsertNextPoint(coord_reduce[int(coord_dof)])
            for p in range(0, len(data)):
                scalar_array[p].InsertNextValue(
                    data[p].vector().array()[x_dof])

        pdata = vtk.vtkPolyData()
        pdata.SetPoints(points)
        for p in range(0, len(data)):
            pdata.GetPointData().AddArray(scalar_array[p])

        glyphfilter = vtk.vtkVertexGlyphFilter()
        glyphfilter.AddInputData(pdata)
        glyphfilter.Update()

    if (not (not filename)):
        filename_ = filename + str(MPI.rank(mpi_comm_world())) + '.vtp'
        #vtk_py.writeXMLPData(glyphfilter.GetOutput(), filename_, verbose=False)
        vtk_py.writeXMLPData(pdata, filename_, verbose=False)

        if (MPI.rank(mpi_comm_world()) == 0):
            pvtufilename = filename + '.pvtp'
            pvtufile = open(pvtufilename, 'w')
            print >> pvtufile, "<?xml version=\"1.0\"?>"
            print >> pvtufile, "<VTKFile type=\"PPolyData\" version=\"0.1\">"
            print >> pvtufile, "<PPolyData GhostLevel=\"0\">"
            print >> pvtufile, "<PPointData Vectors=\"vector\">"
            print >> pvtufile, "<PDataArray type=\"Float32\" Name=\"vector\" NumberOfComponents=\"3\" />"
            print >> pvtufile, "</PPointData>"
            print >> pvtufile, "<PPoints>"
            print >> pvtufile, "<PDataArray type=\"Float32\" NumberOfComponents=\"3\"/>"
            print >> pvtufile, "</PPoints>"

            for p in range(0, MPI.size(mpi_comm_world())):
                print >> pvtufile, "<Piece Source=\"" + os.getcwd(
                ) + "/" + filename + str(p) + '.vtp' + "\" />"
            print >> pvtufile, "</PPolyData>"
            print >> pvtufile, "</VTKFile>"
            pvtufile.close()

    return pdata
Ejemplo n.º 55
0
def main():
    colors = vtk.vtkNamedColors()

    # Set the colors.
    colors.SetColor("AzimuthArrowColor", [255, 77, 77, 255])
    colors.SetColor("ElevationArrowColor", [77, 255, 77, 255])
    colors.SetColor("RollArrowColor", [255, 255, 77, 255])
    colors.SetColor("SpikeColor", [255, 77, 255, 255])
    colors.SetColor("UpSpikeColor", [77, 255, 255, 255])

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

    # Create a camera model.
    camCS = vtk.vtkConeSource()
    camCS.SetHeight(1.5)
    camCS.SetResolution(12)
    camCS.SetRadius(0.4)

    camCBS = vtk.vtkCubeSource()
    camCBS.SetXLength(1.5)
    camCBS.SetZLength(0.8)
    camCBS.SetCenter(0.4, 0, 0)

    camAPD = vtk.vtkAppendPolyData()
    camAPD.AddInputConnection(camCBS.GetOutputPort())
    camAPD.AddInputConnection(camCS.GetOutputPort())

    camMapper = vtk.vtkPolyDataMapper()
    camMapper.SetInputConnection(camAPD.GetOutputPort())
    camActor = vtk.vtkLODActor()
    camActor.SetMapper(camMapper)
    camActor.SetScale(2, 2, 2)

    # Draw the arrows.
    pd = vtk.vtkPolyData()
    ca = vtk.vtkCellArray()
    pts = vtk.vtkPoints()
    pts.InsertNextPoint(0, 1, 0)
    pts.InsertNextPoint(8, 1, 0)
    pts.InsertNextPoint(8, 2, 0)
    pts.InsertNextPoint(10, 0, 0)
    pts.InsertNextPoint(8, -2, 0)
    pts.InsertNextPoint(8, -1, 0)
    pts.InsertNextPoint(0, -1, 0)
    ca.InsertNextCell(7)
    ca.InsertCellPoint(0)
    ca.InsertCellPoint(1)
    ca.InsertCellPoint(2)
    ca.InsertCellPoint(3)
    ca.InsertCellPoint(4)
    ca.InsertCellPoint(5)
    ca.InsertCellPoint(6)
    pd.SetPoints(pts)
    pd.SetPolys(ca)

    pd2 = vtk.vtkPolyData()
    ca2 = vtk.vtkCellArray()
    pts2 = vtk.vtkPoints()
    pts2.InsertNextPoint(0, 1, 0)
    pts2.InsertNextPoint(8, 1, 0)
    pts2.InsertNextPoint(8, 2, 0)
    pts2.InsertNextPoint(10, 0.01, 0)
    ca2.InsertNextCell(4)
    ca2.InsertCellPoint(0)
    ca2.InsertCellPoint(1)
    ca2.InsertCellPoint(2)
    ca2.InsertCellPoint(3)
    pd2.SetPoints(pts2)
    pd2.SetLines(ca2)

    arrowIM = vtk.vtkImplicitModeller()
    arrowIM.SetInputData(pd)
    arrowIM.SetSampleDimensions(50, 20, 8)

    arrowCF = vtk.vtkContourFilter()
    arrowCF.SetInputConnection(arrowIM.GetOutputPort())
    arrowCF.SetValue(0, 0.2)

    arrowWT = vtk.vtkWarpTo()
    arrowWT.SetInputConnection(arrowCF.GetOutputPort())
    arrowWT.SetPosition(5, 0, 5)
    arrowWT.SetScaleFactor(0.85)
    arrowWT.AbsoluteOn()

    arrowT = vtk.vtkTransform()
    arrowT.RotateY(60)
    arrowT.Translate(-1.33198, 0, -1.479)
    arrowT.Scale(1, 0.5, 1)

    arrowTF = vtk.vtkTransformFilter()
    arrowTF.SetInputConnection(arrowWT.GetOutputPort())
    arrowTF.SetTransform(arrowT)

    arrowMapper = vtk.vtkDataSetMapper()
    arrowMapper.SetInputConnection(arrowTF.GetOutputPort())
    arrowMapper.ScalarVisibilityOff()

    # Draw the azimuth arrows.
    a1Actor = vtk.vtkLODActor()
    a1Actor.SetMapper(arrowMapper)
    a1Actor.SetPosition(-9, 0, -1)
    a1Actor.GetProperty().SetColor(colors.GetColor3d("AzimuthArrowColor"))
    a1Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White"))
    a1Actor.GetProperty().SetSpecular(0.3)
    a1Actor.GetProperty().SetSpecularPower(20)
    a1Actor.GetProperty().SetAmbient(0.2)
    a1Actor.GetProperty().SetDiffuse(0.8)

    a2Actor = vtk.vtkLODActor()
    a2Actor.SetMapper(arrowMapper)
    a2Actor.RotateX(180)
    a2Actor.SetPosition(-9, 0, 1)
    a2Actor.GetProperty().SetColor(colors.GetColor3d("AzimuthArrowColor"))
    a2Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White"))
    a2Actor.GetProperty().SetSpecular(0.3)
    a2Actor.GetProperty().SetSpecularPower(20)
    a2Actor.GetProperty().SetAmbient(0.2)
    a2Actor.GetProperty().SetDiffuse(0.8)

    # Draw the elevation arrows.
    a3Actor = vtk.vtkLODActor()
    a3Actor.SetMapper(arrowMapper)
    a3Actor.RotateX(-90)
    a3Actor.SetPosition(-9, -1, 0)
    a3Actor.GetProperty().SetColor(colors.GetColor3d("ElevationArrowColor"))
    a3Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White"))
    a3Actor.GetProperty().SetSpecular(0.3)
    a3Actor.GetProperty().SetSpecularPower(20)
    a3Actor.GetProperty().SetAmbient(0.2)
    a3Actor.GetProperty().SetDiffuse(0.8)

    a4Actor = vtk.vtkLODActor()
    a4Actor.SetMapper(arrowMapper)
    a4Actor.RotateX(90)
    a4Actor.SetPosition(-9, 1, 0)
    a4Actor.GetProperty().SetColor(colors.GetColor3d("ElevationArrowColor"))
    a4Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White"))
    a4Actor.GetProperty().SetSpecular(0.3)
    a4Actor.GetProperty().SetSpecularPower(20)
    a4Actor.GetProperty().SetAmbient(0.2)
    a4Actor.GetProperty().SetDiffuse(0.8)

    # Draw the DOP.
    arrowT2 = vtk.vtkTransform()
    arrowT2.Scale(1, 0.6, 1)
    arrowT2.RotateY(90)

    arrowTF2 = vtk.vtkTransformPolyDataFilter()
    arrowTF2.SetInputData(pd2)
    arrowTF2.SetTransform(arrowT2)

    arrowREF = vtk.vtkRotationalExtrusionFilter()
    arrowREF.SetInputConnection(arrowTF2.GetOutputPort())
    arrowREF.CappingOff()
    arrowREF.SetResolution(30)

    spikeMapper = vtk.vtkPolyDataMapper()
    spikeMapper.SetInputConnection(arrowREF.GetOutputPort())

    a5Actor = vtk.vtkLODActor()
    a5Actor.SetMapper(spikeMapper)
    a5Actor.SetScale(0.3, 0.3, 0.6)
    a5Actor.RotateY(-90)
    a5Actor.SetPosition(-8, 0, 0)
    a5Actor.GetProperty().SetColor(colors.GetColor3d("SpikeColor"))
    a5Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White"))
    a5Actor.GetProperty().SetSpecular(0.3)
    a5Actor.GetProperty().SetAmbient(0.2)
    a5Actor.GetProperty().SetDiffuse(0.8)
    a5Actor.GetProperty().SetSpecularPower(20)

    a7Actor = vtk.vtkLODActor()
    a7Actor.SetMapper(spikeMapper)
    a7Actor.SetScale(0.2, 0.2, 0.7)
    a7Actor.RotateZ(90)
    a7Actor.RotateY(-90)
    a7Actor.SetPosition(-9, 1, 0)
    a7Actor.GetProperty().SetColor(colors.GetColor3d("UpSpikeColor"))
    a7Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White"))
    a7Actor.GetProperty().SetSpecular(0.3)
    a7Actor.GetProperty().SetAmbient(0.2)
    a7Actor.GetProperty().SetDiffuse(0.8)
    a7Actor.GetProperty().SetSpecularPower(20)

    # Focal point.
    ss = vtk.vtkSphereSource()
    ss.SetRadius(0.5)
    fpMapper = vtk.vtkPolyDataMapper()
    fpMapper.SetInputConnection(ss.GetOutputPort())
    fpActor = vtk.vtkLODActor()
    fpActor.SetMapper(fpMapper)
    fpActor.SetPosition(-9, 0, 0)
    fpActor.GetProperty().SetSpecularColor(colors.GetColor3d("White"))
    fpActor.GetProperty().SetSpecular(0.3)
    fpActor.GetProperty().SetAmbient(0.2)
    fpActor.GetProperty().SetDiffuse(0.8)
    fpActor.GetProperty().SetSpecularPower(20)

    # Create the roll arrows.
    arrowWT2 = vtk.vtkWarpTo()
    arrowWT2.SetInputConnection(arrowCF.GetOutputPort())
    arrowWT2.SetPosition(5, 0, 2.5)
    arrowWT2.SetScaleFactor(0.95)
    arrowWT2.AbsoluteOn()

    arrowT3 = vtk.vtkTransform()
    arrowT3.Translate(-2.50358, 0, -1.70408)
    arrowT3.Scale(0.5, 0.3, 1)

    arrowTF3 = vtk.vtkTransformFilter()
    arrowTF3.SetInputConnection(arrowWT2.GetOutputPort())
    arrowTF3.SetTransform(arrowT3)

    arrowMapper2 = vtk.vtkDataSetMapper()
    arrowMapper2.SetInputConnection(arrowTF3.GetOutputPort())
    arrowMapper2.ScalarVisibilityOff()

    # Draw the roll arrows.
    a6Actor = vtk.vtkLODActor()
    a6Actor.SetMapper(arrowMapper2)
    a6Actor.RotateZ(90)
    a6Actor.SetPosition(-4, 0, 0)
    a6Actor.SetScale(1.5, 1.5, 1.5)
    a6Actor.GetProperty().SetColor(colors.GetColor3d("RollArrowColor"))
    a6Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White"))
    a6Actor.GetProperty().SetSpecular(0.3)
    a6Actor.GetProperty().SetSpecularPower(20)
    a6Actor.GetProperty().SetAmbient(0.2)
    a6Actor.GetProperty().SetDiffuse(0.8)

    # Add the actors to the renderer, set the background and size.
    ren.AddActor(camActor)
    ren.AddActor(a1Actor)
    ren.AddActor(a2Actor)
    ren.AddActor(a3Actor)
    ren.AddActor(a4Actor)
    ren.AddActor(a5Actor)
    ren.AddActor(a6Actor)
    ren.AddActor(a7Actor)
    ren.AddActor(fpActor)
    ren.SetBackground(colors.GetColor3d("SlateGray"))
    renWin.SetSize(640, 480)

    # Render the image.

    cam1 = (ren.GetActiveCamera())
    ren.ResetCamera()
    cam1.Azimuth(150)
    cam1.Elevation(30)
    cam1.Dolly(1.5)
    ren.ResetCameraClippingRange()

    # Create a TextActor for Yaw  (a1 and a2 actor's color).
    text = vtk.vtkTextActor()
    text.SetInput("Yaw")
    tprop = text.GetTextProperty()
    tprop.SetFontFamilyToArial()
    tprop.ShadowOff()
    tprop.SetLineSpacing(1.0)
    tprop.SetFontSize(36)
    tprop.SetColor(a1Actor.GetProperty().GetColor())
    text.SetDisplayPosition(20, 50)
    ren.AddActor2D(text)

    # Create a TextActor for Pitch  (a3 and a4 actor's color).
    text2 = vtk.vtkTextActor()
    text2.SetInput("Pitch")
    tprop = text2.GetTextProperty()
    tprop.SetFontFamilyToArial()
    tprop.ShadowOff()
    tprop.SetLineSpacing(1.0)
    tprop.SetFontSize(36)
    tprop.SetColor(a3Actor.GetProperty().GetColor())
    text2.SetDisplayPosition(20, 100)
    ren.AddActor2D(text2)

    # Create a TextActor for roll (a6 actor's color).
    text3 = vtk.vtkTextActor()
    text3.SetInput("Roll")
    tprop = text3.GetTextProperty()
    tprop.SetFontFamilyToArial()
    tprop.ShadowOff()
    tprop.SetLineSpacing(1.0)
    tprop.SetFontSize(36)
    tprop.SetColor(a6Actor.GetProperty().GetColor())
    text3.SetDisplayPosition(20, 150)
    ren.AddActor2D(text3)

    iren.Initialize()
    iren.Start()
Ejemplo n.º 56
0
def get_frustum_actor(frustum_points):

    # Create frustum with lines
    pts = vtk.vtkPoints()
    origin = [0.0, 0.0, 0.0]
    pts.InsertNextPoint(origin)
    print(len(frustum_points))
    for idx in range(0,len(frustum_points)):
        print("point")
        pts.InsertNextPoint(frustum_points[idx])

    # Setup color
    green = [0, 255, 0]

    # Setup the colors array
    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    colors.SetName("Colors")

    for idx in range(0,8):
        # Add the colors to the colors array
        colors.InsertNextTypedTuple(green)

    # Create the lines

    # Create the first line (between Origin and P0)
    line0 = vtk.vtkLine()
    line0.GetPointIds().SetId(0,0) # the second 0 is the index of the Origin in the vtkPoints
    line0.GetPointIds().SetId(1,1) # the second 1 is the index of P0 in the vtkPoints

    # Create the second line (between Origin and P1)
    line1 = vtk.vtkLine()
    line1.GetPointIds().SetId(0,0) # the second 0 is the index of the Origin in the vtkPoints
    line1.GetPointIds().SetId(1,2) # 2 is the index of P1 in the vtkPoints

    # Next two lines from origin
    line2 = vtk.vtkLine()
    line2.GetPointIds().SetId(0,0)
    line2.GetPointIds().SetId(1,3)
    line3 = vtk.vtkLine()
    line3.GetPointIds().SetId(0,0)
    line3.GetPointIds().SetId(1,4)

    # Create box lines
    line4 = vtk.vtkLine()
    line4.GetPointIds().SetId(0,1)
    line4.GetPointIds().SetId(1,2)
    line5 = vtk.vtkLine()
    line5.GetPointIds().SetId(0,2)
    line5.GetPointIds().SetId(1,3)
    line6 = vtk.vtkLine()
    line6.GetPointIds().SetId(0,3)
    line6.GetPointIds().SetId(1,4)
    line7 = vtk.vtkLine()
    line7.GetPointIds().SetId(0,4)
    line7.GetPointIds().SetId(1,1)

    # Create a cell array to store the lines in and add the lines to it
    lines = vtk.vtkCellArray()
    lines.InsertNextCell(line0)
    lines.InsertNextCell(line1)
    lines.InsertNextCell(line2)
    lines.InsertNextCell(line3)
    lines.InsertNextCell(line4)
    lines.InsertNextCell(line5)
    lines.InsertNextCell(line6)
    lines.InsertNextCell(line7)

    # Create a polydata to store everything in
    linesPolyData = vtk.vtkPolyData()

    # Add the points to the dataset
    linesPolyData.SetPoints(pts)

    # Add the lines to the dataset
    linesPolyData.SetLines(lines)

    # Color the lines - associate the first component (red) of the
    # colors array with the first component of the cell array (line 0)
    # and the second component (green) of the colors array with the
    # second component of the cell array (line 1)
    linesPolyData.GetCellData().SetScalars(colors)

    # Visualize
    mapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(linesPolyData)
    else:
        mapper.SetInputData(linesPolyData)

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

    return actor
Ejemplo n.º 57
0
    def load_shabp_geometry(self, shabp_filename, name='main', plot=True):
        model_name = name
        self.gui.eid_maps[name] = {}
        self.gui.nid_maps[name] = {}

        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        skip_reading = self.gui._remove_old_geometry(shabp_filename)
        if skip_reading:
            return

        self.model = read_shabp(shabp_filename,
                                log=self.gui.log,
                                debug=self.gui.debug)
        self.gui.model_type = 'shabp'  # model.model_type

        out = self.model.get_points_elements_regions()
        nodes, elements, patches, components, impact, shadow = out
        #for nid,node in enumerate(nodes):
        #print "node[%s] = %s" %(nid,str(node))

        nnodes = len(nodes)
        nelements = len(elements)
        self.gui.nnodes = nnodes
        self.gui.nelements = nelements
        #print("nnodes = ",self.nnodes)
        #print("nelements = ", self.nelements)

        grid = self.gui.grid
        grid.Allocate(nelements, 1000)

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(nnodes)

        assert len(nodes) > 0
        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.gui.create_global_axes(dim_max)
        for nid, node in enumerate(nodes):
            points.InsertPoint(nid, *node)

        assert len(elements) > 0
        for unused_eid, element in enumerate(elements):
            (p1, p2, p3, p4) = element
            elem = vtkQuad()
            elem.GetPointIds().SetId(0, p1)
            elem.GetPointIds().SetId(1, p2)
            elem.GetPointIds().SetId(2, p3)
            elem.GetPointIds().SetId(3, p4)
            grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

        grid.SetPoints(points)
        grid.Modified()

        # loadShabpResults - regions/loads
        self.gui.scalar_bar_actor.VisibilityOn()
        self.gui.scalar_bar_actor.Modified()

        self.gui.isubcase_name_map = {1: ['S/HABP', '']}
        cases = OrderedDict()
        ID = 1

        self.gui.log.debug("nNodes=%i nElements=%i" %
                           (self.gui.nnodes, self.gui.nelements))
        form, cases = self._fill_shabp_geometry_case(cases, ID, nodes,
                                                     elements, patches,
                                                     components, impact,
                                                     shadow)

        nelements = len(elements)
        node_ids = np.arange(1, nnodes + 1, dtype='int32')
        element_ids = np.arange(1, nelements + 1, dtype='int32')
        self.gui.node_ids = node_ids
        self.gui.element_ids = element_ids
        self.gui._finish_results_io2(model_name, form, cases)
        self.gui.bkp = self.model
Ejemplo n.º 58
0
    def load_shabp_geometry(self, shabp_filename, name='main', plot=True):
        self.parent.eid_maps[name] = {}
        self.parent.nid_maps[name] = {}

        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        skip_reading = self.parent._remove_old_geometry(shabp_filename)
        if skip_reading:
            return

        self.model = read_shabp(shabp_filename,
                                log=self.parent.log,
                                debug=self.parent.debug)
        self.parent.model_type = 'shabp'  # model.model_type

        nodes, elements, patches, components, impact, shadow = self.model.get_points_elements_regions(
        )
        #for nid,node in enumerate(nodes):
        #print "node[%s] = %s" %(nid,str(node))

        nnodes = len(nodes)
        self.nnodes = len(nodes)
        self.nelements = len(elements)
        #print("nnodes = ",self.nnodes)
        #print("nelements = ", self.nelements)

        self.parent.grid.Allocate(self.parent.nelements, 1000)

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(self.parent.nnodes)

        assert len(nodes) > 0
        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.parent.create_global_axes(dim_max)
        for nid, node in enumerate(nodes):
            points.InsertPoint(nid, *node)

        assert len(elements) > 0
        for eid, element in enumerate(elements):
            (p1, p2, p3, p4) = element
            elem = vtkQuad()
            elem.GetPointIds().SetId(0, p1)
            elem.GetPointIds().SetId(1, p2)
            elem.GetPointIds().SetId(2, p3)
            elem.GetPointIds().SetId(3, p4)
            self.parent.grid.InsertNextCell(elem.GetCellType(),
                                            elem.GetPointIds())

        self.parent.grid.SetPoints(points)
        self.parent.grid.Modified()
        if hasattr(self.parent.grid, 'Update'):  # pragma: no cover
            self.parent.grid.Update()

        # loadShabpResults - regions/loads
        self.parent.scalarBar.VisibilityOn()
        self.parent.scalarBar.Modified()

        self.parent.isubcase_name_map = {1: ['S/HABP', '']}
        cases = OrderedDict()
        ID = 1

        self.parent.log.debug("nNodes=%i nElements=%i" %
                              (self.parent.nnodes, self.parent.nelements))
        form, cases = self._fill_shabp_geometry_case(cases, ID, nodes,
                                                     elements, patches,
                                                     components, impact,
                                                     shadow)
        self.parent._finish_results_io2(form, cases)
Ejemplo n.º 59
0
 def addingVTKCoords(self):
     # adding coordinates
     vtk_coords = list(self.coord)
     self.points = vtk.vtkPoints()
     for vtk_coord in vtk_coords:
         self.points.InsertNextPoint(vtk_coord)
Ejemplo n.º 60
0
def ReducePolyData2D(inPoly, outPoly, closed):
    """
  FIXME
  """
    inPts = inPoly.GetPoints()
    if inPts is None:
        return 0

    n = inPts.GetNumberOfPoints()
    if (n < 3):
        return 0
    p0 = inPts.GetPoint(0)
    p1 = inPts.GetPoint(n - 1)

    minusNth = p0[0] == p1[0] and p0[1] == p1[1] and p0[2] == p1[2]
    if (minusNth and closed == 1):
        n = n - 1

    # frenet unit tangent vector and state of kappa (zero or non-zero)
    f = n * [frenet((0.0, 0.0, 0.0), False)]

    # calculate the tangent vector by forward differences
    for i in range(n):
        p0 = inPts.GetPoint(i)
        p1 = inPts.GetPoint((i + 1) % n)
        tL = math.sqrt(vtk.vtkMath.Distance2BetweenPoints(p0, p1))
        if (tL == 0.0):
            tL = 1.0
        f[i].t = ((p1[0] - p0[0]) / tL, (p1[1] - p0[1]) / tL,
                  (p1[2] - p0[2]) / tL)

    # calculate kappa from tangent vectors by forward differences
    # mark those points that have very low curvature
    eps = 1.0e-10

    for i in range(n):
        t0 = f[i].t
        t1 = f[(i + 1) % n].t
        f[i].state = math.fabs(vtk.vtkMath.Dot(t0, t1) - 1.0) < eps

    tempPts = vtk.vtkPoints()

    # mark keepers
    ids = vtk.vtkIdTypeArray()

    # for now, insist on keeping the first point for closure
    ids.InsertNextValue(0)

    for i in range(1, n):
        pre = f[(i - 1 + n) % n].state  # means fik != 1
        cur = f[i].state  # means fik = 1
        nex = f[(i + 1) % n].state

        # possible vertex bend patterns for keep: pre cur nex
        # 0 0 1
        # 0 1 1
        # 0 0 0
        # 0 1 0

        # definite delete pattern
        # 1 1 1

        keep = False

        if (pre and cur and nex):
            keep = False
        elif (not pre and not cur and nex):
            keep = True
        elif (not pre and cur and nex):
            keep = True
        elif (not pre and not cur and not nex):
            keep = True
        elif (not pre and cur and not nex):
            keep = True

        if (keep):
            ids.InsertNextValue(i)

    for i in range(ids.GetNumberOfTuples()):
        tempPts.InsertNextPoint(inPts.GetPoint(ids.GetValue(i)))

    if (closed == 1):
        tempPts.InsertNextPoint(inPts.GetPoint(ids.GetValue(0)))

    outPoly = ConvertPointSequenceToPolyData(tempPts, closed)

    ids = None  #.Delete()
    tempPts = None  #.Delete()
    return 1