Example #1
0
def viewImgWithNodes(img, spacing, contours,g, title=''):

    mlab.figure(bgcolor=(0, 0, 0), size=(900, 900))
    
    #src = mlab.pipeline.scalar_field(img)
    ## Our data is not equally spaced in all directions:
    #src.spacing = [1, 1, 1]
    #src.update_image_data = True
    #
    #mlab.pipeline.iso_surface(src, contours=contours, opacity=0.2)
    nodes = np.array(g.nodes())
    dsize = 4*np.ones(nodes.shape[0],dtype='float32')
    print(dsize.shape,nodes.shape)
    #mlab.points3d(nodes[:,0],nodes[:,1],nodes[:,2],color=(0.0,1.0,0.0))
    mlab.points3d(nodes[:,2],nodes[:,1],nodes[:,0],dsize,color=(0.0,0.0,1.0), scale_factor=0.25)
    
    for n1, n2, edge in g.edges(data=True):
        path = [n1]+edge['path']+[n2]
        pa = np.array(path)
        #print pa
        mlab.plot3d(pa[:,2],pa[:,1],pa[:,0],color=(0,1,0),tube_radius=0.25)
    mlab.view(-125, 54, 'auto','auto')
    mlab.roll(-175)
    mlab.title(title, height=0.1)
    
    mlab.show()
Example #2
0
 def _display_dbs_fired(self):
     self.dbs.display()
     mlab.view(azimuth=self.aximuth,
           elevation=self.elevation,
           distance=self.distance,
           focalpoint=self.focalpoint,
           reset_roll=self.reset_roll)
Example #3
0
def plotsln(mesh, z=None, sln=None, colorbar=False, view=(0,0),
        filename="a.png"):
    """
    Plot a solution for the mesh editor in the online lab.
    """
    x = [n[0] for n in mesh.nodes]
    y = [n[1] for n in mesh.nodes]
    if z == None:
        try:
            z = [n[2] for n in mesh.nodes]
        except IndexError:
            z = [0]*len(y)
    from enthought.mayavi import mlab
    mlab.options.offscreen = True
    mlab.clf()
    #mlab.options.show_scalar_bar = False
    mlab.triangular_mesh(x, y, z, mesh.elems, scalars=sln)
    engine = mlab.get_engine()
    image = engine.current_scene
    image.scene.background = (1.0, 1.0, 1.0)
    image.scene.foreground = (0.0, 0.0, 0.0)
    if colorbar:
        mlab.colorbar(orientation="vertical")
    if view:
        mlab.view(view[0], view[1])
    mlab.savefig(filename)
Example #4
0
def plot_sln_mayavi(sln, notebook=False):
    """
    Plots the Solution() instance sln using Linearizer() and matplotlib.

    Currently only a very simple version is implemented, that takes the
    vertices from linearizer and interpolates them. More sophisticated version
    should take the triangles.
    """
    lin = Linearizer()
    lin.process_solution(sln)
    vert = lin.get_vertices()
    triangles = lin.get_triangles()
    from numpy import zeros
    from enthought.mayavi import mlab
    x = vert[:, 0]
    y = vert[:, 1]
    z = zeros(len(y))
    t = vert[:, 2]
    if notebook:
        # the off screen rendering properly works only with VTK-5.2 or above:
        mlab.options.offscreen = True
    s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
    mlab.view(0, 0)

    # Below is a code that does exactly what the "View along the +Z axis"
    # button does:
    #scene = mlab.get_engine().current_scene.scene
    #scene.camera.focal_point = [0, 0, 0]
    #scene.camera.position = [0, 0, 1]
    #scene.camera.view_up = [0, 1, 0]
    #scene.renderer.reset_camera()
    #scene.render()
    # the above looks ok, but there is still quite a large margin, so we prefer
    # to just call .view(0, 0), which seems to be working fine.
    return s
Example #5
0
    def show_3d(self):
        """SHOW - Use mayavi2 to visualize point cloud.
        
        Usage: DepthImage.show()

        """
       
        from enthought.mayavi import mlab
       
        # Get 3D points
        pts = self.tocloud()

        # I want at most 50K points
        stride = 1 + pts.shape[1]/50000

        pts = np.c_[pts[:,::stride], pts[:,::stride]]
        colors = np.ones(pts.shape[1], dtype=np.uint8)

        # Draw clusters in point cloud
        fig = mlab.figure()
        mlab.points3d(pts[0,:], pts[1,:], pts[2,:], \
                      colors, colormap='spectral', figure=fig, \
                      scale_mode='none', scale_factor=0.02)

        mlab.view(180,180)
        mlab.show() 
Example #6
0
    def show_3d(self):
        """SHOW_3D - Use mayavi2 to visualize point cloud.
        
        Usage: obj.show_3d()

        """

        from enthought.mayavi import mlab

        # I want at most 50K points
        stride = 1 + len(self) / 50000

        pts = self[:, ::stride]
        colors = np.ones(pts.shape[1], dtype=np.uint8)
        # Draw clusters in point cloud
        fig = mlab.figure()
        mlab.points3d(
            pts[0, :],
            pts[1, :],
            pts[2, :],
            colors,
            colormap="spectral",
            figure=fig,
            scale_mode="none",
            scale_factor=0.02,
        )

        mlab.view(180, 180)
        mlab.show()
Example #7
0
File: plot.py Project: certik/phaml
def plot_sln_mayavi(x, y, mesh, sln_values, colorbar=False):
    """
    Plot a solution using mayavi.

    Example:

    >>> from numpy import array
    >>> from femhub.plot import plot_sln_mayavi
    >>> f = plot_sln_mayavi([0, 1, 1], [0, 0, 1], [1, 2, 3])
    >>> f.savefig("a.png")

    """
    from enthought.mayavi import mlab
    #mlab.options.offscreen = True
    mlab.clf()
    #mlab.options.show_scalar_bar = False
    z = [0] * len(x)
    mlab.triangular_mesh(x, y, z, mesh, scalars=sln_values)
    engine = mlab.get_engine()
    image = engine.current_scene
    image.scene.background = (1.0, 1.0, 1.0)
    image.scene.foreground = (0.0, 0.0, 0.0)
    if colorbar:
        mlab.colorbar(orientation="vertical")
    mlab.view(0, 0)
    return mlab
Example #8
0
    def animateVTKFiles_2D(folder):
        if not os.path.isdir(folder):
            return

        vtkFiles = []
        for f in sorted(os.listdir(folder)):
            if f.endswith(".vtk"):
                vtkFiles.append(os.path.join(folder, f))

        if len(vtkFiles) == 0:
            return

        figure = mlab.figure(size=(800, 600))
        figure.scene.disable_render = True
        vtkSource = VTKFileReader()
        vtk_file = vtkFiles[0]
        vtkSource.initialize(vtk_file)
        surface = mlab.pipeline.surface(vtkSource)
        axes = mlab.axes()
        colorbar = mlab.colorbar(object=surface, orientation='horizontal')
        mlab.view(0, 0)
        figure.scene.disable_render = False
        mlab.draw()

        a = animateVTKFiles(figure, vtkSource, vtkFiles)
def rotate():
    mlab.figure(3)
    for tt in linspace(30,160,14):
        mlab.view(0,tt)
        mlab.draw()
        mlab.savefig('sphere-rotate%s.png' % str(int(tt)).zfill(3))
    os.system("convert sphere-rotate*.png sphere.gif")
Example #10
0
def viewImg2(img, spacing, contours):
    print("In viewImg2: (min,max)=(%f,%f)"%(img.min(),img.max()))
    print("contours=",contours)
    mlab.figure(bgcolor=(0, 0, 0), size=(400, 400))
    
    src = mlab.pipeline.scalar_field(img)
    # Our data is not equally spaced in all directions:
    src.spacing = [1, 1, 1]
    src.update_image_data = True
    
    
    # Extract some inner structures: the ventricles and the inter-hemisphere
    # fibers. We define a volume of interest (VOI) that restricts the
    # iso-surfaces to the inner of the brain. We do this with the ExtractGrid
    # filter.
    blur = mlab.pipeline.user_defined(src, filter='ImageGaussianSmooth')
    #mlab.pipeline.volume(blur, vmin=0.2, vmax=0.8)
    mlab.pipeline.iso_surface(src, contours=contours)
    #mlab.pipeline.image_plane_widget(blur,
    #                            plane_orientation='z_axes',
    #                            slice_index=img.shape[0]/2,
    #                        )
    #voi = mlab.pipeline.extract_grid(blur)
    #voi.set(x_min=125, x_max=193, y_min=92, y_max=125, z_min=34, z_max=75)
    
    #mlab.pipeline.iso_surface(src, contours=[1,2], colormap='Spectral')
    #mlab.pipeline.contour3d(blur)
        
    mlab.view(-125, 54, 'auto','auto')
    mlab.roll(-175)
    
    mlab.show()
Example #11
0
def viewImg(img, spacing, contours):
    mlab.figure(bgcolor=(0, 0, 0), size=(400, 400))
    
    src = mlab.pipeline.scalar_field(img)
    # Our data is not equally spaced in all directions:
    src.spacing = [1, 1, 1]
    src.update_image_data = True
    
    
    # Extract some inner structures: the ventricles and the inter-hemisphere
    # fibers. We define a volume of interest (VOI) that restricts the
    # iso-surfaces to the inner of the brain. We do this with the ExtractGrid
    # filter.
    blur = mlab.pipeline.user_defined(blur, filter='ImageGaussianSmooth')
    print("blur type is",type(blur),blur.max())
    #voi = mlab.pipeline.extract_grid(blur)
    #voi.set(x_min=125, x_max=193, y_min=92, y_max=125, z_min=34, z_max=75)
    
    #mlab.pipeline.iso_surface(src, contours=[1,2], colormap='Spectral')
    mlab.pipeline.contour3d(blur)
        
    mlab.view(-125, 54, 'auto','auto')
    mlab.roll(-175)
    
    mlab.show()
Example #12
0
    def add_label(self, label, borders=True, color=(76, 169, 117, 255)):
        """Add an ROI label to the image.

        Parameters
        ----------
        label : str
            label filepath or name
        borders : bool
            show only label borders
        color : (float, float, float, float)
            RGBA color tuple

        """
        from enthought.mayavi import mlab
        self._f.scene.disable_render = True
        view = mlab.view()

        # Figure out where the data is coming from
        if os.path.isfile(label):
            filepath = label
            label_name = os.path.basename(filepath).split('.')[1]
        else:
            label_name = label
            filepath = pjoin(os.environ['SUBJECTS_DIR'],
                             self.subject_id,
                             'label',
                             ".".join([self.hemi, label_name, 'label']))
            if not os.path.exists(filepath):
                raise ValueError('Label file %s does not exist'
                                 % filepath)

        ids = (io.read_label(filepath),)
        label = np.zeros(self._geo.coords.shape[0])
        label[ids] = 1

        if borders:
            n_vertices = label.size
            edges = utils.mesh_edges(self._geo.faces)
            border_edges = label[edges.row] != label[edges.col]
            show = np.zeros(n_vertices, dtype=np.int)
            show[np.unique(edges.row[border_edges])] = 1
            label *= show

        mesh = mlab.pipeline.triangular_mesh_source(self._geo.x,
                                                   self._geo.y,
                                                   self._geo.z,
                                                   self._geo.faces,
                                                   scalars=label)
        surf = mlab.pipeline.surface(mesh, name=label_name)

        if not isinstance(color, tuple) or len(color) != 4:
            raise TypeError("'color' parameter must be a 4-tuple")
        cmap = np.array([(0, 0, 0, 0,), color])
        surf.module_manager.scalar_lut_manager.lut.table = cmap

        self.labels[label_name] = surf

        mlab.view(*view)
        self._f.scene.disable_render = False
Example #13
0
def ChargeDensityFog3D(directory, save_file=None , DrawAtoms=True, DrawCell=True, opacity_range=[0,1]):
    # Get data from calculation files
    with jasp(directory) as calc:
        atoms = calc.get_atoms()
        x, y, z, cd = calc.get_charge_density()

    mlab.figure(bgcolor=(0,0,0), size=(640,480))

    # Draw atoms
    if DrawAtoms == True:
        for atom in atoms:
            mlab.points3d(atom.x,
                          atom.y,
                          atom.z,
                          scale_factor=vdw_radii[atom.number]/10.,
                          resolution=16,
                          color=tuple(cpk_colors[atom.number]),
                          scale_mode='none')
    # Draw unit cell
    if DrawCell == True:
        a1, a2, a3 = atoms.get_cell()
        origin = [0,0,0]
        cell_matrix = [[origin, a1],
                       [origin, a2],
                       [origin, a3],
                       [a1, a1+a2],
                       [a1, a1+a3],
                       [a2, a2+a1],
                       [a2, a2+a3],
                       [a3, a1+a3],
                       [a3, a2+a3],
                       [a1+a2, a1+a2+a3],
                       [a2+a3, a1+a2+a3],
                       [a1+a3, a1+a3+a2]] # contains all points on the box
        for p1, p2 in cell_matrix:
            mlab.plot3d([p1[0], p2[0]], # x-coords of box
                        [p1[1], p2[1]], # y-coords
                        [p1[2], p2[2]]) # z-coords

    # Plot the charge density
    src = mlab.pipeline.scalar_field(x, y, z, cd) #Source data
    vmin = cd.min() #find minimum and maximum value of CD data
    vmax = cd.max()
    vol = mlab.pipeline.volume(src) # Make a volumetric representation of the data

    # Set opacity transfer function
    from tvtk.util.ctf import PiecewiseFunction
    otf = PiecewiseFunction()
    otf.add_point(vmin, opacity_range[0]) #Transparency at zero electron density
    otf.add_point(vmax*1, opacity_range[1]) #Transparency at max electron density
    vol._otf=otf
    vol._volume_property.set_scalar_opacity(otf)

    #Show a legend
    mlab.colorbar(title="e- density\n(e/Ang^3)", orientation="vertical", nb_labels=5, label_fmt='%.2f')
    mlab.view(azimuth=-90, elevation=90, distance='auto') # Set viewing angle
    mlab.show()
    if save_file != None:
        mlab.savefig(save_file)
Example #14
0
 def _display_nucleus_fired(self):
     self.nucleus.display()
     self.nucleus_opacity=0.5
     mlab.view(azimuth=self.aximuth,
           elevation=self.elevation,
           distance=self.distance,
           focalpoint=self.focalpoint,
           reset_roll=self.reset_roll)
Example #15
0
 def _display_neuron_fired(self):
     self.neuron.display(scaling=self.diam_neuron)
     self.z_neuron=-2000
     mlab.view(azimuth=self.aximuth,
           elevation=self.elevation,
           distance=self.distance,
           focalpoint=self.focalpoint,
           reset_roll=self.reset_roll)
Example #16
0
    def add_foci(self, coords, coords_as_verts=False, map_surface=None,
                 scale_factor=1, color=(1, 1, 1), name=None):
        """Add spherical foci, possibly mapping to displayed surf.

        The foci spheres can be displayed at the coordinates given, or
        mapped through a surface geometry. In other words, coordinates
        from a volume-based analysis in MNI space can be displayed on an
        inflated average surface by finding the closest vertex on the
        white surface and mapping to that vertex on the inflated mesh.

        Parameters
        ----------
        coords : numpy array
            x, y, z coordinates in stereotaxic space or array of vertex ids
        coords_as_verts : bool
            whether the coords parameter should be interpreted as vertex ids
        map_surface : Freesurfer surf or None
            surface to map coordinates through, or None to use raw coords
        scale_factor : int
            controls the size of the foci spheres
        color : 3-tuple
            RGB color code for foci spheres
        name : str
            internal name to use

        """
        from enthought.mayavi import mlab

        # Figure out how to interpret the first parameter
        if coords_as_verts:
            coords = self._geo.coords[coords]
            map_surface = None

        # Possibly map the foci coords through a surface
        if map_surface is None:
            foci_coords = np.atleast_2d(coords)
        else:
            foci_surf = io.Surface(self.subject_id, self.hemi, map_surface)
            foci_surf.load_geometry()
            foci_vtxs = utils.find_closest_vertices(foci_surf.coords, coords)
            foci_coords = self._geo.coords[foci_vtxs]

        # Get a unique name (maybe should take this approach elsewhere)
        if name is None:
            name = "foci_%d" % (len(self.foci) + 1)

        # Create the visualization
        self._f.scene.disable_render = True
        view = mlab.view()
        points = mlab.points3d(foci_coords[:, 0],
                               foci_coords[:, 1],
                               foci_coords[:, 2],
                               np.ones(foci_coords.shape[0]),
                               scale_factor=(5. * scale_factor),
                               color=color, name=name)
        self.foci[name] = points
        mlab.view(*view)
        self._f.scene.disable_render = False
Example #17
0
 def showVTKFile_2D(filename):
     figure = mlab.figure(size=(800, 600))
     vtkSource = VTKFileReader()
     vtkSource.initialize(filename)
     surface = mlab.pipeline.surface(vtkSource)
     axes = mlab.axes()
     colorbar = mlab.colorbar(object=surface, orientation='horizontal')
     mlab.view(0, 0)
     mlab.show()
Example #18
0
 def _diam_neuron_changed(self, value):
     self.neuron.display(scaling=value)
     self.z_neuron=0
     self.z_neuron=-2000
     mlab.view(azimuth=self.aximuth,
           elevation=self.elevation,
           distance=self.distance,
           focalpoint=self.focalpoint,
           reset_roll=self.reset_roll)
Example #19
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
Example #20
0
 def _flow_default(self):
     x, y, z = self.points
     u, v, w = self.get_uvw()
     f = self.scene.mlab.flow(x, y, z, u, v, w)
     f.stream_tracer.integration_direction = 'both'
     f.stream_tracer.maximum_propagation = 200
     src = f.mlab_source.m_data
     o = mlab.outline()
     mlab.view(120, 60, 150)
     return f
Example #21
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
Example #22
0
def plotframe(frameno,level=1):

    plotdata = ClawPlotData()
    plotdata.outdir = "_output"
    print "Plotting solution from ",plotdata.outdir
    plotdata = setplot(plotdata)
    try:
        frame = plotdata.getframe(frameno)
    except:
        print "Unable to get frame"
        return
    mlab.figure(1,bgcolor=(1,1,1),size=(700,600))
    mlab.clf()
    for grid in frame.grids:
        if grid.level <= level:

            y = grid.c_center[1]
            x = grid.c_center[0]
            q = grid.q
            eta = q[:,:,3]
            h = q[:,:,0]
            #return x,y,eta
            #eta = where(q[:,:,0] > 1.,eta,nan)
            #import pdb; pdb.set_trace()
        
            topo = eta - h
            cutoff = 0.5
            #cutoff2 = -500.
            shift = 0.
            scale = 10.
            topo1 = scale*where(topo<cutoff, topo-shift, cutoff-shift)
            #topo1 = scale*where(topo>cutoff2, topo1, nan)
            eta1 = scale*where(eta<cutoff, eta-shift, cutoff-shift)
            water1 = where(h>=1.e-3, eta1, nan)
            mlab.mesh(x,y,topo1,colormap='Greens',vmin=-1.0, vmax=0.8)
            mlab.mesh(x,y,water1,colormap='Blues',vmin=-0.8, vmax=0.8)
            #mlab.surf(x,y,topo1,colormap='Greens',warp_scale=10,vmin=-0.8,vmax=0.5)
            #mlab.surf(x,y,water1,colormap='Blues',warp_scale=10,vmin=-0.8,vmax=0.5)
            V = (150.95115856920216,\
             80.12676623482308,\
             13.359093592227218,\
             array([ 2.744     ,  1.70099999, -0.04745156]))
             
            V =  (-108.612973405259,\
              62.96905073871072,\
              13.359093592227456,\
              array([ 2.744     ,  1.70099999, -0.04745156]))
 
            mlab.view(*V)
    t = frame.t
    mlab.title('Time = %5.2f' % t,color=(0,0,0),height=0.1,size=0.5)
Example #23
0
def plotframe(frameno, level=1):

    plotdata = ClawPlotData()
    plotdata.outdir = "_output"
    print "Plotting solution from ", plotdata.outdir
    plotdata = setplot(plotdata)
    try:
        frame = plotdata.getframe(frameno)
    except:
        print "Unable to get frame"
        return
    mlab.figure(1, bgcolor=(1, 1, 1), size=(700, 600))
    mlab.clf()
    for grid in frame.grids:
        if grid.level <= level:

            y = grid.c_center[1]
            x = grid.c_center[0]
            q = grid.q
            eta = q[:, :, 3]
            h = q[:, :, 0]
            #return x,y,eta
            #eta = where(q[:,:,0] > 1.,eta,nan)
            #import pdb; pdb.set_trace()

            topo = eta - h
            cutoff = 0.5
            #cutoff2 = -500.
            shift = 0.
            scale = 10.
            topo1 = scale * where(topo < cutoff, topo - shift, cutoff - shift)
            #topo1 = scale*where(topo>cutoff2, topo1, nan)
            eta1 = scale * where(eta < cutoff, eta - shift, cutoff - shift)
            water1 = where(h >= 1.e-3, eta1, nan)
            mlab.mesh(x, y, topo1, colormap='Greens', vmin=-1.0, vmax=0.8)
            mlab.mesh(x, y, water1, colormap='Blues', vmin=-0.8, vmax=0.8)
            #mlab.surf(x,y,topo1,colormap='Greens',warp_scale=10,vmin=-0.8,vmax=0.5)
            #mlab.surf(x,y,water1,colormap='Blues',warp_scale=10,vmin=-0.8,vmax=0.5)
            V = (150.95115856920216,\
             80.12676623482308,\
             13.359093592227218,\
             array([ 2.744     ,  1.70099999, -0.04745156]))

            V =  (-108.612973405259,\
              62.96905073871072,\
              13.359093592227456,\
              array([ 2.744     ,  1.70099999, -0.04745156]))

            mlab.view(*V)
    t = frame.t
    mlab.title('Time = %5.2f' % t, color=(0, 0, 0), height=0.1, size=0.5)
	def _plotbutton1_fired(self):
		mlab.clf()
		self.loaddata()
		field=mlab.pipeline.scalar_field(self.sregion)     # Generate a scalar field
		mlab.pipeline.volume(field,vmax=self.datamax,vmin=self.datamin) # Render the field with dots

		mlab.outline()
		mlab.xlabel('RA(J2000)')
		mlab.ylabel('DEC(J2000)')
		mlab.zlabel('Velocity')
		mlab.view(azimuth=0, elevation=0)
		mlab.show()
		
		self.field   = field
Example #25
0
    def save(self,it):

        msh = self.__msh
        w = (self.__eqn).get(self.__var)()

        mlab.clf()
        mlab.points3d(msh.x[:,0], msh.x[:,1], zeros(w.shape), w,
                      scale_factor=self.__scale, scale_mode=self.__mode)
        mlab.outline(extent=[msh.BB[0,0],msh.BB[1,0],msh.BB[0,1],msh.BB[1,1],
                     0,0])
        mlab.view(0,0,self.__zoom,self.__xView)
        mlab.colorbar()
        fSol =  ''.join([self.__figDir,'/',self.__name,'%04d.png'% it])
        #print fSol
        mlab.savefig(fSol)
Example #26
0
def plotframe(frameno,level=1, water_opacity=1.):

    plotdata = ClawPlotData()
    plotdata.outdir = outdir
    print "Plotting solution from ",plotdata.outdir
    plotdata = setplot(plotdata)
    try:
        frame = plotdata.getframe(frameno)
    except:
        print "Unable to get frame"
        return
    mlab.figure(1,bgcolor=(1,1,1),size=(700,600))
    mlab.clf()
    for grid in frame.grids:
        if grid.level == level:

            y = grid.c_center[1]
            x = grid.c_center[0]
            q = grid.q
            eta = q[:,:,3]
            h = q[:,:,0]
        
            topo = eta - h
            cutoff = 0.5
            #cutoff2 = -500.
            shift = 0.
            scale = 1.
            topo1 = scale*where(topo<cutoff, topo-shift, cutoff-shift)
            #topo1 = scale*where(topo>cutoff2, topo1, nan)
            eta1 = scale*where(eta<cutoff, eta-shift, cutoff-shift)
            water1 = where(h>=1.e-3, eta1, nan)
            scale = 12.
            #mlab.mesh(x,y,topo1,colormap='Greens',vmin=-1.0, vmax=0.8)
            #mlab.mesh(x,y,water1,colormap='Blues',vmin=-0.8, vmax=0.8)
            mlab.surf(x,y,topo1,colormap='YlGn',warp_scale=scale,\
                          vmin=-0.3,vmax=0.3)
            mlab.surf(x,y,water1,colormap='Blues',warp_scale=scale,\
                          vmin=-0.2,vmax=0.3, opacity=water_opacity)

    # set the view:  (Do V = view() to figure out the current view)
    V = (29.157490879985176,\
     67.560491214404507,\
     79.798910042690324,\
     array([ 0.        ,  1.        , -0.07500005]))

    mlab.view(*V)
    t = frame.t
    mlab.title('Time = %5.2f' % t,color=(0,0,0),height=0.1,size=0.5)
	def _plotbutton2_fired(self):
		mlab.clf()
		self.loaddata()
		field=mlab.contour3d(self.sregion,colormap='gist_ncar')     # Generate a scalar field
		field.contour.maximum_contour = self.datamax
		field.contour.minimum_contour = self.datamin
		field.actor.property.opacity = self.opacity

		mlab.outline()
		mlab.xlabel('RA(J2000)')
		mlab.ylabel('DEC(J2000)')
		mlab.zlabel('Velocity')
		mlab.view(azimuth=0, elevation=0)
		mlab.show()

		self.field   = field
Example #28
0
def move_cam(outpath):
    """ Example to record a stream of images moving the camera around 
    (using offscreen rendering)

    Usage: move_cam(out_path)

    Input:
        outpath - (String) output path to save images
       
    Output:
        -NONE- but stream of images is saved in outpath
    """

    import os.path
    import tf_format
    from enthought.mayavi import mlab
    mlab.options.offscreen = True
    mlab.test_contour3d()

    # Example motion: rotate clockwise around an object
    step = 15 # degrees of change between views

    for i, angle in enumerate(range(0, 360, step)):
        view = mlab.view(azimuth=angle)
        imgname = os.path.join(outpath, 'example' + str(i) + '.png')
        mlab.savefig(imgname)
def image():
    #print getcwd()
    fig = mlab.figure()
    fig.scene.background = (1.,1.,1.)
    fig.scene.jpeg_quality = 100
    
    src = mlab.pipeline.open('/home/jakub/simdata/global_enrichement/eps_f0nodes_1.vtk')
    tc = mlab.pipeline.extract_tensor_components(src)
    tc.filter.scalar_mode = 'component' 
    ws = mlab.pipeline.warp_scalar(tc, warp_scale = 2.)
    #mlab.pipeline.surface(ws)
    cp = mlab.pipeline.cut_plane(ws)
    
    cp.filters[0].widget.enabled = False
    cp.filters[0].plane.normal = (0.,1.,0.)
    su = mlab.pipeline.surface(cp)
    su.actor.property.color = (0.75294117647058822, 0.75294117647058822, 0.75294117647058822)
    su.actor.property.line_width = 4.
    su.actor.mapper.scalar_visibility = False
    
    #print cp.filters
    src2 = mlab.pipeline.open('/home/jakub/simdata/global_enrichement/eps_m0nodes_1.vtk')
    tc2 = mlab.pipeline.extract_tensor_components(src2)
    tc2.filter.scalar_mode = 'component' 
    ws2 = mlab.pipeline.warp_scalar(tc2, warp_scale = 2.)
    #mlab.pipeline.surface(ws)
    cp2 = mlab.pipeline.cut_plane(ws2)
    
    cp2.filters[0].widget.enabled = False
    cp2.filters[0].plane.normal = (0.,1.,0.)
    
    su2 = mlab.pipeline.surface(cp2)
    su2.actor.property.color = (0.,0.,0.)
    su2.actor.property.line_width = 4.
    su2.actor.mapper.scalar_visibility = False
    ax = mlab.axes(color = (0.,0.,0.),
                   xlabel = 'x',
                   ylabel = '',
                   zlabel = 'strain',
                   extent = [0., 3.1, 0., 0., 0., 2.],
                   ranges = [1., 0., 0., 0., 0., 1.],
                   y_axis_visibility = False)
    ax.title_text_property.color = (0.0, 0.0, 0.0)
    ax.label_text_property.color = (0.0, 0.0, 0.0)
    ax.title_text_property.bold = False
    ax.label_text_property.bold = False
    mlab.view(90., 90., 6.0, 'auto')
Example #30
0
def plot_connections(data_file, min, max, bins,
                     params=None, output=''):
    
    print("Creating connection profile graphs.")
    
    # Read data points from file
    f = open(data_file, 'r')

    # Ignore first line
    f.readline()

    data = []

    for line in f:
        temp = line.split(' ')
        if params != None:
            if check_node([int(temp[1])], params):
                data.append([float(temp[4]), float(temp[5])]);
        else:
            data.append([float(temp[4]), float(temp[5])]);

    # Create histogram data based on the retrieved data.
    histogram_data = histogram2d(data, min, max, bins)

    # Open a new Mayavi2 figure
    f = mlab.figure()

    # Convert histogram bin count to relative densities.
    m = np.max(histogram_data[2].max(axis=0))
    histogram_data[2] = histogram_data[2]/float(m)

    # Plot histogram data
    mlab.mesh(histogram_data[0], histogram_data[1], histogram_data[2])
    #surf(histogram_data[0], histogram_data[1], histogram_data[2])

    # Create and save various viewpoints of histogram figure

    mlab.axes(z_axis_visibility=False)

    mlab.view(azimuth=0, elevation=90) # X

    mlab.savefig(output+"xaxis.eps", size=[600,400])

    mlab.view(azimuth=90, elevation=270) # Y

    mlab.savefig(output+"yaxis.eps", size=[600,400])

    mlab.view(azimuth=45, elevation=45) # Perspective

    mlab.savefig(output+"perspective.eps", size=[600,400])

    mlab.colorbar(orientation="vertical")

    mlab.view(azimuth=0, elevation=0) # Z

    mlab.savefig(output+"above.eps", size=[600,400])
Example #31
0
    def add_data(self, array, min=None, max=None, colormap="blue-red"):
        """Display data from a numpy array on the surface.

        Parameters
        ----------
        array : numpy array
            data array (nvtx vector)
        min : float
            min value in colormap (uses real min if None)
        max : float
            max value in colormap (uses real max if None)
        colormap : str
            name of Mayavi colormap to use

        """
        from enthought.mayavi import mlab
        self._f.scene.disable_render = True
        view = mlab.view()

        # Possibly remove old data
        if hasattr(self, "data"):
            self.data["surface"].remove()
            self.data["colorbar"].remove()

        if min is None:
            min = array.min()
        if max is None:
            max = array.max()

        # Set up the visualization pipeline
        mesh = mlab.pipeline.triangular_mesh_source(self._geo.x,
                                                    self._geo.y,
                                                    self._geo.z,
                                                    self._geo.faces,
                                                    scalars=array)
        surf = mlab.pipeline.surface(mesh, colormap=colormap,
                                     vmin=min, vmax=max)

        # Get the colorbar
        bar = mlab.scalarbar(surf)
        bar.scalar_bar_representation.position2 = .8, 0.09

        # Fil in the data dict
        self.data = dict(surface=surf, colorbar=bar)
        mlab.view(*view)
        self._f.scene.disable_render = False
Example #32
0
    def add_overlay(self, source, min=None, max=None, sign="abs",
                    name=None, visible=True):
        """Add an overlay to the overlay dict from a file or array.

        Parameters
        ----------
        src : str or numpy array
            path to the overlay file or numpy array with data
        min : float
            threshold for overlay display
        max : float
            saturation point for overlay display
        sign : {'abs' | 'pos' | 'neg'}
            whether positive, negative, or both values should be displayed
        name : str
            name for the overlay in the internal dictionary
        visible : boolean
            whether the overlay should be visible upon load

        """
        from enthought.mayavi import mlab
        # If source is a string, try to load a file
        if isinstance(source, basestring):
            if name is None:
                basename = os.path.basename(source)
                if basename.endswith(".gz"):
                    basename = basename[:-3]
                if basename.startswith("%s." % self.hemi):
                    basename = basename[3:]
                name = os.path.splitext(basename)[0]
            scalar_data = io.read_scalar_data(source)
        else:
            # Can't think of a good way to check that this will work nicely
            scalar_data = source

        if name in self.overlays:
            "%s%d" % (name, len(self.overlays) + 1)

        if not sign in ["abs", "pos", "neg"]:
            raise ValueError("Overlay sign must be 'abs', 'pos', or 'neg'")

        self._f.scene.disable_render = True
        view = mlab.view()
        self.overlays[name] = Overlay(scalar_data, self._geo, min, max, sign)
        mlab.view(*view)
        self._f.scene.disable_render = False
Example #33
0
def plot_connections(data_file, min, max, bins, params=None, output=''):

    print("Creating connection profile graphs.")

    # Read data points from file
    f = open(data_file, 'r')

    # Ignore first line
    f.readline()

    data = []

    for line in f:
        temp = line.split(' ')
        if params != None:
            if check_node([int(temp[1])], params):
                data.append([float(temp[4]), float(temp[5])])
        else:
            data.append([float(temp[4]), float(temp[5])])

    # Create histogram data based on the retrieved data.
    histogram_data = histogram2d(data, min, max, bins)

    # Open a new Mayavi2 figure
    f = mlab.figure()

    # Convert histogram bin count to relative densities.
    m = np.max(histogram_data[2].max(axis=0))
    histogram_data[2] = histogram_data[2] / float(m)

    # Plot histogram data
    mlab.mesh(histogram_data[0], histogram_data[1], histogram_data[2])
    #surf(histogram_data[0], histogram_data[1], histogram_data[2])

    # Create and save various viewpoints of histogram figure

    mlab.axes(z_axis_visibility=False)

    mlab.view(azimuth=0, elevation=90)  # X

    mlab.savefig(output + "xaxis.eps", size=[600, 400])

    mlab.view(azimuth=90, elevation=270)  # Y

    mlab.savefig(output + "yaxis.eps", size=[600, 400])

    mlab.view(azimuth=45, elevation=45)  # Perspective

    mlab.savefig(output + "perspective.eps", size=[600, 400])

    mlab.colorbar(orientation="vertical")

    mlab.view(azimuth=0, elevation=0)  # Z

    mlab.savefig(output + "above.eps", size=[600, 400])
Example #34
0
    def show_3d(self, colors=None, colormap='gray', scale_factor=0.02, 
                display=True):
        """SHOW_3D - Use mayavi2 to visualize point cloud.
        
        Usage: obj.show_3d(colors, colormap, scale_factor, display)

        Input:
            colors{None} - If none, consider Z as depth and paint points
                accordingly. Otherwise, N-array of scalars.
            colormap{'gray'} - Any colormap that mayavi accepts ('gray',
                'spectral', 'bone', ...)
            scale_factor{0.02} - Define scale of 3D points.
            display{True} - If True, show figure and lock environment. If False, 
                return figure handler.
        """
       
        from enthought.mayavi import mlab
        
        if colors is None:
            colors = self[2,:]

        # I want at most 50K points
        stride = 1 + len(self)/50000

        pts = self[:,::stride]
        colors = colors[::stride]

        # Draw clusters in point cloud
        fig = mlab.figure()
        mlab.points3d(pts[0,:], pts[1,:], pts[2,:], \
                      colors, colormap=colormap, figure=fig, \
                      scale_mode='none', scale_factor=scale_factor)

        mlab.view(180,180)
        
        if show:
            mlab.show() 
        else:
            return fig
Example #35
0
    def saveVTKFilesAsImages_2D(sourceFolder, destinationFolder):
        if not os.path.isdir(sourceFolder) or not os.path.isdir(
                destinationFolder):
            return

        vtkFiles = []
        for f in sorted(os.listdir(sourceFolder)):
            if f.endswith(".vtk"):
                vtkFiles.append(f)

        if len(vtkFiles) == 0:
            return

        figure = mlab.figure(size=(800, 600))
        figure.scene.disable_render = True
        vtkSource = VTKFileReader()
        vtk_file = os.path.join(sourceFolder, vtkFiles[0])
        vtkSource.initialize(vtk_file)
        surface = mlab.pipeline.surface(vtkSource)
        axes = mlab.axes()
        colorbar = mlab.colorbar(object=surface, orientation='horizontal')
        mlab.view(0, 0)
        figure.scene.disable_render = False
        mlab.draw()
        png_file = os.path.join(destinationFolder,
                                vtkFiles[0]).replace('.vtk', '.png')
        mlab.savefig(png_file)

        for f in vtkFiles[1:-1]:
            vtk_file = os.path.join(sourceFolder, f)
            vtkSource.initialize(vtk_file)
            png_file = os.path.join(destinationFolder,
                                    f).replace('.vtk', '.png')
            mlab.savefig(png_file)
            app = QtCore.QCoreApplication.instance()
            if app:
                app.processEvents()
Example #36
0
def plot_sln_mayavi(sln, notebook=False):
    """
    Plots the Solution() instance sln using Linearizer() and matplotlib.

    Currently only a very simple version is implemented, that takes the
    vertices from linearizer and interpolates them. More sophisticated version
    should take the triangles.
    """
    lin = Linearizer()
    lin.process_solution(sln)
    vert = lin.get_vertices()
    triangles = lin.get_triangles()
    from numpy import zeros
    from enthought.mayavi import mlab
    x = vert[:, 0]
    y = vert[:, 1]
    z = zeros(len(y))
    t = vert[:, 2]
    if notebook:
        # the off screen rendering properly works only with VTK-5.2 or above:
        mlab.options.offscreen = True
    mlab.clf()
    s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
    mlab.view(0, 0)

    # Below is a code that does exactly what the "View along the +Z axis"
    # button does:
    #scene = mlab.get_engine().current_scene.scene
    #scene.camera.focal_point = [0, 0, 0]
    #scene.camera.position = [0, 0, 1]
    #scene.camera.view_up = [0, 1, 0]
    #scene.renderer.reset_camera()
    #scene.render()
    # the above looks ok, but there is still quite a large margin, so we prefer
    # to just call .view(0, 0), which seems to be working fine.
    return s
Example #37
0
def viewGraph(g, sub=3,title=''):

    mlab.figure(bgcolor=(0, 0, 0), size=(900, 900))
    nodes = g.nodes()
    random.shuffle(nodes)
    nodes = np.array(nodes[0:100])
    #mlab.points3d(nodes[:,2],nodes[:,1],nodes[:,0],color=(0.0,0.0,1.0))
    edges = g.edges(data=True)
    print(len(edges))
    input('continue')
    count = 0
    for n1, n2, edge in edges:
        count += 1
        if( count % 100 == 0 ):
            print(count)
        path = [n1]+edge['path']+[n2]
        pa = np.array(path)
        #print pa
        mlab.plot3d(pa[::sub,2],pa[::sub,1],pa[::sub,0],color=(0,1,0),tube_radius=0.75)
    mlab.view(-125, 54, 'auto','auto')
    mlab.roll(-175)
    mlab.title(title, height=0.1)
    
    mlab.show()
Example #38
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
Example #39
0
    def getData(self, data_D, data_H, name):
        """
        plot passed in data as a surface
        """

        #plotting
        fig = mlab.figure(size=(512, 512))
        mlab.view(90, 0)

        cl.enqueue_read_buffer(lbm.queue, data_D, data_H).wait()

        rgrid = tvtk.RectilinearGrid()
        rgrid.cell_data.scalars = data_H.ravel()
        rgrid.cell_data.scalars.name = 'scalars'

        rgrid.dimensions = np.array((lbm.Ny + 1, lbm.Nx + 1, 1))
        rgrid.x_coordinates = lbm.Y
        rgrid.y_coordinates = lbm.X
        rgrid.z_coordinates = np.array([0.0])

        src = mlab.pipeline.add_dataset(rgrid)
        s = mlab.pipeline.cell_to_point_data(src)
        s = mlab.pipeline.surface(s)
        sb = mlab.scalarbar(s, title=name)

        #plot lines
        if 1:
            mlab.pipeline.surface(mlab.pipeline.extract_edges(src),
                                  color=(0, 0, 0),
                                  line_width=0.1,
                                  opacity=0.05)

        self.rgrid = rgrid
        self.src = src
        self.data_D = data_D
        self.data_H = data_H
Example #40
0
def plot_sln_mayavi(sln, offscreen=False, show_scale=True):
    """
    Plots the Solution() instance sln using Linearizer() and matplotlib.

    It takes the vertices from linearizer and interpolates them.
    """
    lin = Linearizer()
    lin.process_solution(sln)
    vert = lin.get_vertices()
    triangles = lin.get_triangles()
    from numpy import zeros
    from enthought.mayavi import mlab
    x = vert[:, 0]
    y = vert[:, 1]
    z = zeros(len(y))
    t = vert[:, 2]
    if offscreen:
        # the off screen rendering properly works only with VTK-5.2 or above:
        mlab.options.offscreen = True
    mlab.clf()
    mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
    s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
    mlab.view(0, 0)
    mlab.view(distance=4)
    mlab.view(focalpoint=(.35, 0, 0))
    mlab.colorbar(title="Solution", orientation="vertical")

    #mlab.move(right=-1.0, up=-10.0)
    # Below is a code that does exactly what the "View along the +Z axis"
    # button does:
    #scene = mlab.get_engine().current_scene.scene
    #scene.camera.focal_point = [0, 0, 0]
    #scene.camera.position = [0, 0, 1]
    #scene.camera.view_up = [0, 1, 0]
    #scene.renderer.reset_camera()
    #scene.render()
    # the above looks ok, but there is still quite a large margin, so we prefer
    # to just call .view(0, 0), which seems to be working fine.
    return mlab
# Author: Gael Varoquaux <*****@*****.**>
# Copyright (c) 2008, Enthought, Inc.
# License: BSD Style.

from enthought.mayavi import mlab
import numpy as np
from scipy.special import sph_harm

# Create a sphere
r = 0.3
pi = np.pi
cos = np.cos
sin = np.sin
phi, theta = np.mgrid[0:pi:101j, 0:2 * pi:101j]

x = r * sin(phi) * cos(theta)
y = r * sin(phi) * sin(theta)
z = r * cos(phi)

mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300))
mlab.clf()
# Represent spherical harmonics on the surface of the sphere
for l in range(0, 5):
    for m in range(l):
        s = sph_harm(m, l, theta, phi).real

        mlab.mesh(x + m, y - l, z, scalars=s, colormap='jet')

mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25))
mlab.show()
Example #42
0
# Now to make it look decent ...
ax = mlab.axes(extent=[-10, 10, -12, 12, -7, 7], nb_labels=5)
ax.axes.fly_mode = 'outer_edges'
ax.title_text_property.font_size = 10
ax.title_text_property.font_family = 'courier'
ax.label_text_property.font_family = 'courier'

# And a bit of references if anyone is interested ...
mlab.text(
    0.05,
    0.95,
    'Oxygen-rich ejecta in SNR N132D. Vogt & Dopita, Ap&SS, 311, 521 (2011); Vogt & Shingles, Ap&SS (2013), submitted.',
    width=0.75)
mlab.text(0.05, 0.05, '*****@*****.**', width=0.25)

# Label the axes ...
ax.axes.x_label = 'X (Dec.) [pc]'
ax.axes.y_label = 'Y (R.A.) [pc]'
ax.axes.z_label = 'Z [pc]'
mlab.show()
# Define the view point - useful to make a movie (not build here) ...
mlab.view(90, 0, 60)

# Save it all ...
#mlab.savefig('Vogt+Shingles_test.wrl')
#mlab.savefig('Vogt+Shingles_test.eps')
#mlab.savefig('Vogt+Shingles_test.png')

print 'All done !'
# End of the World as we know it ...
Example #43
0
                       [np.arange(index,   index + N - 1.5),
                        np.arange(index+1, index + N - .5)]
                            ).T)    
    index += N

# Now collapse all positions, scalars and connections in big arrays
x = np.hstack(x)
y = np.hstack(y)
z = np.hstack(z)
s = np.hstack(s)
connections = np.vstack(connections)

# Create the points
src = mlab.pipeline.scalar_scatter(x, y, z, s)

# Connect them
src.mlab_source.dataset.lines = connections

# The stripper filter cleans up connected lines
lines = mlab.pipeline.stripper(src)

# Finally, display the set of lines
mlab.pipeline.surface(lines, colormap='Accent', line_width=1, opacity=.4)

# And choose a nice view
mlab.view(33.6, 106, 5.5, [0, 0, .05])
mlab.roll(125)
mlab.show()


# Show the connections as tubes between sensors
vmax = np.max(con_val)
vmin = np.min(con_val)
for val, nodes in zip(con_val, con_nodes):
    x1, y1, z1 = sens_loc[nodes[0]]
    x2, y2, z2 = sens_loc[nodes[1]]
    points = mlab.plot3d([x1, x2], [y1, y2], [z1, z2], [val, val],
                         vmin=vmin,
                         vmax=vmax,
                         tube_radius=0.001,
                         colormap='RdBu')
    points.module_manager.scalar_lut_manager.reverse_lut = True

mlab.scalarbar(title='Phase Lag Index (PLI)', nb_labels=4)

# Add the sensor names for the connections shown
nodes_shown = list(set([n[0] for n in con_nodes] + [n[1] for n in con_nodes]))

for node in nodes_shown:
    x, y, z = sens_loc[node]
    mlab.text3d(x,
                y,
                z,
                raw.ch_names[picks[node]],
                scale=0.005,
                color=(0, 0, 0))

view = (-88.7, 40.8, 0.76, np.array([-3.9e-4, -8.5e-3, -1e-2]))
mlab.view(*view)
Example #45
0
File: mri.py Project: sjl421/code-2
                                            vmax=2600)
cut_plane2.implicit_plane.origin = (136, 111.5, 82)
cut_plane2.implicit_plane.widget.enabled = False

# Extract two views of the outside surface. We need to define VOIs in
# order to leave out a cut in the head.
voi2 = mlab.pipeline.extract_grid(src)
voi2.set(y_min=112)
outer = mlab.pipeline.iso_surface(voi2,
                                  contours=[
                                      1776,
                                  ],
                                  color=(0.8, 0.7, 0.6))

voi3 = mlab.pipeline.extract_grid(src)
voi3.set(y_max=112, z_max=53)
outer3 = mlab.pipeline.iso_surface(voi3,
                                   contours=[
                                       1776,
                                   ],
                                   color=(0.8, 0.7, 0.6))

mlab.view(-125, 54, 326, (145.5, 138, 66.5))
mlab.roll(-175)

mlab.show()

import shutil

shutil.rmtree('mri_data')
Example #46
0
                                   Z,
                                   Bx,
                                   By,
                                   Bz,
                                   scalars=Bnorm,
                                   name='B field')
vectors = mlab.pipeline.vectors(
    field,
    scale_factor=(X[1, 0, 0] - X[0, 0, 0]),
)
# Mask random points, to have a lighter visualization.
vectors.glyph.mask_input_points = True
vectors.glyph.mask_points.on_ratio = 6

vcp = mlab.pipeline.vector_cut_plane(field)
vcp.glyph.glyph.scale_factor = 5 * (X[1, 0, 0] - X[0, 0, 0])
# For prettier picture:
#vcp.implicit_plane.widget.enabled = False

iso = mlab.pipeline.iso_surface(field,
                                contours=[0.1 * Bmax, 0.4 * Bmax],
                                opacity=0.6,
                                colormap='YlOrRd')

# A trick to make transparency look better: cull the front face
iso.actor.property.frontface_culling = True

mlab.view(39, 74, 0.59, [.008, .0007, -.005])

mlab.show()
Example #47
0
"""

# Create some data
import numpy as np

x, y = np.mgrid[-10:10:200j, -10:10:200j]
z = 100 * np.sin(x * y) / (x * y)

# Visualize it with mlab.surf
from enthought.mayavi import mlab
mlab.figure(bgcolor=(1, 1, 1))
surf = mlab.surf(z, colormap='cool')

# Retrieve the LUT of the surf object.
lut = surf.module_manager.scalar_lut_manager.lut.table.to_array()

# The lut is a 255x4 array, with the columns representing RGBA
# (red, green, blue, alpha) coded with integers going from 0 to 255.

# We modify the alpha channel to add a transparency gradient
lut[:, -1] = np.linspace(0, 255, 256)
# and finally we put this LUT back in the surface object. We could have
# added any 255*4 array rather than modifying an existing LUT.
surf.module_manager.scalar_lut_manager.lut.table = lut

# We need to force update of the figure now that we have changed the LUT.
mlab.draw()
mlab.view(40, 85)

mlab.show()
Example #48
0
def show_model(model, type = 'all', IdxCameras = None):
    """ Visualize data from a bundler model.

    Usage: show_model(model, type, IdxCameras)

    Input:
    model - Moped model to visualize
    type{'all'} - Choose what you want to see: 'pts', 'cam' or 'all'.
    IdxCameras{None} - If type = {'all', 'cam'}, options is a list of camIDs that
        specify which camera(s) to display. If not given, the default if to 
        display all cameras used in the training process.

    Output:
    -NONE-
    """

    if IdxCameras is None:
        IdxCameras = range(model.nViews)
    
    # Our figure
    fig = mlab.figure()
   
    # Display only the points   
    if type.lower() == 'pts':
        # Get a proper scale for the cameras: the std after removing mean
        scale = np.mean( np.std(model.pts3D - \
                                np.mean(model.pts3D, axis=1)[:, None]) )   
        mlab.points3d(model.pts3D[0,:], \
                      model.pts3D[1,:], \
                      model.pts3D[2,:], \
                      scale_mode='none', scale_factor=0.02, \
                      color = (0,0,1), figure = fig)
        
    elif type.lower() == 'cam':
        scale = 0.1 
        for i in IdxCameras:
            # To use draw_camera we need the camera to world transf.
            R, t = tf_format('iRT', model.cam_poses[:, i])
            draw_camera(R, t, scale, figure = fig); # Draw cameras
        
    # Draw 3D points and cameras
    elif type.lower() == 'all':   
        # Get a proper scale for the cameras: the std after removing mean
        scale = np.mean( np.std(model.pts3D - \
                                np.mean(model.pts3D, axis=1)[:, None]) )

        for i in IdxCameras:
            # To use draw_camera we need the camera to world transf.
            R, t = tf_format('iRT', model.cam_poses[:, i])
            draw_camera(R, t, scale, figure = fig); # Draw cameras
        
        mlab.points3d(model.pts3D[0,:], \
                      model.pts3D[1,:], \
                      model.pts3D[2,:], \
                      scale_mode='none', scale_factor=0.02, \
                      color = (0,0,1), figure = fig)
        
    # Oops
    else: 
        print('Unknown option')

    mlab.view(0,0, distance = scale*50, focalpoint = np.r_[0, 0, 0])
    mlab.show() 
Example #49
0
def plot_3d_spectrum_mayavi(fs, fignum=None, vmin=None, vmax=None, 
                            pop_ids=None):
    """
    Logarithmic heatmap of single 3d FS.

    This method relies on MayaVi2's mlab interface. See http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html . To edit plot
    properties, click leftmost icon in the toolbar.

    If you get an ImportError upon calling this function, it is likely that you
    don't have mayavi installed.

    fs: FS to plot
    vmin: Values in fs below vmin are masked in plot.
    vmax: Values in fs above vmax saturate the color spectrum.
    fignum: Figure number to plot into. If None, a new figure will be created.
            Note that these are MayaVi figures, which are separate from
            matplotlib figures.
    pop_ids: If not None, override pop_ids stored in Spectrum.
    """
    from enthought.mayavi import mlab

    fig = mlab.figure(fignum, bgcolor=(1,1,1))
    mlab.clf(fig)

    if vmin is None:
        vmin = fs.min()
    if vmax is None:
        vmax = fs.max()

    # Which entries should I plot?
    toplot = numpy.logical_not(fs.mask)
    toplot = numpy.logical_and(toplot, fs.data >= vmin)

    # For the color mapping
    normalized = (numpy.log(fs)-numpy.log(vmin))\
            /(numpy.log(vmax)-numpy.log(vmin))
    normalized = numpy.minimum(normalized, 1)

    xs,ys,zs = numpy.indices(fs.shape)
    flat_xs = xs.flatten()
    flat_ys = ys.flatten()
    flat_zs = zs.flatten()
    flat_toplot = toplot.flatten()
    
    mlab.barchart(flat_xs[flat_toplot], flat_ys[flat_toplot], 
                  flat_zs[flat_toplot], normalized.flatten()[flat_toplot], 
                  colormap='hsv', scale_mode='none', lateral_scale=1, 
                  figure=fig)

    if pop_ids is None:
        if fs.pop_ids is not None:
            pop_ids = fs.pop_ids
        else:
            pop_ids = ['pop0','pop1','pop2']

    a = mlab.axes(xlabel=pop_ids[0],ylabel=pop_ids[1],zlabel=pop_ids[2], 
                  figure=fig, color=(0,0,0))
    a.axes.label_format = ""
    a.title_text_property.color = (0,0,0)
    mlab.text3d(fs.sample_sizes[0],fs.sample_sizes[1],fs.sample_sizes[2]+1, 
                '(%i,%i,%i)'%tuple(fs.sample_sizes), scale=0.75, figure=fig,
                color=(0,0,0))
    mlab.view(azimuth=-40, elevation=65, distance='auto', focalpoint='auto')

    mlab.show()
Example #50
0
connect_ = tvtk.PolyDataConnectivityFilter(extraction_mode=4)
connect = mlab.pipeline.user_defined(smooth, filter=connect_)

# Compute normals for shading the surface
compute_normals = mlab.pipeline.poly_data_normals(connect)
compute_normals.filter.feature_angle = 80

surf = mlab.pipeline.surface(compute_normals,
                                        color=(0.9, 0.72, 0.62))

#----------------------------------------------------------------------
# Display a cut plane of the raw data
ipw = mlab.pipeline.image_plane_widget(src, colormap='bone', 
                plane_orientation='z_axes',
                slice_index=55)

mlab.view(-165, 32, 350, [143, 133, 73])
mlab.roll(180)

fig.scene.disable_render = False

#----------------------------------------------------------------------
# To make the link between the Mayavi pipeline and the much more
# complex VTK pipeline, we display both:
mlab.show_pipeline(rich_view=False)
from enthought.tvtk.pipeline.browser import PipelineBrowser
browser = PipelineBrowser(fig.scene)
browser.show()

mlab.show()
Example #51
0
#!/usr/bin/env python
# encoding: utf-8
"""
plot_hs.py - Plot the half-sarcomere with mayavi

Created by Dave Williams on 2010-10-4
"""

import numpy as np
from enthought.mayavi import mlab

# Configure the graph
fig = mlab.figure(1, bgcolor=(0, 0, 0), size=(350, 350))
mlab.clf()
fig.scene.parallel_projection = True
mlab.view(-4.0, 84.5, 2423.2, (625.0, 21.4, -3.4))
fil_rad = 2
fil_seg = 12
fil_color = 'jet'
fil_lims = (-1.0, 1.0)


class plot_hs:
    def update_locs(self):
        # Get needed info from the half-sarcomere
        self.thick_xlocs = [t.axial for t in self.hs.thick]
        self.thin_xlocs = [t.axial for t in self.hs.thin]
        self.thick_s = [t.axialforce() for t in self.hs.thick]
        self.thin_s = [t.axialforce() for t in self.hs.thin]
        self.z_line = self.hs.z_line
        ls = self.hs.lattice_spacing
Example #52
0
mlab.figure(bgcolor=(1, 1, 1))
# plot the atoms as spheres
for atom in atoms:
    mlab.points3d(
        atom.x,
        atom.y,
        atom.z,
        scale_factor=vdw_radii[atom.number] / 5.,
        resolution=20,
        # a tuple is required for the color
        color=tuple(cpk_colors[atom.number]),
        scale_mode='none')
# draw the unit cell - there are 8 corners, and 12 connections
a1, a2, a3 = atoms.get_cell()
origin = [0, 0, 0]
cell_matrix = [[origin, a1], [origin, a2], [origin, a3], [a1, a1 + a2],
               [a1, a1 + a3], [a2, a2 + a1], [a2, a2 + a3], [a3, a1 + a3],
               [a3, a2 + a3], [a1 + a2, a1 + a2 + a3], [a2 + a3, a1 + a2 + a3],
               [a1 + a3, a1 + a3 + a2]]
for p1, p2 in cell_matrix:
    mlab.plot3d(
        [p1[0], p2[0]],  # x-positions
        [p1[1], p2[1]],  # y-positions
        [p1[2], p2[2]],  # z-positions
        tube_radius=0.02)
# Now plot the charge density
mlab.contour3d(x, y, z, cd, transparent=True)
# this view was empirically found by iteration
mlab.view(azimuth=-90, elevation=90, distance='auto')
mlab.savefig('images/co-centered-cd.png')
mlab.show()
Example #53
0
def sensor_connectivity_3d(raw, picks, con, idx, n_con=20, min_dist=0.05,
                           scale_factor=0.005, tube_radius=0.001):
    """ Function to plot sensor connectivity showing strongest
        connections(n_con) excluding sensors that are less than min_dist apart.
        https://github.com/mne-tools/mne-python/blob/master/examples/connectivity/plot_sensor_connectivity.py

    Parameters
    ----------
    raw : Raw object
        Instance of mne.io.Raw
    picks : list
        Picks to be included.
    con : ndarray (n_channels, n_channels)
        Connectivity matrix.
    idx : list
        List of indices of sensors of interest.
    n_con : int
        Number of connections of interest.
    min_dist : float
        Minimum distance between sensors allowed.

    Note: Please modify scale factor and tube radius to appropriate sizes
          if the plot looks scrambled.
    """

    # Now, visualize the connectivity in 3D
    try:
        from enthought.mayavi import mlab
    except:
        from mayavi import mlab

    mlab.figure(size=(600, 600), bgcolor=(0.5, 0.5, 0.5))

    # Plot the sensor location
    sens_loc = [raw.info['chs'][picks[i]]['loc'][:3] for i in idx]
    sens_loc = np.array(sens_loc)

    pts = mlab.points3d(sens_loc[:, 0], sens_loc[:, 1], sens_loc[:, 2],
                        color=(1, 1, 1), opacity=1, scale_factor=scale_factor)

    # Get the strongest connections
    threshold = np.sort(con, axis=None)[-n_con]
    ii, jj = np.where(con >= threshold)

    # Remove close connections
    con_nodes = list()
    con_val = list()
    for i, j in zip(ii, jj):
        if sci.linalg.norm(sens_loc[i] - sens_loc[j]) > min_dist:
            con_nodes.append((i, j))
            con_val.append(con[i, j])

    con_val = np.array(con_val)

    # Show the connections as tubes between sensors
    vmax = np.max(con_val)
    vmin = np.min(con_val)
    for val, nodes in zip(con_val, con_nodes):
        x1, y1, z1 = sens_loc[nodes[0]]
        x2, y2, z2 = sens_loc[nodes[1]]
        points = mlab.plot3d([x1, x2], [y1, y2], [z1, z2], [val, val],
                             vmin=vmin, vmax=vmax, tube_radius=tube_radius,
                             colormap='RdBu')
        points.module_manager.scalar_lut_manager.reverse_lut = True

    mlab.scalarbar(title='Phase Lag Index (PLI)', nb_labels=4)

    # Add the sensor names for the connections shown
    nodes_shown = list(set([n[0] for n in con_nodes] +
                           [n[1] for n in con_nodes]))

    for node in nodes_shown:
        x, y, z = sens_loc[node]
        mlab.text3d(x, y, z, raw.ch_names[picks[node]], scale=0.005,
                    color=(0, 0, 0))

    view = (-88.7, 40.8, 0.76, np.array([-3.9e-4, -8.5e-3, -1e-2]))
    mlab.view(*view)
b /= norm

mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
mlab.clf()
pts = mlab.points3d(a, b, c, density, colormap='jet', mode='2dvertex')
mlab.outline(extent=[
    -3 * a.std(), 3 * a.std(), -3 * b.std(), 3 * b.std(), -3 * c.std(),
    3 * c.std()
],
             line_width=2)

Y = np.c_[a, b, c]
U, pca_score, V = np.linalg.svd(Y, full_matrices=False)
x_pca_axis, y_pca_axis, z_pca_axis = V.T * pca_score / pca_score.min()

mlab.view(-20.8, 83, 9, [0.18, 0.2, -0.24])
#mlab.savefig('pca_3d.jpg')
mlab.quiver3d(0.1 * x_pca_axis,
              0.1 * y_pca_axis,
              0.1 * z_pca_axis,
              2 * x_pca_axis,
              2 * y_pca_axis,
              2 * z_pca_axis,
              color=(0.6, 0, 0),
              line_width=2)

x_pca_axis, y_pca_axis, z_pca_axis = 3 * V.T
x_pca_plane = np.r_[x_pca_axis[:2], -x_pca_axis[1::-1]]
y_pca_plane = np.r_[y_pca_axis[:2], -y_pca_axis[1::-1]]
z_pca_plane = np.r_[z_pca_axis[:2], -z_pca_axis[1::-1]]
Example #55
0
    scene = mlab.contour3d((fileh.root.Phi[2:-2, 2:-2, 2:-2, frame]**2),
                           contours=50,
                           extent=ext,
                           vmax=fmax,
                           vmin=fmin)  #, colormap='ylgn')

    # Cutplane
    #E  = gradient(fileh.root.Phi[:,:,:,frame])
    #mlab.quiver3d(E[0], E[1], E[2])
    #src = mlab.pipeline.vector_field(E[2], E[1], E[0])
    #mlab.pipeline.vectors(src, mask_points=20, scale_factor=3.)
    #mlab.pipeline.vector_cut_plane(src, mask_points=1, scale_factor=5)
    #src = mlab.pipeline.vector_field(E[0], E[1], E[2])
    #magnitude = mlab.pipeline.extract_vector_norm(src)
    #flow = mlab.pipeline.streamline(magnitude, seedtype='plane', seed_visible=False, seed_scale=1.0, seed_resolution=100, linetype='line',integration_direction='both')
    #$mlab.axes(color=(0.0,0.0,0.),extent=ext,xlabel='X',ylabel='Y',zlabel='Z')
    #source = mlab.pipeline.scalar_field(fileh.root.Phi[:,:,:,frame]**2)
    #vol = mlab.pipeline.volume(source)
    #a = array(gradient(fileh.root.Phi[:,:,:,frame]))**2
    #mlab.quiver3d(a[0],a[1],a[2])
    #  mlab.view(azimuth=angle%360, distance=128.0)
    mlab.view(azimuth=angle % 360, distance=10.0)
    angle += 1.0
    mlab.colorbar(orientation='vertical', label_fmt="%.2e", nb_labels=5)
    mlab.outline()
    mlab.savefig("Phi3D_" + filename + "_" + string.zfill(frame, 4) +
                 ".jpg")  #, size=(600,600))
    print "[", string.zfill(frame, 4), "/", len(fileh.root.Time[:]), "]"

#mencoder "mf://*.jpg" -mf fps=10 -ovc lavc -o mymovie.av
Example #56
0
magnitude = mlab.pipeline.extract_vector_norm(field)
contours = mlab.pipeline.iso_surface(magnitude,
                                     contours=[
                                         0.01,
                                         0.8,
                                         3.8,
                                     ],
                                     transparent=True,
                                     opacity=0.4,
                                     colormap='YlGnBu',
                                     vmin=0,
                                     vmax=2)

field_lines = mlab.pipeline.streamline(magnitude,
                                       seedtype='line',
                                       integration_direction='both',
                                       colormap='bone',
                                       vmin=0,
                                       vmax=1)

# Tweak a bit the streamline.
field_lines.stream_tracer.maximum_propagation = 100.
field_lines.seed.widget.point1 = [69, 75.5, 75.5]
field_lines.seed.widget.point2 = [82, 75.5, 75.5]
field_lines.seed.widget.resolution = 50
field_lines.seed.widget.enabled = False

mlab.view(42, 73, 104, [79, 75, 76])

mlab.show()