def show_contrasts(subject, contrasts, side, threshold):

    x, y, z, triangles = get_geometry(subject, side, "inflated")   ## inflated or white
    curv = get_curvature_sign(subject, side)

    f = mlab.figure()
    mlab.clf()

    # anatomical mesh
    mlab.triangular_mesh(x, y, z, triangles, transparent=False,
                         opacity=1., name=subject,
        scalars=curv, colormap="bone", vmin=-1, vmax=2)

    mlab.title(subject)

    cmaps = [colormaps[c.split("-")[0]]['colormap'] for c in contrasts]

    for contrast, colormap in zip(contrasts, cmaps):
        # functional mesh
        data = get_contrast(subject, contrast, side)
        func_mesh = mlab.pipeline.triangular_mesh_source(x, y, z, triangles,
                                                     scalars=data)
            # threshold
        thresh = mlab.pipeline.threshold(func_mesh, low=threshold)

        surf = mlab.pipeline.surface(thresh, colormap='hot', transparent=True,
                          opacity=.8) # diminuer pour avoir plus de transparence
        lut = (np.array([colormap(v) for v in np.linspace(.25, 1., 256)]) * 255
                       ).astype(int)

        surf.module_manager.scalar_lut_manager.lut.table = lut

    mlab.draw()

    return f
Beispiel #2
0
    def action(u, x, xv, y, yv, t, n):
        #print 'action, t=',t,'\nu=',u, '\Nx=',x, '\Ny=', y
        if plot == 1:
            mesh(xv, yv, u, title='t=%g' %t[n])
            time.sleep(0.2) # pause between frames

        elif plot == 2:
            # mayavi plotting
            mlab.clf()
            extent1 = (0, 20, 0, 20,-2, 2)
            s = mlab.surf(x , y, u, colormap='Blues', warp_scale=5,extent=extent1)
            mlab.axes(s, color=(.7, .7, .7), extent=extent1,
            ranges=(0, 10, 0, 10, -1, 1), xlabel='', ylabel='',
            zlabel='',
            x_axis_visibility=False, z_axis_visibility=False)
            mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
            mlab.text(2, -2.5, '', z=-4, width=0.1)
            mlab.colorbar(object=None, title=None, orientation='horizontal', nb_labels=None, nb_colors=None, label_fmt=None)
            mlab.title('test 1D t=%g' % t[n])

            mlab.view(142, -72, 50)
            f = mlab.gcf()
            camera = f.scene.camera
            camera.yaw(0)
        
        
        if plot > 0:
            path = 'Figures_wave2D'
            time.sleep(0) # pause between frames
            if save_plot and plot != 2:
                filename = '%s/%08d.png' % (path, n)
                savefig(filename)  # time consuming!
            elif save_plot and plot == 2:
                filename = '%s/%08d.png' % (path,n)
                mlab.savefig(filename)  # time consuming!
Beispiel #3
0
def plotSpherical(dataset, vertices, triangles, ptitle="", tsize=0.4, theight=0.95):
    """Plot the spherical data given a data set, triangle set and vertex set.

    The vertex set defines the direction cosines of the individual samples.
    The triangle set defines how the surfrace must be structured between the samples.
    The data set defines, for each direction cosine, the length of the vector.

    Args:
        | dataset(numpy.array(double)): array of data set values
        | vertices(numpy.array([])): array of direction cosine vertices as [x y z]
        | triangles(numpy.array([])): array of triangles as []
        | ptitle(string): title or header for this display
        | tsize(double): title size (units not quite clear)
        | theight(double): title height (y value) (units not quite clear)

    Returns:
        | provides and mlab figure.

    Raises:
        | No exception is raised.
"""

    # calculate a (x,y,z) data set from the direction vectors
    x = dataset * vertices[:, 0]
    y = dataset * vertices[:, 1]
    z = dataset * vertices[:, 2]

    mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))

    # Visualize the points
    pts = mlab.triangular_mesh(x, y, z, triangles)  # z, scale_mode='none', scale_factor=0.2)
    mlab.title(ptitle, size=tsize, height=theight)
    mlab.show()
Beispiel #4
0
    def Render(self):
        
        t1clock = clock()                    
        self.figure = mlab.figure(bgcolor = (1, 1, 1), fgcolor = (0, 0, 0))#, figure = dataset.class_name[3:])
        self.figure.scene.disable_render = True
        nodesToRender = self.leafCount
        if self.renderToLevel != -1:
            nodesToRender = 0
            for i in range(0, self.renderToLevel):
                nodesToRender += self.nodesPerLevel[i]
            
        vertices = array(zeros((nodesToRender*8, 3)))
        facets = array(zeros((nodesToRender *6, 4)))
        self.centroids = array(zeros((nodesToRender , 3)))                
        self.root.Render(self.renderToLevel, vertices, facets, self.centroids, render_points = False)
        
        
        # Print vertices
        # Print facets
        if self.renderVerticesAndFacets:
            dataset = tvtk.PolyData(points = vertices, polys = facets)
            surf = mlab.pipeline.surface(dataset, opacity = .001)            
            mlab.pipeline.surface(mlab.pipeline.extract_edges(surf), color = (0, 0, 0))
            
            #print 'len 111 = ', len(vertices)
            #print 'len 222 = ', len(facets)
            #print 'Rendering took ', clock() - t1clock
                    
        if self.renderCentroids:
            print 'self.leafCount = ', self.leafCount
            scalars = array(ones(self.leafCount)) * 0.05
            self.centroid_glyphs =  mlab.points3d(self.centroids[:, 0], self.centroids[:, 1], self.centroids[:, 2], scalars, scale_factor=.05, color = (1, 0, 0))#, s, color = (1, 0, 0), )
            
#        outline = mlab.outline(name = str('1'), line_width = 3, color = (0, 1, 0))
#        outline.outline_mode = 'full'        
#        center = self.leaves[0].center
#        radius = self.leaves[0].radius
#        print 'center = ', center
#        print 'radius= ', radius
#        outline.bounds = (center[0] - radius, center[0] + radius,
#                          center[1] - radius, center[1] + radius,
#                          center[2] - radius, center[2] + radius)        

        # temp - rendering points                
        self.RenderPoints()
        
        self.RenderOctreeGraph()   
                        
        mlab.title('Click on centroid')
                        
        picker = self.figure.on_mouse_pick(self.picker_callback)
        # Decrease the tolerance, so that we can more easily select a precise
        # point.
        picker.tolerance = 0.01
        
        self.figure.scene.disable_render = False
        
        # Here, we grab the points describing the individual glyph, to figure
        # out how many points are in an individual glyph.
        self.glyph_points = self.centroid_glyphs.glyph.glyph_source.glyph_source.output.points.to_array()
Beispiel #5
0
def plot_trajectory(perf_data, stimset, stim_class, symbols, post_stim_time=1):
        
    net = perf_data.net
    net.noise_std = 0.0
        
        
    mlab.figure(bgcolor=(0.5, 0.5, 0.5), fgcolor=(0.0, 0.0, 0.0))
    for symbol in symbols:
        stim_md5 = stimset.symbol_to_md5[symbol][0]
        stim = stimset.all_stims[stim_md5]
        net_sims = run_sim(net, {stim_md5:stim},
                           burn_time=100,
                           pre_stim_time = 1,
                           post_stim_time=max(25, post_stim_time),
                           num_trials=1)
        
        sim = net_sims[stim_md5]
        avg_resp = sim.responses[0, :, :].squeeze()
        stim_start = 0
        record_time = len(stim) + 1
        stim_end = len(stim) + post_stim_time
        
        stimsym = stimset.md5_to_symbol[stim_md5]
        #stim_str = '%s:%s (%0.2f)' % (stimsym, ''.join(['%d' % s for s in stim]), perf_data.logit_perf)
        stim_str = '%s:%s' % (stimsym, ''.join(['%d' % s for s in stim]))
    
        t = np.arange(0, stim_end)
        traj = mlab.plot3d(avg_resp[0:stim_end, 0], avg_resp[0:stim_end, 1], avg_resp[0:stim_end, 2], t,
                           colormap='hot', tube_radius=None)
        #mlab.points3d(avg_resp[stim_start, 0], avg_resp[stim_start, 1], avg_resp[stim_start, 2], scale_factor=0.300)
        mlab.points3d(avg_resp[record_time-1, 0], avg_resp[record_time-1, 1], avg_resp[record_time-1, 2], scale_factor=0.900)
    
    mlab.colorbar()
    if len(symbols) == 1:
        mlab.title(stim_str)
Beispiel #6
0
    def plot_u(u, x, xv, y, yv, t, n):
        """User action function for plotting."""
        if t[n] == 0:
            time.sleep(2)
        if plot_method == 1:
            # Works well with Gnuplot backend, not with Matplotlib
            st.mesh(x, y, u, title='t=%g' % t[n], zlim=[-1,1],
                    caxis=[-1,1])
        elif plot_method == 2:
            # Works well with Gnuplot backend, not with Matplotlib
            st.surfc(xv, yv, u, title='t=%g' % t[n], zlim=[-1, 1],
                  colorbar=True, colormap=st.hot(), caxis=[-1,1],
                  shading='flat')
        elif plot_method == 3:
            print 'Experimental 3D matplotlib...under development...'
            # Probably too slow
            #plt.clf()
            ax = fig.add_subplot(111, projection='3d')
            u_surf = ax.plot_surface(xv, yv, u, alpha=0.3)
            #ax.contourf(xv, yv, u, zdir='z', offset=-100, cmap=cm.coolwarm)
            #ax.set_zlim(-1, 1)
            # Remove old surface before drawing
            if u_surf is not None:
                ax.collections.remove(u_surf)
            plt.draw()
            time.sleep(1)
        elif plot_method == 4:
	    # Mayavi visualization
            mlab.clf()
            extent1 = (0, 20, 0, 20,-2, 2)
            s = mlab.surf(x , y, u,
                          colormap='Blues',
                          warp_scale=5,extent=extent1)
            mlab.axes(s, color=(.7, .7, .7), extent=extent1,
                      ranges=(0, 10, 0, 10, -1, 1),
                      xlabel='', ylabel='', zlabel='',
                      x_axis_visibility=False,
                      z_axis_visibility=False)
            mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
            mlab.text(6, -2.5, '', z=-4, width=0.14)
            mlab.colorbar(object=None, title=None,
                          orientation='horizontal',
                          nb_labels=None, nb_colors=None,
                          label_fmt=None)
            mlab.title('Gaussian t=%g' % t[n])
            mlab.view(142, -72, 50)
            f = mlab.gcf()
            camera = f.scene.camera
            camera.yaw(0)

        if plot_method > 0:
            time.sleep(0) # pause between frames
            if save_plot:
                filename = 'tmp_%04d.png' % n
		if plot_method == 4:
                    mlab.savefig(filename)  # time consuming!
		elif plot_method in (1,2):
                    st.savefig(filename)  # time consuming!
Beispiel #7
0
    def _populate_scene(self, scene, title):
        trajectories = self.data.root.positions.read()[:, :self.end, :]
        self.plot_uav_trajectories(trajectories, figure=scene.mayavi_scene)

        area = self.conf['area']
        scene.mayavi_scene.children[0].add_child(
            Outline(manual_bounds=True, bounds=area.flatten()))

        if not self.plain:
            mlab.title(title, figure=scene.mayavi_scene)
 def test_text(self):
     """ Test the text module.
     """
     data = np.random.random((3, 3, 3))
     src = mlab.pipeline.scalar_field(data)
     # Some smoke testing
     mlab.text(0.1, 0.9, 'foo')
     mlab.text(3, 3, 'foo', z=3)
     mlab.title('foo')
     # Check that specifying 2D positions larger than 1 raises an
     # error
     self.assertRaises(ValueError, mlab.text, 0, 1.5, 'test')
Beispiel #9
0
def plot_graphs(locs,stations,nbsta,CLUSTER,nbmin,threshold):
  from mayavi import mlab

  # Event coordinates
  stack_x,stack_y,stack_z=[],[],[]
  for loc in locs:
    stack_x.append(loc['x_mean'])
    stack_y.append(loc['y_mean'])
    stack_z.append(-loc['z_mean'])

  # Extract coordinates
  xsta,ysta,zsta=[],[],[]
  for sta in sorted(stations):
    xsta.append(stations[sta]['x'])
    ysta.append(stations[sta]['y'])
    zsta.append(stations[sta]['elev'])

  # 3D PLOT USING MAYAVI
  logging.info("Plotting...")
  s1=mlab.figure(1,bgcolor=(1,1,1),fgcolor=(0,0,0),size=(1000,900))
  s1=mlab.points3d(xsta,ysta,zsta,color=(1,0,0),scale_factor=0.05,mode='cube')
  s1=mlab.axes(extent=[362,370,7647,7653,-0.5,2.5],color=(0,0,0))
  s1=mlab.outline(extent=[362,370,7647,7653,-0.5,2.5],color=(0,0,0))
  s1=mlab.points3d(stack_x,stack_y,stack_z,scale_factor=0.1,color=(0.8,0.8,0.8))
  s1=mlab.title("threshold=%s, nbmin=%s"%(threshold,nbmin),height=0.1,size=0.35,color=(0,0,0))
  for i_ev in range(len(nbsta)):
    for i_c in range(1,len(CLUSTER)+1):
      if i_ev+1 in CLUSTER[i_c]:
        s1=mlab.points3d(stack_x[i_ev],stack_y[i_ev],stack_z[i_ev],scale_factor=0.1,color=tuple(CZ_Clust_2_color(100*(len(CLUSTER)-i_c)/len(CLUSTER))))
        s1=mlab.text3d(stack_x[i_ev],stack_y[i_ev],stack_z[i_ev],str(i_c),color=(0,0,0),scale=0.1)
  logging.info("Done!")
   
  logging.info("Plotting...")
  s2=mlab.figure(2,bgcolor=(1,1,1),fgcolor=(0,0,0),size=(1000,900))
  mlab.points3d(xsta,ysta,zsta,color=(1,0,0),scale_factor=0.05,mode='cube')
  mlab.axes(extent=[362,370,7647,7653,-0.5,2.5],color=(0,0,0))
  mlab.outline(extent=[362,370,7647,7653,-0.5,2.5],color=(0,0,0))
  mlab.points3d(stack_x,stack_y,stack_z,scale_factor=0.1,color=(0.8,0.8,0.8))
  mlab.title("threshold=%s, nbmin=%s"%(threshold,nbmin),height=0.1,size=0.35,color=(0,0,0))
  for ind_I in range(len(nbsta)):
    for ind_J in range(ind_I+1,len(nbsta)):
      W_IJ=nbsta[ind_I,ind_J]
      if W_IJ >= nbmin:
        mlab.points3d(stack_x[ind_J],stack_y[ind_J],stack_z[ind_J],scale_factor=0.1,color=(0,0,0))
        mlab.points3d(stack_x[ind_I],stack_y[ind_I],stack_z[ind_I],scale_factor=0.1,color=(0,0,0))
        d=(stack_x[ind_J]-stack_x[ind_I],stack_y[ind_J]-stack_y[ind_I],stack_z[ind_J]-stack_z[ind_I])
        norm=np.sqrt(d[0]**2+d[1]**2+d[2]**2)
        s2=mlab.quiver3d(stack_x[ind_I],stack_y[ind_I],stack_z[ind_I],d[0],d[1],d[2],color=tuple(CZ_W_2_color(W_IJ)),mode='2ddash',scale_factor=norm,scale_mode='scalar')
  #mlab.colorbar(s2)
  logging.info("Done!")
  mlab.show()
Beispiel #10
0
def analyze():
    mcs = []
    import mayavi.mlab as mlab
    
    for gamma_b in linspace(2*pi*1e3, 2*pi*17e3, 5):
        mc = MonteCarlo()
        mc.run_stats(35.5e-6, 0.1e-6, 300, gamma_b=gamma_b)
        mcs.append(mc)
        mlab.figure()
        mlab.barchart(mc.cov)
        mlab.axes()
        mlab.title("gamma_b/2pi = "+str(gamma_b/(2*pi)))
    return mcs
        
Beispiel #11
0
 def plot_3d_barchart(self, data_dict, Type, Freq):
     ''' Using the mayavi library, plot a 3D barchart of the data of requested type, and freq.'''
 
     extent_dim = self._get_extent(3)
     Xlocs,Xlabels,Ylocs,Ylabels = self._get_ticks(5,5,extent_dim)
     data = self.get_data_type(data_dict, Type)
     v_min,v_max = self.get_data_scale(data_dict, Type)
     freq_array = data_dict['freq']
     freq_ind = self.get_nearest_freq(freq_array,Freq)
     
     from mayavi import mlab
     mlab.figure( bgcolor=(0.5,0.5,0.5) )# grey bg
     mlab.barchart(data[freq_ind,:,:],vmin=v_min,vmax=v_max,auto_scale=False,colormap='jet',extent = extent_dim)
     mlab.title('Freq %.3e' %freq_array[freq_ind],size=5,height=0.1)
     mlab.show()
 def animation():
     for i in count():
         frame = i % all_verts.shape[2]
         verts = all_verts[:, :, frame].T
         mlab.clf()
         mlab.triangular_mesh(
             verts[:, 0],
             verts[:, 1],
             verts[:, 2],
             faces,
             color=(.9, .7, .7))
         fig.scene.z_minus_view()
         mlab.view(azimuth=180)
         mlab.title('mesh %d' % i, size=0.5, height=0, color=(0, 0, 0))
         yield
    def plotArm(self):
        """Method that plots SQ  in Mayavi"""
        #If you get error with the axes, do the following replacement:
        #in mayavi/modules/axes.py change self.configure_input_data(self.axes, src.outputs[0]) to self.configure_input_data(self.axes, src.outputs[0].output)
        mlab.figure(size=(800, 800), fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
        #mlab.mesh(self.paramx,self.paramy,self.paramz)

        for primitive in self.links:
            mlab.mesh(primitive.W[0], primitive.W[1], primitive.W[2])
            if primitive == self.links[0]:
                #give the base SQ axes and outline
                mlab.axes()
                mlab.outline()
        mlab.title('Arm')
        mlab.show()
        return 0
Beispiel #14
0
def mayavi_addTitle(fig, string, **kwargs):
    r"""Add a title to mayavi figure

    t = mayavi_addTitle(fig, string, **kwargs)

    Parameters
    ----------
    fig : mayavi figure
        Figure to add the title
    string : str
        Title string
    **kwargs : keyword list matching documentation
        Height, color, size are useful

    Returns
    -------
    t : mayavi object
        Title object

    Author
    ------
    Shankar Kulumani		GWU		[email protected]
    """
    t = mlab.title(string, figure=fig, **kwargs)
    return t
Beispiel #15
0
 def isosurface(self,vv=[4.0],clim=None,**kwargs):
     """
     3D isosurfaces of scalar data
     """
     if clim==None:
         clim = [self.data.min(), self.data.max()]
     
     # Create a new scene if there isn't one
     if not self.__dict__.has_key('fig'):
         self.newscene()
     
     # Convert the cell centred data into a scene source
     # Need to set use point (vertex) data
     src = mlab.pipeline.cell_to_point_data(self.ug)
     
     # Add the iso_surface module to the scene
     self.h=mlab.pipeline.iso_surface(src,contours=vv,line_width=1.0,vmin=clim[0],vmax=clim[1],**kwargs)
     
     # Add a colorbar if the isn't one
     if not self.__dict__.has_key('cb'):
         self.colorbar() 
         
     # Add a title if there isn't one
     if not self.__dict__.has_key('title'):
         self.title=mlab.title(self._SpatialgenTitle(),height=0.95,size=0.15)
Beispiel #16
0
    def sliceplane(self, plane_orientation='y_axes', **kwargs):
        """
        Applies the image plane widget to the dataset
        """

        if self.clim == None:
            self.clim = [self.data.min(), self.data.max()]

        # Create a new scene if there isn't one
        if 'fig' not in self.__dict__:
            self.newscene()

        src = mlab.pipeline.cell_to_point_data(self.ug)

        self.h = mlab.pipeline.scalar_cut_plane(
            src,
            plane_orientation=plane_orientation,
            view_controls=True,
            line_width=0.5)

        # Add a colorbar if the isn't one
        if 'cb' not in self.__dict__:
            self.colorbar()

        # Add a title if there isn't one
        if 'title' not in self.__dict__:
            self.title = mlab.title(self._SpatialgenTitle(),
                                    height=0.95,
                                    size=0.15)
Beispiel #17
0
def mlab_title(text, height=0.9, size=0.5):
    t = mlab.title(text=text, height=height, size=size)
    # May customize later on further with eg.:
    # t.width = 0.5
    # t.x_position = 0.25
    # t.y_position = 0.9
    return t
Beispiel #18
0
    def contour(self, vv=[10], clim=None, **kwargs):
        """
        Filled contour plot of scalar data
        """

        if clim == None:
            clim = [self.data.min(), self.data.max()]

        # Create a new scene if there isn't one
        if 'fig' not in self.__dict__:
            self.newscene()

        # Need to set use point (vertex) data
        src = mlab.pipeline.cell_to_point_data(self.ug)

        # Add the contour_surface module to the scene
        self.h = mlab.pipeline.contour_surface(src,
                                               contours=vv,
                                               line_width=1.0,
                                               vmax=clim[1],
                                               vmin=clim[0],
                                               **kwargs)
        self.h.contour.filled_contours = True  # This is the trick to fill the contours

        # Add a colorbar if the isn't one
        if 'cb' not in self.__dict__:
            self.colorbar()

        # Add a title if there isn't one
        if 'title' not in self.__dict__:
            self.title = mlab.title(self._SpatialgenTitle(),
                                    height=0.95,
                                    size=0.15)
Beispiel #19
0
 def volume(self,clim=None,**kwargs):
     """
     3D volumetric plot of scalar data
     
     **Warning** This is really slow and memory hungry!
     """
     if self.clim==None:
         self.clim = [self.data.min(), self.data.max()]
     
     # Create a new scene if there isn't one
     if not self.__dict__.has_key('fig'):
         self.newscene()
     
     # Convert the cell centred data into a scene source
     # Need to set use point (vertex) data
     src = mlab.pipeline.cell_to_point_data(self.ug)
     
     # Add the volume module to the scene
     self.h=mlab.pipeline.volume(src,**kwargs)
     
     # Add a colorbar if the isn't one
     if not self.__dict__.has_key('cb'):
         self.colorbar() 
         
     # Add a title if there isn't one
     if not self.__dict__.has_key('title'):
         self.title=mlab.title(self._SpatialgenTitle(),height=0.95,size=0.15)
Beispiel #20
0
    def surface(self, clim=None, **kwargs):
        """
        Surface plot of the scalar in the 'data' attribute with mayavi

        Works on the 2D and 3D data
        """

        if clim == None:
            clim = [self.data.min(), self.data.max()]

        # Create a new scene if there isn't one
        if 'fig' not in self.__dict__:
            self.newscene()

        src = mlab.pipeline.add_dataset(self.ug)
        self.h = mlab.pipeline.surface(src,
                                       vmin=clim[0],
                                       vmax=clim[1],
                                       **kwargs)

        # Add a colorbar if the isn't one
        if 'cb' not in self.__dict__:
            self.colorbar()

        # Add a title if there isn't one
        if 'title' not in self.__dict__:
            self.title = mlab.title(Spatial.genTitle(self),
                                    height=0.95,
                                    size=0.15)
Beispiel #21
0
    def isosurface(self, vv=[4.0], clim=None, **kwargs):
        """
        3D isosurfaces of scalar data
        """
        if clim == None:
            clim = [self.data.min(), self.data.max()]

        # Create a new scene if there isn't one
        if 'fig' not in self.__dict__:
            self.newscene()

        # Convert the cell centred data into a scene source
        # Need to set use point (vertex) data
        src = mlab.pipeline.cell_to_point_data(self.ug)

        # Add the iso_surface module to the scene
        self.h = mlab.pipeline.iso_surface(src,
                                           contours=vv,
                                           line_width=1.0,
                                           vmin=clim[0],
                                           vmax=clim[1],
                                           **kwargs)

        # Add a colorbar if the isn't one
        if 'cb' not in self.__dict__:
            self.colorbar()

        # Add a title if there isn't one
        if 'title' not in self.__dict__:
            self.title = mlab.title(self._SpatialgenTitle(),
                                    height=0.95,
                                    size=0.15)
Beispiel #22
0
 def contour(self,vv=[10],clim=None,**kwargs):
     """
     Filled contour plot of scalar data
     """
     
     if clim==None:
         clim = [self.data.min(), self.data.max()]
     
     # Create a new scene if there isn't one
     if not self.__dict__.has_key('fig'):
         self.newscene()
     
     # Need to set use point (vertex) data
     src = mlab.pipeline.cell_to_point_data(self.ug)
     
     # Add the contour_surface module to the scene
     self.h=mlab.pipeline.contour_surface(src,contours=vv,line_width=1.0,vmax=clim[1],vmin=clim[0],**kwargs)
     self.h.contour.filled_contours=True # This is the trick to fill the contours
     
     # Add a colorbar if the isn't one
     if not self.__dict__.has_key('cb'):
         self.colorbar() 
         
     # Add a title if there isn't one
     if not self.__dict__.has_key('title'):
         self.title=mlab.title(self._SpatialgenTitle(),height=0.95,size=0.15)
Beispiel #23
0
 def plotSQ(self):
     """Method that plots SQ  in Mayavi"""
     if self.loaded:
         mlab.figure(size=(800, 800), fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
         #mlab.mesh(self.paramx,self.paramy,self.paramz)
         mlab.mesh(self.W[0], self.W[1], self.W[2])
         mlab.outline()
         mlab.title('Superquadric: ' + 'a1: ' + str(self.a1) + '; ' + 'a2: ' \
          + str(self.a2) + '; ' + 'a3: ' + str(self.a3) + '; ' + 'epsilon1: ' \
          + str(self.epsilon1) + '; ' + 'epsilon2: ' + str(self.epsilon2) + '.')
         mlab.axes(
         )  #in mayavi/modules/axes.py change self.configure_input_data(self.axes, src.outputs[0]) to self.configure_input_data(self.axes, src.outputs[0].output)
         mlab.show()
     else:
         self.loadBasicSuperEllipsoid()
         self.plotSQ()
Beispiel #24
0
 def volume(self,clim=None,**kwargs):
     """
     3D volumetric plot of scalar data
     
     **Warning** This is really slow and memory hungry!
     """
     if self.clim==None:
         self.clim = [self.data.min(), self.data.max()]
     
     # Create a new scene if there isn't one
     if not self.__dict__.has_key('fig'):
         self.newscene()
     
     # Convert the cell centred data into a scene source
     # Need to set use point (vertex) data
     src = mlab.pipeline.cell_to_point_data(self.ug)
     
     # Add the volume module to the scene
     self.h=mlab.pipeline.volume(src,**kwargs)
     
     # Add a colorbar if the isn't one
     if not self.__dict__.has_key('cb'):
         self.colorbar() 
         
     # Add a title if there isn't one
     if not self.__dict__.has_key('title'):
         self.title=mlab.title(self._SpatialgenTitle(),height=0.95,size=0.15)
 def update_scene():
     mlab.clf(fig1)  # 清空figure
     vis_points = points[file_i]  # 取出要显示的点云
     vis_points = (vis_points * 1.5 + np.array([1.0, 1.0, 1.0])) * 50  # 对点云进行缩放
     # show point clouds colorized with activations
     activations = mlab.points3d(vis_points[:, 0],
                                 vis_points[:, 1],
                                 vis_points[:, 2],
                                 vis_points[:, 2],
                                 scale_factor=3.0,
                                 scale_mode='none',
                                 figure=fig1)
     mlab.title(str(file_i), color=(0, 0, 0), size=0.3, height=0.01)
     text = '<--- (press g for previous' + 50 * '' + '(press h for next)---->'
     mlab.text(0.01, 0.01, text, color=(0, 0, 0), width=0.98)
     mlab.orientation_axes()
     return
Beispiel #26
0
def show_obj(surface_points_, title, color='b'):
    mlab.figure(bgcolor=(0, 0, 0), fgcolor=(0.7, 0.7, 0.7), size=(1000, 1000))
    if color == 'b':
        color_f = (0, 0, 1)
    elif color == 'r':
        color_f = (1, 0, 0)
    elif color == 'g':
        color_f = (0, 1, 0)
    else:
        color_f = (1, 1, 1)
    points_ = surface_points_
    mlab.points3d(points_[:, 0],
                  points_[:, 1],
                  points_[:, 2],
                  color=color_f,
                  scale_factor=.0007)
    mlab.title(title, size=0.5)
Beispiel #27
0
 def plot_u(u, x, xv, y, yv, t, n):
     print " ploting"
     if t[n] == 0:
         time.sleep(2)
     if plot_method == 1:
         mesh(x, y, u, title='t=%g' % t[n], zlim=[-1,1],
              caxis=[-1,1])
     elif plot_method == 2:
         surfc(xv, yv, u, title='t=%g' % t[n], zlim=[-1, 1],
               colorbar=True, colormap=hot(), caxis=[-1,1],
               shading='flat')
     elif plot_method == 3:
         # mayavi plotting
         mlab.clf()
         extent1 = (0, 20, 0, 20,-2, 2)
         s = mlab.surf(x , y, u, colormap='Blues', warp_scale=5,
                      extent=extent1)
         mlab.axes(s, color=(.7, .7, .7), extent=extent1,
         ranges=(0, 10, 0, 10, -1, 1), xlabel='', ylabel='',
         zlabel='',
         x_axis_visibility=False, z_axis_visibility=False)
         mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
         mlab.text(2, -2.5, '', z=-4, width=0.1)
         mlab.colorbar(object=None, title=None, orientation='horizontal',
                       nb_labels=None, nb_colors=None, label_fmt=None)
         mlab.title('t=%g' % t[n])
         mlab.view(142, -72, 50)
         f = mlab.gcf()
         camera = f.scene.camera
         camera.yaw(0)
         #g = mlab.figure()
         #g.scene.movie_maker.record = True
         
     
     if plot_method > 0:
         if not os.path.exists(path):
             os.makedirs(path)
         time.sleep(0) # pause between frames
         if save_plot and plot_method == 3:
             filename = '%s/%08d.png'%(path,n)
             mlab.savefig(filename)  # time consuming!
         elif save_plot and plot_method != 3:
             filename = '%s/%08d.png'%(path,n)
             savefig(filename)  # time consuming!
    def action(u, x, y, t, n):
        if n > 1:
            # every timestep exactly 2 cells change. If the wave is at the
            # boundary, only two cells change.
            msg = "the plug should travel exactly one cell per time step"
            cells_with_new_value = (u-last_solution) != 0
            print(np.sum(cells_with_new_value))
            assert ((np.sum(cells_with_new_value) == 4) |
                    (np.sum(cells_with_new_value) == 2) |
                    (np.sum(cells_with_new_value) == 0)), msg

        ms2.mlab_source.set(z=u)
        mlab.title('pulse, t = {:.2f}'.format(t[n]))
        last_solution[:, :] = u[:, :]
        # concate filename with zero padded index number as suffix
        filename = os.path.join(out_path, '{}_{:06d}{}'.format(prefix, n, ext))
        print(filename)
        mlab.savefig(filename=filename)
        return
Beispiel #29
0
    def update_scene():

        #  clear figure
        mlab.clf(fig1)

        # Rescale points for visu
        p1 = (query * 1.5 + np.array([1.0, 1.0, 1.0])) * 50.0
        p2 = (supports * 1.5 + np.array([1.0, 1.0, 1.0])) * 50.0

        l1 = p1[:, 2] * 0
        l1[file_i] = 1

        l2 = p2[:, 2] * 0 + 2
        l2[neighbors[file_i]] = 3

        # Show point clouds colorized with activations
        activations = mlab.points3d(p1[:, 0],
                                    p1[:, 1],
                                    p1[:, 2],
                                    l1,
                                    scale_factor=2.0,
                                    scale_mode='none',
                                    vmin=0.0,
                                    vmax=3.0,
                                    figure=fig1)

        activations = mlab.points3d(p2[:, 0],
                                    p2[:, 1],
                                    p2[:, 2],
                                    l2,
                                    scale_factor=3.0,
                                    scale_mode='none',
                                    vmin=0.0,
                                    vmax=3.0,
                                    figure=fig1)

        # New title
        mlab.title(str(file_i), color=(0, 0, 0), size=0.3, height=0.01)
        text = '<--- (press g for previous)' + 50 * ' ' + '(press h for next) --->'
        mlab.text(0.01, 0.01, text, color=(0, 0, 0), width=0.98)
        mlab.orientation_axes()

        return
def sph_plot(l,m):

    theta_range = np.linspace(0,2*np.pi,90,endpoint=True)
    phi_range   = np.linspace(0,  np.pi,45,endpoint=True)
    
    theta,phi = np.meshgrid(theta_range,phi_range)
    
    Ylm = real_sph_harm(m,l,theta,phi)
    rho = abs(Ylm)
    
    X = rho * cos(theta) * sin(phi)
    Y = rho * sin(theta) * sin(phi)
    Z = rho *              cos(phi)

    if 0:
        Ylm_scaled = ( Ylm - np.amin(Ylm) )/(np.amax(Ylm) - np.amin(Ylm))
    else:
        Ylm_scaled = Ylm
    
    if len(sys.argv) > 3:
        # plain old mplot3d
        fig = figure()
        ax = Axes3D(fig)
        ax.plot_surface(X, Y, Z, 
                    facecolors=cm.jet(Ylm_scaled), 
                    rstride=1, cstride=1,
                    antialiased=True )
    
    
        gscale = [x * 0.5 for x in [-1, 1]]
        ax.auto_scale_xyz(gscale, gscale, gscale)
        show()
        
    else:
        # try fancy mayavi2 stuff
        from mayavi import mlab
        
        s = mlab.mesh(X, Y, Z, scalars=Ylm_scaled, vmax=1,vmin=-1) #, extent=[-1, 1, -1, 1, -1, 1])
        mlab.colorbar(s, orientation='vertical',nb_labels=5)
        mlab.title("Real Ylm, l="+str(l)+" m="+str(m),size=0.35,height=0.9)
        mlab.outline(s, extent=[-1, 1, -1, 1, -1, 1])
        mlab.axes(s, extent=[-1, 1, -1, 1, -1, 1],nb_labels=3)
        mlab.show()
Beispiel #31
0
def save_plot(cur_frame_file, source_pc, target_pc, all_avg_l2_dist, config_params):
    mlab.figure( bgcolor=(0, 0, 0))
    mlab.points3d(source_pc[:, 0], source_pc[:, 1], source_pc[:, 2], color=(0.3, 0.45, 1), mode='sphere',
                  scale_factor=0.007, opacity=0.6)
    mlab.points3d(target_pc[:, 0], target_pc[:, 1], target_pc[:, 2], color=(0.8, 0.85, 0.45), mode='sphere',
                  scale_factor=0.007, opacity=0.6)
    if config_params['fid_indices'] is not None:
        mlab.points3d(source_pc[config_params['fid_indices']['source'], 0],
                      source_pc[config_params['fid_indices']['source'], 1],
                      source_pc[config_params['fid_indices']['source'], 2],
                      color=(0.8, 0.2, 0.2), mode='sphere', scale_factor=0.02)
        mlab.points3d(target_pc[config_params['fid_indices']['target'], 0],
                      target_pc[config_params['fid_indices']['target'], 1],
                      target_pc[config_params['fid_indices']['target'], 2],
                      color=(0.2, 0.8, 0.2), mode='sphere', scale_factor=0.02)
    mlab.view(azimuth=135, elevation=55)
    mlab.title(f'avg l2 dist - {all_avg_l2_dist:9.5f}', size=0.8, height=0.7)
    mlab.savefig(cur_frame_file, magnification=2)
    mlab.close()
Beispiel #32
0
    def action(u, x, xv, y, yv, t, n):
        #print 'action, t=',t,'\nu=',u, '\Nx=',x, '\Ny=', y
        if t[n] == 0:
            time.sleep(2)
        if plot_u == 1:
            mesh(x, y, u, title='t=%g' % t[n], zlim=[-1,1],
                 caxis=[-1,1])
        elif plot_u == 2:
            surf(xv, yv, u, title='t=%g' % t[n], zlim=[-1, 1],
                 colorbar=True, colormap=hot(), caxis=[-1,1])

        elif plot_u == 3:
            # mayavi plotting
            mlab.clf()
            extent1 = (0, 20, 0, 20,-2, 2)
            s = mlab.surf(x , y, u, colormap='Blues', warp_scale=5,extent=extent1)
            mlab.axes(s, color=(.7, .7, .7), extent=extent1,
            ranges=(0, 10, 0, 10, -1, 1), xlabel='', ylabel='',
            zlabel='',
            x_axis_visibility=False, z_axis_visibility=False)
            mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
            mlab.text(2, -2.5, '', z=-4, width=0.1)
            mlab.colorbar(object=None, title=None, orientation='horizontal', nb_labels=None, nb_colors=None, label_fmt=None)
            mlab.title('Gaussian t=%g' % t[n])

            mlab.view(142, -72, 50)
            f = mlab.gcf()
            camera = f.scene.camera
            camera.yaw(0)



        
        if plot_u > 0:
            path = 'Figures_wave2D'
            if not os.path.exists(path):
                os.makedirs(path)
            time.sleep(0) # pause between frames
            if save_plot and plot_u != 3:
                filename = '%s/tmp_%08d.png' % (path, n)
            elif save_plot and plot_u == 3:
                filename = '%s/tmp_%08d.png' % (path, n)
                mlab.savefig(filename)  # time consuming!
Beispiel #33
0
def plot_gamma_motor(subject_name, subjects_dir, dir_n, elec_up, mlabViewX,
                     mlabViewY, saveDataBool):
    #make info file
    ch_names = [str(x) for x in np.arange(64)]
    dig_ch_pos = dict(zip(ch_names, elec_up / 1000))
    mon = mne.channels.DigMontage(dig_ch_pos=dig_ch_pos)
    info = mne.create_info(ch_names, 1000., ch_types='ecog', montage=mon)

    name = listdir(dir_n)
    for nam in name:
        if nam != '.DS_Store':
            gama_t = loadmat(dir_n + nam)
            res_re = gama_t['res']
            s = np.mean(res_re[:, 15:, 0], axis=1)  #gamma
            s = np.interp(s, (s.min(), s.max()), (0, 1))
            fig = mlab.figure('gamma_motor_' + nam, size=(800, 700))
            plot_alignment(info,
                           subject=subject_name,
                           subjects_dir=subjects_dir,
                           surfaces=['pial'],
                           ecog=False,
                           fig=fig)
            obj = mlab.points3d(elec_up[:, 0] / 1000,
                                elec_up[:, 1] / 1000,
                                elec_up[:, 2] / 1000,
                                s,
                                colormap='rainbow',
                                scale_mode='none',
                                scale_factor=0.002)
            mlab.colorbar(object=obj,
                          title='gamma',
                          orientation='vertical',
                          nb_labels=8,
                          nb_colors=None,
                          label_fmt=None)
            mlab.title(nam[:-4], size=0.2, height=0.015)

            #chouse point of view
            mlab.view(mlabViewX, mlabViewY)
            if saveDataBool:
                mlab.savefig(nam[:-4] + '.png')
                mlab.savefig(nam[:-4] + '.x3d')
Beispiel #34
0
    def update_scene():

        #  clear figure
        mlab.clf(fig1)

        # Plot new data feature
        points = clouds[file_i]
        labels = cloud_labels[file_i]
        if cloud_normals is not None:
            normals = cloud_normals[file_i]
        else:
            normals = None

        # Rescale points for visu
        points = (points * 1.5 + np.array([1.0, 1.0, 1.0])) * 50.0

        # Show point clouds colorized with activations
        activations = mlab.points3d(points[:, 0],
                                    points[:, 1],
                                    points[:, 2],
                                    labels,
                                    scale_factor=3.0,
                                    scale_mode='none',
                                    figure=fig1)
        if normals is not None and show_normals:
            activations = mlab.quiver3d(points[:, 0],
                                        points[:, 1],
                                        points[:, 2],
                                        normals[:, 0],
                                        normals[:, 1],
                                        normals[:, 2],
                                        scale_factor=10.0,
                                        scale_mode='none',
                                        figure=fig1)

        # New title
        mlab.title(str(file_i), color=(0, 0, 0), size=0.3, height=0.01)
        text = '<--- (press g for previous)' + 50 * ' ' + '(press h for next) --->'
        mlab.text(0.01, 0.01, text, color=(0, 0, 0), width=0.98)
        mlab.orientation_axes()

        return
    def update_scene():

        # 清空当前窗口
        mlab.clf(fig1)

        # 对点云进行缩放以显示
        p1 = (query * 1.5 + np.array([1.0, 1.0, 1.0])) * 50.0
        p2 = (supports * 1.5 + np.array([1.0, 1.0, 1.0])) * 50.0

        l1 = p1[:, 2] * 0  # query中所有点设置为0
        l1[file_i] = 1  # 第file_i个中心点,设置为1

        l2 = p2[:, 2] * 0 + 2  # supports中所有点设置为2
        l2[neighbors[file_i]] = 3  # 第file_i个邻居点组设置为3

        # 显示点云
        activations = mlab.points3d(p1[:, 0],
                                    p1[:, 1],
                                    p1[:, 2],
                                    l1,
                                    scale_factor=2.0,
                                    scale_mode='none',
                                    vmin=0.0,
                                    vmax=3.0,
                                    figure=fig1)

        activations = mlab.points3d(p2[:, 0],
                                    p2[:, 1],
                                    p2[:, 2],
                                    l2,
                                    scale_factor=3.0,
                                    scale_mode='none',
                                    vmin=0.0,
                                    vmax=3.0,
                                    figure=fig1)

        mlab.title(str(file_i), color=(0, 0, 0), size=0.3, height=0.01)
        text = '<--- (press g for previous)' + 50 * ' ' + '(press h for next) --->'
        mlab.text(0.01, 0.01, text, color=(0, 0, 0), width=0.98)
        mlab.orientation_axes()

        return
Beispiel #36
0
def test_reconstruct():
    """Read a OBJ file, reconstruct it's surface using VTK and plot
    """
    filename = './data/shape_model/ITOKAWA/itokawa_low.obj'
    ratio = 0.5
    v, f = wavefront.read_obj(filename)
    dv, df = wavefront.decimate_numpy(v, f, ratio)
    rv, rf = wavefront.reconstruct_numpy(v)

    # create some figures
    orig_fig = mlab.figure()
    reconstruct_fig = mlab.figure()
    _ = graphics.draw_polyhedron_mayavi(v, f, orig_fig)
    mlab.title('Original OBJ')
    _ = graphics.draw_polyhedron_mayavi(rv, rf, reconstruct_fig)
     
    mlab.title('Reconstructed OBJ')

    # display both and complete test
    print('Now compare the two images')
Beispiel #37
0
def show_grasps_range(obj, grasps, ply_name=None, min_score=0.0, max_score=3.2):
    m = np.array(grasps)
    m = m[m[:, 1] < max_score]
    m = m[m[:, 1] >= min_score]
    if not len(m) > 0:
        return
    m = m[np.random.choice(len(m), size=5, replace=True)]  # 随机选择25个显示

    ags = GpgGraspSampler(gripper, sample_config)

    mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0.7, 0.7, 0.7), size=(1024, 768))
    for grasp in m:
        ags.display_grasps3d(grasp[0], 'g')
    if ply_name is None:
        ags.show_surface_points(obj)
    else:
        mlab.pipeline.surface(mlab.pipeline.open(ply_name))
    print("Show [%.1f-%.1f)" % (min_score, max_score))
    mlab.title("[%.1f-%.1f)" % (min_score, max_score), size=0.5, color=(0, 0, 0))
    mlab.show()
Beispiel #38
0
def plot_3d(index, data):
    if not contour_toggle_3d:
        grid = mlab.pipeline.scalar_field(data)
        vol = mlab.pipeline.volume(grid, vmin=1e-06)

        # Change the opacity to something more reasonable
        otf = PiecewiseFunction()
        otf.add_point(0.0, 0.0)
        otf.add_point(0.315, 0.3)
        vol._otf = otf
        vol._volume_property.set_scalar_opacity(otf)
    else:
        mlab.contour3d(data, transparent=True)

    mlab.axes()
    mlab.title(" ".join([field, "mcs = %d" % (index * output_frequency)]),
               size=1,
               opacity=0.8)
    mlab.colorbar(orientation="vertical")
    mlab.show()
    return
Beispiel #39
0
def title(text, color=(0, 0, 0), size=0.3, height=1):
    """
    Draw a title on a Mayavi figure.

    .. warning:: Must be called **after** you've plotted something (e.g.,
        prisms) to the figure. This is a bug.

    Parameters:

    * text : str
        The title
    * color : tuple = (r, g, b)
        RGB of the color of the text
    * size : float
        The size of the text
    * height : float
        The height where the title will be placed on the screen

    """
    _lazy_import_mlab()
    mlab.title(text, color=color, size=size, height=height)
Beispiel #40
0
def t_data_plot(data,dataname,title_name,num_contours,zdr_flag=0,data_min=1.01):
    #camera1=(0.0,0.0,307.7645695540192,np.array([ 79.66195959, 74.22460988,9.96509266]))
    #camera2=(45.00000000000005,54.735610317245346,389.61669188814807,np.array([61.00005691,87.63795239,6.8619907]))
    camera3=(45.0,54.735610317245346,607.35769190957262,np.array([89.80421373,137.88978957,7.30599671]))

    size_x,size_y,size_z=data.shape
    mlab.figure(dataname,bgcolor=(1,1,1),fgcolor=(0,0,0),size=(700,600))

    if zdr_flag==1:
        fig_data=mlab.contour3d(data[:,:,:],vmin=data_min,colormap='jet')
    else:
        fig_data=mlab.contour3d(data[:,:,:],vmin=-30.0,colormap='jet')
    fig_data.contour.number_of_contours=num_contours
    fig_data.actor.property.opacity=0.4
    mlab.title(dataname)
    mlab.outline(color=(0,0,0),extent=[0,size_x,0,size_y,0,size_z])
    colorbar=mlab.colorbar(title=title_name,orientation='vertical',nb_labels=10)
    colorbar.scalar_bar_representation.position=[0.85,0.1]
    colorbar.scalar_bar_representation.position2=[0.12,0.9]
    mlab.view(*camera3)
    mlab.show()
Beispiel #41
0
def title(text, color=(0, 0, 0),  size=0.3, height=1):
    """
    Draw a title on a Mayavi figure.

    .. warning:: Must be called **after** you've plotted something (e.g.,
        prisms) to the figure. This is a bug.

    Parameters:

    * text : str
        The title
    * color : tuple = (r, g, b)
        RGB of the color of the text
    * size : float
        The size of the text
    * height : float
        The height where the title will be placed on the screen

    """
    _lazy_import_mlab()
    mlab.title(text, color=color, size=size, height=height)
Beispiel #42
0
def plot_accuracy(subject_name, subjects_dir, dir_n, elec_up, mlabViewX,
                  mlabViewY, saveDataBool):
    #make info file
    ch_names = [str(x) for x in np.arange(64)]
    dig_ch_pos = dict(zip(ch_names, elec_up / 1000))
    mon = mne.channels.DigMontage(dig_ch_pos=dig_ch_pos)
    info = mne.create_info(ch_names, 1000., ch_types='ecog', montage=mon)

    name = listdir(dir_n)
    for nam in name:
        if nam != '.DS_Store':
            s = np.loadtxt(dir_n + nam)
            s = np.nan_to_num(s[:, 1])
            fig = mlab.figure('accuracy_' + nam, size=(800, 700))
            plot_alignment(info,
                           subject=subject_name,
                           subjects_dir=subjects_dir,
                           surfaces=['pial'],
                           ecog=False,
                           fig=fig)
            obj = mlab.points3d(elec_up[:, 0] / 1000,
                                elec_up[:, 1] / 1000,
                                elec_up[:, 2] / 1000,
                                s,
                                colormap='rainbow',
                                scale_mode='none',
                                scale_factor=0.002)
            mlab.colorbar(object=obj,
                          title='accuracy',
                          orientation='vertical',
                          nb_labels=8,
                          nb_colors=None,
                          label_fmt=None)
            mlab.title(nam[:-4], size=0.2, height=0.015)
            #chouse point of view
            mlab.view(mlabViewX, mlabViewY)
            if saveDataBool:
                mlab.savefig(nam[:-4] + '.png')
                mlab.savefig(nam[:-4] + '.x3d')
Beispiel #43
0
def plot_alpha_touch(subject_name, subjects_dir, file_n, elec_up, mlabViewX,
                     mlabViewY, saveDataBool):
    #make info file
    ch_names = [str(x) for x in np.arange(64)]
    dig_ch_pos = dict(zip(ch_names, elec_up / 1000))
    mon = mne.channels.DigMontage(dig_ch_pos=dig_ch_pos)
    info = mne.create_info(ch_names, 1000., ch_types='ecog', montage=mon)

    data_t = loadmat(file_n)
    res_re = data_t['res']
    for i in range(5):
        s = np.mean(res_re[:, :5, i], axis=1)  #alpha
        s = np.interp(s, (s.min(), s.max()), (0, 1))
        fig = mlab.figure('alpha_touch_' + str(i), size=(800, 700))
        plot_alignment(info,
                       subject=subject_name,
                       subjects_dir=subjects_dir,
                       surfaces=['pial'],
                       ecog=False,
                       fig=fig)
        obj = mlab.points3d(elec_up[:, 0] / 1000,
                            elec_up[:, 1] / 1000,
                            elec_up[:, 2] / 1000,
                            s,
                            colormap='rainbow',
                            scale_mode='none',
                            scale_factor=0.002)
        mlab.colorbar(object=obj,
                      title='alpha',
                      orientation='vertical',
                      nb_labels=8,
                      nb_colors=None,
                      label_fmt=None)
        mlab.title('touch ' + str(i + 1), size=0.2, height=0.015)
        #chouse point of view
        mlab.view(mlabViewX, mlabViewY)
        if saveDataBool:
            mlab.savefig('alpha_touch_' + str(i + 1) + '.png')
            mlab.savefig('alpha_touch_' + str(i + 1) + '.x3d')
Beispiel #44
0
def plot_u(u, x, y, t, n, do=False, save_plot=False):
    """User action function for plotting."""
    if do == False:
        return 0
    else:
        if t[n] == 0:
            time.sleep(2)
    # Mayavi visualization
        mlab.clf()
        extent1 = (0, 20, 0, 20, -2, 2)
        s = mlab.surf(x, y, u, colormap='Blues', extent=extent1)
        mlab.axes(s,
                  color=(.7, .7, .7),
                  extent=extent1,
                  ranges=(0, 10, 0, 10, -1, 1),
                  xlabel='',
                  ylabel='',
                  zlabel='',
                  x_axis_visibility=False,
                  z_axis_visibility=False)
        mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
        mlab.text(6, -2.5, '', z=-4, width=0.14)
        mlab.colorbar(object=None,
                      title=None,
                      orientation='horizontal',
                      nb_labels=None,
                      nb_colors=None,
                      label_fmt=None)
        mlab.title('Waves t=%g' % t[n])
        mlab.view(142, -72, 50)
        f = mlab.gcf()
        camera = f.scene.camera
        camera.yaw(0)

        time.sleep(0)  # pause between frames
        if save_plot:
            filename = 'tmp_%04d.png' % n
            mlab.savefig('./animations/' + filename)  # time consuming!
        mlab.show()
Beispiel #45
0
def test4_1():
	# 场景初始化
	figure = mlab.gcf()

	# 用mlab.points3d建立红色和白色小球的集合
	x1, y1, z1 = np.random.random((3, 10))
	red_glyphs = mlab.points3d(x1, y1, z1, color = (1, 0, 0), resolution = 10)

	x2, y2, z2 = np.random.random((3, 10))
	white_glyphs = mlab.points3d(x2, y2, z2, color = (0.9, 0.9, 0.9), resolution = 10)
	
	outline = mlab.outline(line_width = 3)
	outline.outline_mode = "cornered"
	outline.bounds = (x1[0] - 0.1, x1[0] + 0.1,
					  y1[0] - 0.1, y1[0] + 0.1,
					  z1[0] - 0.1, z1[0] + 0.1,				
		)
	# 处理选取的事件

	glyph_points = red_glyphs.glyph.glyph_source.glyph_source.output.points.to_array()


	def picker_callback(picker):
		if picker.actor in red_glyphs.actor.actors:
			point_id = int(picker.point_id / glyph_points.shape[0])
			if point_id != -1:
				x, y, z = x1[point_id], y1[point_id], z1[point_id]
				outline.bounds = (x - 0.1, x + 0.1, 
								  y - 0.1, y + 0.1,
								  z - 0.1, z + 0.1,
									)


	# 建立相应机制

	picker = figure.on_mouse_pick(picker_callback)
	mlab.title("click on the red balls")
	mlab.show()
Beispiel #46
0
def plot_time_instance(path,t,value,var_num,plot_specs_dict):
    # make one plot at fixed time with multiple slices

    #f = mlab.figure(size=(2000,1500))
    f = mlab.figure(size=(400,300))
    file_list = value.split()
    num_eqn = int(plot_specs_dict['num_eqn'])
    
    minval = plot_specs_dict['minval'][var_num]
    maxval = plot_specs_dict['maxval'][var_num]
    for file_name in file_list:
        plot_slice(path,file_name,f,var_num,num_eqn,minval,maxval)
    mlab.title('Solution at t=' + str(t) + '\n q ' + str(var_num+1),\
                size=0.25)
    cube_range = [plot_specs_dict['domain'][0][0],  
                  plot_specs_dict['domain'][0][1],  
                  plot_specs_dict['domain'][1][0],  
                  plot_specs_dict['domain'][1][1],  
                  plot_specs_dict['domain'][2][0],  
                  plot_specs_dict['domain'][2][1]]
    mlab.axes(extent = cube_range, line_width=3.0)
    ax = mlab.colorbar(orientation='vertical')
    mlab.outline(line_width=0.02)
    #f.scene.x_minus_view()

    binary_list = [-1,1]
    for j in binary_list:
        for k in binary_list:
            for l in binary_list:
                f.scene._update_view(j, k, l, 0, 0, 0)
                save_filename = 'test_output_' + str(j) + '_'\
                                               + str(k) + '_'\
                                               + str(l) + '_'\
                                               + str(t) + '.png'
                mlab.show()
                #mlab.savefig(save_filename)
    f.scene.close()
    return None
Beispiel #47
0
def plot_with_labels(data, label, subsample=None, size=1, color={}, title='', img=None, img_path=None):
    """
    data: Nx3 numpy array
    label: N, numpy array
    subsample: number of subsampled input point cloud
    size: size of points
    color: dict int->tuple(3)
    """
    if img is not None:
        img_path = os.path.join(os.environ['HOME'], 'tmp', 'tmp.jpg')
        cv.imwrite(img_path, img)
    if img_path is not None:
        p = subprocess.Popen(['eog', img_path])
    if subsample is not None and subsample < data.shape[0]:
        ids = np.random.choice(data.shape[0], subsample, replace=False)
        data = data[ids]
        label = label[ids]
    _plot_color(data, label, 0.01*size, color=color)
    if title:
        mlab.title(title)
    mlab.show()
    if img_path is not None:
        p.wait()
Beispiel #48
0
def plot_with_cmap(data, color, num_bins=10, subsample=None, size=1, title=''):
    """
    data: Nx3 numpy array
    color: N, numpy array
    num_bins: int, discretize color into num_bins bins
    subsample: int, number of subsampled input point cloud
    """
    if subsample is not None and subsample < data.shape[0]:
        ids = np.random.choice(data.shape[0], subsample, replace=False)
        data = data[ids]
        color = color[ids]
    assert data.shape[0] == len(color)
    cmap = plt.cm.get_cmap('Spectral')
    c1, c2 = float(min(color)), float(max(color))
    color = (color-c1) / (c2-c1)
    EPS = 1e-4
    bins = np.linspace(-EPS, 1+EPS, num_bins+1)
    for i in xrange(num_bins):
        x = data[(color >= bins[i]) & (color < bins[i+1])]
        c = cmap(1-bins[i])[:3]
        mlab.points3d(x[:,0], x[:,1], x[:,2], color=c, scale_factor=0.01*size)
    if title:
        mlab.title(title)
    mlab.show()
def vis_multiple(multi_points,
                 save_folder,
                 save_name,
                 normalize=True,
                 save_gif=True,
                 delete=False,
                 show=False):
    # points = np.loadtxt(full_path, delimiter=',')
    # points = points[:50, :]
    fig = mlab.figure(size=(1024, 1024))
    for idx, points in enumerate(multi_points):
        if normalize:
            points[:, :3] = pc_normalize(points[:, :3])
        x, y, z = np.split(points[:, :3], 3, axis=-1)
        # vx, vy, vz = np.split(points[:, 3:], 3, axis=-1)
        if save_gif:
            fig.scene.movie_maker.record = True
            fig.scene.movie_maker.directory = './'
        selected_color = colors[idx]
        s = points3d(x,
                     y,
                     z,
                     color=selected_color,
                     scale_factor=0.01,
                     opacity=0.5)
        # mlab.quiver3d(x, y, z, vx, vy, vz, mode='arrow', scale_factor=0.03)
        # ms = s.mlab_source
        # animate(ms, points, transformer)
        axes = mlab.axes()
        axes.axes.fly_mode = 'none'
        axes.axes.bounds = np.array([0, 0.4, 0.4, 0., 0., 0.4])
        mlab.title(save_name, size=0.1)
    if show:
        mlab.show()
    if save_gif:
        save(save_name=save_name, images_folder=save_folder, delete=delete)
Beispiel #50
0
    def streammesh(self,nx=30,ny=30,color=False,**kwargs):
        """
        Plots streamlines originating from points on a mesh
        """

        
        # Create a new scene if there isn't one
        if not self.__dict__.has_key('fig'):
            self.newscene()
        
        if not self.vector_overlay:
            self.loadVectorVTK()
            
        if color:
            src = mlab.pipeline.cell_to_point_data(self.ug) # This colours the streamlines by the scalar field
        else:
            src = mlab.pipeline.add_dataset(self.ug)
             
        X = np.linspace(self.xv.min(),self.xv.max(),nx)
        y0 =self.yv.min()
        y1 = self.yv.max()
        streams=[]
        for x in X:
            stream=mlab.pipeline.streamline(src,seedtype='line',**kwargs)
            stream.stream_tracer.initial_integration_step = 0.1
            stream.stream_tracer.maximum_propagation=10000.0
            stream.stream_tracer.integration_direction = 'both'
            stream.seed.widget.point1 = [x,y1,0.1]
            stream.seed.widget.point2 = [x,y0,0.1]
            stream.seed.widget.resolution = ny
            streams.append(stream)

        # Go back through and turn them off
        for stream in streams:
            stream.seed.widget.enabled = False
            
        # Add a colorbar if the isn't one
        if not self.__dict__.has_key('cb'):
            self.h=stream
            self.colorbar() 
            
        # Add a title if there isn't one
        if not self.__dict__.has_key('title'):
            self.title=mlab.title(self._SpatialgenTitle(),height=0.95,size=0.15)
         
        return streams
Beispiel #51
0
def plot_events(cluster,locs,stations,x,y,z,i,threshold,nbmin,area,nbsta):
  from mayavi import mlab

  # Stations coordinates
  xsta,ysta,zsta=[],[],[]
  for sta in sorted(stations):
    xsta.append(stations[sta]['x'])
    ysta.append(stations[sta]['y'])
    zsta.append(stations[sta]['elev'])

  z_ph=[-elt for elt in z]

  # Initial hypocentral parameters
  xini, yini, zini, zini_ph, to_ini = coord_cluster(cluster[i],locs)

  s=mlab.figure(i,bgcolor=(1,1,1),fgcolor=(0,0,0),size=(1000,900))
  mlab.clf()
  s=mlab.points3d(xini,yini,zini_ph,color=(1,1,0),scale_factor=0.2) # yellow : initial locations
  s=mlab.points3d(xsta,ysta,zsta,color=(1,0,0),scale_factor=0.05,mode='cube')
  s=mlab.points3d(x,y,z_ph,color=(0,1,1),scale_factor=0.2) # cyan : new locations
  s=mlab.axes(extent=area,color=(0,0,0)) # axe des z positif vers le haut
  s=mlab.outline(extent=area,color=(0,0,0))
  s=mlab.title("cluster=%s, threshold=%s, nbmin=%s"%(i,threshold,nbmin),height=0.1,size=0.35,color=(0,0,0))


  if len(cluster[i]) < 20:
    from CZ_W_2_color import *
    for ind_I in range(len(cluster[i])):
      for ind_J in range(ind_I+1,len(cluster[i])):
        ev_I=cluster[i][ind_I]-1
        ev_J=cluster[i][ind_J]-1
        W_IJ=nbsta[ev_I,ev_J]
        if W_IJ >= nbmin:
          mlab.points3d(xini[ind_J],yini[ind_J],zini_ph[ind_J],scale_factor=0.1,color=(0,0,0))
          mlab.points3d(xini[ind_I],yini[ind_I],zini_ph[ind_I],scale_factor=0.1,color=(0,0,0))
          d=(xini[ind_J]-xini[ind_I],yini[ind_J]-yini[ind_I],zini_ph[ind_J]-zini_ph[ind_I])
          norm=np.sqrt(d[0]**2+d[1]**2+d[2]**2)
          s2=mlab.quiver3d(xini[ind_I],yini[ind_I],zini_ph[ind_I],d[0],d[1],d[2],color=tuple(CZ_W_2_color(W_IJ)),mode='2ddash',scale_factor=norm,scale_mode='scalar')

  mlab.show()
Beispiel #52
0
    def sliceplane(self,plane_orientation='y_axes',**kwargs):
        """
        Applies the image plane widget to the dataset
        """        
            
        if self.clim==None:
            self.clim = [self.data.min(), self.data.max()]
        
        # Create a new scene if there isn't one
        if not self.__dict__.has_key('fig'):
            self.newscene()

        src = mlab.pipeline.cell_to_point_data(self.ug)
        
        self.h=mlab.pipeline.scalar_cut_plane(src,plane_orientation=plane_orientation,view_controls=True,line_width=0.5)
        
       # Add a colorbar if the isn't one
        if not self.__dict__.has_key('cb'):
            self.colorbar() 
            
        # Add a title if there isn't one
        if not self.__dict__.has_key('title'):
            self.title=mlab.title(self._SpatialgenTitle(),height=0.95,size=0.15) 
Beispiel #53
0
    def surface(self,clim=None,**kwargs):
        """
        Surface plot of the scalar in the 'data' attribute with mayavi
        
        Works on the 2D and 3D data
        """

        if clim==None:
            clim = [self.data.min(), self.data.max()]
        
        # Create a new scene if there isn't one
        if not self.__dict__.has_key('fig'):
            self.newscene()
        
        src = mlab.pipeline.add_dataset(self.ug)
        self.h=mlab.pipeline.surface(src,vmin=clim[0],vmax=clim[1],**kwargs)
        
        # Add a colorbar if the isn't one
        if not self.__dict__.has_key('cb'):
            self.colorbar() 
            
        # Add a title if there isn't one
        if not self.__dict__.has_key('title'):
            self.title=mlab.title(Spatial.genTitle(self),height=0.95,size=0.15)
Beispiel #54
0
def plot_dipole_locations(dipoles, trans, subject, subjects_dir=None,
                          bgcolor=(1, 1, 1), opacity=0.3,
                          brain_color=(0.7, 0.7, 0.7), mesh_color=(1, 1, 0),
                          fig_name=None, fig_size=(600, 600), mode='cone',
                          scale_factor=0.1e-1, colors=None, verbose=None):
    """Plot dipole locations

    Only the location of the first time point of each dipole is shown.

    Parameters
    ----------
    dipoles : list of instances of Dipole | Dipole
        The dipoles to plot.
    trans : dict
        The mri to head trans.
    subject : str
        The subject name corresponding to FreeSurfer environment
        variable SUBJECT.
    subjects_dir : None | str
        The path to the freesurfer subjects reconstructions.
        It corresponds to Freesurfer environment variable SUBJECTS_DIR.
        The default is None.
    bgcolor : tuple of length 3
        Background color in 3D.
    opacity : float in [0, 1]
        Opacity of brain mesh.
    brain_color : tuple of length 3
        Brain color.
    mesh_color : tuple of length 3
        Mesh color.
    fig_name : str
        Mayavi figure name.
    fig_size : tuple of length 2
        Mayavi figure size.
    mode : str
        Should be ``'cone'`` or ``'sphere'`` to specify how the
        dipoles should be shown.
    scale_factor : float
        The scaling applied to amplitudes for the plot.
    colors: list of colors | None
        Color to plot with each dipole. If None default colors are used.
    verbose : bool, str, int, or None
        If not None, override default verbose level (see mne.verbose).

    Returns
    -------
    fig : instance of mlab.Figure
        The mayavi figure.

    Notes
    -----
    .. versionadded:: 0.9.0
    """
    from mayavi import mlab
    from matplotlib.colors import ColorConverter
    color_converter = ColorConverter()

    trans = _get_mri_head_t(trans)[0]
    subjects_dir = get_subjects_dir(subjects_dir=subjects_dir,
                                    raise_error=True)
    fname = os.path.join(subjects_dir, subject, 'bem',
                         'inner_skull.surf')
    points, faces = read_surface(fname)
    points = apply_trans(trans['trans'], points * 1e-3)

    from .. import Dipole
    if isinstance(dipoles, Dipole):
        dipoles = [dipoles]

    if mode not in ['cone', 'sphere']:
        raise ValueError('mode must be in "cone" or "sphere"')

    if colors is None:
        colors = cycle(COLORS)

    fig = mlab.figure(size=fig_size, bgcolor=bgcolor, fgcolor=(0, 0, 0))
    with warnings.catch_warnings(record=True):  # FutureWarning in traits
        mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2],
                             faces, color=mesh_color, opacity=opacity)

    for dip, color in zip(dipoles, colors):
        rgb_color = color_converter.to_rgb(color)
        with warnings.catch_warnings(record=True):  # FutureWarning in traits
            mlab.quiver3d(dip.pos[0, 0], dip.pos[0, 1], dip.pos[0, 2],
                          dip.ori[0, 0], dip.ori[0, 1], dip.ori[0, 2],
                          opacity=1., mode=mode, color=rgb_color,
                          scalars=dip.amplitude.max(),
                          scale_factor=scale_factor)
    if fig_name is not None:
        mlab.title(fig_name)
    if fig.scene is not None:  # safe for Travis
        fig.scene.x_plus_view()

    return fig
Beispiel #55
0
import os.path as op

from mayavi import mlab

import mne
from mne.io import Raw, read_raw_ctf, read_raw_bti, read_raw_kit
from mne.datasets import sample, spm_face
from mne.viz import plot_trans

print(__doc__)

bti_path = op.abspath(op.dirname(mne.__file__)) + '/io/bti/tests/data/'
kit_path = op.abspath(op.dirname(mne.__file__)) + '/io/kit/tests/data/'
raws = dict(
    Neuromag=Raw(sample.data_path() + '/MEG/sample/sample_audvis_raw.fif'),
    CTF_275=read_raw_ctf(spm_face.data_path() +
                         '/MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds'),
    Magnes_3600wh=read_raw_bti(bti_path + 'test_pdf_linux',
                               bti_path + 'test_config_linux',
                               bti_path + 'test_hs_linux'),
    KIT=read_raw_kit(kit_path + 'test.sqd'),
)

for system, raw in raws.items():
    # We don't have coil definitions for KIT refs, so exclude them
    ref_meg = False if system == 'KIT' else True
    fig = plot_trans(raw.info, trans=None, dig=False, eeg_sensors=False,
                     meg_sensors=True, coord_frame='meg', ref_meg=ref_meg)
    mlab.title(system)
Beispiel #56
0
 def title(*args, **kwargs):
     mlab.title(*args, **kwargs)
Beispiel #57
0
def envelopes3d_group_by(results, 
                         outcome,
                         groupBy = 'policy', 
                         discretesize = None,
                         logSpace=False,
                         ymin = None,
                         ymax = None):
    '''
    
    Function for making 3d envelopes. In contrast to the envelopes in 
    :mod:`graphs`, this version shows the density for every time step, instead 
    of only for the end state. Note that this function makes an envelope for 
    only 1 outcome. This envelopes will group the results based on the
    specified uncertainty. The user can supply a discretesize function
    to control the grouping in case of parameterUncertainties. This function
    will make a separate envelope for each group.
    
    :param results: The return from :meth:`run experiments`.
    :param outcome: Specify the name of outcome of interest for which you want to make 
                    the 3d envelopes.
    :param groupBy: The uncertainty to group by. (default=policy)
    :param discretesize: a discretesize function to control the grouping in case of parameterUncertainties
    :param logSpace: Boolean, if true, the log of the input data is used
    :param ymin: If provided, lower bound for the KDE, if not, ymin = np.min(results.get(outcome))
    :param ymax: If provided, lower bound for the KDE, if not, ymax = np.max(results.get(outcome))
    
    '''
    def f(x, y, results):
        """
        function that performs the kde for each timestep
        """
        
        x1 = x[:,0]
        y1 = y[0,:]
        results = np.asarray(results)
        
        z = []
        for i in range(len(list(x1))):
            data = results[:, i]
            try:
                z1 = kde.gaussian_kde(data)
                z1 = z1.evaluate(y1)
            except:
                z1 = np.zeros(shape=y1.shape)
            z.append(z1)
        z = np.asarray(z)
        z = np.log(z+1)
    
        return z
    
    #prepare the data
    experiments, results = results

    #get time axis
    try:
        time = results.pop('TIME')[0, :]
    except:
        time =  np.arange(0, results.values()[0].shape[1])
    
    
    def make_logical(cases, criterion, interval=False):
        if interval:
            
            return (cases[groupBy] >= criterion[0]) & (cases[groupBy] < criterion[1]) 
        else:
            return cases[groupBy]== criterion
    
    
    #get the results for the specific outcome of interest
    results = results.get(outcome)
    
    #log results
    if logSpace:
        results = np.log(results+1)
   
    #generate the grid
    if ymin == None:
        ymin = np.min(results)
        info("ymin: %s" % ymin)
    if ymax == None:
        ymax = np.max(results)
        info("ymax: %s" % ymax)

    length = min(100, results.shape[1])
    y = np.arange(ymin, ymax, (ymax-ymin)/length)
    X, Y = np.meshgrid(time, y)

    z = []

    #do the preparation for grouping by
    interval=False
    if (experiments[groupBy].dtype == np.float32) |\
       (experiments[groupBy].dtype == np.float64) |\
       ((experiments[groupBy].dtype == np.int) & (len(set(experiments[groupBy])) > 5)):
        interval=True
        if discretesize:
            categories = discretesize(experiments[groupBy])
        else:
            categories = make_continuous_grouping_specifiers(experiments[groupBy])
    else:
        categories = set(experiments[groupBy])
        
    
    for category in categories:
        if interval:
            info("calculating kde for (%s, %s)" % (category))
        else:
            info("calculating kde for %s" % (category))
        logical = make_logical(experiments, category, interval)
        
        Z = f(X.T,Y.T, results=results[logical])
        z.append(Z)

    #calculate the kde for the grid
    #visualize results
    fig = mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
    
    fig.scene.disable_render = True
    for i, category in enumerate(categories):        
        if interval:
            info("plotting (%s, %s)" % (category))
        else:
            info("plotting %s" % (category))
        
        Z = z[i]
        extent = (-14+i*10,-6+i*10, 0,10, 0,5)
        s = mlab.mesh(X,Y, Z.T, extent=extent)
        mlab.outline(s, color=(.7, .7, .7), extent=extent)
        if i==0:
            mlab.axes(s,
                      extent=extent,
                      xlabel = '',
                      ylabel = '',
                      zlabel = 'density',
                      x_axis_visibility=False,
                      y_axis_visibility=False, 
                      z_axis_visibility=False) 
        
        category_name = repr(category)
            
        mlab.text(-16+10*i, i+10, category_name, z=-2, width=0.14)
    fig.scene.disable_render = False
    mlab.title(outcome, line_width=0.5)
    mlab.show()
def plot_3D_spectrum(infile="bloch.tmp", outfile=None, trajectory=None,
                     reorder=False, jump=100., mayavi=False, limits=None,
                     sort=False, png=None, full=False, dryrun=False,
                     interpolate=False):
    """Visualize the eigenvalue spectrum with mayavi.mlab's mesh (3D) and
    matplotlib's pcolormesh (2D).

        Parameters:
        -----------
            infile: str
                Input file.
            outfile: str
                Whether to save the reordered and sorted array before plotting.
            reorder: bool
                Whether to properly sort the input array.
            jump: float
                Whether to remove jump in the eigenvalue surface that exceed
                a given value.
            mayavi: bool
                Whether to produce 3D plots. If false, heatmaps are plotted.
            limits: list
                Set the x- and ylim: [xmin, xmax, ymin, ymax]
            sort: bool
                Sorts the eigenvalues such that one is larger than the other.
            png: str
                Save the heatmap plots in a .png file.
            full: bool
                Add additional heatmap plots.
            trajectory: str
                Plot a trajectory on top of the heatmap.
            dryrun: bool
                Whether to only return the approximate EP position.
            interpolate: bool
                Whether to interpolate |K0-K1| before printing the EP position.
    """

    eps, delta, ev0r, ev0i, ev1r, ev1i = np.loadtxt(infile).T
    ev0 = ev0r + 1j*ev0i
    ev1 = ev1r + 1j*ev1i
    # workound if precision changes for multiple runs
    delta = np.around(delta, decimals=8)
    len_eps, len_delta = [len(np.unique(x)) for x in eps, delta]

    if reorder:
        print "reordering..."
        eps, delta, ev0, ev1 = reorder_file(infile)

    if sort:
        tmp0, tmp1 = 1.*ev0, 1.*ev1
        tmp0[ev1 > ev0] = ev1[ev1 > ev0]
        tmp1[ev1 > ev0] = ev0[ev1 > ev0]

        ev0, ev1 = 1.*tmp0, 1.*tmp1

    # get eps/delta meshgrid
    try:
        eps, delta, ev0, ev1 = [x.reshape(len_eps, len_delta) for
                                x in (eps, delta, ev0, ev1)]
    except ValueError as e:
        print "Data matrix has missing values. Removing outliers:"
        mask = find_outliers(eps)
        len_masked_eps = len(np.unique(eps[mask]))
        eps, delta, ev0, ev1 = [x[mask].reshape(len_masked_eps, -1) for
                                x in (eps, delta, ev0, ev1)]

    # set x/y limits
    if limits:
        eps_min, eps_max = limits[:2]
        delta_min, delta_max = limits[2:]
        limit_mask = ((eps > eps_min) & (eps < eps_max) &
                      (delta > delta_min) & (delta < delta_max))
        for X in ev0, ev1:
            X[~limit_mask] = np.nan

    if outfile:
        v = (eps, delta, ev0.real, ev0.imag, ev1.real, ev1.imag)
        v = np.array([x.flatten() for x in v])
        np.savetxt(outfile, v.T, fmt='%.18f')
        sys.exit()

    # remove Nan values
    ev0 = np.ma.masked_where(np.isnan(ev0), ev0)
    ev1 = np.ma.masked_where(np.isnan(ev1), ev1)

    # print minimum of eigenvalue difference
    i, j = np.unravel_index(np.sqrt((ev0.real-ev1.real)**2 +
                                    (ev0.imag-ev1.imag)**2).argmin(),
                            ev0.shape)
    print "Approximate EP location:"
    print "eps_EP =", eps[i, j]
    print "delta_EP =", delta[i, j]

    if dryrun and not interpolate:
        sys.exit()

    cmap = plt.get_cmap('Blues_r')
    cmap = plt.get_cmap('RdBu_r')
    if mayavi:
        # extent = (0, 1, 0, 1, 0, 1)
        # real part
        for e in ev0, ev1:
            mask = np.zeros_like(eps).astype(bool)
            mask[np.abs(np.diff(e.real, axis=0)) > jump] = True
            mask[np.abs(np.diff(e.real, axis=1)) > jump] = True

            try:
                mask = np.logical_or(mask, ~limit_mask)
            except:
                pass
            mlab.figure(0, bgcolor=(0.5, 0.5, 0.5))
            m1 = mlab.mesh(eps.real, delta.real, e.real, mask=mask)
                           # extent=extent)
            m1.actor.actor.scale = (1,1,0.1)

        mlab.title("Real part", opacity=0.25)
        mlab.axes(color=(0, 0, 0), nb_labels=3,
                  xlabel="epsilon", ylabel="delta", zlabel="Re(K)")

        # imag part
        for e in ev0, ev1:
            mask = np.zeros_like(eps).astype(bool)
            mask[np.abs(np.diff(e.imag, axis=0)) > jump] = True
            mask[np.abs(np.diff(e.imag, axis=1)) > jump] = True

            mlab.figure(1, bgcolor=(0.5, 0.5, 0.5))
            try:
                mask = np.logical_or(mask, ~limit_mask)
            except:
                pass
            m2 = mlab.mesh(eps.real, delta.real, e.imag, mask=mask)
                           # extent=extent)
            m2.actor.actor.scale = (1,1,10)

        mlab.title("Imaginary part", opacity=0.25)
        mlab.axes(color=(0, 0, 0), nb_labels=3,
                  xlabel="epsilon", ylabel="delta", zlabel="Im(K)")

        mlab.show()

    elif full:
        f, axes = plt.subplots(nrows=4, ncols=2, sharex=True, sharey=True)
        (ax1, ax2), (ax3, ax4), (ax5, ax6), (ax7, ax8) = axes

        plt.xticks(rotation=70)
        plt.suptitle(infile)

        ax1.set_title(r"$\Re K_0$")
        im1 = ax1.pcolormesh(eps, delta, ev0.real, cmap=cmap)
        ax2.set_title(r"$\Im K_0$")
        im2 = ax2.pcolormesh(eps, delta, ev0.imag, cmap=cmap)
        ax3.set_title(r"$\Re K_1$")
        im3 = ax3.pcolormesh(eps, delta, ev1.real, cmap=cmap)
        ax4.set_title(r"$\Im K_1$")
        im4 = ax4.pcolormesh(eps, delta, ev1.imag, cmap=cmap)

        ax5.set_title(r"$|\Re K_0 - \Re K_1|^2$")
        Z_real = abs(ev1.real - ev0.real)
        im5 = ax5.pcolormesh(eps, delta, Z_real, cmap=cmap, vmin=0)
        ax6.set_title(r"$|\Im K_0 - \Im K_1|^2$")
        Z_imag = abs(ev1.imag - ev0.imag)
        im6 = ax6.pcolormesh(eps, delta, Z_imag, cmap=cmap, vmin=0)

        Z = np.sqrt(Z_imag**2 + Z_real**2)
        ax7.set_title(r"$\sqrt{(\Re K_0 - \Re K_1)^2 + (\Im K_0 - \Im K_1)^2}$")
        im7 = ax7.pcolormesh(eps, delta, Z, cmap=cmap, vmin=0)

        Z = (Z_imag**2 + Z_real**2)**0.25
        ax8.set_title(r"$\sqrt[4]{(\Re K_0 - \Re K_1)^2 + (\Im K_0 - \Im K_1)^2}$")
        im8 = ax8.pcolormesh(eps, delta, Z, cmap=cmap, vmin=0)

        for im, ax in zip((im1, im2, im3, im4, im5, im6, im7, im8),
                          (ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8)):
            ax.set_xlabel("epsilon")
            ax.set_ylabel("delta")
            ax.set_xlim(eps.min(), eps.max())
            ax.set_ylim(delta.min(), delta.max())
            f.colorbar(im, ax=ax)
            plt.setp(ax.xaxis.get_majorticklabels(), rotation=45)

        plt.tight_layout()
        if png:
            plt.savefig(png)
        else:
            plt.show()
    else:
        f, ax = plt.subplots(nrows=1, ncols=1, sharex=True, sharey=True)

        plt.xticks(rotation=90)
        plt.suptitle(infile)

        Z_real = abs(ev1.real - ev0.real)
        Z_imag = abs(ev1.imag - ev0.imag)
        Z = np.sqrt(Z_imag**2 + Z_real**2)

        ax.set_title(r"$\sqrt{(\Re K_0 - \Re K_1)^2 + (\Im K_0 - \Im K_1)^2}$")

        # add one column and row to meshgrids such that meshgrid doesn't cut
        # away any important data
        eps_u = np.unique(eps)
        delta_u = np.unique(delta)
        eps0, delta0 = np.meshgrid(np.concatenate((eps_u, [2*eps.max()])),
                                   np.concatenate((delta_u, [2*delta.max()])))
        Z0 = np.c_[Z, Z[:, -1]]
        Z0 = np.vstack((Z0, Z0[-1]))

        if interpolate:
            from scipy.interpolate import griddata
            x = np.linspace(eps.min(), eps.max(), 500)
            y = np.linspace(delta.min(), delta.max(), 1000)
            X, Y = np.meshgrid(x, y)
            Z0 = griddata((eps.ravel(), delta.ravel()),
                          Z.ravel(), (X, Y), method='cubic')
            i, j = np.unravel_index(Z0.argmin(), Z0.shape)
            print "eps_EP_interpolated =", X[i, j]
            print "delta_EP_interpolated =", Y[i, j]
            eps0, delta0 = X.T, Y.T

            if dryrun:
                sys.exit()

        # im = ax.pcolormesh(eps0.T, delta0.T, np.log(Z0),
        im = ax.pcolormesh(eps0.T, delta0.T, np.log(Z0),
                           cmap=cmap)

        # correct ticks
        xoffset = np.diff(eps_u).mean()/2
        yoffset = np.diff(delta_u).mean()/2
        ax.set_xticks(eps_u + xoffset)
        ax.set_yticks(delta_u + yoffset)

        # ticklabels
        # ax.set_xticklabels(np.around(eps_u, decimals=4))
        # ax.set_yticklabels(np.around(delta_u, decimals=4))

        # axis labels
        ax.set_xlabel("epsilon")
        ax.set_ylabel("delta")
        if limits:
            print limits
            ax.set_xlim(limits[0], limits[1])
            ax.set_ylim(limits[2], limits[3])
        else:
            ax.set_xlim(eps.min(), eps.max() + 2*xoffset)
            ax.set_ylim(delta.min(), delta.max() + 2*yoffset)

        f.colorbar(im, ax=ax)

        plt.setp(ax.xaxis.get_majorticklabels(), rotation=45)
        plt.subplots_adjust(top=0.875)

        if trajectory:
            # n, eps, delta = np.loadtxt(trajectory, unpack=True)[:3]
            eps, delta = np.loadtxt(trajectory, unpack=True)[:2]
            plt.plot(eps, delta, "r-")
            # for n, (eps, delta) in enumerate(zip(eps, delta)):
            #     plt.text(eps, delta, str(n), fontsize=12)

        if png:
            plt.savefig(png)
        else:
            plt.show()
def ToyModel3d(sample):
    """
    This script configure the 3D render motor (Mayavi) to show an interactive
    reconstruction of the asphalt mixture sample
    """
    src = mlab.pipeline.scalar_field(sample)
    inverse_lut = False
    colors = 5

    iso = mlab.pipeline.iso_surface(src, contours=[1], opacity=0.4, colormap = 'blue-red')
    iso.module_manager.scalar_lut_manager.reverse_lut = inverse_lut
    iso.module_manager.scalar_lut_manager.number_of_colors = colors

    ipw = mlab.pipeline.image_plane_widget(src, plane_orientation='y_axes', slice_index=10, colormap = 'blue-red')
    ipw.module_manager.scalar_lut_manager.reverse_lut = inverse_lut
    ipw.module_manager.scalar_lut_manager.number_of_colors = colors

    scp = mlab.pipeline.scalar_cut_plane(src, colormap = 'blue-red')
    scp.module_manager.scalar_lut_manager.reverse_lut = inverse_lut
    scp.module_manager.scalar_lut_manager.number_of_colors = colors

    #Set the Mayavi Colorbar Ranges
    scp.module_manager.scalar_lut_manager.use_default_range = False
    scp.module_manager.scalar_lut_manager.scalar_bar.position2 = array([ 0.1,  0.8])
    scp.module_manager.scalar_lut_manager.scalar_bar.position = array([ 0.01,  0.15])
    scp.module_manager.scalar_lut_manager.data_range = array([ 0.,  2.])
    scp.module_manager.scalar_lut_manager.scalar_bar.position2 = array([ 0.1,  0.8])
    scp.module_manager.scalar_lut_manager.scalar_bar.position = array([ 0.01,  0.15])
    scp.module_manager.scalar_lut_manager.data_range = array([ 0.,  2.])


    engine = mlab.get_engine()

    textAggregate = Text()
    textMastic = Text()
    textVoids = Text()

    engine.add_filter(textAggregate, scp.module_manager)
    engine.add_filter(textMastic, ipw.module_manager)
    engine.add_filter(textVoids, iso.module_manager)


    textAggregate.text = 'Aggregate'
    textMastic.text = 'Mastic'
    textVoids.text = 'Air Voids'

    textAggregate.actor.text_scale_mode = 'viewport'
    textMastic.actor.text_scale_mode = 'viewport'
    textVoids.actor.text_scale_mode = 'viewport'

    textAggregate.actor.minimum_size = array([ 1, 10])
    textMastic.actor.minimum_size = array([ 1, 10])
    textVoids.actor.minimum_size = array([ 1, 10])

    textAggregate.actor.position = array([ 0.115,  0.7 ])
    textMastic.actor.position = array([ 0.115,  0.45])
    textVoids.actor.position = array([ 0.115,  0.23])


    mlab.orientation_axes()
    mlab.title("Asphalt Mixture Reconstruction", size=0.25)
    mlab.colorbar(title='Material', orientation='vertical', nb_labels=0, nb_colors=3)
    mlab.show()