Beispiel #1
0
    def draw_axes_array(self, point_array, color):
        points_vtk = vtk.vtkPoints()
        for x, y, z in point_array:
            points_vtk.InsertNextPoint(x, -y, z)

        points_polydata = vtk.vtkPolyData()
        points_polydata.SetPoints(points_vtk)

        axes = vtk.vtkAxes()
        axes.SetScaleFactor(0.5)
        sphere = vtk.vtkSphereSource()
        sphere.SetRadius(0.01)
        normals_filter = vtk.vtkPolyDataNormals()
        normals_filter.FlipNormalsOn()
        normals_filter.SetInputConnection(axes.GetOutputPort())

        axes_glyph_mapper = vtk.vtkGlyph3DMapper()
        axes_glyph_mapper.SetInputData(points_polydata)
        axes_glyph_mapper.SetSourceConnection(axes.GetOutputPort())

        axes_glyph_actor = vtk.vtkActor()
        axes_glyph_actor.SetMapper(axes_glyph_mapper)
        axes_glyph_actor.GetProperty().SetPointSize(6)
        axes_glyph_actor.GetProperty().SetColor(color)
        axes_glyph_actor.GetProperty().SetRepresentationToWireframe()

        self.renderer.AddActor(axes_glyph_actor)
 def _get_actors(self):
     """Property getter for self.actors.
     """
     if (bool(self._actors_cache) == False and self.species_table
             and self.world_size and self.particles):
         for sp_id, info in self.species_table.items():
             name = info['name']
             radius = info['radius']
             D = info['D']
             points = vtk.vtkPoints()
             for p_id, p_info in self.particles.items():
                 if p_info['species_id'] == sp_id:
                     points.InsertNextPoint(p_info['position'] *
                                            self.scaling / self.world_size)
             poly_data = vtk.vtkPolyData()
             poly_data.SetPoints(points)
             source = vtk.vtkSphereSource()
             source.SetRadius(radius * self.scaling / self.world_size)
             # XXX
             # XXX There've been several PolyDataSource tries...
             # XXX
             # source = vtk.vtkPointSource()
             # source = vtk.vtkGlyphSource2D()
             # source.SetRadius(radius*self.scaling/self.world_size)
             # source = vtk.vtkDiskSource()
             # source.SetOuterRadius(radius*self.scaling/self.world_size)
             # source.SetGlyphTypeToCircle()
             # source.SetScale(2*radius*self.scaling/self.world_size)
             mapper = vtk.vtkGlyph3DMapper()
             mapper.SetSourceConnection(source.GetOutputPort())
             mapper.SetInputConnection(poly_data.GetProducerPort())
             actor = vtk.vtkActor()
             actor.SetMapper(mapper)
             self._actors_cache[sp_id] = actor
     return self._actors_cache
Beispiel #3
0
def point_to_glyph(points, scale):
    """
    Convert points to glyphs.
    :param points: The points to glyph.
    :param scale: The scale, used to determine the size of the
                  glyph representing the point, expressed as a
                  fraction of the largest side of the bounding
                  box surrounding the points. e.g. 0.05
    :return: The actor.
    """

    bounds = points.GetBounds()
    max_len = 0.0
    for i in range(0, 3):
        max_len = max(bounds[i + 1] - bounds[i], max_len)

    sphere_source = vtk.vtkSphereSource()
    sphere_source.SetRadius(scale * max_len)

    pd = vtk.vtkPolyData()
    pd.SetPoints(points)

    mapper = vtk.vtkGlyph3DMapper()
    mapper.SetInputData(pd)
    mapper.SetSourceConnection(sphere_source.GetOutputPort())
    mapper.ScalarVisibilityOff()
    mapper.ScalingOff()

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

    return actor
 def _get_actors(self):
     """Property getter for self.actors.
     """
     if (bool(self._actors_cache)==False and
         self.species_table and self.world_size and self.particles):
         for sp_id, info in self.species_table.items():
             name = info['name']
             radius = info['radius']
             D = info['D']
             points = vtk.vtkPoints()
             for p_id, p_info in self.particles.items():
                 if p_info['species_id']==sp_id:
                     points.InsertNextPoint(p_info['position']*self.scaling/self.world_size)
             poly_data = vtk.vtkPolyData()
             poly_data.SetPoints(points)
             source = vtk.vtkSphereSource()
             source.SetRadius(radius*self.scaling/self.world_size)
             # XXX
             # XXX There've been several PolyDataSource tries...
             # XXX
             # source = vtk.vtkPointSource() 
             # source = vtk.vtkGlyphSource2D()
             # source.SetRadius(radius*self.scaling/self.world_size)
             # source = vtk.vtkDiskSource() 
             # source.SetOuterRadius(radius*self.scaling/self.world_size)
             # source.SetGlyphTypeToCircle()
             # source.SetScale(2*radius*self.scaling/self.world_size)
             mapper = vtk.vtkGlyph3DMapper()
             mapper.SetSourceConnection(source.GetOutputPort())
             mapper.SetInputConnection(poly_data.GetProducerPort())
             actor = vtk.vtkActor()
             actor.SetMapper(mapper)
             self._actors_cache[sp_id] = actor
     return self._actors_cache
    def __init__(self, renderer, output_path, start_frame_index,
                 block_sets: List[TFrameBlockData]):
        self.start_frame_index = start_frame_index
        self.output_path = output_path
        self.renderer = renderer

        self.frame_count = len(block_sets)
        self.block_sets = block_sets

        colors = vtk.vtkNamedColors()

        self.block_locations = vtk.vtkPoints()
        self.block_labels = vtk.vtkStringArray()
        self.block_labels.SetName("label")
        self.verts = vtk.vtkCellArray()

        self.block_polydata = vtk.vtkPolyData()
        self.block_polydata.SetPoints(self.block_locations)
        self.block_polydata.SetVerts(self.verts)
        self.block_polydata.GetPointData().AddArray(self.block_labels)

        self.block_label_hierarchy = vtk.vtkPointSetToLabelHierarchy()
        self.block_label_hierarchy.SetInputData(self.block_polydata)
        self.block_label_hierarchy.SetLabelArrayName("label")

        self.block_label_placement_mapper = vtk.vtkLabelPlacementMapper()
        self.block_label_placement_mapper.SetInputConnection(
            self.block_label_hierarchy.GetOutputPort())
        self.block_label_placement_mapper.SetRenderStrategy(
            vtk.vtkFreeTypeLabelRenderStrategy())
        self.block_label_placement_mapper.SetShapeToRoundedRect()
        self.block_label_placement_mapper.SetBackgroundColor(1.0, 1.0, 0.7)
        self.block_label_placement_mapper.SetBackgroundOpacity(0.4)
        self.block_label_placement_mapper.SetMargin(3)

        self.block_mapper = vtk.vtkGlyph3DMapper()
        self.block_mapper.SetInputData(self.block_polydata)

        block = vtk.vtkCubeSource()
        block.SetXLength(VoxelVolumeParameters.BLOCK_SIZE)
        block.SetYLength(VoxelVolumeParameters.BLOCK_SIZE)
        block.SetZLength(VoxelVolumeParameters.BLOCK_SIZE)
        self.block_mapper.SetSourceConnection(block.GetOutputPort())

        # block actor
        self.block_actor = vtk.vtkActor()
        self.block_actor.SetMapper(self.block_mapper)
        self.block_actor.GetProperty().SetColor(
            colors.GetColor3d("PowderBlue"))
        self.block_actor.GetProperty().SetLineWidth(0.1)
        self.block_actor.GetProperty().SetRepresentationToWireframe()

        # label actor
        self.block_label_actor = vtk.vtkActor2D()
        self.block_label_actor.SetMapper(self.block_label_placement_mapper)

        self.renderer.AddActor(self.block_actor)
        self.renderer.AddActor(self.block_label_actor)
Beispiel #6
0
 def render(self, pointsData, scalarsArray, vectorsArray, nspecies, colouringOptions, vectorsOptions, lut,
            invert=False):
     """
     Render vectors.
     
     """
     self._logger.debug("Rendering vectors")
     
     # points
     points = vtk.vtkPoints()
     points.SetData(pointsData.getVTK())
     
     # polydata
     arrowPolyData = vtk.vtkPolyData()
     arrowPolyData.SetPoints(points)
     arrowPolyData.GetPointData().SetScalars(scalarsArray.getVTK())
     arrowPolyData.GetPointData().SetVectors(vectorsArray.getVTK())
 
     # arrow source
     arrowSource = vtk.vtkArrowSource()
     arrowSource.SetShaftResolution(vectorsOptions.vectorResolution)
     arrowSource.SetTipResolution(vectorsOptions.vectorResolution)
     if invert:
         arrowSource.InvertOn()
     arrowSource.Update()
     
     # glyph mapper
     arrowGlyph = vtk.vtkGlyph3DMapper()
     arrowGlyph.OrientOn()
     if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
         arrowGlyph.SetInputConnection(arrowPolyData.GetProducerPort())
     else:
         arrowGlyph.SetInputData(arrowPolyData)
     arrowGlyph.SetSourceConnection(arrowSource.GetOutputPort())
     arrowGlyph.SetScaleModeToScaleByMagnitude()
     arrowGlyph.SetScaleArray("vectors")
     arrowGlyph.SetScalarModeToUsePointFieldData()
     arrowGlyph.SelectColorArray("colours")
     arrowGlyph.SetScaleFactor(vectorsOptions.vectorScaleFactor)
     arrowMapper = arrowGlyph
     arrowMapper.SetLookupTable(lut)
     utils.setMapperScalarRange(arrowMapper, colouringOptions, nspecies)
 
     # actor
     arrowActor = vtk.vtkActor()
     arrowActor.SetMapper(arrowMapper)
     
     # store attributes
     self._actor = utils.ActorObject(arrowActor)
     self._data["Points"] = pointsData
     self._data["Scalars"] = scalarsArray
     self._data["Vectors"] = vectorsArray
     self._data["LUT"] = lut
     self._data["Scale factor"] = vectorsOptions.vectorScaleFactor
    def _get_actors(self):
        """override a base-class member function
        """
        for sid, actor in self._actors_cache.items():
            self._renderer.RemoveActor(actor)
        self._actors_cache.clear()

        if self.particle_space is not None:
            # bounds = [numpy.inf, 0.0, numpy.inf, 0.0, numpy.inf, 0.0]
            # cmap = create_color_map(len(self.particle_space.species))
            # for i, sid in enumerate(self.particle_space.species):
            #     color = cmap[i]
            for sid in self.particle_space.species:
                if sid not in self.color_map.keys():
                    continue
                color = self.color_map[sid]

                particles = self.particle_space.list_particles(sid)
                if len(particles) == 0:
                    continue

                points = vtk.vtkPoints()
                radius = 0.0
                for pid, particle in particles:
                    points.InsertNextPoint(
                        numpy.asarray(particle.position) / self.view_scale)
                    radius = max(particle.radius / self.view_scale, radius)

                points.ComputeBounds()
                b = points.GetBounds()
                # bounds = [
                #     min(bounds[0], b[0]), max(bounds[1], b[1]),
                #     min(bounds[2], b[2]), max(bounds[3], b[3]),
                #     min(bounds[4], b[4]), max(bounds[5], b[5])]

                poly_data = vtk.vtkPolyData()
                poly_data.SetPoints(points)

                # source = vtk.vtkPointSource()
                # source.SetRadius(radius)
                source = vtk.vtkSphereSource()
                source.SetRadius(radius)

                mapper = vtk.vtkGlyph3DMapper()
                mapper.SetSourceConnection(source.GetOutputPort())
                mapper.SetInputConnection(poly_data.GetProducerPort())
                actor = vtk.vtkActor()
                actor.SetMapper(mapper)
                actor.GetProperty().SetColor(color)
                self._actors_cache[sid] = actor

        debug('actors: %s' % self._actors_cache)
        return self._actors_cache
Beispiel #8
0
    def draw_vertices(self):

        self.vertex = vertex = vtkSphereSource()
        vertex.SetRadius(self.vertex_size * self.vertex_scale)
        vertex.SetPhiResolution(15)
        vertex.SetThetaResolution(15)

        mapper1 = vtkGlyph3DMapper()
        mapper1.SetInputData(self.polydata)
        mapper1.SetSourceConnection(vertex.GetOutputPort())
        mapper1.ScalingOff()
        mapper1.ScalarVisibilityOff()

        actor1 = vtkActor()
        actor1.SetMapper(mapper1)
        actor1.GetProperty().SetDiffuseColor(0.6, 0.6, 1.0)
        actor1.GetProperty().SetDiffuse(1.0)
        self.main.renderer.AddActor(actor1)

        if self.data.get('fixed', None):

            self.support = support = vtkSphereSource()
            support.SetRadius(self.vertex_size * 1.5 * self.vertex_scale)
            support.SetPhiResolution(15)
            support.SetThetaResolution(15)

            mapper2 = vtkGlyph3DMapper()
            mapper2.SetInputData(self.bcs)
            mapper2.SetSourceConnection(support.GetOutputPort())
            mapper2.ScalingOff()
            mapper2.ScalarVisibilityOff()

            actor2 = vtkActor()
            actor2.SetMapper(mapper2)
            actor2.GetProperty().SetDiffuseColor(1.0, 0.8, 0.0)
            actor2.GetProperty().SetDiffuse(1.0)
            self.main.renderer.AddActor(actor2)

        else:
            self.support = None
Beispiel #9
0
    def __init__(self, project, deformed=False):
        super().__init__()
        
        self.project = project 
        self.preprocessor = project.preprocessor
        self.deformed = deformed
        self.process_scaleFactor()

        self._connections = self._createConnections()
        # self._sequence = self._createSequence()

        self._data = vtk.vtkPolyData()
        self._mapper = vtk.vtkGlyph3DMapper()
Beispiel #10
0
    def AddMarker(self, x, y, z):
        s = vtk.vtkSphereSource()
        s.SetCenter(x, y, z)
        s.SetRadius(self.spacing[0])

        m = vtk.vtkGlyph3DMapper()
        m.SetInputConnection(s.GetOutputPort())
        m.OrientOn()

        a = vtk.vtkActor()
        a.SetMapper(m)

        self.ren.AddActor(a)
Beispiel #11
0
    def draw_vertices(self):
        self.vertex = vertex = vtkSphereSource()
        vertex.SetRadius(self.vertex_size * self.vertex_scale)
        vertex.SetPhiResolution(10)
        vertex.SetThetaResolution(10)

        mapper = vtkGlyph3DMapper()
        mapper.SetInputData(self.polydata)
        mapper.SetSourceConnection(vertex.GetOutputPort())
        mapper.ScalingOff()
        mapper.ScalarVisibilityOff()

        actor = vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetDiffuseColor(0.5, 0.5, 1.0)
        actor.GetProperty().LightingOff()
        actor.GetProperty().SetDiffuse(1.0)
        self.main.renderer.AddActor(actor)
Beispiel #12
0
    def create_local_grid_actor(self, cell_size, polydata):
        """Create a default voxel map VTK actor with a local grid polydata and cell dimensions."""
        array_name = polydata.GetPointData().GetArrayName(0)
        polydata.GetPointData().SetActiveScalars(array_name)
        colors = get_default_color_map()

        cube_source = get_vtk_cube_source(cell_size)
        mapper = vtk.vtkGlyph3DMapper()
        mapper.SetSourceConnection(cube_source.GetOutputPort())
        mapper.SetScaleModeToNoDataScaling()
        mapper.SetInputData(polydata)

        mapper.ScalarVisibilityOn()
        mapper.SetUseLookupTableScalarRange(True)
        mapper.SetLookupTable(colors)

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.SetUserTransform(vtk.vtkTransform())
        return actor
Beispiel #13
0
    def __init__(self, elements, project, *args, **kwargs):
        super().__init__()

        self.elements = elements
        self.project = project
        self.preprocessor = project.preprocessor

        self.hidden_elements = kwargs.get('hidden_elements', set())
        self.pressure_plot = kwargs.get('pressure_plot', False)

        self._key_index = {j: i for i, j in enumerate(self.elements.keys())}

        self.transparent = True
        self.bff = 5  # bug fix factor

        self._data = vtk.vtkPolyData()
        self._mapper = vtk.vtkGlyph3DMapper()
        self.colorTable = None
        self._colors = vtk.vtkUnsignedCharArray()
        self._colors.SetNumberOfComponents(3)
        self._colors.SetNumberOfTuples(len(self.elements))
Beispiel #14
0
    def draw_blocks(self):

        for location in self.data['blocks'].get('locations', []):
            self.locations.InsertNextPoint(location)
        self.blocks.SetPoints(self.locations)

        self.block = block = vtkCubeSource()
        size = self.data['blocks'].get('size', 1)
        block.SetXLength(size)
        block.SetYLength(size)
        block.SetZLength(size)

        mapper = vtkGlyph3DMapper()
        mapper.SetInputData(self.blocks)
        mapper.SetSourceConnection(block.GetOutputPort())

        self.block_actor = actor = vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetDiffuseColor(0.7, 0.7, 1.0)
        actor.GetProperty().SetDiffuse(1.0)
        actor.GetProperty().EdgeVisibilityOn()
        self.main.renderer.AddActor(actor)
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
 
        points = vtk.vtkPoints()
        points.InsertNextPoint(0, 0, 0)
        points.InsertNextPoint(1, 1, 1)
        points.InsertNextPoint(2, 2, 2)

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

        # Create anything you want here, we will use a cube for the demo.
        cubeSource = vtk.vtkCubeSource()

        glyph3dMapper = vtk.vtkGlyph3DMapper()
        glyph3dMapper.SetSourceConnection(cubeSource.GetOutputPort())
        glyph3dMapper.SetInputConnection(polyData.GetProducerPort())
        glyph3dMapper.Update()

        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(glyph3dMapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Beispiel #16
0
    def buildPipeline(self):
        """ execute() -> None
        Dispatch the vtkRenderer to the actual rendering widget
        """       
        self.colorInputModule = self.wmod.forceGetInputFromPort( "colors", None )
        
        if self.input() == None: 
            print>>sys.stderr, "Must supply 'volume' port input to VectorCutPlane"
            return
              
        xMin, xMax, yMin, yMax, zMin, zMax = self.input().GetWholeExtent()       
        spacing = self.input().GetSpacing()
        sx, sy, sz = spacing       
        origin = self.input().GetOrigin()
        ox, oy, oz = origin
        
        cellData = self.input().GetCellData()  
        pointData = self.input().GetPointData()     
        vectorsArray = pointData.GetVectors()
        
        if vectorsArray == None: 
            print>>sys.stderr, "Must supply point vector data for 'volume' port input to VectorVolume"
            return

        self.setRangeBounds( list( vectorsArray.GetRange(-1) ) )
        self.nComponents = vectorsArray.GetNumberOfComponents()
        for iC in range(-1,3): print "Value Range %d: %s " % ( iC, str( vectorsArray.GetRange( iC ) ) )
        for iV in range(10): print "Value[%d]: %s " % ( iV, str( vectorsArray.GetTuple3( iV ) ) )
        
        self.initialOrigin = self.input().GetOrigin()
        self.initialExtent = self.input().GetExtent()
        self.initialSpacing = self.input().GetSpacing()
        self.dataBounds = self.getUnscaledWorldExtent( self.initialExtent, self.initialSpacing, self.initialOrigin ) 
        dataExtents = ( (self.dataBounds[1]-self.dataBounds[0])/2.0, (self.dataBounds[3]-self.dataBounds[2])/2.0, (self.dataBounds[5]-self.dataBounds[4])/2.0 )
        centroid = ( (self.dataBounds[0]+self.dataBounds[1])/2.0, (self.dataBounds[2]+self.dataBounds[3])/2.0, (self.dataBounds[4]+self.dataBounds[5])/2.0  )
        self.pos = [ self.initialSpacing[i]*self.initialExtent[2*i] for i in range(3) ]
        if ( (self.initialOrigin[0] + self.pos[0]) < 0.0): self.pos[0] = self.pos[0] + 360.0

        self.resample = vtk.vtkExtractVOI()
        self.resample.SetInput( self.input() ) 
        self.resample.SetVOI( self.initialExtent )
        self.ApplyGlyphDecimationFactor()
        lut = self.getLut()
        
        if self.colorInputModule <> None:
            colorInput = self.colorInputModule.getOutput()
            self.color_resample = vtk.vtkExtractVOI()
            self.color_resample.SetInput( colorInput ) 
            self.color_resample.SetVOI( self.initialExtent )
            self.color_resample.SetSampleRate( sampleRate, sampleRate, 1 )
#            self.probeFilter = vtk.vtkProbeFilter()
#            self.probeFilter.SetSourceConnection( self.resample.GetOutputPort() )           
#            colorInput = self.colorInputModule.getOutput()
#            self.probeFilter.SetInput( colorInput )
            resampledColorInput = self.color_resample.GetOutput()
            shiftScale = vtk.vtkImageShiftScale()
            shiftScale.SetOutputScalarTypeToFloat ()           
            shiftScale.SetInput( resampledColorInput ) 
            valueRange = self.getScalarRange()
            shiftScale.SetShift( valueRange[0] )
            shiftScale.SetScale ( (valueRange[1] - valueRange[0]) / 65535 )
            colorFloatInput = shiftScale.GetOutput() 
            colorFloatInput.Update()
            colorInput_pointData = colorFloatInput.GetPointData()     
            self.colorScalars = colorInput_pointData.GetScalars()
            self.colorScalars.SetName('color')
            lut.SetTableRange( valueRange ) 
        
        self.glyph = vtk.vtkGlyph3DMapper() 
#        if self.colorInputModule <> None:   self.glyph.SetColorModeToColorByScalar()            
#        else:                               self.glyph.SetColorModeToColorByVector()          
        scalarRange = self.getScalarRange()
        self.glyph.SetScaleModeToScaleByMagnitude()
        self.glyph.SetColorModeToMapScalars()     
        self.glyph.SetUseLookupTableScalarRange(1)
        self.glyph.SetOrient( 1 ) 
#        self.glyph.ClampingOn()
        self.glyph.SetRange( scalarRange[0:2] )
        self.glyph.SetInputConnection( self.resample.GetOutputPort()  )
        self.arrow = vtk.vtkArrowSource()
        self.glyph.SetSourceConnection( self.arrow.GetOutputPort() )
        self.glyph.SetLookupTable( lut )
        self.glyphActor = vtk.vtkActor() 
        self.glyphActor.SetMapper( self.glyph )
        self.renderer.AddActor( self.glyphActor )
        self.renderer.SetBackground( VTK_BACKGROUND_COLOR[0], VTK_BACKGROUND_COLOR[1], VTK_BACKGROUND_COLOR[2] ) 
        self.set3DOutput(wmod=self.wmod) 
Beispiel #17
0
    def AddASD_actors(self, ren, renWin, mode, viz_type, iren):
        ASDMomActors.timer_count = 0
        ASDMomActors.camera_pos = np.zeros(3, dtype=np.float32)
        ASDMomActors.camera_focal = np.zeros(3, dtype=np.float32)
        ASDMomActors.camera_yaw = 0.0
        ASDMomActors.camera_roll = 0.0
        ASDMomActors.camera_pitch = 0.0
        ASDMomActors.camera_azimuth = 0.0
        ASDMomActors.camera_elevation = 0.0

        ASD_data = ASDVTKReading.ASDReading()
        # Add the data structures with regards to reading the data
        ASD_data.ReadingWrapper(mode=mode, viz_type=viz_type)

        ASDMomActors.kmc_disp = ASD_data.kmc_flag
        ASDMomActors.cluster_disp = ASD_data.cluster_flag
        ########################################################################
        # Data structures for the generation of the smooth grid
        ########################################################################
        ASDMomActors.glob_flag_2D = ASD_data.flag_2D
        ASDMomActors.glob_color_x = ASD_data.selected_colors_x
        ASDMomActors.glob_color_y = ASD_data.selected_colors_y
        ASDMomActors.glob_color_z = ASD_data.selected_colors_z
        ########################################################################
        # Look up tables for colors
        ########################################################################
        # This is a diverging RWB color mapping based on the work of Kenneth
        # Moreland and with the vtk examples provided by Andrew Maclean
        if ASDMomActors.glob_flag_2D:
            self.lut = vtk.vtkLookupTable()
            num_colors = 256
            self.lut.SetNumberOfTableValues(num_colors)

            self.transfer_func = vtk.vtkColorTransferFunction()
            self.transfer_func.SetColorSpaceToDiverging()
            self.transfer_func.AddRGBPoint(0, 0.230, 0.299, 0.754)
            self.transfer_func.AddRGBPoint(1, 0.706, 0.016, 0.150)

            for ii, ss in enumerate(
                [float(xx) / float(num_colors) for xx in range(num_colors)]):
                cc = self.transfer_func.GetColor(ss)
                self.lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
            self.lut.Build()
        else:
            self.lut = vtk.vtkLookupTable()
            num_colors = 256
            self.lut.SetNumberOfTableValues(num_colors)

            self.transfer_func = vtk.vtkColorTransferFunction()
            self.transfer_func.SetColorSpaceToDiverging()
            self.transfer_func.AddRGBPoint(-0, 0.230, 0.299, 0.754)
            self.transfer_func.AddRGBPoint(1, 0.706, 0.016, 0.150)

        for ii, ss in enumerate(
            [float(xx) / float(num_colors) for xx in range(num_colors)]):
            cc = self.transfer_func.GetColor(ss)
            self.lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
        self.lut.Build()

        ########################################################################
        # Data structures for the generation of the smooth grid
        ########################################################################

        # Passing the data from the full system to the PolyData
        ASDMomActors.src = vtk.vtkPolyData()
        ASDMomActors.src.SetPoints(ASD_data.selected_points)
        ASDMomActors.src.GetPointData().SetScalars(ASD_data.selected_colors_z)
        ASDMomActors.src.GetPointData().SetVectors(ASD_data.selected_vectors)
        scalar_range = ASDMomActors.src.GetScalarRange()

        ########################################################################
        # Finding useful geometrical information of the sample
        ########################################################################
        # Finding the middle of the sample
        # Also making sure that if the sample is 2D one has no problem with boudings
        # this is mostly useful if splatters are used
        (ASDMomActors.xmin, ASDMomActors.xmax, ASDMomActors.ymin,
         ASDMomActors.ymax, ASDMomActors.zmin,
         ASDMomActors.zmax) = ASDMomActors.src.GetBounds()
        if ASDMomActors.xmin == ASDMomActors.xmax:
            ASDMomActors.xmin = 0.0
            ASDMomActors.xmax = 1.0
        if ASDMomActors.ymin == ASDMomActors.ymax:
            ASDMomActors.ymin = 0.0
            ASDMomActors.ymax = 1.0
        if ASDMomActors.zmin == ASDMomActors.zmax:
            ASDMomActors.zmin = 0.0
            ASDMomActors.zmax = 1.0
        ASDMomActors.xmid = (ASDMomActors.xmin + ASDMomActors.xmax) * 0.5
        ASDMomActors.ymid = (ASDMomActors.ymin + ASDMomActors.ymax) * 0.5
        ASDMomActors.zmid = (ASDMomActors.zmin + ASDMomActors.zmax) * 0.5
        ASDMomActors.height = max(ASDMomActors.xmax, ASDMomActors.ymax,
                                  ASDMomActors.zmax) * 1.75
        self.dist_x = np.absolute(ASDMomActors.xmax - ASDMomActors.xmin)
        self.dist_y = np.absolute(ASDMomActors.ymax - ASDMomActors.ymin)
        self.dist_z = np.absolute(ASDMomActors.zmax - ASDMomActors.zmin)
        ASDMomActors.camera_pos[0] = ASDMomActors.xmid
        ASDMomActors.camera_pos[1] = ASDMomActors.ymid
        ASDMomActors.camera_pos[2] = ASDMomActors.height
        ASDMomActors.camera_focal[0] = ASDMomActors.xmid
        ASDMomActors.camera_focal[1] = ASDMomActors.ymid
        ASDMomActors.camera_focal[2] = ASDMomActors.zmid
        # The delaunay tesellation seems to be the best way to transform the point cloud
        # to a surface for volume rendering, the problem is that it is too slow for large
        # data sets, meaning that the best option is first to prune out the data to ensure
        # that one has a manageable number of data points over which to do the construction

        # surface reconstruction and splatter techniques also can be used to generate something
        # akin to the kind of surfaces we want. The issue is that they transform the data to a
        # regular mesh by default. And thus it is a problem for most kind of systems
        if ASDMomActors.glob_flag_2D:
            # Passing the data to generate a triangulation of the data
            MagDensMethod = vtk.vtkDelaunay2D()
            MagDensMethod.SetInputData(ASDMomActors.src)
            MagDensMethod.BoundingTriangulationOff()
            MagDensMethod.SetTolerance(0.005)
            # Time the execution of the delaunay tessellation
            SM_timer = vtk.vtkExecutionTimer()
            SM_timer.SetFilter(MagDensMethod)
            MagDensMethod.Update()
            SM = SM_timer.GetElapsedWallClockTime()
            print("2D Delaunay:", SM)

            # Creating the mapper for the smooth surfaces
            ASDMomActors.MagDensMap = vtk.vtkDataSetMapper()
            ASDMomActors.MagDensMap.SetScalarRange(scalar_range)
            ASDMomActors.MagDensMap.SetInputConnection(
                MagDensMethod.GetOutputPort())
            ASDMomActors.MagDensMap.SetLookupTable(self.lut)
            ASDMomActors.MagDensMap.SetColorModeToMapScalars()
            ASDMomActors.MagDensMap.Update()

            # Creating the actor for the smooth surfaces
            ASDMomActors.MagDensActor = vtk.vtkLODActor()
            ASDMomActors.MagDensActor.SetMapper(ASDMomActors.MagDensMap)
            ASDMomActors.MagDensActor.GetProperty().SetOpacity(0.75)
            ASDMomActors.MagDensActor.GetProperty().EdgeVisibilityOff()

        else:
            ####################################################################
            # Setting the parameters for the visualization of 3D structures with
            # splatters
            ####################################################################
            MagDensMethod = vtk.vtkShepardMethod()
            MagDensMethod.SetInputData(ASDMomActors.src)
            MagDensMethod.SetModelBounds(ASDMomActors.xmin, ASDMomActors.xmax,
                                         ASDMomActors.ymin, ASDMomActors.ymax,
                                         ASDMomActors.zmin, ASDMomActors.zmax)
            # This should get rid of the problems when trying to map very thin structures in 2D
            if self.dist_x == min(self.dist_x, self.dist_y, self.dist_z):
                MagDensMethod.SetSampleDimensions(3, int(ASDMomActors.ymax),
                                                  int(ASDMomActors.zmax))
            elif self.dist_y == min(self.dist_x, self.dist_y, self.dist_z):
                MagDensMethod.SetSampleDimensions(int(ASDMomActors.xmax), 3,
                                                  int(ASDMomActors.zmax))
            elif self.dist_z == min(self.dist_x, self.dist_y, self.dist_z):
                MagDensMethod.SetSampleDimensions(int(ASDMomActors.xmax),
                                                  int(ASDMomActors.ymax), 3)
    # This parameter determines how far in the sample (normalized to 1) the
    # method will look to interpolate, greatly affects performance
            MagDensMethod.SetMaximumDistance(0.1)

            # Time the execution of the checkerboard splatter
            SP_timer = vtk.vtkExecutionTimer()
            SP_timer.SetFilter(MagDensMethod)
            MagDensMethod.Update()
            SP = SP_timer.GetElapsedWallClockTime()
            print("3D Shepard Method:", SP)

            # Mapper for the image obtained from the 3D reconstruction method
            ASDMomActors.MagDensMap = vtk.vtkSmartVolumeMapper()
            ASDMomActors.MagDensMap.SetBlendModeToComposite()
            ASDMomActors.MagDensMap.SetInputConnection(
                MagDensMethod.GetOutputPort())

            # Function for the opacity gradient
            volumeGradientOpacity = vtk.vtkPiecewiseFunction()
            volumeGradientOpacity.AddPoint(-1, 0.25)
            volumeGradientOpacity.AddPoint(0.5, 0.75)
            volumeGradientOpacity.AddPoint(1.0, 1.0)

            # Properties of the volume to be rendered
            ASDMomActors.volumeProperty = vtk.vtkVolumeProperty()
            ASDMomActors.volumeProperty.SetInterpolationType(1)
            ASDMomActors.volumeProperty.SetColor(self.transfer_func)
            ASDMomActors.volumeProperty.SetAmbient(0.6)
            ASDMomActors.volumeProperty.SetDiffuse(0.6)
            ASDMomActors.volumeProperty.SetSpecular(0.1)
            ASDMomActors.volumeProperty.SetGradientOpacity(
                volumeGradientOpacity)
            #volumeProperty.ShadeOn()

            # Volume actor, this works in a different way than LOD actors
            ASDMomActors.MagDensActor = vtk.vtkVolume()
            ASDMomActors.MagDensActor.SetMapper(ASDMomActors.MagDensMap)
            ASDMomActors.MagDensActor.SetProperty(self.volumeProperty)

    ####################################################################
    # Alternative rendering methods
    ####################################################################
    # The checkerboard splatter method, much faster than the Shepard method
    # however, it seems to change the values of the scalars embeded in the
    # point data which results in incorrect diplay of the magnetization
    #cbdSplatter = vtk.vtkCheckerboardSplatter()
    #cbdSplatter.ScalarWarpingOff()
    #cbdSplatter.SetFootprint(2)
    #cbdSplatter.SetExponentFactor(-5)
    #cbdSplatter.SetParallelSplatCrossover(2)
    #cbdSplatter.SetOutputScalarTypeToDouble()
    #cbdSplatter.CappingOn()
    #cbdSplatter.ScalarWarpingOn()
    #cbdSplatter.SetRadius(1)

    # 3D delaunay method, the far superior as it conserves the shape of the
    # sample, however it is extremely slow, with a rendering of a 3D image
    # taking several minutes
    #smooth_loop = vtk.vtkDelaunay3D()
    #smooth_loop.SetInputData(self.src)
    #smooth_loop.SetTolerance(0.01)
    #smooth_loop.SetAlpha(2)
    #smooth_loop.AlphaTrisOff()
    #smooth_loop.Update()

    ########################################################################
    # Data structures for the spins
    ########################################################################
    # Passing the data from the full system to the PolyData
        ASDMomActors.src_spins = vtk.vtkPolyData()
        ASDMomActors.src_spins.SetPoints(ASD_data.selected_points)
        ASDMomActors.src_spins.GetPointData().SetScalars(
            ASD_data.selected_colors_z)
        ASDMomActors.src_spins.GetPointData().SetVectors(
            ASD_data.selected_vectors)
        scalar_range_spins = ASDMomActors.src_spins.GetScalarRange()
        ########################################################################
        # Data structures for the contours
        ########################################################################
        # Define the contour filters
        contours = vtk.vtkContourFilter()
        contours.SetInputConnection(MagDensMethod.GetOutputPort())
        # This generates the contours, it will do 5 between the -1 and 0.5 range
        cont_num = 5
        range_cont = (-1, 0.5)
        contours.GenerateValues(cont_num, range_cont)
        # Map the contours to graphical primitives
        contMapper = vtk.vtkPolyDataMapper()
        contMapper.SetInputConnection(contours.GetOutputPort())
        contMapper.SetScalarVisibility(False)  # colored contours
        contMapper.SetScalarRange(scalar_range)
        # Create an actor for the contours
        ASDMomActors.contActor = vtk.vtkLODActor()
        ASDMomActors.contActor.SetMapper(contMapper)
        ASDMomActors.contActor.GetProperty().SetColor(0, 0, 0)
        ASDMomActors.contActor.GetProperty().SetLineWidth(1.0)
        ASDMomActors.contActor.VisibilityOff()

        ########################################################################
        # Data structures for the impurity cluster
        ########################################################################
        if ASD_data.cluster_flag:

            # Passing the data from the cluster to the PolyData
            src_clus = vtk.vtkPolyData()
            src_clus.SetPoints(ASD_data.coord_c)
            src_clus.GetPointData().SetScalars(ASD_data.colors_clus)

            # Passing the data from the selected impurities
            src_imp = vtk.vtkPolyData()
            src_imp.SetPoints(ASD_data.points_clus_imp)
            src_imp.GetPointData().SetScalars(ASD_data.colors_imp)
            src_imp.Modified()

            atomSource = vtk.vtkDelaunay2D()
            atomSource.SetInputData(src_clus)
            atomSource.BoundingTriangulationOff()
            atomSource.SetTolerance(0.05)
            atomSource.Update()

            smoothFilter = vtk.vtkSmoothPolyDataFilter()
            smoothFilter.SetInputConnection(atomSource.GetOutputPort())
            smoothFilter.SetNumberOfIterations(5)
            smoothFilter.SetRelaxationFactor(0.1)
            smoothFilter.FeatureEdgeSmoothingOff()
            smoothFilter.BoundarySmoothingOn()
            smoothFilter.Update()

            # Creating the mapper for the smooth surfaces
            atomMapper = vtk.vtkDataSetMapper()
            atomMapper.SetScalarRange(scalar_range)
            atomMapper.SetInputConnection(smoothFilter.GetOutputPort())
            atomMapper.SetColorMode(2)
            atomMapper.Update()

            # Creating the actor for the smooth surfaces
            ASDMomActors.atom = vtk.vtkLODActor()
            ASDMomActors.atom.SetMapper(atomMapper)
            ASDMomActors.atom.GetProperty().EdgeVisibilityOff()
            ASDMomActors.atom.GetProperty().SetSpecularPower(30)
            ASDMomActors.atom.GetProperty().SetAmbient(0.2)
            ASDMomActors.atom.GetProperty().SetDiffuse(0.8)
            ASDMomActors.atom.GetProperty().SetOpacity(0.50)

            # Set up imp sources
            atomSource_imp = vtk.vtkSphereSource()
            atomSource_imp.SetRadius(2.5)
            atomSource_imp.SetThetaResolution(20)
            atomSource_imp.SetPhiResolution(20)

            # Mapping the spheres to the actual points on the selected impurities
            atomMapper_imp = vtk.vtkGlyph3DMapper()
            atomMapper_imp.SetInputData(src_imp)
            atomMapper_imp.SetSourceConnection(atomSource_imp.GetOutputPort())
            atomMapper_imp.SetScaleFactor(0.2)
            atomMapper_imp.SetScaleModeToNoDataScaling()
            atomMapper_imp.Update()

            # Creating the selected impurity actors
            ASDMomActors.atom_imp = vtk.vtkLODActor()
            ASDMomActors.atom_imp.SetMapper(atomMapper_imp)
            ASDMomActors.atom_imp.GetProperty().SetSpecular(0.3)
            ASDMomActors.atom_imp.GetProperty().SetSpecularPower(30)
            ASDMomActors.atom_imp.GetProperty().SetAmbient(0.2)
            ASDMomActors.atom_imp.GetProperty().SetDiffuse(0.8)

    ########################################################################
    # Setting information of the directions
    ########################################################################
        # Create vectors
        arrow = vtk.vtkArrowSource()
        arrow.SetTipRadius(0.20)
        arrow.SetShaftRadius(0.10)
        arrow.SetTipResolution(20)
        arrow.SetShaftResolution(20)

        # Create the mapper for the spins
        arrowMapper = vtk.vtkGlyph3DMapper()
        arrowMapper.SetSourceConnection(arrow.GetOutputPort())
        arrowMapper.SetInputData(ASDMomActors.src)
        arrowMapper.SetScaleFactor(0.50)
        arrowMapper.SetScalarVisibility(False)
        arrowMapper.SetScaleModeToNoDataScaling()
        arrowMapper.Update()

        # Define the vector actor for the spins
        ASDMomActors.vector = vtk.vtkLODActor()
        ASDMomActors.vector.SetMapper(arrowMapper)
        ASDMomActors.vector.GetProperty().SetSpecular(0.3)
        ASDMomActors.vector.GetProperty().SetSpecularPower(60)
        ASDMomActors.vector.GetProperty().SetAmbient(0.2)
        ASDMomActors.vector.GetProperty().SetDiffuse(0.8)
        ASDMomActors.vector.GetProperty().SetColor(0, 0, 0)
        ASDMomActors.vector.VisibilityOff()

        ########################################################################
        # Setting information of the spins
        ########################################################################
        # Create vectors
        ASDMomActors.spinarrow = vtk.vtkArrowSource()
        ASDMomActors.spinarrow.SetTipRadius(0.20)
        ASDMomActors.spinarrow.SetShaftRadius(0.10)
        ASDMomActors.spinarrow.SetTipResolution(20)
        ASDMomActors.spinarrow.SetShaftResolution(20)

        # Create the mapper for the spins
        ASDMomActors.SpinMapper = vtk.vtkGlyph3DMapper()
        ASDMomActors.SpinMapper.SetSourceConnection(
            ASDMomActors.spinarrow.GetOutputPort())
        ASDMomActors.SpinMapper.SetInputData(ASDMomActors.src_spins)
        ASDMomActors.SpinMapper.SetScalarRange(scalar_range_spins)
        ASDMomActors.SpinMapper.SetScaleFactor(0.50)
        ASDMomActors.SpinMapper.SetScaleModeToNoDataScaling()
        ASDMomActors.SpinMapper.SetLookupTable(self.lut)
        ASDMomActors.SpinMapper.SetColorModeToMapScalars()
        ASDMomActors.SpinMapper.Update()

        # Define the vector actor for the spins
        ASDMomActors.Spins = vtk.vtkLODActor()
        ASDMomActors.Spins.SetMapper(ASDMomActors.SpinMapper)
        ASDMomActors.Spins.GetProperty().SetSpecular(0.3)
        ASDMomActors.Spins.GetProperty().SetSpecularPower(60)
        ASDMomActors.Spins.GetProperty().SetAmbient(0.2)
        ASDMomActors.Spins.GetProperty().SetDiffuse(0.8)
        ASDMomActors.Spins.VisibilityOff()

        ########################################################################
        # Creation of the data structures for the data clipping
        ########################################################################
        # Right now this only can clip polydata, which is fine for 2D structures
        # however, for the 3d delaunay tesellation, the output is an unstructured
        # grid, which means that annother type of clipper is required
        ASDMomActors.plane = vtk.vtkPlane()
        ASDMomActors.plane.SetOrigin(ASDMomActors.xmin, ASDMomActors.ymid, 0)
        ASDMomActors.plane.SetNormal(1, 0, 0)
        if ASDMomActors.glob_flag_2D:
            self.clipper = vtk.vtkClipPolyData()
            self.clipper.SetInputConnection(MagDensMethod.GetOutputPort())
            self.clipper.SetClipFunction(ASDMomActors.plane)
            self.clipper.InsideOutOn()

            ASDMomActors.clipperMapper = vtk.vtkPolyDataMapper()
            ASDMomActors.clipperMapper.SetInputConnection(
                self.clipper.GetOutputPort())
            ASDMomActors.clipperMapper.SetLookupTable(self.lut)

            ASDMomActors.clipperActor = vtk.vtkLODActor()
            ASDMomActors.clipperActor.SetMapper(ASDMomActors.clipperMapper)
            ASDMomActors.clipperActor.VisibilityOff()
        else:
            self.clipper = vtk.vtkClipVolume()
            self.clipper.SetInputConnection(MagDensMethod.GetOutputPort())
            self.clipper.SetClipFunction(ASDMomActors.plane)
            self.clipper.InsideOutOn()

            ASDMomActors.clipperMapper = vtk.vtkDataSetMapper()
            ASDMomActors.clipperMapper.SetInputConnection(
                self.clipper.GetOutputPort())
            ASDMomActors.clipperMapper.SetLookupTable(self.transfer_func)

            ASDMomActors.clipperActor = vtk.vtkActor()
            ASDMomActors.clipperActor.SetMapper(ASDMomActors.clipperMapper)
            ASDMomActors.clipperActor.GetProperty().SetOpacity(1.00)

        if (ASD_data.kmc_flag):
            ########################################################################
            # Setting data structures for the KMC particle visualization
            ########################################################################
            ASDMomActors.KMC_src = vtk.vtkPolyData()
            ASDMomActors.KMC_src.SetPoints(ASD_data.coord_KMC)

            # Atom sphere
            KMC_part = vtk.vtkSphereSource()
            KMC_part.SetRadius(1.75)
            KMC_part.SetThetaResolution(40)
            KMC_part.SetPhiResolution(40)
            # Atom glyph
            KMC_part_mapper = vtk.vtkGlyph3DMapper()
            KMC_part_mapper.SetInputData(ASDMomActors.KMC_src)
            KMC_part_mapper.SetSourceConnection(KMC_part.GetOutputPort())
            KMC_part_mapper.SetScaleFactor(0.5)
            KMC_part_mapper.ClampingOn()
            KMC_part_mapper.SetScaleModeToNoDataScaling()
            KMC_part_mapper.SetColorModeToMapScalars()
            KMC_part_mapper.Update()
            # Atoms actors
            ASDMomActors.KMC_part_actor = vtk.vtkLODActor()
            ASDMomActors.KMC_part_actor.SetMapper(KMC_part_mapper)
            ASDMomActors.KMC_part_actor.GetProperty().SetOpacity(0.9)
            ASDMomActors.KMC_part_actor.GetProperty().SetColor(0.0, 0.0, 1.0)
            ASDMomActors.KMC_part_actor.GetProperty().EdgeVisibilityOn()
            ASDMomActors.KMC_part_actor.GetProperty().SetEdgeColor(0, 0, 0)
        ########################################################################
        # Setting the information for the axes widget
        ########################################################################
        # Create the axes actor
        axes = vtk.vtkAxesActor()
        axes.SetShaftTypeToCylinder()
        axes.SetCylinderRadius(0.05)
        axes.SetNormalizedShaftLength(0.9, 0.9, 0.9)
        axes.SetNormalizedTipLength(0.40, 0.40, 0.40)
        # The properties of the text can be controlled independently
        axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().SetColor(
            0.0, 0.0, 0.0)
        axes.GetYAxisCaptionActor2D().GetCaptionTextProperty().SetColor(
            0.0, 0.0, 0.0)
        axes.GetZAxisCaptionActor2D().GetCaptionTextProperty().SetColor(
            0.0, 0.0, 0.0)
        axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().ShadowOff()
        axes.GetYAxisCaptionActor2D().GetCaptionTextProperty().ShadowOff()
        axes.GetZAxisCaptionActor2D().GetCaptionTextProperty().ShadowOff()

        # The axes actor is then used as an orientation marker widget, the advantage
        # of setting it up as a widget is that it is interactive and one can move it
        # and that it moves as the zoom changes
        # Must make sure that the widget is part of the main class so that it can
        # be actually rendered and no segfaults occurr
        ASDMomActors.OrientMarker = vtk.vtkOrientationMarkerWidget()
        ASDMomActors.OrientMarker.SetOutlineColor(0.9300, 0.5700, 0.1300)
        ASDMomActors.OrientMarker.SetOrientationMarker(axes)
        ASDMomActors.OrientMarker.SetViewport(0.0, 0.0, 0.3, 0.3)

        ########################################################################
        # Setting the information for the scalar bar widget
        ########################################################################
        # Create the scalar bar actor
        ASDMomActors.scalar_bar = vtk.vtkScalarBarActor()
        if ASDMomActors.glob_flag_2D:
            ASDMomActors.scalar_bar.SetLookupTable(
                ASDMomActors.MagDensMap.GetLookupTable())
        else:
            ASDMomActors.scalar_bar.SetLookupTable(self.transfer_func)

        ASDMomActors.scalar_bar.GetLabelTextProperty().SetColor(0.0, 0.0, 0.0)
        ASDMomActors.scalar_bar.SetNumberOfLabels(5)
        ASDMomActors.scalar_bar.GetLabelTextProperty().ShadowOff()
        ASDMomActors.scalar_bar.GetLabelTextProperty().BoldOff()
        ASDMomActors.scalar_bar.GetLabelTextProperty().ItalicOff()
        ASDMomActors.scalar_bar.SetLabelFormat("%-#6.1f")
        ASDMomActors.scalar_bar.SetBarRatio(0.5)

        # Create the scalar_bar_widget
        ASDMomActors.scalar_bar_widget = vtk.vtkScalarBarWidget()
        ASDMomActors.scalar_bar_widget.SetScalarBarActor(
            ASDMomActors.scalar_bar)

        # Representation to actually control where the scalar bar is
        scalarBarRep = ASDMomActors.scalar_bar_widget.GetRepresentation()
        scalarBarRep.SetOrientation(0)  # 0 = Horizontal, 1 = Vertical
        scalarBarRep.GetPositionCoordinate().SetValue(0.30, 0.05)
        scalarBarRep.GetPosition2Coordinate().SetValue(0.50, 0.05)

        ########################################################################
        # Setting information of the renderer
        ########################################################################
        # Define the renderer
        # Add the actors to the scene
        if ASDMomActors.glob_flag_2D:
            ren.AddActor(ASDMomActors.MagDensActor)
        else:
            ren.AddViewProp(ASDMomActors.MagDensActor)

        ren.AddActor(ASDMomActors.Spins)
        ren.AddActor(ASDMomActors.vector)
        ren.AddActor(ASDMomActors.contActor)
        ren.AddActor(self.clipperActor)

        # If there is information about the cluster add the needed actors
        if ASD_data.cluster_flag:
            ren.AddActor(ASDMomActors.atom)
            ren.AddActor(ASDMomActors.atom_imp)

    #If the KMC particles are present add them to the renderer
        if ASD_data.kmc_flag:
            ren.AddActor(ASDMomActors.KMC_part_actor)

    # Defining the camera directions

        ren.GetActiveCamera().Azimuth(ASDMomActors.camera_azimuth)
        ren.GetActiveCamera().Elevation(ASDMomActors.camera_elevation)
        ren.GetActiveCamera().Yaw(ASDMomActors.camera_yaw)
        ren.GetActiveCamera().Roll(ASDMomActors.camera_roll)
        ren.GetActiveCamera().Pitch(ASDMomActors.camera_pitch)
        ren.GetActiveCamera().SetFocalPoint(self.camera_focal)
        ren.GetActiveCamera().SetPosition(self.camera_pos)
        ren.GetActiveCamera().SetViewUp(0, 1, 0)
        # Must make sure the widgets is called before the renderer is called
        # Scalar bar
        ASDMomActors.scalar_bar_widget.SetInteractor(iren)
        ASDMomActors.scalar_bar_widget.On()
        # Orient marker
        ASDMomActors.OrientMarker.SetInteractor(iren)
        ASDMomActors.OrientMarker.SetEnabled(1)
        ########################################################################
        # Start the renderer
        ########################################################################
        iren.Start()
        renWin.Render()

        return
Beispiel #18
0
    def render(self,
               pointsData,
               scalarsArray,
               vectorsArray,
               nspecies,
               colouringOptions,
               vectorsOptions,
               lut,
               invert=False):
        """
        Render vectors.
        
        """
        self._logger.debug("Rendering vectors")

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

        # polydata
        arrowPolyData = vtk.vtkPolyData()
        arrowPolyData.SetPoints(points)
        arrowPolyData.GetPointData().SetScalars(scalarsArray.getVTK())
        arrowPolyData.GetPointData().SetVectors(vectorsArray.getVTK())

        # arrow source
        arrowSource = vtk.vtkArrowSource()
        arrowSource.SetShaftResolution(vectorsOptions.vectorResolution)
        arrowSource.SetTipResolution(vectorsOptions.vectorResolution)
        if invert:
            arrowSource.InvertOn()
        arrowSource.Update()

        # glyph mapper
        arrowGlyph = vtk.vtkGlyph3DMapper()
        arrowGlyph.OrientOn()
        if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
            arrowGlyph.SetInputConnection(arrowPolyData.GetProducerPort())
        else:
            arrowGlyph.SetInputData(arrowPolyData)
        arrowGlyph.SetSourceConnection(arrowSource.GetOutputPort())
        arrowGlyph.SetScaleModeToScaleByMagnitude()
        arrowGlyph.SetScaleArray("vectors")
        arrowGlyph.SetScalarModeToUsePointFieldData()
        arrowGlyph.SelectColorArray("colours")
        arrowGlyph.SetScaleFactor(vectorsOptions.vectorScaleFactor)
        arrowMapper = arrowGlyph
        arrowMapper.SetLookupTable(lut)
        utils.setMapperScalarRange(arrowMapper, colouringOptions, nspecies)

        # actor
        arrowActor = vtk.vtkActor()
        arrowActor.SetMapper(arrowMapper)

        # store attributes
        self._actor = utils.ActorObject(arrowActor)
        self._data["Points"] = pointsData
        self._data["Scalars"] = scalarsArray
        self._data["Vectors"] = vectorsArray
        self._data["LUT"] = lut
        self._data["Scale factor"] = vectorsOptions.vectorScaleFactor
Beispiel #19
0
def main():
    titles = list()
    textMappers = list()
    textActors = list()

    uGrids = list()
    mappers = list()
    actors = list()
    renderers = list()

    uGrids.append(MakeVertex())
    titles.append('VTK_VERTEX (=1)')
    uGrids.append(MakePolyVertex())
    titles.append('VTK_POLY_VERTEX (=2)')
    uGrids.append(MakeLine())
    titles.append('VTK_LINE (=3)')
    uGrids.append(MakePolyLine())
    titles.append('VTK_POLY_LINE (=4)')
    uGrids.append(MakeTriangle())
    titles.append('VTK_TRIANGLE (=5)')
    uGrids.append(MakeTriangleStrip())
    titles.append('VTK_TRIANGLE_STRIP (=6)')
    uGrids.append(MakePolygon())
    titles.append('VTK_POLYGON (=7)')
    uGrids.append(MakePixel())
    titles.append('VTK_PIXEL (=8)')
    uGrids.append(MakeQuad())
    titles.append('VTK_QUAD (=9)')
    uGrids.append(MakeTetra())
    titles.append('VTK_TETRA (=10)')
    uGrids.append(MakeVoxel())
    titles.append('VTK_VOXEL (=11)')
    uGrids.append(MakeHexahedron())
    titles.append('VTK_HEXAHEDRON (=12)')
    uGrids.append(MakeWedge())
    titles.append('VTK_WEDGE (=13)')
    uGrids.append(MakePyramid())
    titles.append('VTK_PYRAMID (=14)')
    uGrids.append(MakePentagonalPrism())
    titles.append('VTK_PENTAGONAL_PRISM (=15)')
    uGrids.append(MakeHexagonalPrism())
    titles.append('VTK_HEXAGONAL_PRISM (=16)')

    colors = vtk.vtkNamedColors()

    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(600, 600)
    renWin.SetWindowName('LinearCellDemo')

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

    # Create one sphere for all
    sphere = vtk.vtkSphereSource()
    sphere.SetPhiResolution(21)
    sphere.SetThetaResolution(21)
    sphere.SetRadius(.08)

    # Create one text property for all
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(10)
    textProperty.SetJustificationToCentered()


    # Create and link the mappers actors and renderers together.
    for i in range(0, len(uGrids)):
        print('Creating:', titles[i])
        textMappers.append(vtk.vtkTextMapper())
        textActors.append(vtk.vtkActor2D())

        mappers.append(vtk.vtkDataSetMapper())
        actors.append(vtk.vtkActor())
        renderers.append(vtk.vtkRenderer())
        mappers[i].SetInputData(uGrids[i])
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(colors.GetColor3d('Tomato'))
        actors[i].GetProperty().EdgeVisibilityOn()
        actors[i].GetProperty().SetLineWidth(3)
        actors[i].GetProperty().SetOpacity(.5)
        renderers[i].AddViewProp(actors[i])

        textMappers[i].SetInput(titles[i])
        textActors[i].SetMapper(textMappers[i])
        textActors[i].SetPosition(50, 10)
        renderers[i].AddViewProp(textActors[i])

        # Label the points
        labelMapper = vtk.vtkLabeledDataMapper()
        labelMapper.SetInputData(uGrids[i])
        labelActor = vtk.vtkActor2D()
        labelActor.SetMapper(labelMapper)
        renderers[i].AddViewProp(labelActor)

        # Glyph the points
        pointMapper = vtk.vtkGlyph3DMapper()
        pointMapper.SetInputData(uGrids[i])
        pointMapper.SetSourceConnection(sphere.GetOutputPort())
        pointMapper.ScalingOff()
        pointMapper.ScalarVisibilityOff()

        pointActor = vtk.vtkActor()
        pointActor.SetMapper(pointMapper)
        pointActor.GetProperty().SetDiffuseColor(colors.GetColor3d('Banana'))
        pointActor.GetProperty().SetSpecular(.6)
        pointActor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0)
        pointActor.GetProperty().SetSpecularPower(100)
        renderers[i].AddViewProp(pointActor)

        renWin.AddRenderer(renderers[i])

    # Setup the viewports
    xGridDimensions = 4
    yGridDimensions = 4
    rendererSize = 240
    renWin.SetSize(rendererSize * xGridDimensions, rendererSize * yGridDimensions)
    for row in range(0, yGridDimensions):
        for col in range(0, xGridDimensions):
            index = row * xGridDimensions + col

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

            if index > (len(actors) - 1):
                # Add a renderer even if there is no actor.
                # This makes the render window background all the same color.
                ren = vtk.vtkRenderer()
                ren.SetBackground(colors.GetColor3d('SlateGray'))
                ren.SetViewport(viewport)
                renWin.AddRenderer(ren)
                continue

            renderers[index].SetViewport(viewport)
            renderers[index].SetBackground(colors.GetColor3d('SlateGray'))
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(-30)
            if index == 0:
                renderers[index].GetActiveCamera().Dolly(0.1)
                renderers[index].ResetCameraClippingRange()
            if index == 4:
                renderers[index].GetActiveCamera().Dolly(0.8)
                renderers[index].ResetCameraClippingRange()
            renderers[index].ResetCameraClippingRange()

    renWin.Render()
    iRen.Initialize()
    iRen.Start()
Beispiel #20
0
    def Add_MomActors(self,ren,renWin,iren,ASDdata,window):
        """Main wrapper to add the needed actors for visualization of the moments.
        Class that contains the data structures for creation of the glyphs or the 
        visualization of the magnetic moments. It also has the capacity to create 
        tessellations for the visualization of volume vendering.

        Args:
            ren: current renderer.
            renWin: current rendering window.
            iren: current interactor for the renderer.
            ASDdata: class where the data read from the ASD simulations is stored.
            window: QMainWindow object where the visualization is performed.

        Author
        ----------
        Jonathan Chico
        """

        import vtk
        import numpy as np

        ASDMomActors.timer_count=0
        ASDMomActors.camera_pos=np.zeros(3,dtype=np.float32)
        ASDMomActors.camera_focal=np.zeros(3,dtype=np.float32)
        ASDMomActors.camera_yaw=0.0
        ASDMomActors.camera_roll=0.0
        ASDMomActors.camera_pitch=0.0
        ASDMomActors.camera_azimuth=0.0
        ASDMomActors.camera_elevation=0.0
        ASDMomActors.kmc_disp=ASDdata.kmc_flag
        ASDMomActors.cluster_disp=ASDdata.cluster_flag
        ASDMomActors.glob_color=ASDdata.colors
        #-----------------------------------------------------------------------
        # Look up tables for colors
        #-----------------------------------------------------------------------
        # This is a diverging RWB color mapping based on the work of Kenneth
        # Moreland and with the vtk examples provided by Andrew Maclean
        if ASDdata.flag2D:
            ASDMomActors.lut = vtk.vtkLookupTable()
            num_colors = 256
            ASDMomActors.lut.SetNumberOfTableValues(num_colors)
            ASDMomActors.transfer_func = vtk.vtkColorTransferFunction()
            ASDMomActors.transfer_func.SetColorSpaceToDiverging()
            ASDMomActors.transfer_func.AddRGBPoint(0, 0.230, 0.299, 0.754)
            ASDMomActors.transfer_func.AddRGBPoint(1, 0.706, 0.016, 0.150)
            for ii,ss in enumerate([float(xx)/float(num_colors) for xx in range(num_colors)]):
                cc = ASDMomActors.transfer_func.GetColor(ss)
                ASDMomActors.lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
            ASDMomActors.lut.Build()
        else:
            ASDMomActors.lut = vtk.vtkLookupTable()
            num_colors = 256
            ASDMomActors.lut.SetNumberOfTableValues(num_colors)
            ASDMomActors.transfer_func = vtk.vtkColorTransferFunction()
            ASDMomActors.transfer_func.SetColorSpaceToDiverging()
            ASDMomActors.transfer_func.AddRGBPoint(-0, 0.230, 0.299, 0.754)
            ASDMomActors.transfer_func.AddRGBPoint( 1, 0.706, 0.016, 0.150)
            for ii,ss in enumerate([float(xx)/float(num_colors) for xx in range(num_colors)]):
                cc = ASDMomActors.transfer_func.GetColor(ss)
                ASDMomActors.lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
            ASDMomActors.lut.Build()
        #-----------------------------------------------------------------------
        # Data structures for the generation of the smooth grid
        #-----------------------------------------------------------------------
        # Passing the data from the full system to the PolyData
        ASDMomActors.src=vtk.vtkPolyData()
        ASDMomActors.src.SetPoints(ASDdata.coord)
        ASDMomActors.src.GetPointData().SetScalars(ASDdata.colors[2])
        ASDMomActors.src.GetPointData().SetVectors(ASDdata.moments)
        scalar_range = ASDMomActors.src.GetScalarRange()
        #-----------------------------------------------------------------------
        # Finding useful geometrical information of the sample
        #-----------------------------------------------------------------------
        # Finding the middle of the sample
        # Also making sure that if the sample is 2D one has no problem with bounds
        # this is mostly useful if splatters are used
        (ASDMomActors.xmin,ASDMomActors.xmax,ASDMomActors.ymin,ASDMomActors.ymax,\
        ASDMomActors.zmin,ASDMomActors.zmax)= ASDMomActors.src.GetBounds()
        if ASDMomActors.xmin==ASDMomActors.xmax:
            ASDMomActors.xmin=0.0
            ASDMomActors.xmax=1.0
        if ASDMomActors.ymin==ASDMomActors.ymax:
            ASDMomActors.ymin=0.0
            ASDMomActors.ymax=1.0
        if ASDMomActors.zmin==ASDMomActors.zmax:
            ASDMomActors.zmin=0.0
            ASDMomActors.zmax=1.0
        ASDMomActors.xmid = (ASDMomActors.xmin+ASDMomActors.xmax)*0.5
        ASDMomActors.ymid = (ASDMomActors.ymin+ASDMomActors.ymax)*0.5
        ASDMomActors.zmid = (ASDMomActors.zmin+ASDMomActors.zmax)*0.5
        ASDMomActors.height=max(ASDMomActors.xmax,ASDMomActors.ymax,ASDMomActors.zmax)*1.75
        self.dist_x=np.absolute(ASDMomActors.xmax-ASDMomActors.xmin)
        self.dist_y=np.absolute(ASDMomActors.ymax-ASDMomActors.ymin)
        self.dist_z=np.absolute(ASDMomActors.zmax-ASDMomActors.zmin)
        ASDMomActors.camera_pos[0]=ASDMomActors.xmid
        ASDMomActors.camera_pos[1]=ASDMomActors.ymid
        ASDMomActors.camera_pos[2]=ASDMomActors.height
        ASDMomActors.camera_focal[0]=ASDMomActors.xmid
        ASDMomActors.camera_focal[1]=ASDMomActors.ymid
        ASDMomActors.camera_focal[2]=ASDMomActors.zmid
        # The delaunay tessellation seems to be the best way to transform the point cloud
        # to a surface for volume rendering, the problem is that it is too slow for large
        # data sets, meaning that the best option is first to prune out the data to ensure
        # that one has a manageable number of data points over which to do the construction
        # surface reconstruction and splatter techniques also can be used to generate something
        # akin to the kind of surfaces we want. The issue is that they transform the data to a
        # regular mesh by default. And thus it is a problem for most kind of systems
        if ASDdata.flag2D:
            # Passing the data to generate a triangulation of the data
            ASDMomActors.MagDensMethod = vtk.vtkDelaunay2D()
            ASDMomActors.MagDensMethod.SetInputData(ASDMomActors.src)
            ASDMomActors.MagDensMethod.BoundingTriangulationOff()
            ASDMomActors.MagDensMethod.SetTolerance(0.005)
            # Time the execution of the delaunay tessellation
            SM_timer = vtk.vtkExecutionTimer()
            SM_timer.SetFilter(ASDMomActors.MagDensMethod)
            ASDMomActors.MagDensMethod.Update()
            SM = SM_timer.GetElapsedWallClockTime()
            print ("2D Delaunay:", SM)
            # Creating the mapper for the smooth surfaces
            ASDMomActors.MagDensMap = vtk.vtkDataSetMapper()
            ASDMomActors.MagDensMap.SetScalarRange(scalar_range)
            ASDMomActors.MagDensMap.SetInputConnection(ASDMomActors.MagDensMethod.GetOutputPort())
            ASDMomActors.MagDensMap.SetLookupTable(ASDMomActors.lut)
            ASDMomActors.MagDensMap.SetColorModeToMapScalars()
            ASDMomActors.MagDensMap.Update()
            # Creating the actor for the smooth surfaces
            ASDMomActors.MagDensActor = vtk.vtkLODActor()
            ASDMomActors.MagDensActor.SetMapper(ASDMomActors.MagDensMap)
            ASDMomActors.MagDensActor.GetProperty().SetOpacity(0.75)
            ASDMomActors.MagDensActor.GetProperty().EdgeVisibilityOff()
            if window.DensBox.isChecked():
                ASDMomActors.MagDensActor.VisibilityOn()
            else:
                ASDMomActors.MagDensActor.VisibilityOff()
        else:
            #-------------------------------------------------------------------
            # Setting the parameters for the visualization of 3D structures with
            # splatters
            #-------------------------------------------------------------------
            ASDMomActors.MagDensMethod = vtk.vtkGaussianSplatter()
            ASDMomActors.MagDensMethod.SetInputData(ASDMomActors.src)
            #-------------------------------------------------------------------
            # Options for the Gaussian splatter. These determine the quality of the
            # rendering, increasing the radius smoothens out the volume but performance
            # decreases rapidly
            #-------------------------------------------------------------------
            dist=(np.asarray(ASDMomActors.src.GetPoint(0))-np.asarray(ASDMomActors.src.GetPoint(1)))
            norm=np.sqrt(dist.dot(dist))
            if norm<1:
                rad_fac=0.040
            else:
                rad_fac=0.40
            ASDMomActors.MagDensMethod.SetRadius(rad_fac)
            ASDMomActors.MagDensMethod.ScalarWarpingOn()
            #-------------------------------------------------------------------
            # The exponent factor determines how fast the gaussian splatter decay
            # they again can be used to improve quality at the sake of rendering time
            #-------------------------------------------------------------------
            ASDMomActors.MagDensMethod.SetExponentFactor(-10)
            ASDMomActors.MagDensMethod.NormalWarpingOn()
            ASDMomActors.MagDensMethod.SetEccentricity(10)
            #-------------------------------------------------------------------
            # The Null value can be used to try to eliminate contributions not belonging
            # to the actual sample
            #-------------------------------------------------------------------
            ASDMomActors.MagDensMethod.SetNullValue(-10)
            #-------------------------------------------------------------------
            # Set the actual size of the rendering model
            #-------------------------------------------------------------------
            ASDMomActors.MagDensMethod.SetModelBounds(ASDMomActors.xmin,ASDMomActors.xmax,\
            ASDMomActors.ymin,ASDMomActors.ymax,ASDMomActors.zmin,ASDMomActors.zmax)
            # This should get rid of the problems when trying to map very thin structures in 2D
            if self.dist_x==min(self.dist_x,self.dist_y,self.dist_z) and self.dist_x<3:
                ASDMomActors.MagDensMethod.SetSampleDimensions(3,int(ASDMomActors.ymax),int(ASDMomActors.zmax))
            elif self.dist_y==min(self.dist_x,self.dist_y,self.dist_z) and self.dist_y<3:
                ASDMomActors.MagDensMethod.SetSampleDimensions(int(ASDMomActors.xmax),3,int(ASDMomActors.zmax))
            elif self.dist_z==min(self.dist_x,self.dist_y,self.dist_z) and self.dist_z<3:
                ASDMomActors.MagDensMethod.SetSampleDimensions(int(ASDMomActors.xmax),int(ASDMomActors.ymax),3)
            # Timming for the execution of the volume creation
            SP_timer = vtk.vtkExecutionTimer()
            SP_timer.SetFilter(ASDMomActors.MagDensMethod)
            ASDMomActors.MagDensMethod.Update()
            SP = SP_timer.GetElapsedWallClockTime()
            print ("3D vtkGaussianSplatter Method:", SP)
            # Scalar opacities
            funcOpacityScalar = vtk.vtkPiecewiseFunction()
            funcOpacityScalar.AddPoint(-1.00,0.00)
            funcOpacityScalar.AddPoint( 0.00,0.05)
            funcOpacityScalar.AddPoint( 0.50,0.50)
            funcOpacityScalar.AddPoint( 0.75,1.00)
            # Gradient opacities
            volumeGradientOpacity = vtk.vtkPiecewiseFunction()
            volumeGradientOpacity.AddPoint(0.000,0.0)
            volumeGradientOpacity.AddPoint(0.001,1.0)
            volumeGradientOpacity.AddPoint(1.000,1.0)
            # Volume properties
            ASDMomActors.volumeProperty = vtk.vtkVolumeProperty()
            ASDMomActors.volumeProperty.SetColor(ASDMomActors.transfer_func)
            ASDMomActors.volumeProperty.SetInterpolationTypeToLinear()
            ASDMomActors.volumeProperty.SetAmbient(0.6)
            ASDMomActors.volumeProperty.SetDiffuse(0.6)
            ASDMomActors.volumeProperty.SetSpecular(0.1)
            ASDMomActors.volumeProperty.SetGradientOpacity(volumeGradientOpacity)
            ASDMomActors.volumeProperty.SetScalarOpacity(funcOpacityScalar)
            # Volume Mapper
            ASDMomActors.MagDensMap = vtk.vtkSmartVolumeMapper()
            ASDMomActors.MagDensMap.SetInputConnection(ASDMomActors.MagDensMethod.GetOutputPort())
            # Volume Actor
            ASDMomActors.MagDensActor = vtk.vtkVolume()
            ASDMomActors.MagDensActor.SetMapper(ASDMomActors.MagDensMap)
            ASDMomActors.MagDensActor.SetProperty(self.volumeProperty)
            if window.DensBox.isChecked():
                ASDMomActors.MagDensActor.VisibilityOn()
            else:
                ASDMomActors.MagDensActor.VisibilityOff()
        #-----------------------------------------------------------------------
        # Data structures for the spins
        #-----------------------------------------------------------------------
        # Passing the data from the full system to the PolyData
        ASDMomActors.src_spins=vtk.vtkPolyData()
        ASDMomActors.src_spins.SetPoints(ASDdata.coord)
        ASDMomActors.src_spins.GetPointData().SetScalars(ASDdata.colors[2])
        ASDMomActors.src_spins.GetPointData().SetVectors(ASDdata.moments)
        scalar_range_spins = ASDMomActors.src_spins.GetScalarRange()
        #-----------------------------------------------------------------------
        # Data structures for the contours
        #-----------------------------------------------------------------------
        # Define the contour filters
        contours = vtk.vtkContourFilter()
        contours.SetInputConnection(ASDMomActors.MagDensMethod.GetOutputPort())
        # This generates the contours, it will do 5 between the -1 and 0.5 range
        cont_num=5
        range_cont=(-1,0.5)
        contours.GenerateValues(cont_num,range_cont)
        # Map the contours to graphical primitives
        contMapper = vtk.vtkPolyDataMapper()
        contMapper.SetInputConnection(contours.GetOutputPort())
        contMapper.SetScalarVisibility(False) # colored contours
        contMapper.SetScalarRange(scalar_range)
        # Create an actor for the contours
        ASDMomActors.contActor = vtk.vtkLODActor()
        ASDMomActors.contActor.SetMapper(contMapper)
        ASDMomActors.contActor.GetProperty().SetColor(0, 0, 0)
        ASDMomActors.contActor.GetProperty().SetLineWidth(1.0)
        ASDMomActors.contActor.VisibilityOff()
        #-----------------------------------------------------------------------
        # Setting information of the directions
        #-----------------------------------------------------------------------
        # Create vectors
        arrow = vtk.vtkArrowSource()
        arrow.SetTipRadius(0.20)
        arrow.SetShaftRadius(0.10)
        arrow.SetTipResolution(20)
        arrow.SetShaftResolution(20)
        # Create the mapper for the spins
        arrowMapper = vtk.vtkGlyph3DMapper()
        arrowMapper.SetSourceConnection(arrow.GetOutputPort())
        arrowMapper.SetInputData(ASDMomActors.src)
        arrowMapper.SetScaleFactor(0.50)
        arrowMapper.SetScalarVisibility(False)
        arrowMapper.SetScaleModeToNoDataScaling()
        arrowMapper.Update()
        # Define the vector actor for the spins
        ASDMomActors.vector = vtk.vtkLODActor()
        ASDMomActors.vector.SetMapper(arrowMapper)
        ASDMomActors.vector.GetProperty().SetSpecular(0.3)
        ASDMomActors.vector.GetProperty().SetSpecularPower(60)
        ASDMomActors.vector.GetProperty().SetAmbient(0.2)
        ASDMomActors.vector.GetProperty().SetDiffuse(0.8)
        ASDMomActors.vector.GetProperty().SetColor(0, 0, 0)
        ASDMomActors.vector.VisibilityOff()
        #-----------------------------------------------------------------------
        # Setting information of the spins
        #-----------------------------------------------------------------------
        # Create vectors
        ASDMomActors.spinarrow = vtk.vtkArrowSource()
        ASDMomActors.spinarrow.SetTipRadius(0.20)
        ASDMomActors.spinarrow.SetShaftRadius(0.10)
        ASDMomActors.spinarrow.SetTipResolution(20)
        ASDMomActors.spinarrow.SetShaftResolution(20)
        # Create the mapper for the spins
        ASDMomActors.SpinMapper = vtk.vtkGlyph3DMapper()
        ASDMomActors.SpinMapper.SetSourceConnection(ASDMomActors.spinarrow.GetOutputPort())
        ASDMomActors.SpinMapper.SetInputData(ASDMomActors.src_spins)
        ASDMomActors.SpinMapper.SetScalarRange(scalar_range_spins)
        ASDMomActors.SpinMapper.SetScaleFactor(0.50)
        ASDMomActors.SpinMapper.SetScaleModeToNoDataScaling()
        ASDMomActors.SpinMapper.SetLookupTable(self.lut)
        ASDMomActors.SpinMapper.SetColorModeToMapScalars()
        ASDMomActors.SpinMapper.Update()
        # Define the vector actor for the spins
        ASDMomActors.Spins = vtk.vtkLODActor()
        ASDMomActors.Spins.SetMapper(ASDMomActors.SpinMapper)
        ASDMomActors.Spins.GetProperty().SetSpecular(0.3)
        ASDMomActors.Spins.GetProperty().SetSpecularPower(60)
        ASDMomActors.Spins.GetProperty().SetAmbient(0.2)
        ASDMomActors.Spins.GetProperty().SetDiffuse(0.8)
        if window.SpinsBox.isChecked():
            ASDMomActors.Spins.VisibilityOn()
        else:
            ASDMomActors.Spins.VisibilityOff()
        if (ASDdata.kmc_flag):
            #-------------------------------------------------------------------
            # Setting data structures for the KMC particle visualization
            #-------------------------------------------------------------------
            ASDMomActors.KMC_src=vtk.vtkPolyData()
            ASDMomActors.KMC_src.SetPoints(ASDdata.coord_KMC)
            # Atom sphere
            KMC_part = vtk.vtkSphereSource()
            KMC_part.SetRadius(1.75)
            KMC_part.SetThetaResolution(40)
            KMC_part.SetPhiResolution(40)
            # Atom glyph
            KMC_part_mapper = vtk.vtkGlyph3DMapper()
            KMC_part_mapper.SetInputData(ASDMomActors.KMC_src)
            KMC_part_mapper.SetSourceConnection(KMC_part.GetOutputPort())
            KMC_part_mapper.SetScaleFactor(0.5)
            KMC_part_mapper.ClampingOn()
            KMC_part_mapper.SetScaleModeToNoDataScaling()
            KMC_part_mapper.SetColorModeToMapScalars()
            KMC_part_mapper.Update()
            # Atoms actors
            ASDMomActors.KMC_part_actor = vtk.vtkLODActor()
            ASDMomActors.KMC_part_actor.SetMapper(KMC_part_mapper)
            ASDMomActors.KMC_part_actor.GetProperty().SetOpacity(0.9)
            ASDMomActors.KMC_part_actor.GetProperty().SetColor(0.0, 0.0, 1.0)
            ASDMomActors.KMC_part_actor.GetProperty().EdgeVisibilityOn()
            ASDMomActors.KMC_part_actor.GetProperty().SetEdgeColor(0,0,0)
        #-----------------------------------------------------------------------
        # Setting information of the renderer
        #-----------------------------------------------------------------------
        # Define the renderer
        # Add the actors to the scene
        if ASDdata.flag2D:
            ren.AddActor(ASDMomActors.MagDensActor)
        else:
            ren.AddViewProp(ASDMomActors.MagDensActor)
        ren.AddActor(ASDMomActors.Spins)
        ren.AddActor(ASDMomActors.vector)
        ren.AddActor(ASDMomActors.contActor)
        #If the KMC particles are present add them to the renderer
        if ASDdata.kmc_flag:
            ren.AddActor(ASDMomActors.KMC_part_actor)
        # Defining the camera directions
        ren.GetActiveCamera().Azimuth(ASDMomActors.camera_azimuth)
        ren.GetActiveCamera().Elevation(ASDMomActors.camera_elevation)
        ren.GetActiveCamera().Yaw(ASDMomActors.camera_yaw)
        ren.GetActiveCamera().Roll(ASDMomActors.camera_roll)
        ren.GetActiveCamera().Pitch(ASDMomActors.camera_pitch)
        ren.GetActiveCamera().SetFocalPoint(ASDMomActors.camera_focal)
        ren.GetActiveCamera().SetPosition(ASDMomActors.camera_pos)
        ren.GetActiveCamera().SetViewUp(0,1,0)
        #-----------------------------------------------------------------------
        # Start the renderer
        #-----------------------------------------------------------------------
        iren.Start()
        renWin.Render()
        return;
def main():
    cps = vtk.vtkConvexPointSet()
    points = vtk.vtkPoints()
    points.InsertNextPoint(0, 0, 0)
    points.InsertNextPoint(1, 0, 0)
    points.InsertNextPoint(1, 1, 0)
    points.InsertNextPoint(0, 1, 0)
    points.InsertNextPoint(0, 0, 1)
    points.InsertNextPoint(1, 0, 1)
    points.InsertNextPoint(1, 1, 1)
    points.InsertNextPoint(0, 1, 1)
    points.InsertNextPoint(0.5, 0, 0)
    points.InsertNextPoint(1, 0.5, 0)
    points.InsertNextPoint(0.5, 1, 0)
    points.InsertNextPoint(0, 0.5, 0)
    points.InsertNextPoint(0.5, 0.5, 0)

    for i in range(0, 13):
        cps.GetPointIds().InsertId(i, i)

    ug = vtk.vtkUnstructuredGrid()
    ug.Allocate(1, 1)
    ug.InsertNextCell(cps.GetCellType(), cps.GetPointIds())
    ug.SetPoints(points)

    colors = vtk.vtkNamedColors()

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputData(ug)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d("Tomato"))
    actor.GetProperty().SetLineWidth(3)
    actor.GetProperty().EdgeVisibilityOn()

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

    # Create a polydata to store everything in
    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)

    pointMapper = vtk.vtkGlyph3DMapper()
    pointMapper.SetInputData(polyData)
    pointMapper.SetSourceConnection(sphere.GetOutputPort())

    pointActor = vtk.vtkActor()
    pointActor.SetMapper(pointMapper)
    pointActor.GetProperty().SetColor(colors.GetColor3d("Peacock"))

    # Create a renderer, render window, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("ConvexPointSet")
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add the actors to the scene
    renderer.AddActor(actor)
    renderer.AddActor(pointActor)
    renderer.SetBackground(colors.GetColor3d("Silver"))

    renderer.ResetCamera()
    renderer.GetActiveCamera().Azimuth(210)
    renderer.GetActiveCamera().Elevation(30)
    renderer.ResetCameraClippingRange()

    # Render and interact
    renderWindow.SetSize(640, 480)
    renderWindow.Render()
    renderWindowInteractor.Start()
Beispiel #22
0
 def Add_EneActors(self, ren, renWin, iren, ASDdata):
     import numpy as np
     import vtk
     #-----------------------------------------------------------------------
     # Initialize variables
     #-----------------------------------------------------------------------
     ASDEneActors.timer_count = 0
     ASDEneActors.camera_pos = np.zeros(3, dtype=np.float32)
     ASDEneActors.camera_focal = np.zeros(3, dtype=np.float32)
     ASDEneActors.camera_yaw = 0.0
     ASDEneActors.camera_roll = 0.0
     ASDEneActors.camera_pitch = 0.0
     ASDEneActors.camera_azimuth = 0.0
     ASDEneActors.camera_elevation = 0.0
     ASDEneActors.cluster_disp = ASDdata.cluster_flag
     #-----------------------------------------------------------------------
     # Look up tables for colors
     #-----------------------------------------------------------------------
     # This is a diverging RWB color mapping based on the work of Kenneth
     # Moreland and with the vtk examples provided by Andrew Maclean
     if ASDdata.flag2D:
         self.lut = vtk.vtkLookupTable(
         )  ## Lookup table to assign color to the actors
         num_colors = 256
         self.lut.SetNumberOfTableValues(num_colors)
         self.transfer_func = vtk.vtkColorTransferFunction(
         )  ## Function to map data to the colormap
         self.transfer_func.SetColorSpaceToDiverging()
         self.transfer_func.AddRGBPoint(0, 0.230, 0.299, 0.754)
         self.transfer_func.AddRGBPoint(1, 0.706, 0.016, 0.150)
         for ii, ss in enumerate(
             [float(xx) / float(num_colors) for xx in range(num_colors)]):
             cc = self.transfer_func.GetColor(ss)
             self.lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
         self.lut.Build()
     else:
         self.lut = vtk.vtkLookupTable(
         )  ## Lookup table to assign color to the actors
         num_colors = 256
         self.lut.SetNumberOfTableValues(num_colors)
         self.transfer_func = vtk.vtkColorTransferFunction(
         )  ## Function to map data to the colormap
         self.transfer_func.SetColorSpaceToDiverging()
         self.transfer_func.AddRGBPoint(-0, 0.230, 0.299, 0.754)
         self.transfer_func.AddRGBPoint(1, 0.706, 0.016, 0.150)
         for ii, ss in enumerate(
             [float(xx) / float(num_colors) for xx in range(num_colors)]):
             cc = self.transfer_func.GetColor(ss)
             self.lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
         self.lut.Build()
     #-----------------------------------------------------------------------
     # Data structures for the generation of the smooth grid
     #-----------------------------------------------------------------------
     # Passing the data from the full system to the PolyData
     ASDEneActors.src = vtk.vtkPolyData()
     ASDEneActors.src.SetPoints(ASDdata.coord)
     ASDEneActors.src.GetPointData().SetScalars(ASDdata.energies[0])
     ASDEneActors.scalar_range = ASDEneActors.src.GetScalarRange()
     #-----------------------------------------------------------------------
     # Finding useful geometrical information of the sample
     #-----------------------------------------------------------------------
     # Finding the middle of the sample
     # Also making sure that if the sample is 2D one has no problem with boudings
     # this is mostly useful if splatters are used
     (ASDEneActors.xmin, ASDEneActors.xmax, ASDEneActors.ymin,
      ASDEneActors.ymax, ASDEneActors.zmin,
      ASDEneActors.zmax) = ASDEneActors.src.GetBounds()
     if ASDEneActors.xmin == ASDEneActors.xmax:
         ASDEneActors.xmin = 0.0
         ASDEneActors.xmax = 1.0
     if ASDEneActors.ymin == ASDEneActors.ymax:
         ASDEneActors.ymin = 0.0
         ASDEneActors.ymax = 1.0
     if ASDEneActors.zmin == ASDEneActors.zmax:
         ASDEneActors.zmin = 0.0
         ASDEneActors.zmax = 1.0
     ASDEneActors.xmid = (ASDEneActors.xmin + ASDEneActors.xmax) * 0.5
     ASDEneActors.ymid = (ASDEneActors.ymin + ASDEneActors.ymax) * 0.5
     ASDEneActors.zmid = (ASDEneActors.zmin + ASDEneActors.zmax) * 0.5
     ASDEneActors.height = max(ASDEneActors.xmax, ASDEneActors.ymax,
                               ASDEneActors.zmax) * 1.75
     self.dist_x = np.absolute(
         ASDEneActors.xmax - ASDEneActors.xmin
     )  ## Auxiliary data to find max distance in the x-direction
     self.dist_y = np.absolute(
         ASDEneActors.ymax - ASDEneActors.ymin
     )  ## Auxiliary data to find max distance in the y-direction
     self.dist_z = np.absolute(
         ASDEneActors.zmax - ASDEneActors.zmin
     )  ## Auxiliary data to find max distance in the z-direction
     ASDEneActors.camera_pos[0] = ASDEneActors.xmid
     ASDEneActors.camera_pos[1] = ASDEneActors.ymid
     ASDEneActors.camera_pos[2] = ASDEneActors.height
     ASDEneActors.camera_focal[0] = ASDEneActors.xmid
     ASDEneActors.camera_focal[1] = ASDEneActors.ymid
     ASDEneActors.camera_focal[2] = ASDEneActors.zmid
     # The delaunay tesellation seems to be the best way to transform the point cloud
     # to a surface for volume rendering, the problem is that it is too slow for large
     # data sets, meaning that the best option is first to prune out the data to ensure
     # that one has a manageable number of data points over which to do the construction
     # surface reconstruction and splatter techniques also can be used to generate something
     # akin to the kind of surfaces we want. The issue is that they transform the data to a
     # regular mesh by default. And thus it is a problem for most kind of systems
     if ASDdata.flag2D:
         # Passing the data to generate a triangulation of the data
         ASDEneActors.EneDensMethod = vtk.vtkDelaunay2D()
         ASDEneActors.EneDensMethod.SetInputData(ASDEneActors.src)
         ASDEneActors.EneDensMethod.BoundingTriangulationOff()
         ASDEneActors.EneDensMethod.SetTolerance(0.005)
         # Time the execution of the delaunay tessellation
         SM_timer = vtk.vtkExecutionTimer()
         SM_timer.SetFilter(ASDEneActors.EneDensMethod)
         ASDEneActors.EneDensMethod.Update()
         SM = SM_timer.GetElapsedWallClockTime()
         print("2D Delaunay:", SM)
         # Creating the mapper for the smooth surfaces
         ASDEneActors.EneDensMap = vtk.vtkDataSetMapper()
         ASDEneActors.EneDensMap.SetScalarRange(ASDEneActors.scalar_range)
         ASDEneActors.EneDensMap.SetInputConnection(
             ASDEneActors.EneDensMethod.GetOutputPort())
         ASDEneActors.EneDensMap.SetLookupTable(self.lut)
         ASDEneActors.EneDensMap.SetColorModeToMapScalars()
         ASDEneActors.EneDensMap.Update()
         # Creating the actor for the smooth surfaces
         ASDEneActors.EneDensActor = vtk.vtkLODActor()
         ASDEneActors.EneDensActor.SetMapper(ASDEneActors.EneDensMap)
         ASDEneActors.EneDensActor.GetProperty().SetOpacity(0.75)
         ASDEneActors.EneDensActor.GetProperty().EdgeVisibilityOff()
     else:
         #-------------------------------------------------------------------
         # Setting the parameters for the visualization of 3D structures with
         # splatters
         #-------------------------------------------------------------------
         ASDEneActors.EneDensMethod = vtk.vtkShepardMethod()
         ASDEneActors.EneDensMethod.SetInputData(ASDEneActors.src)
         ASDEneActors.EneDensMethod.SetModelBounds(
             ASDEneActors.xmin, ASDEneActors.xmax, ASDEneActors.ymin,
             ASDEneActors.ymax, ASDEneActors.zmin, ASDEneActors.zmax)
         # This should get rid of the problems when trying to map very thin structures in 2D
         if self.dist_x == min(self.dist_x, self.dist_y, self.dist_z):
             ASDEneActors.EneDensMethod.SetSampleDimensions(
                 3, int(ASDEneActors.ymax), int(ASDEneActors.zmax))
         elif self.dist_y == min(self.dist_x, self.dist_y, self.dist_z):
             ASDEneActors.EneDensMethod.SetSampleDimensions(
                 int(ASDEneActors.xmax), 3, int(ASDEneActors.zmax))
         elif self.dist_z == min(self.dist_x, self.dist_y, self.dist_z):
             ASDEneActors.EneDensMethod.SetSampleDimensions(
                 int(ASDEneActors.xmax), int(ASDEneActors.ymax), 3)
         # This parameter determines how far in the sample (normalized to 1) the
         # method will look to interpolate, greatly affects performance
         ASDEneActors.EneDensMethod.SetMaximumDistance(0.1)
         # Time the execution of the checkerboard splatter
         SP_timer = vtk.vtkExecutionTimer()
         SP_timer.SetFilter(ASDEneActors.EneDensMethod)
         ASDEneActors.EneDensMethod.Update()
         SP = SP_timer.GetElapsedWallClockTime()
         print("3D Shepard Method:", SP)
         # Mapper for the image obtained from the 3D reconstruction method
         ASDEneActors.EneDensMap = vtk.vtkSmartVolumeMapper()
         ASDEneActors.EneDensMap.SetBlendModeToComposite()
         ASDEneActors.EneDensMap.SetInputConnection(
             ASDEneActors.EneDensMethod.GetOutputPort())
         # Function for the opacity gradient
         volumeGradientOpacity = vtk.vtkPiecewiseFunction()
         volumeGradientOpacity.AddPoint(-1, 0.25)
         volumeGradientOpacity.AddPoint(0.5, 0.75)
         volumeGradientOpacity.AddPoint(1.0, 1.0)
         # Properties of the volume to be rendered
         ASDEneActors.volumeProperty = vtk.vtkVolumeProperty()
         ASDEneActors.volumeProperty.SetInterpolationType(1)
         ASDEneActors.volumeProperty.SetColor(self.transfer_func)
         ASDEneActors.volumeProperty.SetAmbient(0.6)
         ASDEneActors.volumeProperty.SetDiffuse(0.6)
         ASDEneActors.volumeProperty.SetSpecular(0.1)
         ASDEneActors.volumeProperty.SetGradientOpacity(
             volumeGradientOpacity)
         # Volume actor, this works in a different way than LOD actors
         ASDEneActors.EneDensActor = vtk.vtkVolume()
         ASDEneActors.EneDensActor.SetMapper(ASDEneActors.EneDensMap)
         ASDEneActors.EneDensActor.SetProperty(self.volumeProperty)
     #-----------------------------------------------------------------------
     # Energy spheres
     #-----------------------------------------------------------------------
     ASDEneActors.EneAtom = vtk.vtkSphereSource()
     ASDEneActors.EneAtom.SetRadius(0.50)
     ASDEneActors.EneAtom.SetThetaResolution(10)
     ASDEneActors.EneAtom.SetPhiResolution(10)
     #-----------------------------------------------------------------------
     # Set the mapper for the energies
     #-----------------------------------------------------------------------
     ASDEneActors.EneMapper = vtk.vtkGlyph3DMapper()
     ASDEneActors.EneMapper.SetSourceConnection(
         ASDEneActors.EneAtom.GetOutputPort())
     ASDEneActors.EneMapper.SetInputData(ASDEneActors.src)
     ASDEneActors.EneMapper.SetScalarRange(ASDEneActors.scalar_range)
     ASDEneActors.EneMapper.SetScaleFactor(1.00)
     ASDEneActors.EneMapper.SetScaleModeToNoDataScaling()
     ASDEneActors.EneMapper.SetLookupTable(self.lut)
     ASDEneActors.EneMapper.SetColorModeToMapScalars()
     ASDEneActors.EneMapper.Update()
     #-----------------------------------------------------------------------
     # Energy actors
     #-----------------------------------------------------------------------
     ASDEneActors.EneActor = vtk.vtkLODActor()
     ASDEneActors.EneActor.SetMapper(ASDEneActors.EneMapper)
     ASDEneActors.EneActor.GetProperty().SetSpecular(0.3)
     ASDEneActors.EneActor.GetProperty().SetSpecularPower(60)
     ASDEneActors.EneActor.GetProperty().SetAmbient(0.2)
     ASDEneActors.EneActor.GetProperty().SetDiffuse(0.8)
     ASDEneActors.EneActor.VisibilityOff()
     #-----------------------------------------------------------------------
     # Setting information of the renderer
     #-----------------------------------------------------------------------
     # Define the renderer
     # Add the actors to the scene
     if ASDdata.flag2D:
         ren.AddActor(ASDEneActors.EneDensActor)
     else:
         ren.AddViewProp(ASDEneActors.EneDensActor)
     ren.AddActor(ASDEneActors.EneActor)
     # Defining the camera directions
     ren.GetActiveCamera().Azimuth(ASDEneActors.camera_azimuth)
     ren.GetActiveCamera().Elevation(ASDEneActors.camera_elevation)
     ren.GetActiveCamera().Yaw(ASDEneActors.camera_yaw)
     ren.GetActiveCamera().Roll(ASDEneActors.camera_roll)
     ren.GetActiveCamera().Pitch(ASDEneActors.camera_pitch)
     ren.GetActiveCamera().SetFocalPoint(ASDEneActors.camera_focal)
     ren.GetActiveCamera().SetPosition(ASDEneActors.camera_pos)
     ren.GetActiveCamera().SetViewUp(0, 1, 0)
     #-----------------------------------------------------------------------
     # Start the renderer
     #-----------------------------------------------------------------------
     iren.Start()
     renWin.Render()
     return
def main():
    titles = list()
    textMappers = list()
    textActors = list()

    uGrids = list()
    mappers = list()
    actors = list()
    renderers = list()

    uGrids.append(MakeUnstructuredGrid(vtk.vtkQuadraticEdge()))
    titles.append("VTK_QUADRATIC_EDGE (= 21)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkQuadraticTriangle()))
    titles.append("VTK_QUADRATIC_TRIANGLE (= 22)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkQuadraticQuad()))
    titles.append("VTK_QUADRATIC_QUAD (= 23)")

    uGrids.append(MakeQuadraticPolygon())
    titles.append("VTK_QUADRATIC_POLYGON (= 36)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkQuadraticTetra()))
    titles.append("VTK_QUADRATIC_TETRA (= 24)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkQuadraticHexahedron()))
    titles.append("VTK_QUADRATIC_HEXAHEDRON (= 25)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkQuadraticWedge()))
    titles.append("VTK_QUADRATIC_WEDGE (= 26)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkQuadraticPyramid()))
    titles.append("VTK_QUADRATIC_PYRAMID (= 27)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkBiQuadraticQuad()))
    titles.append("VTK_BIQUADRATIC_QUAD (= 28)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkTriQuadraticHexahedron()))
    titles.append("VTK_TRIQUADRATIC_HEXAHEDRON (= 29)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkQuadraticLinearQuad()))
    titles.append("VTK_QUADRATIC_LINEAR_QUAD (= 30)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkQuadraticLinearWedge()))
    titles.append("VTK_QUADRATIC_LINEAR_WEDGE (= 31)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkBiQuadraticQuadraticWedge()))
    titles.append("VTK_BIQUADRATIC_QUADRATIC_WEDGE (= 32)")

    uGrids.append(MakeUnstructuredGrid(
        vtk.vtkBiQuadraticQuadraticHexahedron()))
    titles.append("VTK_BIQUADRATIC_QUADRATIC_HEXAHEDRON (= 33)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkBiQuadraticTriangle()))
    titles.append("VTK_BIQUADRATIC_TRIANGLE (= 34)")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkCubicLine()))
    titles.append("VTK_CUBIC_LINE (= 35)")

    colors = vtk.vtkNamedColors()

    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(600, 600)
    renWin.SetWindowName("Isoparametric Cell")

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

    # Create one sphere for all
    sphere = vtk.vtkSphereSource()
    sphere.SetPhiResolution(21)
    sphere.SetThetaResolution(21)
    sphere.SetRadius(.08)

    # Create one text property for all
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(10)
    textProperty.SetJustificationToCentered()

    # Create and link the mappers actors and renderers together.
    for i in range(0, len(uGrids)):
        print("Creating:", titles[i])
        textMappers.append(vtk.vtkTextMapper())
        textActors.append(vtk.vtkActor2D())

        textMappers[i].GetTextProperty().SetFontSize(10)
        textMappers[i].GetTextProperty().ShadowOn()
        mappers.append(vtk.vtkDataSetMapper())
        actors.append(vtk.vtkActor())
        renderers.append(vtk.vtkRenderer())
        mappers[i].SetInputData(uGrids[i])
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(colors.GetColor3d("Tomato"))
        actors[i].GetProperty().EdgeVisibilityOn()
        actors[i].GetProperty().SetLineWidth(3)
        actors[i].GetProperty().SetOpacity(.5)
        renderers[i].AddViewProp(actors[i])

        textMappers[i].SetInput(titles[i])
        textActors[i].SetMapper(textMappers[i])
        textActors[i].SetPosition(50, 10)
        renderers[i].AddViewProp(textActors[i])

        # Label the points
        labelMapper = vtk.vtkLabeledDataMapper()
        labelMapper.SetInputData(uGrids[i])
        labelActor = vtk.vtkActor2D()
        labelActor.SetMapper(labelMapper)
        renderers[i].AddViewProp(labelActor)

        # Glyph the points
        pointMapper = vtk.vtkGlyph3DMapper()
        pointMapper.SetInputData(uGrids[i])
        pointMapper.SetSourceConnection(sphere.GetOutputPort())
        pointMapper.ScalingOff()
        pointMapper.ScalarVisibilityOff()

        pointActor = vtk.vtkActor()
        pointActor.SetMapper(pointMapper)
        pointActor.GetProperty().SetDiffuseColor(colors.GetColor3d("Banana"))
        pointActor.GetProperty().SetSpecular(.6)
        pointActor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0)
        pointActor.GetProperty().SetSpecularPower(100)
        renderers[i].AddViewProp(pointActor)

        renWin.AddRenderer(renderers[i])

    # Setup the viewports
    xGridDimensions = 4
    yGridDimensions = 4
    rendererSize = 240
    renWin.SetSize(rendererSize * xGridDimensions,
                   rendererSize * yGridDimensions)
    for row in range(0, yGridDimensions):
        for col in range(0, xGridDimensions):
            index = row * xGridDimensions + col

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

            if index > (len(actors) - 1):
                # Add a renderer even if there is no actor.
                # This makes the render window background all the same color.
                ren = vtk.vtkRenderer()
                ren.SetBackground(colors.GetColor3d("SlateGray"))
                ren.SetViewport(viewport)
                renWin.AddRenderer(ren)
                continue

            renderers[index].SetViewport(viewport)
            renderers[index].SetBackground(colors.GetColor3d("SlateGray"))
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(-30)
            renderers[index].ResetCameraClippingRange()

    iRen.Initialize()
    renWin.Render()
    iRen.Start()
Beispiel #24
0
    def Add_NeighActors(self, ren, renWin, iren, ASDdata, mode):
        """This defines the actors for the visualization of neighbours from the struct file.
        It allows for the visualization of the Heisenberg exchange interaction and
        of the DM vectors.
        Args:
            ren: current renderer for the VTK visualization.
            renWin: VTK window where the visualization is performed.
            iren: current window interactor for the VTK visualization
            ASData: class containing the data read from the UppASD simulations.
            mode: value indicating whether one is visualizing the Heisenberg exchange or DMI vectors (1/2)

        Author
        ----------
        Jonathan Chico
        """
        import vtk
        import numpy as np

        ASDNeighActors.timer_count = 0
        ASDNeighActors.camera_pos = np.zeros(3, dtype=np.float32)
        ASDNeighActors.camera_focal = np.zeros(3, dtype=np.float32)
        ASDNeighActors.camera_yaw = 0.0
        ASDNeighActors.camera_roll = 0.0
        ASDNeighActors.camera_pitch = 0.0
        ASDNeighActors.camera_azimuth = 0.0
        ASDNeighActors.camera_elevation = 0.0
        #-----------------------------------------------------------------------
        # Data structures for the atoms in the neighbour map
        #-----------------------------------------------------------------------
        AtomGrid = vtk.vtkPolyData()
        AtomGrid.SetPoints(ASDdata.coord)
        ASDNeighActors.SLMax = AtomGrid.GetNumberOfPoints()
        #-----------------------------------------------------------------------
        # Atom sphere
        #-----------------------------------------------------------------------
        Atom = vtk.vtkSphereSource()
        Atom.SetRadius(0.50)
        Atom.SetThetaResolution(10)
        Atom.SetPhiResolution(10)
        #-----------------------------------------------------------------------
        # Atom glyph
        #-----------------------------------------------------------------------
        Atoms = vtk.vtkGlyph3DMapper()
        Atoms.SetInputData(AtomGrid)
        Atoms.SetSourceConnection(Atom.GetOutputPort())
        Atoms.SetScaleFactor(0.5)
        Atoms.ClampingOn()
        Atoms.SetScaleModeToNoDataScaling()
        Atoms.SetColorModeToMapScalars()
        Atoms.Update()
        #-----------------------------------------------------------------------
        # Atoms actors
        #-----------------------------------------------------------------------
        ASDNeighActors.AtomsActor = vtk.vtkLODActor()
        ASDNeighActors.AtomsActor.SetMapper(Atoms)
        ASDNeighActors.AtomsActor.GetProperty().SetOpacity(0.9)
        ASDNeighActors.AtomsActor.GetProperty().SetColor(0.5, 0.5, 0.5)
        #-----------------------------------------------------------------------
        # Data structures for the neighbours in the neighbour mapper
        #-----------------------------------------------------------------------
        self.lut = vtk.vtkLookupTable()
        num_colors = 256
        self.lut.SetNumberOfTableValues(num_colors)
        self.transfer_func = vtk.vtkColorTransferFunction()
        self.transfer_func.SetColorSpaceToDiverging()
        self.transfer_func.AddRGBPoint(0, 0.230, 0.299, 0.754)
        self.transfer_func.AddRGBPoint(1, 0.706, 0.016, 0.150)
        for ii, ss in enumerate(
            [float(xx) / float(num_colors) for xx in range(num_colors)]):
            cc = self.transfer_func.GetColor(ss)
            self.lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
        self.lut.Build()
        #-----------------------------------------------------------------------
        # Grid for neighbours
        #-----------------------------------------------------------------------
        ASDNeighActors.NeighGrid = vtk.vtkPolyData()
        ASDNeighActors.NeighGrid.SetPoints(ASDdata.neighs)
        ASDNeighActors.NeighGrid.GetPointData().SetScalars(
            ASDdata.neigh_colors)
        if mode == 2:
            ASDNeighActors.NeighGrid.GetPointData().SetVectors(
                ASDdata.DM_vectors)
        ASDNeighActors.NumNeigh = ASDNeighActors.NeighGrid.GetNumberOfPoints()
        scalar_range = ASDNeighActors.NeighGrid.GetScalarRange()
        #-----------------------------------------------------------------------
        # Finding useful geometrical information of the sample
        # Finding the middle of the sample
        # Also making sure that if the sample is 2D one has no problem with boudings
        # this is mostly useful if splatters are used
        #-----------------------------------------------------------------------
        (ASDNeighActors.xmin, ASDNeighActors.xmax, ASDNeighActors.ymin,
         ASDNeighActors.ymax, ASDNeighActors.zmin,
         ASDNeighActors.zmax) = ASDNeighActors.NeighGrid.GetBounds()
        if ASDNeighActors.xmin == ASDNeighActors.xmax:
            ASDNeighActors.xmin = 0.0
            ASDNeighActors.xmax = 1.0
        if ASDNeighActors.ymin == ASDNeighActors.ymax:
            ASDNeighActors.ymin = 0.0
            ASDNeighActors.ymax = 1.0
        if ASDNeighActors.zmin == ASDNeighActors.zmax:
            ASDNeighActors.zmin = 0.0
            ASDNeighActors.zmax = 1.0
        ASDNeighActors.xmid = (ASDNeighActors.xmin + ASDNeighActors.xmax) * 0.5
        ASDNeighActors.ymid = (ASDNeighActors.ymin + ASDNeighActors.ymax) * 0.5
        ASDNeighActors.zmid = (ASDNeighActors.zmin + ASDNeighActors.zmax) * 0.5
        ASDNeighActors.height = max(ASDNeighActors.xmax, ASDNeighActors.ymax,
                                    ASDNeighActors.zmax) * 1.75
        self.dist_x = np.absolute(ASDNeighActors.xmax - ASDNeighActors.xmin)
        self.dist_y = np.absolute(ASDNeighActors.ymax - ASDNeighActors.ymin)
        self.dist_z = np.absolute(ASDNeighActors.zmax - ASDNeighActors.zmin)
        ASDNeighActors.camera_pos[0] = ASDNeighActors.xmid
        ASDNeighActors.camera_pos[1] = ASDNeighActors.ymid
        ASDNeighActors.camera_pos[2] = ASDNeighActors.height
        ASDNeighActors.camera_focal[0] = ASDNeighActors.xmid
        ASDNeighActors.camera_focal[1] = ASDNeighActors.ymid
        ASDNeighActors.camera_focal[2] = ASDNeighActors.zmid
        #-----------------------------------------------------------------------
        # Neighbour glyphs
        #-----------------------------------------------------------------------
        if mode == 1:
            ASDNeighActors.NeighGlyphs = vtk.vtkSphereSource()
            ASDNeighActors.NeighGlyphs.SetRadius(0.50)
            ASDNeighActors.NeighGlyphs.SetThetaResolution(40)
            ASDNeighActors.NeighGlyphs.SetPhiResolution(40)
        else:
            ASDNeighActors.NeighGlyphs = vtk.vtkArrowSource()
            ASDNeighActors.NeighGlyphs.SetTipRadius(0.20)
            ASDNeighActors.NeighGlyphs.SetShaftRadius(0.10)
            ASDNeighActors.NeighGlyphs.SetTipResolution(40)
            ASDNeighActors.NeighGlyphs.SetShaftResolution(40)
        #-----------------------------------------------------------------------
        # Glyph source
        #-----------------------------------------------------------------------
        ASDNeighActors.NeighGlyph3D = vtk.vtkGlyph3D()
        ASDNeighActors.NeighGlyph3D.SetSourceConnection(
            ASDNeighActors.NeighGlyphs.GetOutputPort())
        ASDNeighActors.NeighGlyph3D.SetVectorModeToUseNormal()
        ASDNeighActors.NeighGlyph3D.SetInputData(ASDNeighActors.NeighGrid)
        if mode == 1:
            ASDNeighActors.NeighGlyph3D.SetScaleFactor(1.05)
        elif mode == 2:
            ASDNeighActors.NeighGlyph3D.SetScaleFactor(1.25)
        ASDNeighActors.NeighGlyph3D.SetColorModeToColorByScalar()
        ASDNeighActors.NeighGlyph3D.SetScaleModeToDataScalingOff()
        if mode == 2:
            ASDNeighActors.NeighGlyph3D.SetVectorModeToUseVector()
        ASDNeighActors.NeighGlyph3D.Update()
        #-----------------------------------------------------------------------
        # Set up Neighbour glyphs
        #-----------------------------------------------------------------------
        ASDNeighActors.NeighMapper = vtk.vtkPolyDataMapper()
        ASDNeighActors.NeighMapper.SetInputConnection(
            ASDNeighActors.NeighGlyph3D.GetOutputPort())
        ASDNeighActors.NeighMapper.SetScalarRange(scalar_range)
        ASDNeighActors.NeighMapper.SetLookupTable(self.lut)
        ASDNeighActors.NeighMapper.SetColorModeToMapScalars()
        ASDNeighActors.NeighMapper.Update()
        #-----------------------------------------------------------------------
        # Neighbour actors
        #-----------------------------------------------------------------------
        ASDNeighActors.NeighActor = vtk.vtkLODActor()
        ASDNeighActors.NeighActor.SetMapper(ASDNeighActors.NeighMapper)
        ASDNeighActors.NeighActor.GetProperty().SetSpecular(0.3)
        ASDNeighActors.NeighActor.GetProperty().SetSpecularPower(60)
        ASDNeighActors.NeighActor.GetProperty().SetAmbient(0.2)
        ASDNeighActors.NeighActor.GetProperty().SetDiffuse(0.8)
        #-----------------------------------------------------------------------
        # Grid for the center atom
        #-----------------------------------------------------------------------
        ASDNeighActors.CenterGrid = vtk.vtkPolyData()
        ASDNeighActors.CenterGrid.SetPoints(ASDdata.atomCenter)
        ASDNeighActors.CenterGrid.Modified()
        #-----------------------------------------------------------------------
        # Source for the center atom, a sphere
        #-----------------------------------------------------------------------
        ASDNeighActors.CenterSource = vtk.vtkSphereSource()
        ASDNeighActors.CenterSource.SetRadius(0.50)
        ASDNeighActors.CenterSource.SetThetaResolution(40)
        ASDNeighActors.CenterSource.SetPhiResolution(40)
        #-----------------------------------------------------------------------
        # Mapper for the center actor
        #-----------------------------------------------------------------------
        ASDNeighActors.Center = vtk.vtkGlyph3DMapper()
        ASDNeighActors.Center.SetInputData(ASDNeighActors.CenterGrid)
        ASDNeighActors.Center.SetSourceConnection(
            ASDNeighActors.CenterSource.GetOutputPort())
        ASDNeighActors.Center.SetScaleFactor(1.25)
        ASDNeighActors.Center.SetScaleModeToNoDataScaling()
        ASDNeighActors.Center.Update()
        #-----------------------------------------------------------------------
        # Actor for the center atom
        #-----------------------------------------------------------------------
        ASDNeighActors.CenterActor = vtk.vtkLODActor()
        ASDNeighActors.CenterActor.SetMapper(ASDNeighActors.Center)
        ASDNeighActors.CenterActor.GetProperty().SetColor(0.4, 0.8, 0.4)
        ASDNeighActors.CenterActor.GetProperty().SetSpecular(0.3)
        ASDNeighActors.CenterActor.GetProperty().SetSpecularPower(60)
        ASDNeighActors.CenterActor.GetProperty().SetAmbient(0.2)
        ASDNeighActors.CenterActor.GetProperty().SetDiffuse(0.8)
        #-----------------------------------------------------------------------
        # Defining the camera directions
        #-----------------------------------------------------------------------
        ren.GetActiveCamera().Azimuth(0)
        ren.GetActiveCamera().Elevation(0)
        ren.GetActiveCamera().SetFocalPoint(ASDNeighActors.xmid,
                                            ASDNeighActors.ymid,
                                            ASDNeighActors.zmid)
        ren.GetActiveCamera().SetPosition(ASDNeighActors.xmid,
                                          ASDNeighActors.ymid,
                                          ASDNeighActors.height)
        ren.GetActiveCamera().Azimuth(ASDNeighActors.camera_azimuth)
        ren.GetActiveCamera().Elevation(ASDNeighActors.camera_elevation)
        ren.GetActiveCamera().Yaw(ASDNeighActors.camera_yaw)
        ren.GetActiveCamera().Roll(ASDNeighActors.camera_roll)
        ren.GetActiveCamera().Pitch(ASDNeighActors.camera_pitch)
        ren.GetActiveCamera().SetFocalPoint(ASDNeighActors.camera_focal)
        ren.GetActiveCamera().SetPosition(ASDNeighActors.camera_pos)
        ren.GetActiveCamera().SetViewUp(0, 1, 0)
        #-----------------------------------------------------------------------
        # Adding the actors for the neighbour mapping
        #-----------------------------------------------------------------------
        ren.AddActor(ASDNeighActors.NeighActor)
        ren.AddActor(ASDNeighActors.AtomsActor)
        ren.AddActor(ASDNeighActors.CenterActor)
        iren.Start()
        renWin.Render()
        return
Beispiel #25
0
 def Add_ClusterActors(self,ASDdata,iren,renWin,ren):
     import vtk
     ########################################################################
     # Data structures for the impurity cluster
     ########################################################################
     # Passing the data from the cluster to the PolyData
     src_clus=vtk.vtkPolyData()
     src_clus.SetPoints(ASDdata.coord_c)
     src_clus.GetPointData().SetScalars(ASDdata.colors_clus)
     # Passing the data from the selected impurities
     src_imp=vtk.vtkPolyData()
     src_imp.SetPoints(ASDdata.points_clus_imp)
     src_imp.GetPointData().SetScalars(ASDdata.colors_imp)
     src_imp.Modified()
     # Setting up the gaussian splatter for the clusters
     atomSource = vtk.vtkGaussianSplatter()
     atomSource.SetInputData(src_clus)
     atomSource.SetRadius(0.100)
     atomSource.ScalarWarpingOff()
     atomSource.SetExponentFactor(-20)
     atomSource.Update()
     bound=atomSource.GetModelBounds()
     atomSource.SetModelBounds(bound[0],bound[1],bound[2],bound[3],bound[4]*0.25,bound[5]*0.25)
     atomSource.Update()
     # Setting up a contour filter
     atomSurface = vtk.vtkContourFilter()
     atomSurface.SetInputConnection(atomSource.GetOutputPort())
     atomSurface.SetValue(0, 0.01)
     # Setting up the mapper
     atomMapper = vtk.vtkPolyDataMapper()
     atomMapper.SetInputConnection(atomSurface.GetOutputPort())
     atomMapper.ScalarVisibilityOff()
     # Creating the actor for the smooth surfaces
     ASDGenActors.atom = vtk.vtkActor()
     ASDGenActors.atom.SetMapper(atomMapper)
     ASDGenActors.atom.GetProperty().SetColor(0.0,0.0,0.0)
     ASDGenActors.atom.GetProperty().EdgeVisibilityOff()
     ASDGenActors.atom.GetProperty().SetSpecularPower(30)
     ASDGenActors.atom.GetProperty().SetAmbient(0.2)
     ASDGenActors.atom.GetProperty().SetDiffuse(0.8)
     ASDGenActors.atom.GetProperty().SetOpacity(0.25)
     # Set up imp sources
     atomSource_imp = vtk.vtkSphereSource()
     atomSource_imp.SetRadius(2.5)
     atomSource_imp.SetThetaResolution(20)
     atomSource_imp.SetPhiResolution(20)
     # Mapping the spheres to the actual points on the selected impurities
     atomMapper_imp = vtk.vtkGlyph3DMapper()
     atomMapper_imp.SetInputData(src_imp)
     atomMapper_imp.SetSourceConnection(atomSource_imp.GetOutputPort())
     atomMapper_imp.SetScaleFactor(0.2)
     atomMapper_imp.SetScaleModeToNoDataScaling()
     atomMapper_imp.Update()
     # Creating the selected impurity actors
     ASDGenActors.atom_imp = vtk.vtkLODActor()
     ASDGenActors.atom_imp.SetMapper(atomMapper_imp)
     ASDGenActors.atom_imp.GetProperty().SetSpecular(0.3)
     ASDGenActors.atom_imp.GetProperty().SetSpecularPower(30)
     ASDGenActors.atom_imp.GetProperty().SetAmbient(0.2)
     ASDGenActors.atom_imp.GetProperty().SetDiffuse(0.8)
     # If there is information about the cluster add the needed actors
     ren.AddActor(ASDGenActors.atom)
     ren.AddActor(ASDGenActors.atom_imp)
     ########################################################################
     # Start the renderer
     ########################################################################
     iren.Start()
     renWin.Render()
     return
Beispiel #26
0
    def buildPipeline(self):
        """ execute() -> None
        Dispatch the vtkRenderer to the actual rendering widget
        """
        self.colorInputModule = self.wmod.forceGetInputFromPort("colors", None)

        if self.input() == None:
            print >> sys.stderr, "Must supply 'volume' port input to VectorCutPlane"
            return

        xMin, xMax, yMin, yMax, zMin, zMax = self.input().GetWholeExtent()
        spacing = self.input().GetSpacing()
        sx, sy, sz = spacing
        origin = self.input().GetOrigin()
        ox, oy, oz = origin

        cellData = self.input().GetCellData()
        pointData = self.input().GetPointData()
        vectorsArray = pointData.GetVectors()

        if vectorsArray == None:
            print >> sys.stderr, "Must supply point vector data for 'volume' port input to VectorVolume"
            return

        self.setRangeBounds(list(vectorsArray.GetRange(-1)))
        self.nComponents = vectorsArray.GetNumberOfComponents()
        for iC in range(-1, 3):
            print "Value Range %d: %s " % (iC, str(vectorsArray.GetRange(iC)))
        for iV in range(10):
            print "Value[%d]: %s " % (iV, str(vectorsArray.GetTuple3(iV)))

        self.initialOrigin = self.input().GetOrigin()
        self.initialExtent = self.input().GetExtent()
        self.initialSpacing = self.input().GetSpacing()
        self.dataBounds = self.getUnscaledWorldExtent(self.initialExtent,
                                                      self.initialSpacing,
                                                      self.initialOrigin)
        dataExtents = ((self.dataBounds[1] - self.dataBounds[0]) / 2.0,
                       (self.dataBounds[3] - self.dataBounds[2]) / 2.0,
                       (self.dataBounds[5] - self.dataBounds[4]) / 2.0)
        centroid = ((self.dataBounds[0] + self.dataBounds[1]) / 2.0,
                    (self.dataBounds[2] + self.dataBounds[3]) / 2.0,
                    (self.dataBounds[4] + self.dataBounds[5]) / 2.0)
        self.pos = [
            self.initialSpacing[i] * self.initialExtent[2 * i]
            for i in range(3)
        ]
        if ((self.initialOrigin[0] + self.pos[0]) < 0.0):
            self.pos[0] = self.pos[0] + 360.0

        self.resample = vtk.vtkExtractVOI()
        self.resample.SetInput(self.input())
        self.resample.SetVOI(self.initialExtent)
        self.ApplyGlyphDecimationFactor()
        lut = self.getLut()

        if self.colorInputModule <> None:
            colorInput = self.colorInputModule.getOutput()
            self.color_resample = vtk.vtkExtractVOI()
            self.color_resample.SetInput(colorInput)
            self.color_resample.SetVOI(self.initialExtent)
            self.color_resample.SetSampleRate(sampleRate, sampleRate, 1)
            #            self.probeFilter = vtk.vtkProbeFilter()
            #            self.probeFilter.SetSourceConnection( self.resample.GetOutputPort() )
            #            colorInput = self.colorInputModule.getOutput()
            #            self.probeFilter.SetInput( colorInput )
            resampledColorInput = self.color_resample.GetOutput()
            shiftScale = vtk.vtkImageShiftScale()
            shiftScale.SetOutputScalarTypeToFloat()
            shiftScale.SetInput(resampledColorInput)
            valueRange = self.getScalarRange()
            shiftScale.SetShift(valueRange[0])
            shiftScale.SetScale((valueRange[1] - valueRange[0]) / 65535)
            colorFloatInput = shiftScale.GetOutput()
            colorFloatInput.Update()
            colorInput_pointData = colorFloatInput.GetPointData()
            self.colorScalars = colorInput_pointData.GetScalars()
            self.colorScalars.SetName('color')
            lut.SetTableRange(valueRange)

        self.glyph = vtk.vtkGlyph3DMapper()
        #        if self.colorInputModule <> None:   self.glyph.SetColorModeToColorByScalar()
        #        else:                               self.glyph.SetColorModeToColorByVector()
        scalarRange = self.getScalarRange()
        self.glyph.SetScaleModeToScaleByMagnitude()
        self.glyph.SetColorModeToMapScalars()
        self.glyph.SetUseLookupTableScalarRange(1)
        self.glyph.SetOrient(1)
        #        self.glyph.ClampingOn()
        self.glyph.SetRange(scalarRange[0:2])
        self.glyph.SetInputConnection(self.resample.GetOutputPort())
        self.arrow = vtk.vtkArrowSource()
        self.glyph.SetSourceConnection(self.arrow.GetOutputPort())
        self.glyph.SetLookupTable(lut)
        self.glyphActor = vtk.vtkActor()
        self.glyphActor.SetMapper(self.glyph)
        self.renderer.AddActor(self.glyphActor)
        self.renderer.SetBackground(VTK_BACKGROUND_COLOR[0],
                                    VTK_BACKGROUND_COLOR[1],
                                    VTK_BACKGROUND_COLOR[2])
        self.set3DOutput(wmod=self.wmod)
Beispiel #27
0
    def createField(self,
                    polydata_valid,
                    polydata_invalid,
                    radius,
                    scalar_bar=False):
        """Create the field."""
        actors_list = []

        #### valid ####
        # source
        source_valid = vtk.vtkSphereSource()
        source_valid.SetPhiResolution(self.resolution)
        source_valid.SetThetaResolution(self.resolution)
        source_valid.SetRadius(radius)

        # lut
        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(1024)
        lut.SetHueRange(0.667, 0.0)
        lut.SetRange(self.field_min, self.field_max)
        lut.SetRampToLinear()
        lut.Build()

        # glyph mapper
        mapper_valid = vtk.vtkGlyph3DMapper()
        mapper_valid.SetInputData(polydata_valid)
        mapper_valid.SetSourceConnection(source_valid.GetOutputPort())
        mapper_valid.ClampingOff()
        mapper_valid.SetScaleFactor(1.0)
        mapper_valid.SetScaleModeToNoDataScaling()
        mapper_valid.SetLookupTable(lut)
        mapper_valid.SetScalarRange(self.field_min, self.field_max)

        # actor
        actor_valid = vtk.vtkActor()
        actor_valid.SetMapper(mapper_valid)
        actors_list.append(actor_valid)

        #### invalid ####
        if polydata_invalid is not None:
            # source
            source_invalid = vtk.vtkCubeSource()
            source_invalid.SetXLength(1.7 * radius)
            source_invalid.SetYLength(1.7 * radius)
            source_invalid.SetZLength(1.7 * radius)

            # glyph mapper
            mapper_invalid = vtk.vtkGlyph3DMapper()
            mapper_invalid.SetInputData(polydata_invalid)
            mapper_invalid.SetSourceConnection(source_invalid.GetOutputPort())
            mapper_invalid.ClampingOff()
            mapper_invalid.SetScaleFactor(1.0)
            mapper_invalid.SetScaleModeToNoDataScaling()

            # actor
            actor_invalid = vtk.vtkActor()
            actor_invalid.SetMapper(mapper_invalid)
            actor_invalid.GetProperty().SetColor(0.6, 0.6, 0.6)
            actors_list.append(actor_invalid)

        # create a scalar bar
        if scalar_bar:
            scalar_bar_actor = vtk.vtkScalarBarActor()
            scalar_bar_actor.SetLookupTable(lut)
            actors_list.append(scalar_bar_actor)

        return actors_list
Beispiel #28
0
spheres = list()
for i in range(100):
    spheres.append(
        Sphere(np.array([0., 3. * i, 0.]), 1, np.array([10., 0., 0.])))

visuData = DefineVisuData(spheres)
positions, radii, velocities = visuData
polydata = vtk.vtkPolyData()
polydata.SetPoints(positions)
polydata.GetPointData().SetScalars(radii)

glyph = vtk.vtkPolyData()
sphereSource = ReferenceSphere()

glyph3Dmapper = vtk.vtkGlyph3DMapper()
glyph3Dmapper.SetSourceConnection(sphereSource.GetOutputPort())
glyph3Dmapper.SetInputData(polydata)
glyph3Dmapper.Update()

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

# create a rendering window and renderer
renderer = vtk.vtkRenderer()
renderer.SetBackground(0.4, 0.6, 0.8)
renderer.AddActor(actor)

renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindow.SetSize(500, 500)
def main():
    colors = vtk.vtkNamedColors()

    filename = get_program_parameters()

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

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

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

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

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

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

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

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

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

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

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

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

    categoricalLut.DeepCopy(originalLut)
    categoricalLut.IndexedLookupOn()

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

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

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

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

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

    renderer = contextView.GetRenderer()

    renderWindow = contextView.GetRenderWindow()

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

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

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

    renderer.SetActiveCamera(aCamera)
    renderer.ResetCamera()

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

    renderWindowInteractor.Start()
sphere.SetRadius(0.1)

# Setup actor and mapper
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(functionSource.GetOutputPort())

actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(colors.GetColor3d("DarkSlateGrey"))
actor.GetProperty().SetLineWidth(3.0)

# Create a polydata to store everything in
polyData = vtk.vtkPolyData()
polyData.SetPoints(points)

pointMapper = vtk.vtkGlyph3DMapper()
pointMapper.SetInputData(polyData)
pointMapper.SetSourceConnection(sphere.GetOutputPort())

pointActor = vtk.vtkActor()
pointActor.SetMapper(pointMapper)
pointActor.GetProperty().SetColor(colors.GetColor3d("Peacock"))

# Setup render window, renderer, and interactor
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindow.SetWindowName("ParametricSpline")

renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
Beispiel #31
0
    def AddASDNeigh_actors(self, ren, renWin, mode, viz_type, iren):
        # Reading the data for the nieghbours
        ASD_data = ASDVTKReading.ASDReading()
        ASD_data.ReadingWrapper(mode, viz_type)

        # Set the maximum number of entried in the slider to be equal to the number of atoms
        ########################################################################
        # Data structures for the atoms in the neighbour map
        ########################################################################
        AtomGrid = vtk.vtkPolyData()
        AtomGrid.SetPoints(ASD_data.coord)
        ASDNeighActors.SLMax = AtomGrid.GetNumberOfPoints()
        # Atom sphere
        Atom = vtk.vtkSphereSource()
        Atom.SetRadius(0.50)
        Atom.SetThetaResolution(10)
        Atom.SetPhiResolution(10)
        # Atom glyph
        Atoms = vtk.vtkGlyph3DMapper()
        Atoms.SetInputData(AtomGrid)
        Atoms.SetSourceConnection(Atom.GetOutputPort())
        Atoms.SetScaleFactor(0.5)
        Atoms.ClampingOn()
        Atoms.SetScaleModeToNoDataScaling()
        Atoms.SetColorModeToMapScalars()
        Atoms.Update()
        # Atoms actors
        ASDNeighActors.AtomsActor = vtk.vtkLODActor()
        ASDNeighActors.AtomsActor.SetMapper(Atoms)
        ASDNeighActors.AtomsActor.GetProperty().SetOpacity(0.9)
        ASDNeighActors.AtomsActor.GetProperty().SetColor(0.5, 0.5, 0.5)
        ########################################################################
        # Data structures for the neighbours in the neighbour mapper
        ########################################################################
        #Grid for neighbours
        ASDNeighActors.NeighGrid = vtk.vtkPolyData()
        ASDNeighActors.NeighGrid.SetPoints(ASD_data.neighs)
        ASDNeighActors.NeighGrid.GetPointData().SetScalars(ASD_data.nTypes)
        ASDNeighActors.NumNeigh = ASDNeighActors.NeighGrid.GetNumberOfPoints()
        #Neighbour glyphs
        ASDNeighActors.Neigh = vtk.vtkSphereSource()
        ASDNeighActors.Neigh.SetRadius(0.50)
        ASDNeighActors.Neigh.SetThetaResolution(20)
        ASDNeighActors.Neigh.SetPhiResolution(20)
        # Set up Neighbour glyphs
        ASDNeighActors.Neighs = vtk.vtkGlyph3DMapper()
        ASDNeighActors.Neighs.SetInputData(ASDNeighActors.NeighGrid)
        ASDNeighActors.Neighs.SetSourceConnection(
            ASDNeighActors.Neigh.GetOutputPort())
        ASDNeighActors.Neighs.SetScaleFactor(1.25)
        ASDNeighActors.Neighs.SetColorModeToMapScalars()
        ASDNeighActors.Neighs.SetScaleModeToNoDataScaling()
        ASDNeighActors.Neighs.SetScalarRange(
            ASDNeighActors.NeighGrid.GetPointData().GetScalars().GetRange())
        # Color lookup table for neighbours
        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(2)
        lut.SetTableValue(0, 0.0, 1.0, 0.0, 0.5)
        lut.SetTableValue(1, 0.0, 0.0, 1.0, 0.5)
        lut.SetTableRange(ASD_data.nTypes.GetRange())
        lut.Build()
        # Fill up Lookup Table with appropiate colors
        ASDNeighActors.Neighs.SetLookupTable(lut)
        ASDNeighActors.Neighs.Update()
        # Neighbour actors
        ASDNeighActors.NeighActor = vtk.vtkLODActor()
        ASDNeighActors.NeighActor.SetMapper(ASDNeighActors.Neighs)
        ASDNeighActors.NeighActor.GetProperty().SetSpecularColor(0.4, 0.8, 0.4)
        ASDNeighActors.NeighActor.GetProperty().SetSpecular(0.3)
        ASDNeighActors.NeighActor.GetProperty().SetSpecularPower(60)
        ASDNeighActors.NeighActor.GetProperty().SetAmbient(0.2)
        ASDNeighActors.NeighActor.GetProperty().SetDiffuse(0.8)
        # Setting up information needed for the camera
        self.xmin, self.xmax = self.AtomsActor.GetXRange()
        self.ymin, self.ymax = self.AtomsActor.GetYRange()
        self.zmin, self.zmax = self.AtomsActor.GetZRange()
        self.xmid = (self.xmin + self.xmax) / 2
        self.ymid = (self.ymin + self.ymax) / 2
        self.zmid = (self.zmin + self.zmax) / 2
        self.height = max(self.xmax, self.ymax, self.zmax) * 1.75
        # Defining the camera directions
        ren.GetActiveCamera().Azimuth(0)
        ren.GetActiveCamera().Elevation(0)
        ren.GetActiveCamera().SetFocalPoint(self.xmid, self.ymid, self.zmid)
        ren.GetActiveCamera().SetPosition(self.xmid, self.ymid, self.height)
        # Adding the actors for the neighbour mapping
        ren.AddActor(ASDNeighActors.NeighActor)
        ren.AddActor(ASDNeighActors.AtomsActor)
        iren.Start()
        renWin.Render()