예제 #1
0
    def play(self, fileroot='Network', mspikes=[], gspikes=[], save_png=False,
             sim_step=10, windowsize=10):
        view = mlab.view()
        f = mlab.gcf()
        if not mspikes:
            mspikes = self.mspikes
        if not gspikes:
            gspikes = self.gspikes
        img_counter = 0
        ts = sort(array([t for t in set(gspikes[:,0])])) # can use either spike set
        ts = ts[(ts > self.sim_start) * (ts < self.sim_end)]
        mqueue = []; gqueue = [];
        for t in ts[::sim_step]:
            self.t = t
            mlab.gcf().scene.disable_render=True
            timestamp = u"Time: %.1f" % (t)
            print timestamp
            if save_png:
                # Diplay time stamp
                f.name = timestamp
                try:ftitle.text = timestamp
                except:ftitle = mlab.title(timestamp)

            # Delete old spheres
            if len(mqueue) >= windowsize:
                mpts=mqueue.pop(0)
                mpts.parent.parent.remove()
                gpts=gqueue.pop(0)
                gpts.parent.parent.remove()

            # It would be great to make prevoius arrays dimmer

            # Plot activate spheres
            mqueue.append(self.plot_points(self.mx,
                                           self.my,
                                           self.mz,
                                           mspikes,
                                           t=t,
                                           color=(1., 1., 1.),
                                           csize = self.mcsize))
            gqueue.append(self.plot_points(self.gx,
                                           self.gy,
                                           self.gz,
                                           gspikes,
                                           t=t,
                                           color=(1., 1., 1.),
                                           csize = self.gcsize))
            mlab.view(view [0], view [1], view [2], view [3])
            mlab.gcf().scene.disable_render=False
            if save_png:
                f.scene.save_png('img/%s_%03d.png' % (fileroot, img_counter))
                img_counter += 1
        return mqueue, gqueue
예제 #2
0
def run_mlab_file(filename, image_file):
    ## XXX: Monkey-patch mlab.show, so that we keep control of the 
    ## the mainloop
    old_show = mlab.show
    def my_show(func=None):
        pass
    mlab.show = my_show
    mlab.clf()
    e = mlab.get_engine()
    e.close_scene(mlab.gcf())
    execfile(filename, {'__name__': '__main__'})
    mlab.savefig(image_file)
    size = mlab.gcf().scene.get_size()
    for scene in e.scenes:
        e.close_scene(scene)
    mlab.show = old_show
예제 #3
0
def evolve_visual3d(msnake, levelset=None, num_iters=20):
    """
    Visual evolution of a three-dimensional morphological snake.
    
    Parameters
    ----------
    msnake : MorphGAC or MorphACWE instance
        The morphological snake solver.
    levelset : array-like, optional
        If given, the levelset of the solver is initialized to this. If not
        given, the evolution will use the levelset already set in msnake.
    num_iters : int, optional
        The number of iterations.
    """
    from enthought.mayavi import mlab
    
    if levelset is not None:
        msnake.levelset = levelset
    
    fig = mlab.gcf()
    mlab.clf()
    src = mlab.pipeline.scalar_field(msnake.data)
    mlab.pipeline.image_plane_widget(src, plane_orientation='x_axes', colormap='gray')
    cnt = mlab.contour3d(msnake.levelset, contours=[0.5])
    
    for i in xrange(num_iters):
        msnake.step()
        cnt.mlab_source.scalars = msnake.levelset
    
    # Return the last levelset.
    return msnake.levelset
예제 #4
0
def m2screenshot(mayavi_fig=None, mpl_axes=None, autocrop=True):
    """ Capture a screeshot of the Mayavi figure and display it in the
        matplotlib axes.
    """
    import pylab as pl

    # Late import to avoid triggering wx imports before needed.
    from enthought.mayavi import mlab

    if mayavi_fig is None:
        mayavi_fig = mlab.gcf()
    else:
        mlab.figure(mayavi_fig)
    if mpl_axes is not None:
        pl.axes(mpl_axes)

    filename = tempfile.mktemp(".png")
    mlab.savefig(filename, figure=mayavi_fig)
    image3d = pl.imread(filename)
    if autocrop:
        bg_color = mayavi_fig.scene.background
        image3d = autocrop_img(image3d, bg_color)
    pl.imshow(image3d)
    pl.axis("off")
    os.unlink(filename)
예제 #5
0
def evolve_visual3d(msnake, levelset=None, num_iters=20):
    """
    Visual evolution of a three-dimensional morphological snake.
    
    Parameters
    ----------
    msnake : MorphGAC or MorphACWE instance
        The morphological snake solver.
    levelset : array-like, optional
        If given, the levelset of the solver is initialized to this. If not
        given, the evolution will use the levelset already set in msnake.
    num_iters : int, optional
        The number of iterations.
    """
    from enthought.mayavi import mlab

    if levelset is not None:
        msnake.levelset = levelset

    fig = mlab.gcf()
    mlab.clf()
    src = mlab.pipeline.scalar_field(msnake.data)
    mlab.pipeline.image_plane_widget(src,
                                     plane_orientation='x_axes',
                                     colormap='gray')
    cnt = mlab.contour3d(msnake.levelset, contours=[0.5])

    for i in xrange(num_iters):
        msnake.step()
        cnt.mlab_source.scalars = msnake.levelset

    # Return the last levelset.
    return msnake.levelset
예제 #6
0
    def display(self):
        """ Display Electrode in Mayavi """
        f = mlab.figure(figure=mlab.gcf(),
                        bgcolor=(0,0,0),
                        size=(800,600))

        # Build Electrode tip
        x, y, z = self.shaft[0,:].T
        self.mlab_tip = mlab.points3d(array(x),
                                      array(y),
                                      array(z),
                                      scale_factor=self.diameter,
                                      color=(0.5, 0.5, 0.5),
                                      name='Electrode Tip')
        self.mlab_tip.glyph.glyph_source.glyph_source.theta_resolution = 30
        self.mlab_tip.glyph.glyph_source.glyph_source.phi_resolution   = 16

        # Build Electrode Shaft
        x, y, z = self.shaft.T
        self.mlab_shaft = mlab.plot3d(x.T, y.T, z.T,
                               color=(0.5, 0.5, 0.5),
                               tube_radius=self.diameter / 2,
                               tube_sides=40,
                               name='Electrode')
        self.mlab_shaft.parent.parent.filter.capping=True
예제 #7
0
def run_mlab_file(filename, image_file):
    ## XXX: Monkey-patch mlab.show, so that we keep control of the
    ## the mainloop
    old_show = mlab.show

    def my_show(func=None):
        pass

    mlab.show = my_show
    mlab.clf()
    e = mlab.get_engine()
    e.close_scene(mlab.gcf())
    execfile(filename, {'__name__': '__main__'})
    mlab.savefig(image_file)
    size = mlab.gcf().scene.get_size()
    for scene in e.scenes:
        e.close_scene(scene)
    mlab.show = old_show
예제 #8
0
def autoPositionCamera():
    """
    Set camera position looking along the x-axis.
    """
    s = mlab.gcf().scene
    s.disable_render = True
    mlab.view(90,90,distance='auto',focalpoint='auto')
    mlab.roll(0)
    s.disable_render = False
예제 #9
0
def set_camera():
    F = mlab.gcf()
    F.scene.camera.position = [-4.5084283567916916, 5.0826441241530347, 2.5157264953414766]
    F.scene.camera.focal_point = [0.0, 0.0, 0.50000002980232239]
    F.scene.camera.view_angle = 30.0
    F.scene.camera.view_up = [0.20751975331326181, -0.19601355433774734, 0.9583914849896602]
    F.scene.camera.clipping_range = [3.2568212087935651, 11.823288751122519]
    F.scene.camera.compute_view_plane_normal()
    F.scene.render()
예제 #10
0
def plot_anat_3d(anat=None, anat_sform=None, scale=1,
                 sulci_opacity=0.5, gyri_opacity=0.3,
                 opacity=1,
                 outline_color=None):
    fig = mlab.gcf()
    disable_render = fig.scene.disable_render
    fig.scene.disable_render = True
    if anat is None:
        anat, anat_sform, anat_max = _AnatCache.get_anat()
    ###########################################################################
    # Display the cortical surface (flattenned)
    anat_src = affine_img_src(anat, anat_sform, scale=scale, name='Anat')
    
    anat_src.image_data.point_data.add_array(_AnatCache.get_blurred())
    anat_src.image_data.point_data.get_array(1).name = 'blurred'
    anat_blurred = mlab.pipeline.set_active_attribute(
                                anat_src, point_scalars='blurred')
            
    cortex_surf = mlab.pipeline.set_active_attribute(
                            mlab.pipeline.contour(anat_blurred), 
                    point_scalars='scalar')
        
    # XXX: the choice in vmin and vmax should be tuned to show the
    # sulci better
    cortex = mlab.pipeline.surface(cortex_surf,
                colormap='copper', 
                opacity=opacity,
                vmin=4800, vmax=5000)
    cortex.enable_contours = True
    cortex.contour.filled_contours = True
    cortex.contour.auto_contours = False
    cortex.contour.contours = [0, 5000, 7227.8]
    #cortex.actor.property.backface_culling = True
    # XXX: Why do we do 'frontface_culling' to see the front.
    cortex.actor.property.frontface_culling = True

    cortex.actor.mapper.interpolate_scalars_before_mapping = True
    cortex.actor.property.interpolation = 'flat'

    # Add opacity variation to the colormap
    cmap = cortex.module_manager.scalar_lut_manager.lut.table.to_array()
    cmap[128:, -1] = gyri_opacity*255
    cmap[:128, -1] = sulci_opacity*255
    cortex.module_manager.scalar_lut_manager.lut.table = cmap

    if outline_color is not None:
        outline = mlab.pipeline.iso_surface(
                            anat_blurred,
                            contours=[0.4],
                            color=outline_color)
        outline.actor.property.backface_culling = True


    fig.scene.disable_render = disable_render
    return cortex
예제 #11
0
def start_vtk(component):
    f = mlab.figure(size=(700,500))
    m = mlab.test_mesh()
    scene = mlab.gcf().scene
    render_window = scene.render_window
    renderer = scene.renderer
    rwi = scene.interactor
    window = EnableVTKWindow(rwi, renderer,
            component = component,
            istyle_class = tvtk.InteractorStyleTrackballCamera,
            bgcolor = "transparent",
            event_passthrough = True,
            )
    mlab.show()
예제 #12
0
def main():
    # Create some x-y data series to plot
    x = linspace(-2.0, 10.0, 100)
    pd = ArrayPlotData(index = x)
    for i in range(5):
        pd.set_data("y" + str(i), jn(i,x))

    # Create some line plots of some of the data
    plot = Plot(pd, bgcolor="none", padding=30, border_visible=True,
                 overlay_border=True, use_backbuffer=False)
    plot.legend.visible = True
    plot.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="auto")
    plot.plot(("index", "y3"), name="j_3", color="auto")
    plot.tools.append(PanTool(plot))
    zoom = ZoomTool(component=plot, tool_mode="box", always_on=False)
    plot.overlays.append(zoom)

    # Create the mlab test mesh and get references to various parts of the
    # VTK pipeline
    f = mlab.figure(size=(600,500))
    m = mlab.test_mesh()
    scene = mlab.gcf().scene
    render_window = scene.render_window
    renderer = scene.renderer
    rwi = scene.interactor

    plot.resizable = ""
    plot.bounds = [200,200]
    plot.padding = 25
    plot.outer_position = [30,30]
    plot.tools.append(MoveTool(component=plot,drag_button="right"))

    container = OverlayPlotContainer(bgcolor = "transparent",
                    fit_window = True)
    container.add(plot)

    # Create the Enable Window
    window = EnableVTKWindow(rwi, renderer,
            component=container,
            #istyle_class = tvtk.InteractorStyleSwitch,
            #istyle_class = tvtk.InteractorStyle,
            istyle_class = tvtk.InteractorStyleTrackballCamera,
            bgcolor = "transparent",
            event_passthrough = True,
            )

    mlab.show()
    return window, render_window
예제 #13
0
파일: video.py 프로젝트: alfkjartan/imusim
def createVideo(filename, renderers, tMin, tMax, framerate=25,
        resolution=None):
    """
    Create a video of a 3D visualisation.

    The video is created using the current MayaVi figure, which should be setup
    beforehand to correctly position the camera and any other elements that
    should be rendered.

    @param filename: Name of the video file to create.
    @param renderers: List of L{AnimatedRenderer} objects to use.
    @param tMin: Time from which to begin rendering.
    @param tMax: Time at which to stop rendering.
    @param framerate: Framerate of the video in frames per second.
    @param resolution: Resolution of the video (width, height). If not
        specified, the resolution of the current figure is used.
    """
    if not isinstance(renderers, collections.Iterable):
        renderers = [renderers]

    figure = mlab.gcf()
    if resolution is not None:
        originalResolution = figure.scene.get_size()
        figure.scene.set_size(resolution)
    figure.scene.off_screen_rendering = True
    figure.scene.disable_render = True

    frameTimes = np.arange(tMin, tMax, 1.0/framerate)

    try:
        imageDir = tempfile.mkdtemp()
        for f,t in enumerate(frameTimes):
            for r in renderers:
                r.renderUpdate(t)
            framefile = os.path.join(imageDir, '%06d.png'%(f))
            mlab.savefig(framefile, size=resolution)
            assert os.path.exists(framefile)

        retval = subprocess.call(['ffmpeg', '-f','image2', '-r', str(framerate),
                '-i', '%s'%os.path.join(imageDir,'%06d.png'), '-sameq',
                filename, '-pass','2'])
    finally:
        shutil.rmtree(imageDir)
        figure.scene.disable_render = False
        figure.scene.off_screen_rendering = False
        if resolution is not None:
            figure.scene.set_size(originalResolution)
예제 #14
0
    def display(self):
        """ Display Electrode in Mayavi """
        f = mlab.figure(figure=mlab.gcf(),
                        bgcolor=(0,0,0),
                        size=(800,600))

        # Call Super Class
        Electrode.display(self)

        # Build electrode contacts
        c0 = find_new_point(self.sphere_center, self.direction, self.contact_height * 3 / 2)
        c1 = find_new_point(self.sphere_center, self.direction, self.contact_height * 7 / 2)
        c2 = find_new_point(self.sphere_center, self.direction, self.contact_height * 11 / 2)
        c3 = find_new_point(self.sphere_center, self.direction, self.contact_height * 15 / 2)

        contactCenters = array([c0, c1, c2, c3])
        contact = []
        for ii in xrange(4):
            topContact = find_new_point(contactCenters[ii,:], self.direction, self.contact_height / 2)
            bottomContact = find_new_point(contactCenters[ii,:], [-1 * ii for ii in self.direction], self.contact_height / 2)
            contact.append([bottomContact, topContact])

        contact_array = array(contact)
        x, y, z = contact_array.T

        activity_array = array([
            [self.contact0, self.contact0],
            [self.contact1, self.contact1],
            [self.contact2, self.contact2],
            [self.contact3, self.contact3]])
        src = pipeline.scalar_scatter(x.T, y.T, z.T, activity_array)
        src.mlab_source.dataset.lines = array([[0, 1], [2, 3], [4, 5], [6, 7]])
        src.name = 'Contacts'

        self.mlab_contacts = pipeline.tube(src,
                                                tube_radius=self.diameter * 1.03 / 2,
                                                tube_sides=40,
                                                name='DBS Contacts',)
        stripper = pipeline.stripper(self.mlab_contacts)
        surface = pipeline.surface(stripper)
        self.mlab_contacts.filter.capping = True
        surface.module_manager.scalar_lut_manager.lut_mode = 'RdBu'
        surface.module_manager.scalar_lut_manager.reverse_lut = True
        #surface.module_manager.scalar_lut_manager.use_default_range = False
        surface.module_manager.scalar_lut_manager.use_default_range = True
        surface.module_manager.scalar_lut_manager.data_range = array([-1., 1.])
예제 #15
0
    def display(self):
        """ Display Nucleus in Mayavi """
        # Create and display a triangular mesh
        from enthought.mayavi.mlab import triangular_mesh
        f = mlab.figure(figure=mlab.gcf(),
                        bgcolor=(0,0,0),
                        size=(800,600))
        self.mlab_mesh = triangular_mesh(self.pts[:, 0],
                                         self.pts[:, 1],
                                         self.pts[:, 2],
                                         self.tris,
                                         color=self.color,
                                         name=self.name)

        # Visual Tweaks
        #self.mlab_mesh.actor.property.backface_culling = True
        self.mlab_mesh.parent.parent.filter.splitting = False
예제 #16
0
    def display(self):
        """ Plot background field """
        f = mlab.figure(figure=mlab.gcf(),
                bgcolor=(0,0,0),
                size=(800,600))

        self.mpts0 = self.plot_points(self.mx,
                                      self.my,
                                      self.mz,
                                      color=(0.1, 0.1, 0.3),
                                      csize=self.mcsize)
        self.gpts0 = self.plot_points(self.gx,
                                      self.gy,
                                      self.gz,
                                      color=(0.1, 0.3, 0.1),
                                      csize=self.gcsize)
        self.mpts0.parent.parent.scene.z_plus_view()
예제 #17
0
파일: mlab.py 프로젝트: sanjianke87/coseis
 def __init__( self, x0=0, y0=0, z0=0, scale=1.0, color=(0,1,0), line_width=3, **kwargs ):
     from enthought.mayavi import mlab
     fig = mlab.gcf()
     render = fig.scene.disable_render
     fig.scene.disable_render = True
     xx = x0 + scale / 200.0 * np.array( [
         [  -49,  -40, np.nan ],
         [   51,   60, np.nan ],
         [  -60,  -51, np.nan ],
         [   40,   49, np.nan ],
         [  -30,   50, np.nan ],
         [  -40,   40, np.nan ],
         [  -50,   30, np.nan ],
     ] )
     yy = y0 + scale / 200.0 * np.array( [
         [   10,   90, np.nan ],
         [   10,   90, np.nan ],
         [  -90,  -10, np.nan ],
         [  -90,  -10, np.nan ],
         [  100,  100, np.nan ],
         [    0,    0, np.nan ],
         [ -100, -100, np.nan ],
     ] )
     zz = z0 * np.ones_like( xx )
     glyphs = [5], [0,2,4,5,6], [0,3], [0,2], [2,4,6], [1,2], [1], [0,2,5,6], [], [2]
     hh = []
     for g in glyphs:
         i = np.array( [ i for i in range(7) if i not in g ] )
         h = []
         for x in -0.875, 0.125, 0.875:
             h += [ mlab.plot3d(
                 scale * x + xx[i].flatten(), yy[i].flatten(), zz[i].flatten(),
                 color=color,
                 tube_radius=None,
                 line_width=line_width,
                 **kwargs
             ) ]
         hh += [h]
     self.glyphs = hh
     x = x0 + scale / 200.0 * np.array( [-81, -79, np.nan, -71, -69] )
     y = y0 + scale / 200.0 * np.array( [-60, -40, np.nan, 40, 60] )
     z = z0 * np.ones_like( x )
     h = mlab.plot3d( x, y, z, color=color, line_width=line_width, tube_radius=None, **kwargs )
     self.colon = h
     fig.scene.disable_render = render
     return
예제 #18
0
파일: cubeDemo.py 프로젝트: buguen/minf
    def __init__(self):
        HasTraits.__init__(self)
        self._scene = mlab.gcf().scene
        #self.q1 = mlab.quiver3d(-2.0,0.0,0.0,1.0,0.0,0.0, colormap='Reds',mode='arrow')
        #self.q2 = mlab.quiver3d(-1.0,0.0,0.0,1.0,0.0,0.0, colormap='Greens',mode='arrow')
        #self.q3 = mlab.quiver3d(0.0,0.0,0.0,1.0,0.0,0.0, colormap='Blues',mode='arrow')
        #self.q4 = mlab.quiver3d(1.0,0.0,0.0,1.0,0.0,0.0, colormap='Reds',mode='arrow')
        #self.q5 = mlab.quiver3d(2.0,0.0,0.0,1.0,0.0,0.0,  colormap='Greens',mode='arrow')
        #self.q6 = mlab.quiver3d(3.0,0.0,0.0,1.0,0.0,0.0,  colormap='Blues',mode='arrow')


        self.queue = Queue()
        self.c = CaptureThread("COM4")
        self.c.start()

        simModel = loadBVHFile('walk.bvh', conversionFactor=0.01)

        self.configure_traits()
예제 #19
0
파일: mlab.py 프로젝트: sanjianke87/coseis
 def __call__( self, time=None ):
     from enthought.mayavi import mlab
     fig = mlab.gcf()
     render = fig.scene.disable_render
     fig.scene.disable_render = True
     self.colon.visible = False
     for hh in self.glyphs:
         for h in hh:
             h.visible = False
     if time is not None:
         self.colon.visible = True
         m = int( time / 60 )
         d = int( (time % 60) / 10 )
         s = int( time % 10 )
         self.glyphs[m][0].visible = True
         self.glyphs[d][1].visible = True
         self.glyphs[s][2].visible = True
     fig.scene.disable_render = render
     return
예제 #20
0
    def __init__(self, tMin, tMax, *renderers):
        """
        Initialise idle animator.

        @param tMin: Time to start animation.
        @param tMax: Time at which to wrap back to tMin.
        @param renderers: List of L{AnimatedRenderer} objects.
        """
        HasTraits.__init__(self)
        self._renderers = renderers
        self._tMin = tMin
        self._tMax = tMax
        self.speed = 1
        self.time = tMin
        self.playing = False
        self._scene = mlab.gcf().scene
        autoPositionCamera()
        for r in self._renderers:
            r.renderUpdate(self.time)
        self.edit_traits()
예제 #21
0
def main():
    from enthought.tvtk.api import tvtk
    from enthought.mayavi import mlab
    from enthought.enable.vtk_backend.vtk_window import EnableVTKWindow

    f = mlab.figure(size=(900, 850))
    m = mlab.test_mesh()
    scene = mlab.gcf().scene
    render_window = scene.render_window
    renderer = scene.renderer
    rwi = scene.interactor

    # Create the plot
    timer_controller = TimerController()
    plots = create_plot_component(timer_controller)
    specplot, timeplot, spectrogram = plots

    for i, p in enumerate(plots):
        p.set(resizable="", bounds=[200, 200], outer_x=0, bgcolor="transparent")
        p.outer_y = i * 250
        p.tools.append(MoveTool(p, drag_button="right"))
        p.tools.append(PanTool(p))
        p.tools.append(ZoomTool(p))

    spectrogram.tools[-1].set(tool_mode="range", axis="value")
    spectrogram.tools[-2].set(constrain=True, constrain_direction="y")

    container = OverlayPlotContainer(bgcolor="transparent", fit_window=True)
    container.add(*plots)
    container.timer_callback = timer_controller.on_timer

    window = EnableVTKWindow(
        rwi,
        renderer,
        component=container,
        istyle_class=tvtk.InteractorStyleTrackballCamera,
        bgcolor="transparent",
        event_passthrough=True,
    )

    mlab.show()
예제 #22
0
def m2screenshot(mayavi_fig=None, mpl_axes=None, autocrop=True):
    """ Capture a screeshot of the Mayavi figure and display it in the
        matplotlib axes.
    """
    import pylab as pl
    if mayavi_fig is None:
        mayavi_fig = mlab.gcf()
    else:
        mlab.figure(mayavi_fig)
    if mpl_axes is not None:
        pl.axes(mpl_axes)

    filename = tempfile.mktemp('.png')
    mlab.savefig(filename, figure=mayavi_fig)
    image3d = pl.imread(filename)
    if autocrop:
        bg_color = mayavi_fig.scene.background
        image3d = autocrop_img(image3d, bg_color)
    pl.imshow(image3d)
    pl.axis('off')
    os.unlink(filename)
예제 #23
0
def draw_atoms(at,
               colours=None,
               colorbar=None,
               atom_scale_factor=1.0,
               cell=True,
               origin=[0., 0., 0.],
               shift=[.5, .5, .5],
               supercell=[1, 1, 1],
               bonds=True,
               cutoff_factor=1.2,
               bond_radius=0.2,
               bond_colour=(.55, .55, .55),
               arrows=None,
               arrow_colour=(0, 0, 0),
               arrow_scale_factor=1.0,
               clf=True):

    if clf: mlab.clf()

    fig = mlab.gcf()
    fig.scene.disable_render = True

    balls = add_balls(at, colours, colorbar, atom_scale_factor)

    if cell:
        add_cell(at, balls, origin, shift, supercell)

    if bonds:
        add_bonds(at, balls, cutoff_factor, bond_radius, bond_colour)

    if arrows:
        arrows = add_arrows(at, arrows, arrow_colour, arrow_scale_factor)

    fig.scene.disable_render = False

    if arrows:
        return (balls, arrows)
    else:
        return balls
예제 #24
0
 def doit():
     global s
     global iter
     if iter == 0:
         print "plotting the triangular mesh..."
         s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
         print "  done."
         print "adjusting view..."
         mlab.view(0, 0)
         print "  done."
     else:
         print "changing the source..."
         # This doesn't work due to a bug in mayavi/VTK:
         # http://github.com/certik/mhd-hermes/issues#issue/1
         #s.mlab_source.reset(x=x, y=y, z=z, triangles=triangles, scalars=t)
         # so until this is fixed, let's call triangular_mesh and delete the
         # old mesh (this is slow but works):
         scene = mlab.gcf().scene
         scene.disable_render = True
         s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
         mlab.get_engine().scenes[0].children[:1] = []
         scene.disable_render = False
         print "  done."
     iter += 1
예제 #25
0
    def play(self, fileroot='cell', show_colorbar=True, show_title=False):
        ''' Step through cell response over time '''
        dt = self.play_dt
        tstop = self.play_tstop
        nrn.init()
        nrn.cvode_active(0)
        img_counter=0
        f = mlab.gcf()
        if show_colorbar: mlab.colorbar(self.mlab_cell)
        nrn.initPlot()
        nrn.init()
        nrn.initPlot()
        nrn.init()
        for x in xrange(0, int(tstop/dt)):
            timestamp = "TIME: %.1f" % (x*dt)
            print timestamp
            if show_title:
                try:
                    ftitle.text = timestamp
                except:
                    ftitle = mlab.title(timestamp)
            nrn.continuerun(x*dt)

            dataset = self.mlab_cell.mlab_source.dataset
            v = array(self.calculate_voltage())
            dataset.point_data.remove_array('data')
            array_id = dataset.point_data.add_array(v.T.ravel())
            dataset.point_data.get_array(array_id).name = 'data'
            dataset.point_data.update()
            self.mlab_cell.update_data()
            self.mlab_cell.update_pipeline()

            if self.save_img:
                f.scene.save_png('img/%s_%03d.png' % (fileroot, img_counter))

            img_counter += 1
예제 #26
0
 def doit():
     global s
     global iter
     if iter == 0:
         print "plotting the triangular mesh..."
         s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
         print "  done."
         print "adjusting view..."
         mlab.view(0, 0)
         print "  done."
     else:
         print "changing the source..."
         # This doesn't work due to a bug in mayavi/VTK:
         # http://github.com/certik/mhd-hermes/issues#issue/1
         #s.mlab_source.reset(x=x, y=y, z=z, triangles=triangles, scalars=t)
         # so until this is fixed, let's call triangular_mesh and delete the
         # old mesh (this is slow but works):
         scene = mlab.gcf().scene
         scene.disable_render = True
         s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
         mlab.get_engine().scenes[0].children[:1] = []
         scene.disable_render = False
         print "  done."
     iter += 1
예제 #27
0
# -*- coding: utf-8 -*-
"""
使用Mayavi绘制多为数组下标存取的演示图像。
"""
import numpy as np
from enthought.mayavi import mlab

x, y, z = np.mgrid[:6,:7,:8]
c = np.zeros((6, 7, 8), dtype=np.int)
c.fill(1)
k = np.random.randint(2,5,size=(6, 7))

idx_i, idx_j, _ = np.ogrid[:6, :7, :8]
idx_k = k[:,:, np.newaxis] + np.arange(3)
c[idx_i, idx_j, idx_k] = np.random.randint(2,6, size=(6,7,3))

mlab.points3d(x[c>1], y[c>1], z[c>1], c[c>1], mode="cube", scale_factor=0.8, 
    scale_mode="none", transparent=True, vmin=0, vmax=8, colormap="Greys")

mlab.points3d(x[c==1], y[c==1], z[c==1], c[c==1], mode="cube", scale_factor=0.8,
    scale_mode="none", transparent=True, vmin=0, vmax=8, colormap="Greys", opacity = 0.2)
mlab.gcf().scene.background = (1,1,1)

mlab.figure()
x, y, z = np.mgrid[:6,:7,:3]
mlab.points3d(x, y, z, c[idx_i, idx_j, idx_k], mode="cube", scale_factor=0.8, 
    scale_mode="none", transparent=True, vmin=0, vmax=8, colormap="Greys", opacity = 1)
mlab.gcf().scene.background = (1,1,1)
mlab.show()
    def display(self,
                func,
                segfunc=False,
                scaling=1,
                replace=True,
                clim=None,
                colormap='jet'):
        ''' Display current cell in mayavi
        '''
        #from neuron import h
        from numpy import array, vstack, float_
        from enthought.mayavi import mlab
        from enthought.mayavi.mlab import pipeline
        if replace:
            try:
                self.mlab_cell.parent.parent.parent.parent.parent.parent.remove(
                )
            except AttributeError:
                pass
        ### Turn off vtk warnings # # # # # # # # # # # # # # # # # # # # # # #
        from vtk import vtkObject
        o = vtkObject
        o.GetGlobalWarningDisplay()
        o.SetGlobalWarningDisplay(0)  # Turn it off.

        f = mlab.figure(figure=mlab.gcf(), bgcolor=(1, 1, 1), size=(800, 600))

        self.build_tree(func, segfunc)
        ##        xs = self.xyzdv[:,0]
        ##        ys = self.xyzdv[:,1]
        ##        zs = self.xyzdv[:,2]
        xs = float_(self.xyzdv[:, 0])
        ys = float_(self.xyzdv[:, 1])
        zs = float_(self.xyzdv[:, 2])

        # don't want scaling for soma segments
        ##        diams = self.xyzdv[:,3]
        diams = float_(self.xyzdv[:, 3])
        #nonsoma = (diams < 15) # non-somatic
        nonsoma = ones(shape(diams))
        diams += diams * nonsoma * (scaling - 1)
        #diams = self.xyzdv[:,3] * scaling # larger scaling makes neurons more visible
        ##        data = self.xyzdv[:,4]
        data = float_(self.xyzdv[:, 4])
        edges = self.connections

        # Display in mayavi
        pts = pipeline.scalar_scatter(xs, ys, zs, diams / 2.0, name=str(self))
        dataset = pts.mlab_source.dataset
        dataset.point_data.get_array(0).name = 'diameter'
        dataset.lines = vstack(edges)

        array_id = dataset.point_data.add_array(data.T.ravel())
        dataset.point_data.get_array(array_id).name = 'data'
        dataset.point_data.update()

        #### Create tube with diameter data
        src = pipeline.set_active_attribute(pts, point_scalars='diameter')
        stripper = pipeline.stripper(src)
        tube = pipeline.tube(stripper, tube_sides=8, tube_radius=1)
        tube.filter.capping = True
        tube.filter.use_default_normal = False
        tube.filter.vary_radius = 'vary_radius_by_absolute_scalar'
        #tube.filter.radius_factor = 90.0 # just for making movies
        src2 = pipeline.set_active_attribute(tube, point_scalars='data')

        lines = pipeline.surface(src2, colormap=colormap)
        if clim:
            from numpy import array
            lines.parent.scalar_lut_manager.use_default_range = False
            lines.parent.scalar_lut_manager.data_range = array(clim)
        self.mlab_cell = lines
예제 #29
0
        
if __name__ == "__main__":
    k = 4
    N = 2
    NP = 12
    points = pu.uniformcubepoints(NP)
    v = [[1,1,1]]
#    v = [[0,0,0]]
    meshevents = lambda m: pps.stokescubemesh(N, m)
#    OT = 'obstructiontag'
#    meshevents = lambda m: pps.cubeobstruction(m, OT)
    mp = MeshPlotter()
    meshevents(mp)
    emm.figure(bgcolor=(1,1,1))

    u, p = pps.stokespressure(k,meshevents,{pps.inputbdytag:pps.pfn(0), pps.outputbdytag:pps.pfn(1.0)}, points, False, N==1)
    pt = points.reshape(NP,NP,NP,3).transpose((3,0,1,2))
    ut = u.reshape(NP,NP,NP,3).transpose((3,0,1,2))        

    emm.quiver3d(pt[0],pt[1],pt[2], ut[0],ut[1],ut[2], opacity = 0.4)

#    emm.flow(pt[0],pt[1],pt[2], ut[0],ut[1],ut[2], seedtype='plane', seed_resolution=10, seed_visible=True, scalars=p.reshape(NP,NP,NP))
    mp.plot(emm.gcf())
    mp.plotbdy(emm.gcf(), pps.closedbdytag)

#    emm.figure()
#    uut = uu.transpose()
#    emm.quiver3d(pt[0],pt[1],pt[2], uut[0],uut[1],uut[2])
    emm.show()
예제 #30
0
#Center the atoms about 1/2 the bounds
xshft=bndx/2.0-sum(xs)/len(xs)
yshft=bndy/2.0-sum(ys)/len(ys)
zshft=bndz/2.0-sum(zs)/len(zs)
xs=map(lambda x:x+xshft,xs)
ys=map(lambda y:y+yshft,ys)
zs=map(lambda z:z+zshft,zs)

N=len(xs)
print "Lattice has %d atoms.\n" % N

#Plotting
if ploton==1:
    from enthought.mayavi import mlab
    fig=mlab.gcf()
    mlab.points3d(xs,ys,zs)
    mlab.plot3d([0,bndx],[0,0],[0,0])
    mlab.plot3d([0,0],[0,bndy],[0,0])
    mlab.plot3d([0,0],[0,0],[0,bndz])
    mlab.show()

#Ask before overwriting a file.
try:
    val=raw_input("Continue? (y/n): ")
    if not(val in ('y','Y')):
        print "Okey dokey, stopping."
        exit(0)
    ofil=open(sys.argv[8],"w")
except ValueError:
    exit(0)
예제 #31
0
# -*- coding: utf-8 -*-
import numpy as np
from enthought.mayavi import mlab

const = 2.19967e34
x, y = np.ogrid[0:7000000:200j, 500:1500:100j]
s = const * np.exp(-x / y) * np.sqrt(x) / (y**1.5)
surface = mlab.contour3d(s)
surface.contour.maximum_contour = 15
surface.contour.number_of_contours = 10
surface.actor.property.opacity = 0.4
mlab.figure()

mlab.pipeline.volume(mlab.pipeline.scalar_field(s))
mlab.figure()

field = mlab.pipeline.scalar_field(s)
mlab.pipeline.volume(field, vmin=1.5, vmax=80)
cut = mlab.pipeline.scalar_cut_plane(field.children[0],
                                     plane_orientation="y_axes")
cut.enable_contours = True
cut.contour.number_of_contours = 40
mlab.gcf().scene.background = (0.8, 0.8, 0.8)
mlab.show()
예제 #32
0
def close():
    """Close the scene."""
    f = mlab.gcf()
    e = mlab.get_engine()
    v = e.get_viewer(f)
    v.close()
예제 #33
0
    from divers import multimedia
    theta, phi = local.get_grid(50, 25, gtype='triangular')
    r = np.ones_like(theta)
    x, y, z = vectors.spher2cart_coord(r, phi, theta)
    points = np.array([x, y, z]).T
    grid = Delaunay(points)
    #keep = phi>pi
    #theta,phi = theta[keep],phi[keep]
    l, m = 2, 2
    asl = 0.01

    for k in [0, 1., 2.]:
        for l in range(1, 5):
            for m in range(0, l + 1, 1):
                mlab.figure(size=(1000, 800))
                mlab.gcf().scene.disable_render = True
                if l == 0 or l == 1:
                    asl = 0.1
                else:
                    asl = 0.01
                old_center = None
                for i, t in enumerate(np.linspace(0, 2 * pi, 100)):
                    print k, l, m, i
                    r, th, ph = surface(theta, phi, l, m, t, asl=asl, k=k)
                    center, size, normal = local.surface_normals(
                        r, ph, th, grid, gtype='triangular')

                    if i == 0:
                        colors = r
                        r_c, phi_c, theta_c = vectors.cart2spher_coord(
                            *center.T)
              vmax=8,
              colormap="Greys")

mlab.points3d(x[c == 1],
              y[c == 1],
              z[c == 1],
              c[c == 1],
              mode="cube",
              scale_factor=0.8,
              scale_mode="none",
              transparent=True,
              vmin=0,
              vmax=8,
              colormap="Greys",
              opacity=0.2)
mlab.gcf().scene.background = (1, 1, 1)

mlab.figure()
x, y, z = np.mgrid[:6, :7, :3]
mlab.points3d(x,
              y,
              z,
              c[idx_i, idx_j, idx_k],
              mode="cube",
              scale_factor=0.8,
              scale_mode="none",
              transparent=True,
              vmin=0,
              vmax=8,
              colormap="Greys",
              opacity=1)
예제 #35
0
# -*- coding: utf-8 -*-
import numpy as np
from enthought.mayavi import mlab

x, y = np.ogrid[-2:2:20j, -2:2:20j]
z = x * np.exp(-x**2 - y**2)

face = mlab.surf(x, y, z, warp_scale=2)
mlab.axes(xlabel='x', ylabel='y', zlabel='z')
mlab.outline(face)

c = 2 * x + y
# 获得Array2DSource
img = mlab.gcf().children[0].image_data
# 注意c的第0轴对应于x,第一轴对应于y,因此需要先将其转置
# 标量数组只接受一维数组,因此调用ravel()方法将数组变成一维的
array_id = img.point_data.add_array(c.T.ravel())
img.point_data.get_array(array_id).name = "color"
img.point_data.update()

normals = mlab.gcf().children[0].children[0].children[0]
surf = normals.children[0]
del normals.children[0]
active_attr = mlab.pipeline.set_active_attribute(normals,
                                                 point_scalars="color")
active_attr.children.append(surf)
mlab.show()
예제 #36
0
def make_plots(plots,argd=None,figs=None,save=False,overwrite=True,showfigs=True):
    """
    Generate plots and maybe save them.
    
    :param plots: A comma-seperated string of plots to show
    :param argd:
        The dictionary to use to find the arguments of the plot function. If
        None, global variables will be used.
    :param figs: 
        A list of figure numbers to use for each of the figures in `plots`. If
        None, the current figure will be used as the starting point.
    :param str save:
        A directory in which to save the plots. If False, they will not be
        saved, if True, the current directory will be used.
    :param bool overwrite:
        If True and plots are being saved, any existing plot will be
        overwritten. Otherwise, the figure will not be saved.
    :parm bool showfigs:
        If True, the figures will be shown (in whatever GUI is the correct one
        for the type).
    """
    import os,shutil,inspect,subprocess   
    
    if save is True:
        save='.'
    if isinstance(save,basestring) and not save.endswith(os.sep):
        save+=os.sep        
    
    if plots is None:
        plots = _plotreg.keys()
    elif isinstance(plots,basestring):
        if '*' in plots:
            import re
            plots = plots.replace('*','.*')
            regex = re.compile(plots)
            plots = [p for p in plot_names()[0] if regex.match(p)]
        else:
            plots = plots.split(',')
        
    if figs is None:
        figs = arange(len(plots))+1
         
    if len(figs) != len(plots):
        raise ValueError("plots don't match figs")
    
    if argd is None:
        argd = globals()
            
    plotd={}
    for p,fnum in zip(plots,figs):
        if p not in _plotreg:
            raise KeyError('plotname %s not found'%p)
        plotd[p] = (_plotreg[p][0],fnum,_plotreg[p][1],_plotreg[p][2],_plotreg[p][3])
        
    isinter = plt.isinteractive()
    plt.ioff()
    anympl = False
    try:
        for fname,(figf,fignum,figsize,ftype,tweakbbox) in plotd.iteritems(): 
            print 'figure',fname
            
            if 'mpl' in ftype:
                anympl = True
                if isinter:
                    plt.ion()
                plt.close(fignum)
                plt.figure(fignum,figsize=figsize)
                plt.ioff()
            elif 'mayavi' in ftype:
                from enthought.mayavi import mlab as M
                if len(M.get_engine().scenes) > 0:
                    M.gcf().parent.close_scene(M.gcf())
                f=M.figure(fignum,size=figsize) 
                #this is buggy
                #f.scene.set_size(figsize) 
                #M.clf()
            else:
                raise ValueError('unrecognized figtype')
                
            argsp =  inspect.getargspec(figf)
            if argsp[2] is not None:
                figf(**argd)
            else:
                args=[]
                for arg in argsp[0]:
                    args.append(argd[arg])
                figf(*args)
            
            if save:
                epsconv = False
                if ftype=='mpltoeps':
                    epsconv = 'png'
                    savefunc = plt.savefig
                    saveexts = ['png']
                elif ftype.startswith('mpl'):
                    savefunc = plt.savefig
                    saveexts = ftype[3:].strip()
                    if saveexts=='':
                        saveexts = ['eps','pdf']
                    else:
                        saveexts = saveexts.split(',')
                elif ftype.startswith('mayavi'):
                    savefunc = M.savefig
                    saveexts = ftype[6:].strip()
                    if saveexts=='':
                        saveexts = ['png']
                    else:
                        saveexts = saveexts.split(',')
                        if 'eps' in saveexts:
                            saveexts.remove('eps')
                            if 'png' not in saveexts:
                                saveexts.append('png')
                            epsconv = 'png'
                else:
                    raise ValueError('unrecognized figtype')
                
                for saveext in saveexts:
                    fn = '%s%s.%s'%(save,fname,saveext)
                    epsfns = None
                    
                    if not overwrite and os.path.exists(fn):
                        print fn,'exists, skipping (use -o at command line to overwrite)'
                    else:
                        print 'saving',fn
                        savefunc(fn)
                        if saveext == epsconv:
                            epsfns = (fn,'%s%s.%s'%(save,fname,'eps'))
                
                if epsfns is not None:
                    from os import system
                    fn,epsfn = epsfns
                    print 'converting',fn,'to',epsfn
                    retcode = subprocess.call('convert %s %s'%(fn,epsfn),shell=True)
                    if retcode is not 0:
                        raise ValueError('convert failed to convert %s to %s'%(fn,epsfn))
                    
                    if tweakbbox is not None:
                        print 'updating eps bounding box on',epsfn,'to',tweakbbox
                        with open(epsfn+'.tmpwrite','w') as fw:
                            with open(epsfn,'r') as fr:
                                for l in fr:
                                    if 'BoundingBox' in l and 'Page' not in l:
                                        newline = l.split(':')[0]+(': %s %s %s %s\n'%tweakbbox)
                                        fw.write(newline)
                                    else:
                                        fw.write(l)
                        shutil.move(epsfn+'.tmpwrite',epsfn)
                    
    finally:
        if isinter:
            plt.ion()
    if showfigs and anympl:
        plt.draw()
예제 #37
0
# -*- coding: utf-8 -*-
import numpy as np
from enthought.mayavi import mlab

x, y = np.ogrid[-2:2:20j, -2:2:20j]
z = x * np.exp(-x**2 - y**2)

face = mlab.surf(x, y, z, warp_scale=2)
mlab.axes(xlabel='x', ylabel='y', zlabel='z')
mlab.outline(face)

from enthought.tvtk.pipeline.browser import PipelineBrowser
b = PipelineBrowser()
b.root_object = [mlab.gcf().scene.render_window]
b.show()
mlab.show()
mscene = mlab.gcf()
tscene = mscene.scene
rw = tscene.render_window
a1 = rw.renderers[0].view_props[0]
# -*- coding: utf-8 -*-
import numpy as np
from enthought.mayavi import mlab

x, y, z = np.ogrid[-2:2:40j, -2:2:40j, -2:0:40j]
s = 2/np.sqrt((x-1)**2 + y**2 + z**2) + 1/np.sqrt((x+1)**2 + y**2 + z**2)
surface = mlab.contour3d(s)
surface.contour.maximum_contour = 15
surface.contour.number_of_contours = 10
surface.actor.property.opacity = 0.4
mlab.figure()

mlab.pipeline.volume(mlab.pipeline.scalar_field(s))
mlab.figure()

field = mlab.pipeline.scalar_field(s)
mlab.pipeline.volume(field, vmin=1.5, vmax=10)
cut = mlab.pipeline.scalar_cut_plane(field.children[0], plane_orientation="y_axes")
cut.enable_contours = True
cut.contour.number_of_contours = 40
mlab.gcf().scene.background = (0.8, 0.8, 0.8)
mlab.show()
예제 #39
0
def close():
    """Close the scene."""
    f = mlab.gcf()
    e = mlab.get_engine()
    e.window.close()
예제 #40
0

from enthought.mayavi import mlab
import numpy as np

mlab.clf()

# Number of lines
n_lines = 200
# Number of points per line
n_points = 100

# Create Example Coordinates
xyz = []
for ii in xrange( n_lines ):
    xyz.append( 
            np.cumsum( np.random.random( ( n_points, 3 ) ), axis=0 )
        )

fig = mlab.gcf()
fig.scene.disable_render = True
for this_xyz in xyz:
    x, y, z = this_xyz
    mlab.plot3d( x,
                y,
                z, tube_sides=7, tube_radius=0.1 )

fig.scene.disable_render = False

mlab.show()
예제 #41
0
def plot_anat_3d(
    anat=None, anat_affine=None, scale=1, sulci_opacity=0.5, gyri_opacity=0.3, opacity=None, outline_color=None
):
    # Late import to avoid triggering wx imports before needed.
    from enthought.mayavi import mlab

    fig = mlab.gcf()
    disable_render = fig.scene.disable_render
    fig.scene.disable_render = True
    if anat is None:
        anat, anat_affine, anat_max = _AnatCache.get_anat()
        anat_blurred = _AnatCache.get_blurred()
    else:
        from scipy import ndimage

        # XXX: This should be in a separate function
        anat_blurred = ndimage.gaussian_filter(
            (
                ndimage.morphology.binary_fill_holes(ndimage.gaussian_filter((anat > 4800).astype(np.float), 6) > 0.5)
            ).astype(np.float),
            2,
        ).T.ravel()

    if opacity is None:
        from enthought.tvtk.api import tvtk

        version = tvtk.Version()
        if (version.vtk_major_version, version.vtk_minor_version) < (5, 2):
            opacity = 0.99
        else:
            opacity = 1
    ###########################################################################
    # Display the cortical surface (flattenned)
    anat_src = affine_img_src(anat, anat_affine, scale=scale, name="Anat")

    anat_src.image_data.point_data.add_array(anat_blurred)
    anat_src.image_data.point_data.get_array(1).name = "blurred"
    anat_src.image_data.point_data.update()
    anat_blurred = mlab.pipeline.set_active_attribute(anat_src, point_scalars="blurred")

    anat_blurred.update_pipeline()
    # anat_blurred = anat_src

    cortex_surf = mlab.pipeline.set_active_attribute(mlab.pipeline.contour(anat_blurred), point_scalars="scalar")

    # XXX: the choice in vmin and vmax should be tuned to show the
    # sulci better
    cortex = mlab.pipeline.surface(cortex_surf, colormap="copper", opacity=opacity, vmin=4800, vmax=5000)
    cortex.enable_contours = True
    cortex.contour.filled_contours = True
    cortex.contour.auto_contours = False
    cortex.contour.contours = [0, 5000, 7227.8]
    # cortex.actor.property.backface_culling = True
    # XXX: Why do we do 'frontface_culling' to see the front.
    cortex.actor.property.frontface_culling = True

    cortex.actor.mapper.interpolate_scalars_before_mapping = True
    cortex.actor.property.interpolation = "flat"

    # Add opacity variation to the colormap
    cmap = cortex.module_manager.scalar_lut_manager.lut.table.to_array()
    cmap[128:, -1] = gyri_opacity * 255
    cmap[:128, -1] = sulci_opacity * 255
    cortex.module_manager.scalar_lut_manager.lut.table = cmap

    if outline_color is not None:
        outline = mlab.pipeline.iso_surface(anat_blurred, contours=[0.4], color=outline_color, opacity=0.9)
        outline.actor.property.backface_culling = True

    fig.scene.disable_render = disable_render
    return cortex
예제 #42
0
number of points per ball, and divide the point id by this number.

We use an outline to display which ball was selected by positioning it on
the corresponding ball.
"""

# Author: Gael Varoquaux <gael dot varoquaux at normalesup.org> 
# Copyright (c) 2009, Enthought, Inc.
# License: BSD style.

import numpy as np
from enthought.mayavi import mlab 

################################################################################
# Disable the rendering, to get bring up the figure quicker:
figure = mlab.gcf()
mlab.clf()
figure.scene.disable_render = True

# Creates two set of points using mlab.points3d: red point and
# white points
x1, y1, z1 = np.random.random((3, 10))
red_glyphs = mlab.points3d(x1, y1, z1, color=(1, 0, 0),
                resolution=20)

x2, y2, z2 = np.random.random((3, 10))
white_glyphs = mlab.points3d(x2, y2, z2, color=(0.9, 0.9, 0.9), 
                resolution=20)

# Add an outline to show the selected point and center it on the first
# data point.
예제 #43
0
def plot_map_3d(
    map,
    affine,
    cut_coords=None,
    anat=None,
    anat_affine=None,
    threshold=None,
    offscreen=False,
    vmin=None,
    vmax=None,
    cmap=None,
    view=(38.5, 70.5, 300, (-2.7, -12, 9.1)),
):
    """ Plot a 3D volume rendering view of the activation, with an
        outline of the brain.

        Parameters
        ----------
        map : 3D ndarray
            The activation map, as a 3D image.
        affine : 4x4 ndarray
            The affine matrix going from image voxel space to MNI space.
        cut_coords: 3-tuple of floats, optional
            The MNI coordinates of a 3D cursor to indicate a feature
            or a cut, in MNI coordinates and order.
        anat : 3D ndarray, optional
            The anatomical image to be used as a background. If None, the 
            MNI152 T1 1mm template is used. If False, no anatomical
            image is used.
        anat_affine : 4x4 ndarray, optional
            The affine matrix going from the anatomical image voxel space to 
            MNI space. This parameter is not used when the default 
            anatomical is used, but it is compulsory when using an
            explicite anatomical image.
        threshold : float, optional
            The lower threshold of the positive activation. This
            parameter is used to threshold the activation map.
        offscreen: boolean, optional
            If True, Mayavi attempts to plot offscreen. Will work only
            with VTK >= 5.2.
        vmin : float, optional
            The minimal value, for the colormap
        vmax : float, optional
            The maximum value, for the colormap
        cmap : a callable, or a pylab colormap
            A callable returning a (n, 4) array for n values between 
            0 and 1 for the colors. This can be for instance a pylab
            colormap.

        Notes
        -----

        If you are using a VTK version below 5.2, there is no way to
        avoid opening a window during the rendering under Linux. This is 
        necessary to use the graphics card for the rendering. You must
        maintain this window on top of others and on the screen.

    """
    # Late import to avoid triggering wx imports before needed.
    from enthought.mayavi import mlab

    if offscreen:
        global off_screen_engine
        if off_screen_engine is None:
            from enthought.mayavi.core.off_screen_engine import OffScreenEngine

            off_screen_engine = OffScreenEngine()
        off_screen_engine.start()
        fig = mlab.figure(
            "__private_plot_map_3d__", bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 330), engine=off_screen_engine
        )
        mlab.clf(figure=fig)
    else:
        fig = mlab.gcf()
        fig = mlab.figure(fig, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 350))
    disable_render = fig.scene.disable_render
    fig.scene.disable_render = True
    if threshold is None:
        threshold = stats.scoreatpercentile(np.abs(map).ravel(), 80)
    contours = []
    lower_map = map[map <= -threshold]
    if np.any(lower_map):
        contours.append(lower_map.max())
    upper_map = map[map >= threshold]
    if np.any(upper_map):
        contours.append(map[map > threshold].min())

    ###########################################################################
    # Display the map using iso-surfaces
    if len(contours) > 0:
        map_src = affine_img_src(map, affine)
        module = mlab.pipeline.iso_surface(map_src, contours=contours, vmin=vmin, vmax=vmax)
        if callable(cmap):
            # Stick the colormap in mayavi
            module.module_manager.scalar_lut_manager.lut.table = (255 * cmap(np.linspace(0, 1, 256))).astype(np.int)
    else:
        module = None

    if not anat is False:
        plot_anat_3d(anat=anat, anat_affine=anat_affine, scale=1.05, outline_color=(0.9, 0.9, 0.9), gyri_opacity=0.2)

    ###########################################################################
    # Draw the cursor
    if cut_coords is not None:
        x0, y0, z0 = cut_coords
        mlab.plot3d((-90, 90), (y0, y0), (z0, z0), color=(0.5, 0.5, 0.5), tube_radius=0.25)
        mlab.plot3d((x0, x0), (-126, 91), (z0, z0), color=(0.5, 0.5, 0.5), tube_radius=0.25)
        mlab.plot3d((x0, x0), (y0, y0), (-72, 109), color=(0.5, 0.5, 0.5), tube_radius=0.25)

    mlab.view(*view)
    fig.scene.disable_render = disable_render

    return module