Ejemplo n.º 1
0
 def preview(self):
     """ Display a preview of the data structure in the preview
         window.
     """
     self._preview_window.clear()
     self._preview_window.add_source(self.data_source)
     data = lambda name: self.data_sources[name]
     g = Glyph()
     g.glyph.glyph_source.glyph_source = \
                 g.glyph.glyph_source.glyph_list[0]
     g.glyph.scale_mode = 'data_scaling_off'
     if not (self.has_vector_data or self.data_type_ == 'vector'):
         g.glyph.glyph_source.glyph_source.glyph_type = 'cross'
         g.actor.property.representation = 'points'
         g.actor.property.point_size = 3.
     self._preview_window.add_module(g)
     if not self.data_type_ in ('point', 'vector') or self.lines:
         s = Surface()
         s.actor.property.opacity = 0.3
         self._preview_window.add_module(s)
     if not self.data_type_ == 'point':
         self._preview_window.add_filter(ExtractEdges())
         s = Surface()
         s.actor.property.opacity = 0.2
         self._preview_window.add_module(s)
Ejemplo n.º 2
0
 def create_plot(self):
     from mayavi.modules.api import Surface, Vectors
     self.surface = Surface()
     self.surface1 = Surface()
     self.surface1.actor.property.representation = 'wireframe'
     self.surface1.actor.actor.visibility = self.enable_grid
     self.surface.actor.actor.visibility = self.enable_surface
     self.vectors = Vectors()
     self.engine = self.scene.engine
     self.engine.add_source(self.src)
     self.engine.add_module(self.surface, obj=self.src)
     self.engine.add_module(self.surface1, obj=self.src)
     self.engine.add_module(self.vectors, obj=self.src)
     self.module_manager = self.engine.scenes[0].children[0].children[0]
     self.module_manager.vector_lut_manager.show_legend = True
     self.vectors.actor.actor.visibility = self.enable_vectors
     self.surface.actor.actor.visibility = self.enable_surface
     if self.legend == "Scalar Legend":
         self.module_manager.vector_lut_manager.show_legend = False
         self.module_manager.scalar_lut_manager.show_legend = True
     else:
         self.module_manager.vector_lut_manager.show_legend = True
         self.module_manager.scalar_lut_manager.show_legend = False
     if self.point_cell == "Point Data":
         self.module_manager.lut_data_mode = 'point data'
     else:
         self.module_manager.lut_data_mode = 'cell data'
     self.vectors.glyph.glyph.scale_factor = self.vector_scale_size
     self.src.point_scalars_name = 'abs^2'
     self.src.cell_scalars_name = 'abs^2'
Ejemplo n.º 3
0
    def _show_one_gaussian(self, gauss, engine, scale=1.0):
        """Plot one of the gaussians."""
        from mayavi.sources.api import ParametricSurface
        from mayavi.modules.api import Surface

        source = ParametricSurface()
        source.function = 'ellipsoid'
        engine.add_source(source)

        eigval, eigvec = np.linalg.eig(gauss.sigma)

        angles = rotationMatrixToEulerAngles(eigvec.T) * 180.0 / np.pi
        surface = Surface()
        source.add_module(surface)
        actor = surface.actor

        actor.property.opacity = 0.5
        actor.property.color = tuple(np.random.rand(3))
        actor.mapper.scalar_visibility = False
        actor.property.backface_culling = True
        actor.actor.orientation = np.array([0.0, 0.0, 0.0])
        actor.actor.origin = np.array([0.0, 0.0, 0.0])
        actor.actor.position = np.array(gauss.mu)
        actor.actor.scale = np.array(scale * np.sqrt(eigval))
        actor.actor.rotate_x(angles[0])
        actor.actor.rotate_y(angles[1])
        actor.actor.rotate_z(angles[2])
        return surface
Ejemplo n.º 4
0
    def plot_stiffness(self, editor, object):
        '''This method gets the input data from the current tstepper
        which is the root of the tree. Sets up the context and 
        gets the stiffness matrix.
        '''
        K = self._get_stiffness(editor, object)
        K_dense = DenseMtx(assemb=K)

        # prepare plotting of the matrix in Mayavi
        #
        z_data = K_dense.mtx.flatten()
        z_max = max(z_data)
        n_dofs = K.n_dofs

        spoints = tvtk.StructuredPoints(origin=(0, 0, 0),
                                        spacing=(1, -1, 1),
                                        dimensions=(n_dofs, n_dofs, 1))
        spoints.point_data.scalars = z_data
        spoints.point_data.scalars.name = 'Stiffness'

        e = get_engine()
        src = VTKDataSource(data=spoints)
        e.add_source(src)
        scale_factor = .1 / float(z_max) * n_dofs
        ws = WarpScalar()
        ws.filter.scale_factor = scale_factor
        e.add_filter(ws)
        e.add_filter(PolyDataNormals())
        s = Surface()
        e.add_module(s)
Ejemplo n.º 5
0
    def setUp(self):
        """Initial setting up of test fixture, automatically called by TestCase before any other test method is invoked"""
        e = NullEngine()
        # Uncomment to see visualization for debugging etc.
        #e = Engine()
        e.start()
        e.new_scene()
        self.e = e

        r = VTKXMLFileReader()
        r.initialize(get_example_data('pyramid_ug.vtu'))
        e.add_source(r)
        r.point_scalars_name = 'temperature'
        o = Outline()
        e.add_module(o)
        c = Contour()
        e.add_filter(c)
        n = PolyDataNormals()
        e.add_filter(n)
        aa = SetActiveAttribute()
        e.add_filter(aa)
        aa.point_scalars_name = 'pressure'
        s = Surface()
        e.add_module(s)
        self.scene = e.current_scene
        return
Ejemplo n.º 6
0
    def setup(self):
        m = mlab
        fname = self.vis3d.file_list[0]
        var = self.vis3d.var
        self.d = VTKXMLFileReader()
        self.d.initialize(fname)
        self.src = m.pipeline.add_dataset(self.d)
        self.warp_vector = m.pipeline.warp_vector(self.src)
        #self.surf = m.pipeline.surface(self.warp_vector)
        engine = m.get_engine()
        self.etc = ExtractTensorComponents()
        engine.add_filter(self.etc, self.warp_vector)
        surface2 = Surface()
        self.surface = surface2
        engine.add_filter(surface2, self.etc)
        lut = self.etc.children[0]
        lut.scalar_lut_manager.set(show_scalar_bar=True,
                                   show_legend=True,
                                   data_name=var)
        lut.scalar_lut_manager.scalar_bar.orientation = 'horizontal'
        lut.scalar_lut_manager.scalar_bar_representation.trait_set(
            maximum_size=np.array([100000, 100000]),
            minimum_size=np.array([1, 1]),
            position=np.array([0.3, 0.05]),
            position2=np.array([0.65, 0.1]),
        )

        lut.scalar_lut_manager.label_text_property.trait_set(
            font_family='times', italic=False, bold=False)
        lut.scalar_lut_manager.title_text_property.trait_set(
            font_family='times', italic=False, bold=False)
        self.etc.filter.scalar_mode = 'component'
Ejemplo n.º 7
0
    def _add_sources_to_scene(self):
        """Add the sources to the main scene."""
        mayavi_engine = self.mlab_model.engine
        mayavi_engine.add_source(self.sources[0])

        mayavi_engine.add_module(Surface())
        self._add_liggghts_source_to_scene(self.sources[1])
        self._add_liggghts_source_to_scene(self.sources[2])
    def _animate(self):

        self.scene.engine.current_scene = self.scene4.mayavi_scene
        src = mlab.pipeline.open((self.address+'\density\density_00.vtu'))
        src.play = False
        src.add_module(Surface(name='animate_density'))
        # self.scene.engine.current_scene.children[0].children[0].children[0].enable_contours=True
        # self.scene.engine.current_scene.children[0].children[0].children[0].contour.filled_contours=True
        self.scene.engine.current_scene.children[0].children[0].children[0].module_manager.scalar_lut_manager.show_legend=True
Ejemplo n.º 9
0
 def create_plot(self):
     from mayavi.modules.api import Surface, Vectors
     self.surface = Surface()
     self.surface1 = Surface()
     self.surface1.actor.property.representation = 'wireframe'
     self.surface1.actor.actor.visibility = self.enable_grid
     self.surface.actor.actor.visibility = self.enable_surface
     self.engine = self.scene.engine
     self.engine.add_source(self.src)
     self.engine.add_module(self.surface, obj=self.src)
     self.engine.add_module(self.surface1, obj=self.src)
     self.module_manager = self.engine.scenes[0].children[0].children[0]
     self.surface.actor.actor.visibility = self.enable_surface
     self.module_manager.scalar_lut_manager.show_legend = self.enable_legend
     if self.point_cell == "Point Data":
         self.module_manager.lut_data_mode = 'point data'
     else:
         self.module_manager.lut_data_mode = 'cell data'
Ejemplo n.º 10
0
 def generate_data_mayavi(self):
     """Shows how you can generate data using mayavi instead of mlab."""
     from mayavi.sources.api import ParametricSurface
     from mayavi.modules.api import Outline, Surface
     e = self.scene.engine
     s = ParametricSurface()
     e.add_source(s)
     e.add_module(Outline())
     e.add_module(Surface())
Ejemplo n.º 11
0
    def xregister_mv_pipelines(self, e):
        '''Register as a source in the pipelane
        '''
        # Remarks[rch]:
        #
        # Pipeline construction
        # ---------------------
        # Maybe this should be done only on demand
        # when the visualization is requested either by the update
        # event triggered here, or by the user. For a batch-like
        # simulation no scenes would be necessary.
        #
        # In that case, the engine could be simply registered and
        # the pipeline construction can be deffered to the explicit
        # request.
        #
        # Further question concerns the multiplicity of the relations.
        # One tracer can construct several sources. The source can be
        # for example the standard array source or parametric surface.
        # There should be no link back to the tracer.
        #
        # Links between tracers and scenes
        # --------------------------------
        # On the other hand, several tracers can contribute to a single
        # scene. Then the tracer explicitly specifies the name
        # of the scene it is contributing to. This type of sharing makes
        # sence if the spatial context of the tracer is the same.
        #
        # The scene management is a separate issue, no general
        # rules can be formulated at this time.
        #
        scene = e.new_scene()
        scene.name = 'Polar domain'

        # Construct the source
        from mayavi.sources.vtk_data_source import VTKDataSource
        from tvtk.api import tvtk

        self._mv_src = VTKDataSource(name='Time-Strain Cylinder',
                                     data=tvtk.PolyData())
        e.add_source(self._mv_src)

        # Construct the warp filter
        if self.var_warp_on:
            from mayavi.filters.api import WarpVector
            e.add_filter(WarpVector())

        # Construct visualization modules
        from mayavi.modules.api import Outline, Surface
        s = Surface()
        e.add_module(Outline())
        e.add_module(s)
        s.module_manager.scalar_lut_manager.show_scalar_bar = True
        s.module_manager.scalar_lut_manager.reverse_lut = True
Ejemplo n.º 12
0
    def __init__(self, **kw):

        e = get_engine()

        super(MVPolyData, self).__init__(**kw)
        from mayavi.modules.api import Outline, Surface, Labels

        self.src = VTKDataSource(name=self.name, data=self.pd)
        e.add_source(self.src)

        o = Outline()
        e.add_module(o)
        s = Surface()
        e.add_module(s)
Ejemplo n.º 13
0
    def do(self):
        script = self.script

        ############################################################
        # Create a new scene and set up the visualization.
        scene = self.new_scene()

        # Read a VTK (old style) data file.
        source = VTKFileReader()
        source.initialize(get_example_data('heart.vtk'))
        script.add_source(source)

        script.add_module(Surface())

        # In order to test the restoration of visualization properly
        # we should modify the camera
        view(130., 44., 65., [14., 14., 14.])
        
        ############################################################
        # Test if saving a visualization and restoring it works.

        # Save visualization.
        f = BytesIO()
        f.name = abspath('test.mv2') # We simulate a file.
        script.save_visualization(f)
        f.seek(0) # So we can read this saved data.

        # This is the old camera state
        old_camera_state = get_state(scene.scene.camera)

        # Remove existing scene.
        engine = script.engine
        engine.close_scene(scene)

        # Load visualization
        script.load_visualization(f)
        scene = engine.current_scene

        # Now do the check.
        new_camera_state = get_state(scene.scene.camera)

        for attr, new_value in new_camera_state.items():
            if attr.startswith("_"):
                continue
            new_value = array(new_value)
            old_value = array(old_camera_state[attr])
            assert (new_value == old_value).all()
Ejemplo n.º 14
0
    def rebuild_pipeline(self, pd):
        src = VTKFileReader(base_file_name='%s_0.vtk' % self.position)
        self.engine.add_source(src)
        if self.warp:
            self.engine.add_filter(WarpVector())

        if self.name in src._point_tensors_list:
            src.point_tensors_name = self.name
            self.engine.add_filter(ExtractTensorComponents())
        elif self.name in src._point_vectors_list:
            src.point_vectors_name = self.name
            self.engine.add_filter(ExtractVectorComponents())
        elif self.name in src._point_scalars_list:
            src.point_scalars_name = self.name
        s = Surface()
        s.actor.property.point_size = 5.
        self.engine.add_module(s)
        src.scene.z_plus_view()
Ejemplo n.º 15
0
    def rebuild_pipeline(self, pd):
        src = VTKDataSource(name=self.name, data=pd)
        self.engine.add_source(src)
        if self.warp:
            self.engine.add_filter(WarpVector())

        if self.name in src._point_tensors_list:
            src.point_tensors_name = self.name
            self.engine.add_filter(ExtractTensorComponents())
        elif self.name in src._point_vectors_list:
            src.point_vectors_name = self.name
            self.engine.add_filter(ExtractVectorComponents())
        elif self.name in src._point_scalars_list:
            src.point_scalars_name = self.name
        s = Surface()
        s.actor.property.point_size = 5.
        self.engine.add_module(s)
        src.scene.z_plus_view()
Ejemplo n.º 16
0
 def atomic_displacement_ellipsoids(self, ux, uy, uz, 
                                    Uxx, Uyy, Uzz, Uyz, Uxz, Uxy,
                                    colors, p=0.99):
 
     self.fig.scene.disable_render = True 
     
     n_atm = ux.shape[0]
             
     for i in range(n_atm):
         
         s, a = self.__probability_ellipsoid(Uxx[i], Uyy[i], Uzz[i], 
                                             Uyz[i], Uxz[i], Uxy[i], p)
         
         source = ParametricSurface()
         source.function = 'ellipsoid'
         
         self.engine.add_source(source)
         
         surface = Surface()
         source.add_module(surface)
         
         actor = surface.actor 
         actor.property.opacity = 1.0
         actor.property.color = colors[i]
         
         actor.mapper.scalar_visibility = False 
         actor.property.backface_culling = True 
         
         actor.property.diffuse = 1.0
         actor.property.specular = 0.0
         
         actor.actor.origin = np.array([0,0,0])
         actor.actor.position = np.array([ux[i],uy[i],uz[i]])
         
         actor.actor.scale = np.array([s[0],s[1],s[2]])
         actor.actor.orientation = np.array([a[0],a[1],a[2]]) #ZXY
 
         actor.enable_texture = True
         actor.property.representation = 'surface'
         
     self.fig.scene.disable_render = False 
Ejemplo n.º 17
0
 def setup(self):
     m = mlab
     fname = self.vis3d.file_list[0]
     self.d = VTKXMLFileReader()
     self.d.initialize(fname)
     self.src = m.pipeline.add_dataset(self.d)
     self.warp_vector = m.pipeline.warp_vector(self.src)
     self.surf = m.pipeline.surface(self.warp_vector)
     engine = m.get_engine()
     etc = ExtractTensorComponents()
     engine.add_filter(etc, self.warp_vector)
     surface2 = Surface()
     engine.add_filter(surface2, etc)
     etc.filter.scalar_mode = 'component'
     lut = etc.children[0]
     lut.scalar_lut_manager.set(show_scalar_bar=True,
                                show_legend=True,
                                data_name='strain field')
     lut.scalar_lut_manager.scalar_bar.set(height=0.1,
                                           width=0.7,
                                           position=np.array([0.1, 0.1]))
Ejemplo n.º 18
0
    def __init__(self, **kw):

        super(MVStructuredGrid, self).__init__(**kw)
        e = get_engine()

        from mayavi.modules.api import \
            StructuredGridOutline, GridPlane

        self.src = VTKDataSource(name=self.name, data=self.pd)
        e.add_source(self.src)

        o = StructuredGridOutline()
        e.add_module(o)

        for axis in ['x', 'y', 'z']:
            g = GridPlane(name='%s - grid plane' % axis)
            g.grid_plane.axis = axis
            e.add_module(g)

        if self.scalars or self.vectors or self.tensors:
            s = Surface()
            e.add_module(s)
Ejemplo n.º 19
0
def main():
    mayavi.new_scene()

    # Read the example data: fire_ug.vtu.
    r = VTKXMLFileReader()
    filename = join(mayavi2.get_data_dir(dirname(abspath(__file__))),
                    'fire_ug.vtu')
    r.initialize(filename)
    mayavi.add_source(r)
    # Set the active point scalars to 'u'.
    r.point_scalars_name = 'u'

    # Simple outline for the data.
    o = Outline()
    mayavi.add_module(o)

    # Branch the pipeline with a contour -- the outline above is
    # directly attached to the source whereas the contour below is a
    # filter and will branch the flow of data.   An isosurface in the
    # 'u' data attribute is generated and normals generated for it.

    c = Contour()
    mayavi.add_filter(c)
    n = PolyDataNormals()
    mayavi.add_filter(n)

    # Now we want to show the temperature 't' on the surface of the 'u'
    # iso-contour.  This is easily done by using the SetActiveAttribute
    # filter below.

    aa = SetActiveAttribute()
    mayavi.add_filter(aa)
    aa.point_scalars_name = 't'

    # Now view the iso-contours of 't' with a Surface filter.
    s = Surface(enable_contours=True)
    mayavi.add_module(s)
    def _mayavi(self):
        """Shows how you can generate data using mayavi instead of mlab."""
        print('updating mayavi')

        e = self.scene.engine

        #网格scene配置
        e.current_scene = self.scene.mayavi_scene
        e.add_source(self.simp_solver.resultdata.vtkdatasource_mesh)
        e.add_module(Surface(name = 'mesh_wireframe'))
        e.current_scene.children[0].children[0].children[0].actor.property.representation = 'wireframe'
        e.current_scene.children[0].children[0].children[0].actor.property.color = (0,0,0)
        e.current_scene.children[0].children[0].children[0].actor.property.line_width = 1.0
        e.add_module(Surface(name='mesh_solid'))

        #位移scene配置
        e.current_scene = self.scene0.mayavi_scene
        e.add_source(self.simp_solver.resultdata.vtkdatasource_displacement)
        e.add_module(Surface(name = 'displacement'))
        self.scene.engine.current_scene.children[0].children[0].children[0].enable_contours = True
        self.scene.engine.current_scene.children[0].children[0].children[0].contour.filled_contours = True
        self.scene.engine.current_scene.children[0].children[0].children[0].module_manager.scalar_lut_manager.show_legend = True

        #应力scene配置
        e.current_scene = self.scene1.mayavi_scene
        e.add_source(self.simp_solver.resultdata.vtkdatasource_stress)
        e.add_module(Surface(name = 'stress'))
        self.scene.engine.current_scene.children[0].children[0].children[0].enable_contours = True
        self.scene.engine.current_scene.children[0].children[0].children[0].contour.filled_contours = True
        self.scene.engine.current_scene.children[0].children[0].children[0].module_manager.scalar_lut_manager.show_legend = True

        #应变scene配置
        e.current_scene = self.scene2.mayavi_scene
        e.add_source(self.simp_solver.resultdata.vtkdatasource_strain)
        e.add_module(Surface(name = 'strain'))
        self.scene.engine.current_scene.children[0].children[0].children[0].enable_contours = True
        self.scene.engine.current_scene.children[0].children[0].children[0].contour.filled_contours = True
        self.scene.engine.current_scene.children[0].children[0].children[0].module_manager.scalar_lut_manager.show_legend = True

        #密度scene配置
        e.current_scene = self.scene3.mayavi_scene
        e.add_source(self.simp_solver.resultdata.vtkdatasource_density)
        e.add_module(Surface(name = 'density'))
        self.scene.engine.current_scene.children[0].children[0].children[0].module_manager.scalar_lut_manager.show_legend = True
Ejemplo n.º 21
0
def tresdeizar(X, Y, anchox, anchoy, angulo):
    engine = Engine()
    engine.start()
    scene = engine.new_scene()
    scene.scene.disable_render = True  # for speed

    visual.set_viewer(scene)

    surfaces = []
    for k in range(0, len(X)):
        source = ParametricSurface()
        source.function = 'ellipsoid'
        engine.add_source(source)

        surface = Surface()
        source.add_module(surface)

        actor = surface.actor  # mayavi actor, actor.actor is tvtk actor

        actor.property.opacity = 0.7
        actor.property.color = (0, 0, 1)  # tuple(np.random.rand(3))
        actor.mapper.scalar_visibility = False  # don't colour ellipses by their scalar indices into colour map

        actor.actor.orientation = np.array([90, angulo[k], 0
                                            ])  #* 90 #(angulo[k]) # in degrees

        actor.actor.position = np.array([X[k], Y[k], 0])
        actor.actor.scale = np.array(
            [anchox[k] / 2, anchox[k] / 2, anchoy[k] / 2])

        surfaces.append(surface)

        source.scene.background = (1.0, 1.0, 1.0)

    CellScann.set_img_3deizada(mlab)
    return mlab.show()
Ejemplo n.º 22
0
def visStack(v, opacity=.5, color=(1, 0, 0), mode=''):

    if mode != 'same':
        mlab.figure(bgcolor=(1, 1, 1))

    s = mlab.get_engine()  # Returns the running mayavi engine.
    scene = s.current_scene  # Returns the current scene.
    scene.scene.disable_render = True  # for speed

    origion = [0, 0, 0]
    label = 'Segmentation'

    A = ArraySource(scalar_data=v)
    A.origin = np.array(origion)
    D = s.add_source(A)  # add the data to the Mayavi engine
    #Apply gaussain 3d filter to smooth visualization

    #    F=mlab.pipeline.user_defined(D, filter='ImageGaussianSmooth')
    #    F.filter.set_standard_deviation(0,0,0)
    contour = Contour()
    s.add_filter(contour)

    #    smooth = mlab.pipeline.user_defined(contour, filter='SmoothPolyDataFilter')
    #    smooth.filter.number_of_iterations = 1
    #    smooth.filter.relaxation_factor = 0

    surface = Surface()
    s.add_module(surface)

    surface.module_manager.scalar_lut_manager.lut_mode = u'coolwarm'
    surface.module_manager.scalar_lut_manager.reverse_lut = True
    surface.actor.property.opacity = opacity
    surface.actor.mapper.scalar_visibility = False
    surface.actor.property.color = color  #color

    return surface
    def setUp(self):
        """Initial setting up of test fixture, automatically called by TestCase before any other test method is invoked"""
        e = NullEngine()
        # Uncomment to see visualization for debugging etc.
        #e = Engine()
        e.start()
        e.new_scene()
        self.e=e

        sgrid=datasets.generateStructuredGrid()
        src = VTKDataSource(data = sgrid)
        e.add_source(src)

        c = Contour()
        # `name` is used for the notebook tabs.
        n = PolyDataNormals(name='Normals')
        o = Optional(filter=n, label_text='Compute normals')
        coll = Collection(filters=[c, o], name='IsoSurface')
        e.add_filter(coll)
        s = Surface()
        e.add_module(s)
        self.coll = coll
        self.scene = e.current_scene
        return
Ejemplo n.º 24
0
    def init_view_objects(self, *args):
        """Initialize (or re-initialize) all the view elements in the scene.
        This needs to be called when q-space modeled area changes (changing the outline) or
            q-resolution, etc.
        """
        #Prevent drawing all the intermediate steps
        self.scene.disable_render = True

        #First, we need to remove any data sources and modules from a previous run,
        #   if they exist.
        # (this is only needed when chaning q-space parameters)
        for x in [
                'data_src', 'point_data_src', 'iso', 'points_module_surface',
                'points_module_glyph', 'outline', 'mouse_text', 'mouse_cube'
        ]:
            if hasattr(self, x):
                getattr(self, x).remove()
        #Now the corner labels
        if hasattr(self, 'corner_text'):
            for txt in self.corner_text:
                txt.remove()

        engine = self.engine

        #We get the qspace_displayed array from experiment and make a copy of it.
        #   This object will REMAIN here and just have its data updated.
        self.data_src = ArraySource(
            scalar_data=model.experiment.exp.get_qspace_displayed().copy())
        self.data_src.scalar_name = "coverage"
        self.data_src.visible = False
        engine.add_source(self.data_src)

        # --- Text overlay for warnings ----
        txt = Text(text="(Points were thinned down)", position_in_3d=False)
        txt.x_position = 0.02
        txt.y_position = 0.98
        txt.actor.text_scale_mode = "none"
        txt.actor.text_property.font_size = 14
        txt.actor.text_property.vertical_justification = "top"
        self.warning_text = txt
        engine.add_module(self.warning_text)
        self.warning_text.visible = self.warning_text_visible

        #---- Make the isosurface object that goes with the volume coverage data -----
        iso = IsoSurface()
        self.iso = iso
        #Scale the isosurface so that the size is actually q-vector
        iso.actor.actor.scale = tuple(
            np.array([1.0, 1.0, 1.0]) * model.experiment.exp.inst.q_resolution)
        #And we offset the position so that the center is at q-space (0,0,0)
        iso.actor.actor.position = tuple(
            np.array([1.0, 1.0, 1.0]) * -model.experiment.exp.inst.qlim)
        # When set to 1, This helps them to show up right in partially transparent mode.
        iso.actor.property.backface_culling = 0
        iso.actor.property.frontface_culling = 0
        #Add the module to the data source, to make it plot that data
        self.data_src.add_module(iso)

        # ---- Now we make a point data source, for the individual reflection plot ---
        self.point_data_src = VTKDataSource(name="Reflection point positions")
        self.point_data_src.visible = False
        engine.add_source(self.point_data_src)
        self.point_data_src.data = self.make_point_data(
        )  #still needs to get set.

        # ---- Make a module of simple points, using the Surface module ----
        self.points_module_surface = Surface()
        self.points_module_surface.name = "Single reflections as pixels (Surface)"
        self.point_data_src.add_module(self.points_module_surface)
        # points representation = just plot a pixel for each vertex.
        self.points_module_surface.actor.property.set(representation='points',
                                                      point_size=3)

        # ---- Make a module of glyphs, making spheres for each point ----
        self.points_module_glyph = Glyph()
        self.points_module_glyph.name = "Single reflections as spheres (Glyph)"
        #No scaling of glyph size with scalar data
        self.points_module_glyph.glyph.scale_mode = 'data_scaling_off'
        gs = self.points_module_glyph.glyph.glyph_source
        gs.glyph_source = gs.glyph_dict['sphere_source']
        #How many vertices does each sphere have? 3 = fastest.
        gs.glyph_source.phi_resolution = 3
        gs.glyph_source.theta_resolution = 3
        #And how big does each sphere end up?
        gs.glyph_source.radius = 0.1
        #Add the module to the same point data source, to show it
        self.point_data_src.add_module(self.points_module_glyph)

        # Hide points initially
        self.points_module_surface.visible = False
        self.points_module_glyph.visible = False

        #Get the color look-up table
        self.points_lut = self.points_module_glyph.module_manager.scalar_lut_manager.lut.table.to_array(
        )
        self.points_lut_original = 1 * self.points_lut

        # ---- Simple outline for all of the data. -----
        self.outline = Outline()
        #Manually make the outline = the modeled volume, which is +- qlim = 1/d_min
        self.outline.manual_bounds = True
        self.outline.bounds = tuple(
            np.array([-1., 1., -1., 1., -1., 1.]) *
            model.experiment.exp.inst.qlim)
        #Add it to the scene directly.
        engine.add_module(self.outline)

        #--- Label the HKL of the corners ---
        if config_gui.cfg.label_corners:
            q = model.instrument.inst.qlim
            #This the reciprocal lattice vectors
            rec = model.experiment.exp.crystal.reciprocal_lattice
            self.corner_text = []
            for x in [-q, q]:
                for y in [-q, q]:
                    for z in [-q, q]:
                        (h, k, l) = model.crystal_calc.get_hkl_from_q(
                            column([x, y, z]), rec)
                        label = "%d,%d,%d" % (h, k, l)
                        txt = Text(text=label, position_in_3d=False)
                        txt.position_in_3d = True
                        txt.x_position = x
                        txt.y_position = y
                        txt.z_position = z
                        txt.actor.text_scale_mode = "none"
                        txt.actor.text_property.font_size = 14
                        txt.actor.text_property.vertical_justification = "top"
                        txt.actor.text_property.justification = "left"
                        txt.actor.property.color = (0.75, 1.0, 1.0)
                        engine.add_module(txt)
                        self.corner_text.append(txt)

        # ---- A text overlay, to show what is under the mouse -----
#        self.mouse_text = Text(text=self.MOUSE_TEXT_WITH_NO_REFLECTION, position_in_3d=False)
#        self.mouse_text.x_position=0.02
#        self.mouse_text.y_position=0.98
#        self.mouse_text.actor.text_scale_mode = "none"
#        self.mouse_text.actor.text_property.font_size = 20
#        self.mouse_text.actor.text_property.vertical_justification = "top"
#        engine.add_module(self.mouse_text)

# ---- A cube highlighting where the mouse is ----
        self.mouse_cube = Glyph()
        self.mouse_cube.name = "Cube highlighting mouse position (Glyph)"
        #No scaling of glyph size with scalar data
        self.mouse_cube.glyph.scale_mode = 'data_scaling_off'
        self.mouse_cube.glyph.color_mode = 'no_coloring'
        gs = self.mouse_cube.glyph.glyph_source
        gs.glyph_source = gs.glyph_dict['cube_source']
        self.mouse_cube.actor.property.representation = "wireframe"
        self.mouse_cube.actor.property.specular = 1.0  # to make edge always white
        self.mouse_point_data_src = VTKDataSource()
        self.mouse_point_data_src.name = "Mouse position (VTK Data)"
        self.mouse_point_data_src.visible = True
        engine.add_source(self.mouse_point_data_src)
        self.mouse_point_data_src.data = self.make_single_point_data((0, 0, 0))
        self.mouse_point_data_src.add_module(self.mouse_cube)
        self.mouse_cube.visible = False

        #        #--- Reciprocal axes 3D view ----
        #        c = model.experiment.exp.crystal #@type c Crystal
        #        (a,b,c) = (c.recip_a, c.recip_b, c.recip_c)
        #        offset = model.experiment.exp.inst.qlim
        #        self.scene.mlab.plot3d([offset, offset+a[0]], [offset, offset+a[1]], [offset, offset+a[2]], color=(1,0,0))
        #        self.scene.mlab.plot3d([offset, offset+b[0]], [offset, offset+b[1]], [offset, offset+b[2]], color=(0,1,0))
        #        self.scene.mlab.plot3d([offset, offset+c[0]], [offset, offset+c[1]], [offset, offset+c[2]], color=(0,0,1))

        #Re-enable drawing
        self.scene.disable_render = False
        self._engine.add_module(module)

    def add_filter(self, filter):
        self._engine.add_module(filter)

    def clear(self):
        self._engine.current_scene.scene.disable_render = True
        self._engine.current_scene.children[:] = []
        self._engine.current_scene.scene.disable_render = False

    #-----------------------------------------------------------------------
    # Private API
    #-----------------------------------------------------------------------

    def __engine_default(self):
        e = Engine()
        e.start()
        e.new_scene(self._scene)
        return e

if __name__ == '__main__':
    from pyface.api import GUI
    from mayavi.sources.api import ParametricSurface
    from mayavi.modules.api import Outline, Surface
    pw = PreviewWindow()
    pw.add_source(ParametricSurface())
    pw.add_module(Outline())
    pw.add_module(Surface())

    pw.edit_traits()
Ejemplo n.º 26
0
    def do(self):
        """Test for the SetActiveAttribute filter.
        """
        from mayavi.sources.api import VTKXMLFileReader
        from mayavi.filters.contour import Contour
        from mayavi.filters.api import PolyDataNormals
        from mayavi.filters.set_active_attribute import SetActiveAttribute
        from mayavi.modules.api import Surface, Outline

        mayavi = script = self.script

        scene = self.new_scene()
        r = VTKXMLFileReader()
        r.initialize(get_example_data('fire_ug.vtu'))
        mayavi.add_source(r)
        r.point_scalars_name = 'u'
        o = Outline()
        mayavi.add_module(o)
        c = Contour()
        mayavi.add_filter(c)
        n = PolyDataNormals()
        mayavi.add_filter(n)
        aa = SetActiveAttribute()
        mayavi.add_filter(aa)
        aa.point_scalars_name = 't'
        s = Surface()
        mayavi.add_module(s)

        scene.scene.isometric_view()
        # Check if things are OK.
        self.check()

        ############################################################
        # Test if saving a visualization and restoring it works.

        # Save visualization.
        f = BytesIO()
        f.name = abspath('test.mv2') # We simulate a file.
        mayavi.save_visualization(f)
        f.seek(0) # So we can read this saved data.

        # Remove existing scene.
        engine = mayavi.engine
        engine.close_scene(s)

        # Load visualization
        mayavi.load_visualization(f)
        s = engine.current_scene

        # Now do the check.
        s.scene.isometric_view()
        self.check()

        ############################################################
        # Test if the Mayavi2 visualization can be deep-copied.

        # Pop the source object.
        source = s.children.pop()
        # Add it back to see if that works without error.
        s.children.append(source)
        # Now do the check.
        self.check()

        # Now deepcopy the source and replace the existing one with
        # the copy.  This basically simulates cutting/copying the
        # object from the UI via the right-click menu on the tree
        # view, and pasting the copy back.
        source1 = copy.deepcopy(source)
        s.children[0] = source1
        # Now do the check.
        s.scene.isometric_view()
        self.check()
Ejemplo n.º 27
0
def view_data():
    s = Surface()
    mayavi.add_module(s)
    s.module_manager.scalar_lut_manager.show_scalar_bar = True
Ejemplo n.º 28
0
    def do(self):
        """Test for the SetActiveAttribute filter.
        """
        from mayavi.sources.api import VTKXMLFileReader
        from mayavi.filters.contour import Contour
        from mayavi.filters.api import PolyDataNormals
        from mayavi.filters.set_active_attribute import SetActiveAttribute
        from mayavi.modules.api import Surface, Outline

        mayavi = script = self.script

        scene = self.new_scene()
        r = VTKXMLFileReader()
        r.initialize(get_example_data('fire_ug.vtu'))
        mayavi.add_source(r)
        r.point_scalars_name = 'u'
        o = Outline()
        mayavi.add_module(o)
        c = Contour()
        mayavi.add_filter(c)
        n = PolyDataNormals()
        mayavi.add_filter(n)
        aa = SetActiveAttribute()
        mayavi.add_filter(aa)
        aa.point_scalars_name = 't'
        s = Surface()
        mayavi.add_module(s)

        scene.scene.isometric_view()
        # Check if things are OK.
        self.check()

        ############################################################
        # Test if saving a visualization and restoring it works.

        # Save visualization.
        f = BytesIO()
        f.name = abspath('test.mv2')  # We simulate a file.
        mayavi.save_visualization(f)
        f.seek(0)  # So we can read this saved data.

        # Remove existing scene.
        engine = mayavi.engine
        engine.close_scene(s)

        # Load visualization
        mayavi.load_visualization(f)
        s = engine.current_scene

        # Now do the check.
        s.scene.isometric_view()
        self.check()

        ############################################################
        # Test if the Mayavi2 visualization can be deep-copied.

        # Pop the source object.
        source = s.children.pop()
        # Add it back to see if that works without error.
        s.children.append(source)
        # Now do the check.
        self.check()

        # Now deepcopy the source and replace the existing one with
        # the copy.  This basically simulates cutting/copying the
        # object from the UI via the right-click menu on the tree
        # view, and pasting the copy back.
        source1 = copy.deepcopy(source)
        s.children[0] = source1
        # Now do the check.
        s.scene.isometric_view()
        self.check()
    def do(self):
        ############################################################
        # Imports.
        script = self.script
        from mayavi.sources.vtk_file_reader import VTKFileReader
        from mayavi.filters.contour import Contour
        from mayavi.filters.optional import Optional
        from mayavi.filters.collection import Collection
        from mayavi.filters.api import PolyDataNormals
        from mayavi.modules.api import Surface

        ############################################################
        # Create a new scene and set up the visualization.
        s = self.new_scene()

        # Read a VTK (old style) data file.
        r = VTKFileReader()
        r.initialize(get_example_data('heart.vtk'))
        script.add_source(r)

        c = Contour()
        # `name` is used for the notebook tabs.
        n = PolyDataNormals(name='Normals')
        o = Optional(filter=n, label_text='Compute normals')
        coll = Collection(filters=[c, o], name='IsoSurface')
        script.add_filter(coll)
        s = Surface()
        script.add_module(s)

        ########################################
        # do the testing.
        def check(coll):
            """Check if test status is OK given the collection."""
            c, o = coll.filters
            c = c.filter
            n = o.filter
            assert coll.outputs[0].point_data.scalars.range == (127.5, 127.5)
            # Adding a contour should create the appropriate output in
            # the collection.
            c.contours.append(200)
            assert coll.outputs[0].point_data.scalars.range == (127.5, 200.0)
            # the collection's output should be that of the normals.
            assert coll.outputs[0] is n.outputs[0]
            # disable the optional filter and check.
            o.enabled = False
            assert 'disabled' in o.name
            assert coll.outputs[0] is c.outputs[0]
            # Set back everything to original state.
            c.contours.pop()
            o.enabled = True
            assert coll.outputs[0].point_data.scalars.range == (127.5, 127.5)
            assert coll.outputs[0] is n.outputs[0]
            assert 'disabled' not in o.name

        check(coll)

        ############################################################
        # Test if saving a visualization and restoring it works.

        # Save visualization.
        f = StringIO()
        f.name = abspath('test.mv2') # We simulate a file.
        script.save_visualization(f)
        f.seek(0) # So we can read this saved data.

        # Remove existing scene.
        engine = script.engine
        engine.close_scene(s)

        # Load visualization
        script.load_visualization(f)
        s = engine.current_scene

        # Now do the check.
        coll = s.children[0].children[0]
        check(coll)

        ############################################################
        # Test if the Mayavi2 visualization can be deep-copied.

        # Pop the source object.
        source = s.children.pop()
        # Add it back to see if that works without error.
        s.children.append(source)
        # Now do the check.
        coll = s.children[0].children[0]
        check(coll)

        # Now deepcopy the source and replace the existing one with
        # the copy.  This basically simulates cutting/copying the
        # object from the UI via the right-click menu on the tree
        # view, and pasting the copy back.
        source1 = copy.deepcopy(source)
        s.children[0] = source1
        # Now do the check.
        coll = s.children[0].children[0]
        check(coll)