def showDsweep():
    k_s_sweep = [10**(x-5) for x in range(10)]
    sl_div_diam_sweep = [5.0*(x+1)/1000 for x in range(20)]
    vol_ratio_sweep = [5.0*(x+1)/100 for x in range(10)]    
    
    Dmsd = numpy.load(data_dir + "/D_numpy.npy")
    kDa = 1.660538921e-30;
    mass = 40.0*kDa; 
    viscosity = 8.9e-4; 
    diameter = 5e-9; 
    T = 300.0; 
    Dbase = k_b*T/(3.0*numpy.pi*viscosity*diameter);
    Dmsd = Dmsd/Dbase
    
    mlab.figure(1, size=(800, 800), fgcolor=(1, 1, 1),
                                    bgcolor=(0.5, 0.5, 0.5))
    mlab.clf()
    contours = numpy.arange(0.01,2,0.2).tolist()
    obj = mlab.contour3d(Dmsd,contours=contours,transparent=True,vmin=contours[0],vmax=contours[-1])
    outline = mlab.outline(color=(.7, .7, .7),extent=(0,10,0,20,0,10))
    axes = mlab.axes(outline, color=(.7, .7, .7),
            nb_labels = 5,
            ranges=(k_s_sweep[0], k_s_sweep[-1], sl_div_diam_sweep[0], sl_div_diam_sweep[-1], vol_ratio_sweep[0], vol_ratio_sweep[-1]), 
            xlabel='spring stiffness', 
            ylabel='step length',
            zlabel='volume ratio')
    mlab.colorbar(obj,title='D',nb_labels=5)

    mlab.show()
Exemplo n.º 2
0
    def show_volume(self, bbox):
        """
        show the volume with the given bounding box
        """
        # load the data
        with h5py.File(self.h5fn, 'r') as f:
            seg1 = f["segmentation"]["labels"][bbox[2]:bbox[5],bbox[1]:bbox[4],bbox[0]:bbox[3]]
            raw = f["raw"]["volume"][bbox[2]:bbox[5],bbox[1]:bbox[4],bbox[0]:bbox[3]]
        
        print "Drawing volume"
        t0 = time.time()
        
        #draw everything
        fig1 = mlab.figure(1, size=(500,450))
        mlab.clf(fig1)
        visCell.drawImagePlane(fig1, raw, 'gist_ncar')
        visCell.drawVolumeWithoutReferenceCell(fig1, seg1, np.array((-1,)), (0,0,1),0.5)
        with h5py.File(self.h5fn, 'r') as f:
            visCell.drawLabels(fig1, f, seg1, bbox)

        fig2 = mlab.figure(2, size=(500,450))
        mlab.clf(fig2)

        visCell.draw2DView(fig2, raw[20:-20,:,:], seg1[20:-20,:,:], -1)
        
        t = time.time() - t0
        print "Time for drawing:",t
Exemplo n.º 3
0
def plotOrs(*ptss):

    mlab.figure(34); mlab.clf()

    r = 1
    phi, theta = 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.mesh(x,y,z, colormap='gray',opacity=.2)
    
    
    
    colors = [(1,0,0),(0,1,0),(0,0,1)]
    print len(colors)
    print len(ptss)
    for (pts,col) in izip(ptss,colors):
        print col        
        ors = normr(pts)
        # Create a sphere
        
        x,y,z = ors.T
        
        mlab.points3d(x,y,z,color=col)
        mlab.plot3d(x,y,z,color=col,tube_radius=.025)
Exemplo n.º 4
0
 def _render_model(self):
   figure = mlab.gcf()
   mlab.clf()
   s = mlab.triangular_mesh(self.coords[:,0], self.coords[:,1],
                            self.coords[:,2], self.tri_index,
                            color=(0.5,0.5,0.5))
   return s.scene
Exemplo n.º 5
0
def _plot_subnetwork_graph(Theta, coords, network_ix):
    (x, y, z) = coords
    p = Theta.shape[0]
    network_ix = network_ix * np.ones((p,))
    # 3D glass image of brain
    fig = mlab.figure(bgcolor=(1, 1, 1), size=(900, 769))
    mlab.clf()
    fig.scene.disable_render = True
    vmin = np.min(Theta[np.abs(Theta) != 0])
    vmax = np.max(np.abs(Theta))
    tubes, nodes = plot_graph(-Theta, x, y, z,
                              node_size=.6,
                              edge_vmin=vmin,
                              edge_vmax=vmax,
                              node_colormap='spectral',
                              node_color=(0.2, 0.2, 0.2),
                              node_scalar=network_ix,
                              tube_radius=.15)
    lut = tubes.module_manager.scalar_lut_manager.lut.table.to_array()
    lut = 255 * plt.cm.hot_r(np.linspace(0, 1, 256))
    tubes.module_manager.scalar_lut_manager.lut.table = lut
    tubes.update_pipeline()
    #nodes.module_manager.scalar_lut_manager.lut.table = color
    nodes.update_pipeline()

    viz3d.plot_anat_3d(outline_color=(0, 0, 0), gyri_opacity=0.15)
    fig.scene.disable_render = False
    return fig
Exemplo n.º 6
0
    def update_plot(self,s):   
	mlab.clf()
        self.s = s
	self.s1 = self.vessel()
        self.src = mlab.pipeline.scalar_field(self.s, 
                                         scaling=(1, 1, 1), 
                                         origin=(1,1,1))
        
        self.src.spacing = [ 0.75,1, 1]
        
        #iso surface
	if ((self.n_min == 1) and (self.n_max== 1)):
	    mincon = 0
	    self.m=mlab.pipeline.iso_surface(self.src, vmin=0, vmax=1, contours=200, opacity=0.3) 
	else:
	    mincon = self.n_min/100
	    self.m=mlab.pipeline.iso_surface(self.src, vmin=self.n_min/100, vmax=self.n_max/100, contours=200, opacity=0.3)
	
	vol=s
	vol[nonzero(vol>=mincon)]=1
	vol[nonzero(vol<mincon)]=0
	volvox=sum(vol)*0.0156
	volvox = unicode(volvox)
	print sum(vol)
	print "volume objek = ", volvox, "cm3"
	
        self.m.module_manager.scalar_lut_manager.show_scalar_bar = True
	self.src1 = mlab.pipeline.scalar_field(self.s1,scaling=(1, 1, 1),origin=(1,1,1))
	self.src1.spacing = [0.75,1 , 1] 
	self.m1=mlab.pipeline.iso_surface(self.src1,contours=[self.s1.min()+0.01*self.s1.ptp(), ],opacity=0.1)         
        self.mlab.colorbar(orientation='vertical', title="capasitance") 
	cancer_vol = "Ca. Volume: " + volvox + " cm3"
	#self.mlab.text(0.1,0.1,unicode(cancer_vol))
        self.mlab.show()     
Exemplo n.º 7
0
	def _plotbutton1_fired(self):
		mlab.clf()
		self.loaddata()
		self.sregion[np.where(self.sregion<self.datamin)] = self.datamin
		self.sregion[np.where(self.sregion>self.datamax)] = self.datamax

		# The following codes from: http://docs.enthought.com/mayavi/mayavi/auto/example_atomic_orbital.html#example-atomic-orbital
		field = mlab.pipeline.scalar_field(self.sregion)     # Generate a scalar field
		colored = self.sregion
		vol=self.sregion.shape
		for v in range(0,vol[2]-1):
			colored[:,:,v] = self.extent[4] + v*(-1)*abs(self.hdr['cdelt3'])
		new = field.image_data.point_data.add_array(colored.T.ravel())
		field.image_data.point_data.get_array(new).name = 'color'
		field.image_data.point_data.update()

		field2 = mlab.pipeline.set_active_attribute(field, point_scalars='scalar')
		contour = mlab.pipeline.contour(field2)
		contour2 = mlab.pipeline.set_active_attribute(contour, point_scalars='color')

		mlab.pipeline.surface(contour2, colormap='jet', opacity=self.opacity)
		
		## Insert a continuum plot
		##im = pyfits.open('g28_SMA1.cont.image.fits')
		##dat = im[0].data
		##dat0 = dat[0]
		##channel = dat0[0]
		##region = np.swapaxes(channel[self.xstart:self.xend,self.ystart:self.yend]*1000.,0,1)
		##field = mlab.contour3d(region, colormap='gist_ncar')
		##field.contour.minimum_contour = 5

		self.field = field
		self.labels()
		mlab.view(azimuth=0, elevation=0, distance='auto')
		mlab.show()
Exemplo n.º 8
0
 def Lname(self,Lname):
     # change layout and build/load
     if hasattr(self,'_maya_fig') and self._maya_fig._is_running:
         mlab.clf()
     self._L = Layout(Lname)
     self._Lname = Lname
     self.reset_config()
Exemplo n.º 9
0
    def set_info(self, X, y_dict, selected_y_key, dim_names, val_mapper, learner, title=None, include_std=False):
            
        assert X.shape[1] == len(dim_names)
        
        self.original_dim = len(dim_names)
        if len(dim_names) == 2:
            dim_names.append( 'None' )
            X = np.hstack( (X, np.zeros( (X.shape[0],1) ) ) )

        mlab.clf()

        self.learner = learner
        self.X = X
        self.y_dict =  y_dict
        self.y_keys = y_dict.keys()
        
        self.val_mapper = val_mapper
        self.filter_ = RbfFilter(X[:,3:],None)
        self.x1_name, self.x2_name, self.x3_name = dim_names[:3]
        self.param_names = list( dim_names[3:] )
        self.title = title
        self.include_std = include_std

        self.grid_cache = {}
        self.lut_manager_list = []

        self.initialized= False
        if self.y_selected == selected_y_key:
            self.set_y()
        else:
            self.y_selected = selected_y_key
        
        self.initialized= True
Exemplo n.º 10
0
def plotvfonsph3D(theta_rad, phi_rad, E_th, E_ph, freq=0.0,
                     vcoord='sph', projection='equirectangular'):
    PLOT3DTYPE = "quiver"
    (x, y, z) = sph2crtISO(theta_rad, phi_rad)
    from mayavi import mlab
    
    mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300))
    mlab.clf()
    if PLOT3DTYPE == "MESH_RADIAL" :
        r_Et = numpy.abs(E_th)
        r_Etmx = numpy.amax(r_Et)
        mlab.mesh(r_Et*(x)-1*r_Etmx, r_Et*y, r_Et*z, scalars=r_Et)
        r_Ep = numpy.abs(E_ph)
        r_Epmx = numpy.amax(r_Ep)
        mlab.mesh(r_Ep*(x)+1*r_Epmx , r_Ep*y, r_Ep*z, scalars=r_Ep)
    elif PLOT3DTYPE == "quiver":
        ##Implement quiver plot
        s2cmat = getSph2CartTransfMatT(numpy.array([x,y,z]))
        E_r = numpy.zeros(E_th.shape)
        E_fldsph = numpy.rollaxis(numpy.array([E_r, E_ph, E_th]), 0, 3)[...,numpy.newaxis]
        E_fldcrt = numpy.rollaxis(numpy.matmul(s2cmat, E_fldsph).squeeze(), 2, 0)
        #print E_fldcrt.shape
        mlab.quiver3d(x+1.5, y, z,
                      numpy.real(E_fldcrt[0]),
                      numpy.real(E_fldcrt[1]),
                      numpy.real(E_fldcrt[2]))
        mlab.quiver3d(x-1.5, y, z,
                      numpy.imag(E_fldcrt[0]),
                      numpy.imag(E_fldcrt[1]),
                      numpy.imag(E_fldcrt[2]))              
    mlab.show()
Exemplo n.º 11
0
def draw_earth():

    mlab.figure(1, bgcolor=(0.48, 0.48, 0.48), fgcolor=(0, 0, 0),
                   size=(400, 400))
    mlab.clf()

    # Display continents outline, using the VTK Builtin surface 'Earth'
    continents_src = BuiltinSurface(source='earth', name='Continents')
    # The on_ratio of the Earth source controls the level of detail of the
    # continents outline.
    continents_src.data_source.on_ratio = 2 
    continents = mlab.pipeline.surface(continents_src, color=(0, 0, 0))

    # Display a semi-transparent sphere, for the surface of the Earth
    # We use a sphere Glyph, throught the points3d mlab function, rather than
    # building the mesh ourselves, because it gives a better transparent
    # rendering.
    sphere = mlab.points3d(0, 0, 0, scale_mode='none', scale_factor=2, color=(0.67, 0.77, 0.93),
                           resolution=50, opacity=0.7, name='Earth')

    # These parameters, as well as the color, where tweaked through the GUI,
    # with the record mode to produce lines of code usable in a script.
    sphere.actor.property.specular = 0.45
    sphere.actor.property.specular_power = 5
    # Backface culling is necessary for better transparent rendering.
    sphere.actor.property.backface_culling = True
Exemplo n.º 12
0
def mark_gt_box3d( lidar_dir, gt_boxes3d_dir, mark_dir):

    os.makedirs(mark_dir, exist_ok=True)
    fig   = mlab.figure(figure=None, bgcolor=(0,0,0), fgcolor=None, engine=None, size=(500, 500))
    dummy = np.zeros((10,10,3),dtype=np.uint8)

    for file in sorted(glob.glob(lidar_dir + '/*.npy')):
        name = os.path.basename(file).replace('.npy','')

        lidar_file   = lidar_dir     +'/'+name+'.npy'
        boxes3d_file = gt_boxes3d_dir+'/'+name+'.npy'
        lidar   = np.load(lidar_file)
        boxes3d = np.load(boxes3d_file)

        mlab.clf(fig)
        draw_didi_lidar(fig, lidar, is_grid=1, is_axis=1)
        if len(boxes3d)!=0:
            draw_didi_boxes3d(fig, boxes3d)

        azimuth,elevation,distance,focalpoint = MM_PER_VIEW1
        mlab.view(azimuth,elevation,distance,focalpoint)
        mlab.show(1)
        imshow('dummy',dummy)
        cv2.waitKey(1)

        mlab.savefig(mark_dir+'/'+name+'.png',figure=fig)
Exemplo n.º 13
0
def bigtest():
    from jds_image_proc.clouds import voxel_downsample
    from jds_image_proc.pcd_io import load_xyz
    import mayavi.mlab as mlab
    
    pts = load_xyz("/home/joschu/Data/scp/three_objs_ds.pcd")
    #pts = voxel_downsample(xyz, .03, False)


    mlab.clf()
    mlab.points3d(pts[:,0], pts[:,1], pts[:,2], color = (1,1,1), scale_factor=.01)
    
    clus = []
    
    labels = decompose(pts, .025)
    for i in xrange(labels.max()+1):
        clu = np.flatnonzero(labels == i)
        clus.append(clu)

    for clu in sorted(clus, key=len, reverse=True):
        if len(clu) < 10: break
        dirs = ss.get_sphere_points(1)
        sup_pd = np.dot(pts[clu,:], dirs.T)
        best_d = sup_pd.max(axis=0)
        print "max deficit",(sup_pd - best_d[None,:]).max(axis=1).min()
        mlab.points3d(pts[clu,0], pts[clu,1], pts[clu,2], color = (rand(),rand(),rand()), scale_factor=.01)
        raw_input()
Exemplo n.º 14
0
 def test_test_backend(self):
     """Test if setting the backend to 'test' works."""
     mlab.options.backend = 'test'
     mlab.test_contour3d()
     mlab.clf()
     mlab.pipeline.open(get_example_data('cube.vti'))
     mlab.clf()
Exemplo n.º 15
0
def init_mlab_scene(size):
	fig = mlab.figure('Viz', size=size, bgcolor=(0,0,0))
	fig.scene.set_size(size)
	fig.scene.anti_aliasing_frames = 0

	mlab.clf()
	return fig
Exemplo n.º 16
0
def zoncaview(m):
    """
    m is a healpix sky map, such as provided by WMAP or Planck.
    """

    nside = hp.npix2nside(len(m))
    vmin = -1e3; vmax = 1e3

    # Set up some grids:
    xsize = ysize = 1000
    theta = np.linspace(np.pi, 0, ysize)
    phi   = np.linspace(-np.pi, np.pi, xsize)
    longitude = np.radians(np.linspace(-180, 180, xsize))
    latitude = np.radians(np.linspace(-90, 90, ysize))

    # Project the map to a rectangular matrix xsize x ysize:
    PHI, THETA = np.meshgrid(phi, theta)
    grid_pix = hp.ang2pix(nside, THETA, PHI)
    grid_map = m[grid_pix]

    # Create a sphere:
    r = 0.3
    x = r*np.sin(THETA)*np.cos(PHI)
    y = r*np.sin(THETA)*np.sin(PHI)
    z = r*np.cos(THETA)

    # The figure:
    mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300))
    mlab.clf()

    mlab.mesh(x, y, z, scalars=grid_map, colormap="jet", vmin=vmin, vmax=vmax)

    mlab.draw()

    return
def plot3D(name, X, Y, Z, zlabel):
    """
    Plots a 3d surface plot of Z using the mayavi mlab.mesh function.

    Parameters
    ----------
    name: string
        The name of the figure.
    X: 2d ndarray
        The x-axis data.
    Y: 2d ndarray
        The y-axis data.
    Z: 2d nd array
        The z-axis data.
    zlabel: The title that appears on the z-axis.
    """
    mlab.figure(name)
    mlab.clf()
    plotData = mlab.mesh(X/(np.max(X) - np.min(X)),
                         Y/(np.max(Y) - np.min(Y)),
                         Z/(np.max(Z) - np.min(Z)))
    mlab.outline(plotData)
    mlab.axes(plotData, ranges=[np.min(X), np.max(X),
                                np.min(Y), np.max(Y),
                                np.min(Z), np.max(Z)])
    mlab.xlabel('Space ($x$)')
    mlab.ylabel('Time ($t$)')
    mlab.zlabel(zlabel)
Exemplo n.º 18
0
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
Exemplo n.º 19
0
def plot_sphere_func(f, grid='Clenshaw-Curtis', theta=None, phi=None, colormap='jet', fignum=0):

    # Note: all grids except Clenshaw-Curtis have holes at the poles

    import matplotlib
    matplotlib.use('WxAgg')
    matplotlib.interactive(True)
    from mayavi import mlab

    if grid == 'Driscoll-Healy':
        b = f.shape[0] / 2
    elif grid == 'Clenshaw-Curtis':
        b = (f.shape[0] - 2) / 2
    elif grid == 'SOFT':
        b = f.shape[0] / 2
    elif grid == 'Gauss-Legendre':
        b = (f.shape[0] - 2) / 2

    if theta is None or phi is None:
        theta, phi = meshgrid(b=b, convention=grid)

    phi = np.r_[phi, phi[0, :][None, :]]
    theta = np.r_[theta, theta[0, :][None, :]]
    f = np.r_[f, f[0, :][None, :]]

    x = np.sin(theta) * np.cos(phi)
    y = np.sin(theta) * np.sin(phi)
    z = np.cos(theta)

    mlab.figure(fignum, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(600, 400))
    mlab.clf()
    mlab.mesh(x, y, z, scalars=f, colormap=colormap)

    # mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25))
    mlab.show()
Exemplo n.º 20
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!
Exemplo n.º 21
0
def process_launch():
    '''Procédure reliant une fenetre graphique et le coeur du programme'''
    global nb_etapesIV
    nb_etapes=nb_etapesIV.get()#On récupère le nombre d'étapes
    fig=mlab.figure(1)
    mlab.clf()#La fenêtre de dessin est initialisée
    mlab.draw(terrain([(0,1,2),(2,3,4),(4,5,6)],[(Point(0,0,0),Point(1,0,0)),(Point(1,0,0),Point(1,1,0)),(Point(0,0,0),Point(1,1,0)),(Point(1,1,0),Point(0,1,0)),(Point(0,0,0),Point(0,1,0)),(Point(0,0,0),Point(-1,1,0)),(Point(-1,1,0),Point(0,1,0))],nb_etapes))#On affiche le dessin
Exemplo n.º 22
0
def run_mlab_examples():
    from mayavi import mlab
    from mayavi.tools.animator import Animator

    ############################################################
    # run all the "test_foobar" functions in the mlab module.
    for name, func in getmembers(mlab):
        if not callable(func) or not name[:4] in ('test', 'Test'):
            continue

        if sys.platform == 'win32' and name == 'test_mesh_mask_custom_colors':
            # fixme: This test does not seem to work on win32, disabling for now.
            continue

        mlab.clf()
        GUI.process_events()
        obj = func()

        if isinstance(obj, Animator):
            obj.delay = 10
            # Close the animation window.
            obj.close()
            while is_timer_running(obj.timer):
                GUI.process_events()
                sleep(0.05)

        # Mayavi has become too fast: the operator cannot see if the
        # Test function was succesful.
        GUI.process_events()
        sleep(0.1)
Exemplo n.º 23
0
def lorenz_plot(name, N=10, res=2000, step=2, t=10, seed_=120):
    # Select initial conditions
    seed(seed_)
    x0 = -15 + 30 * np.random.rand(N, 3)

    # Solve for the trajectories
    t = np.linspace(0, t, res)
    pts = np.empty((N, res, 3))
    for i, x in enumerate(x0):
        pts[i] = odeint(lorenz_ode, x, t)

    # Select the colors for the different curves.
    colors = np.zeros((N, 3))
    colors[:,1] = np.linspace(0, 1, N)
    colors = map(tuple, colors.tolist())

    # Plot the different trajectories.
    for x, color in zip(pts, colors):
        mlab.plot3d(x[:,0], x[:,1], x[:,2], tube_radius=.2, color=color)

    # Position the camera.
    mlab.gcf().scene.camera.position = np.array([165.40890060328016, -140.77357847515529, 8.2574865327247622]) / 1.55
    mlab.gcf().scene.camera.focal_point = [-1.7792501449584961, -3.6287221908569336, 23.397351264953613]
    mlab.gcf().scene.camera.view_up = [-0.078467260964232038, -0.20339450183237351, 0.97594752194015633]
    mlab.gcf().scene.camera.clipping_range = [128.64624663718814, 328.22549479639167]

    # Save the plot.
    mlab.savefig(name)
    mlab.clf()
Exemplo n.º 24
0
def disp_pts(pts1, pts2, color1=(1,0,0), color2=(0,1,0)):
    figure = mlab.gcf()
    mlab.clf()
    figure.scene.disable_render = True

    pts1_glyphs   = mlab.points3d(pts1[:,0], pts1[:,1], pts1[:,2], color=color1, resolution=20, scale_factor=0.001)
    pts2_glyphs   = mlab.points3d(pts2[:,0], pts2[:,1], pts2[:,2], color=color2, resolution=20, scale_factor=0.001)
    glyph_points1 = pts1_glyphs.glyph.glyph_source.glyph_source.output.points.to_array()
    glyph_points2 = pts2_glyphs.glyph.glyph_source.glyph_source.output.points.to_array()

    dd = 0.001

    outline1 = mlab.outline(pts1_glyphs, line_width=3)
    outline1.outline_mode = 'full'
    p1x, p1y, p1z = pts1[0,:]
    outline1.bounds = (p1x-dd, p1x+dd,
                       p1y-dd, p1y+dd,
                       p1z-dd, p1z+dd)

    pt_id1 = mlab.text(0.8, 0.2, '0 .', width=0.1, color=color1)

    outline2 = mlab.outline(pts2_glyphs, line_width=3)
    outline2.outline_mode = 'full'
    p2x, p2y, p2z = pts2[0,:]
    outline2.bounds = (p2x-dd, p2x+dd,
                       p2y-dd, p2y+dd,
                       p2z-dd, p2z+dd)  
    pt_id2 = mlab.text(0.8, 0.01, '0 .', width=0.1, color=color2)
    
    figure.scene.disable_render = False


    def picker_callback(picker):
        """ Picker callback: this gets called during pick events.
        """
        if picker.actor in pts1_glyphs.actor.actors:
            point_id = picker.point_id/glyph_points1.shape[0]
            if point_id != -1:
                ### show the point id
                pt_id1.text = '%d .'%point_id
                #mlab.title('%d'%point_id)
                x, y, z = pts1[point_id,:]
                outline1.bounds = (x-dd, x+dd,
                                   y-dd, y+dd,
                                   z-dd, z+dd)
        elif picker.actor in pts2_glyphs.actor.actors:
            point_id = picker.point_id/glyph_points2.shape[0]
            if point_id != -1:
                ### show the point id
                pt_id2.text = '%d .'%point_id
                x, y, z = pts2[point_id,:]
                outline2.bounds = (x-dd, x+dd,
                                   y-dd, y+dd,
                                   z-dd, z+dd)


    picker = figure.on_mouse_pick(picker_callback)
    picker.tolerance = dd/2.
    mlab.show()
Exemplo n.º 25
0
def do_mlab():
    ############################################################
    # run all the "test_foobar" functions in the mlab module.
    for name, func in getmembers(mlab):
        if not callable(func) or not name[:4] in ('test', 'Test'):
            continue
        mlab.clf()
        func()
Exemplo n.º 26
0
 def plotData3D(self):
     if self.data is not None:
         a = self.data
         #mlab.pipeline.volume(mlab.pipeline.scalar_field(a))
         mlab.figure(1, size=(500, 500), fgcolor=(0, 0, 0),
                                 bgcolor=(1, 1, 1))
         mlab.clf()
         mlab.pipeline.volume(mlab.pipeline.scalar_field(a), vmin=0.3, vmax=1)
Exemplo n.º 27
0
def helix(name, resolution=401):
    z = np.linspace(0, 2, resolution)
    x = np.cos(4 * np.pi * z)
    y = np.sin(4 * np.pi * z)
    c = mlab.plot3d(x, y, z, line_width=.2, color=(1, 0, 0))
    # Save the plot.
    mlab.savefig(name)
    mlab.clf()
Exemplo n.º 28
0
 def clear_figure(self):
     r"""
     Method for clearing the current figure.
     """
     from mayavi import mlab
     mlab.clf(figure=self.figure)
     if len(self._actors) > 0:
         self.figure.scene.remove_actors(self._actors)
Exemplo n.º 29
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!
Exemplo n.º 30
0
def points3d():
    pts = np.linspace(0, 4 * np.pi, 30)
    x = np.sin(2 * pts)
    y = np.cos(pts)
    z = np.cos(2 * pts)
    s = 2 + np.sin(pts)
    mlab.points3d(x, y, z, s, colormap="cool", scale_factor=.15)
    mlab.savefig("points3d.png", size=png_size)
    mlab.clf()
Exemplo n.º 31
0
def trajectory3d(mode,xdata,ydata,zdata,fig=None,scalardata=None,vmin=None,vmax=None,color=(0,0,0),data_cmap=None,data_alpha=1,zscale=500.,tube_radius=0.01,tube_sides=15,set_view=None):
    """
    fig: integer or string, optional. Figure key will plot data on corresponding mlab figure, if it exists, or create a new one
    mode: string; coordinate system of 3D projection. Options are 'rectangle' (default), 'sphere' or 'cylinder'
    xdata: 1D array; longitude values for data array
    ydata: 1D array; latitude values for data array
    zdata: 1D array; depth values for data array
    scalardata: 1D array, optional; 1D scalar field to plot colors along trajectoy
    zscale: scalar, optional; change vertical scaling for plotting, such that the vertical axis is scaled as topo_z/zscale (assumes topo_z units are m); default zscale is 500 
    vmin: float, optional; colorbar minimum for data
    vmax: float, optional; colorbar maximum for data
    data_cmap: string, optional; colormap for data surface, default is blue-red
    data_alpha: float or int, optional; opacity for data surface from 0 to 1, default is 1
    tube_radius: float, optional; radius of tube
    tube_sides: int, optional; number of sides of tube
    set_view: array_like, optional; set the mayavi camera angle with input [azimuth, elevation, distance, focal point], default is 
    """
        
    
    #make figure
    if fig is None: 
        mlab.figure(size = (1024,768),bgcolor = (1,1,1), fgcolor = (0.5, 0.5, 0.5))
        mlab.clf()
    else:
        mlab.figure(figure=fig,bgcolor = (1,1,1))
    
    #do coordinate transformation

    if xdata is not None and ydata is not None and zdata is not None:
        phi_iso, theta_iso = np.meshgrid(((ydata*np.pi*2)/360.)+np.pi/2.,(xdata*np.pi*2)/360.)

        # Create variable dimensions
        if mode == 'sphere':
            x_iso = np.sin(phi_iso) * np.cos(theta_iso[::-1]) * (1 -zdata/zscale)
            y_iso = np.sin(phi_iso) * np.sin(theta_iso[::-1]) * (1 -zdata/zscale)
            z_iso = np.cos(phi_iso) * (1 -zdata/zscale)
        elif mode == 'cylinder':
            x_iso = np.sin(phi_iso) * np.cos(theta_iso[::-1])
            y_iso = np.sin(phi_iso) * np.sin(theta_iso[::-1])
            z_iso = -zdata/zscale
        elif mode == 'rectangle':
            x_iso = xdata
            y_iso = ydata
            z_iso =-zdata/zscale
    else:
        #raise error if all three fields are not provided
        print('ERROR: not all data fields are provided. Must provide 1D data x, y and z data points')  
    

    #map data surface
    if scalardata is not None:
        m = mlab.plot3d(x_iso,y_iso,z_iso, scalardata,opacity=data_alpha,tube_radius=tube_radius,tube_sides=tube_sides,color=color,vmin=vmin,vmax=vmax)
    
    else:
        m = mlab.plot3d(x_iso,y_iso,z_iso, opacity=data_alpha,tube_radius=tube_radius,tube_sides=tube_sides,color=color,vmin=vmin,vmax=vmax)
    
    return m
Exemplo n.º 32
0
def plot_alpha_sphere():
  x,y,z = make_sphere(50, 1.0)

  mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300))
  mlab.clf()

  s = np.zeros(x.shape)
  mlab.mesh(x, y, z, scalars=s, colormap='jet', opacity=0.1)
  mlab.show(stop=True)
Exemplo n.º 33
0
    def clear_figure(self):
        r"""
        Method for clearing the current figure.
        """
        from mayavi import mlab

        mlab.clf(figure=self.figure)
        if len(self._actors) > 0:
            self.figure.scene.remove_actors(self._actors)
Exemplo n.º 34
0
 def redraw_scene2(self):
     mlab.clf(figure=self.scene2.mayavi_scene)
     self.draw_source_cloud(self.scene2, right_data)
     self.right_pick = mlab.outline(line_width=3,
                                    color=(1, 0, 1),
                                    name='right_picker',
                                    figure=self.scene2.mayavi_scene)
     self.right_pick.outline_mode = 'cornered'
     self.right_pick.bounds = (0, 0, 0, 0, 0, 0)
Exemplo n.º 35
0
def plot_big(MH, MHexam, points_proj, points_projal, skel_projal, ViewP, proj_type, plot_type="normal", fnum=1):
  
    # Plotting
    print "Plot figure z-axis reversed (because z=0 is top of scan)"
    mlab.figure(fnum, bgcolor=(1,1,1), size=(800,800))
    mlab.clf()
    #airway plot    
    mlab.triangular_mesh(MH.vertices[:,0], MH.vertices[:,1], MH.vertices[:,2]*(-1), 
                         MH.faces, colormap='Blues', representation='wireframe', 
                         line_width=0.5)
    try:
        mlab.triangular_mesh(MHexam.vertices[:,0], MHexam.vertices[:,1], 
                             MHexam.vertices[:,2]*(-1), MHexam.faces,
                             colormap='Greens', representation='surface',
                             opacity=0.2)
    except:
        print "Example mesh not plotted"
    #airway axes
    #mlab.axes('off') #extent=([-200, 200, -200,200, 200,-200])) 
    #points on the airway
    mlab.points3d(MH.silvert1[:,0], MH.silvert1[:,1], MH.silvert1[:,2]*(-1), 
                  scale_factor=1, color=(0,0,0))
#    #projected points
    mlab.points3d(points_proj[:,0], points_proj[:,1], points_proj[:,2]*(-1), 
                  scale_factor=1, color=(0,0,0))  
    
    if plot_type is "normal":        
#    #alignment points
        mlab.points3d(MH.points[:,0], MH.points[:,1], MH.points[:,2]*(-1), 
                      scale_factor=2, color=(0,1,0))
        
        #skeleton
        mlab.points3d(MH.skel[:,0], MH.skel[:,1], MH.skel[:,2]*(-1), 
                      scale_factor=0.5, color=(0.5,0.5,1))
    #    #alignment points
        mlab.points3d(points_projal[:,0], points_projal[:,1], points_projal[:,2]*(-1), 
                      scale_factor=2, color=(0,1,0))
        
    try:
        mlab.points3d(skel_projal[:,0], skel_projal[:,1], skel_projal[:,2]*(-1), 
                      scale_factor=0.5, color=(0.5,0.5,1))
    except:
        print "skeleton not plotted"
    #view direction
    #if proj_type=="Lodox":
    #    ViewL=np.array([ViewP, ViewP])
    #    ViewL[0,2]=30; ViewL[1,2]=-30        
    #    
    #    mlab.plot3d(ViewL[:,0]/10, ViewL[:,1], ViewL[:,2]*(-1), 
    #                color=(0,0,0), 
    #                tube_radius=1, opacity=1)
    
    #elif proj_type=="normal":
    #    mlab.points3d(ViewP[0]/10, ViewP[1], ViewP[2]*(-1), 
    #                  scale_factor=4, color=(1,0,0))
    
    mlab.view(elevation=80,azimuth=20)
Exemplo n.º 36
0
def puttdog(sfdog):
    mlab.clf()
    cutdog, numpug = devidedog(sfdog)
    fileddog = mlab.pipeline.scalar_field(cutdog)
    mlab.pipeline.volume(fileddog, vmin=0, vmax=numpug - 1)
    mlab.colorbar()
    # mlab.show()

    pass
Exemplo n.º 37
0
def plot3d():
    num = np.pi / 1000
    pts = np.arange(0, 2 * np.pi + num, num)
    x = np.cos(pts) * (1 + np.cos(pts * 6))
    y = np.sin(pts) * (1 + np.cos(pts * 6))
    z = np.sin(pts * 6 / 11)
    mlab.plot3d(x, y, z)
    mlab.savefig("plot3d.png", size=png_size)
    mlab.clf()
Exemplo n.º 38
0
def draw_dots3d(dots, edges, fignum, clear=True,
                title='',
                size=(1024, 768), graph_colormap='viridis',
                bgcolor=(1, 1, 1),
                node_color=(0.3, 0.65, 0.3), node_size=0.01,
                edge_color=(0.3, 0.3, 0.9), edge_size=0.003,
                text_size=0.14, text_color=(0, 0, 0), text_coords=[0.84, 0.75], text={},
                title_size=0.3,
                angle=get_ra()):

    # https://stackoverflow.com/questions/17751552/drawing-multiplex-graphs-with-networkx

    # numpy array of x, y, z positions in sorted node order
    xyz = shrink_to_3d(dots)

    if fignum == 0:
        mlab.figure(fignum, bgcolor=bgcolor, fgcolor=text_color, size=size)

    # Mayavi is buggy, and following code causes sockets leak.
    #if mlab.options.offscreen:
    #    mlab.figure(fignum, bgcolor=bgcolor, fgcolor=text_color, size=size)
    #elif fignum == 0:
    #    mlab.figure(fignum, bgcolor=bgcolor, fgcolor=text_color, size=size)

    if clear:
        mlab.clf()

    # the x,y, and z co-ordinates are here
    # manipulate them to obtain the desired projection perspective

    pts = mlab.points3d(xyz[:, 0], xyz[:, 1], xyz[:, 2],
                        scale_factor=node_size,
                        scale_mode='none',
                        color=node_color,
                        #colormap=graph_colormap,
                        resolution=20,
                        transparent=False)

    mlab.text(text_coords[0], text_coords[1], '\n'.join(['{} = {}'.format(n, v) for n, v in text.items()]), width=text_size)

    if clear:
        mlab.title(title, height=0.95)
        mlab.roll(next(angle))
        mlab.orientation_axes(pts)
        mlab.outline(pts)

    """
    for i, (x, y, z) in enumerate(xyz):
        label = mlab.text(x, y, str(i), z=z,
                          width=text_size, name=str(i), color=text_color)
        label.property.shadow = True
    """

    pts.mlab_source.dataset.lines = edges
    tube = mlab.pipeline.tube(pts, tube_radius=edge_size)
    mlab.pipeline.surface(tube, color=edge_color)
def simulate(sim_time, dt, sat, ground_track, sat_marker, picture_marker,
             picture_points):
    elapsed_time = 0
    start_time = time.time()
    step_start_time = start_time
    time_deviation = 0

    for i in [0, 1, 2]:
        sat.vel[i] = -sat.vel[i]
    sat = stepTime(sat, int(sat.period()), 10)
    for i in [0, 1, 2]:
        sat.vel[i] = -sat.vel[i]
    sat = stepTime(sat, int(sat.period()) * 2, 10)
    while elapsed_time < sim_time:
        ##SIMULATION LOOP##
        #step through time
        sat = stepTime(sat, dt, dt)

        ## create 2d map with track
        updateGroundMap(ground_track, sat_marker, sat, picture_marker,
                        picture_points)
        plt.pause(0.05)
        plt.draw()

        ## create 3d globe with track
        mlab.clf()
        scaling_factor = m.sqrt(400000**2 / 3)
        line = mlab.quiver3d(sat.last_pos[int(sat.period() / dt), 1],
                             sat.last_pos[int(sat.period() / dt), 0],
                             sat.last_pos[int(sat.period() / dt), 2],
                             sat.spin_vector[0],
                             sat.spin_vector[1],
                             sat.spin_vector[2],
                             scale_factor=400000,
                             line_width=2,
                             figure=fig,
                             color=(1, 0, 0),
                             mode='2darrow')
        mlab.points3d(picture_points[:, 0],
                      picture_points[:, 1],
                      picture_points[:, 2],
                      figure=fig,
                      scale_factor=200000,
                      color=(1, 0, 1))
        mlab.draw()
        #make sure step only last one second in real time
        if abs(time.time() - step_start_time) <= 1:
            if 1 - abs(time.time() - step_start_time) - time_deviation > 0:
                time.sleep(1 - abs(time.time() - step_start_time) -
                           time_deviation)
            else:
                time.sleep(1 - abs(time.time() - step_start_time))
        step_start_time = time.time()
        elapsed_time = time.time() - start_time
        print(elapsed_time)
        time_deviation = abs(start_time - time.time()) % 1
Exemplo n.º 40
0
 def redraw_scene(self, scene, input_xyz, clear=True):
     if clear: mlab.clf(figure=scene.mayavi_scene)
     if input_xyz.shape[1] == 2:
         x, y = input_xyz.transpose()
         z = np.zeros(x.shape)
     elif input_xyz.shape[1] == 3:
         x, y, z = input_xyz.transpose()
     else:
         raise NotImplementedError
     mlab.points3d(x, y, z, mode='point', figure=scene.mayavi_scene)
Exemplo n.º 41
0
def capture_image(func, filename):
    """ Runs a function doing some mayavi drawing and save the resulting
        scene to a file.
    """
    mlab.clf()
    func()
    if not filename[-4:] in ('.jpg', '.png'):
        filename = '%s.jpg' % filename
    mlab.savefig(filename, size=(400, 400))
    os.system('convert %s -trim %s' % (filename, filename))
Exemplo n.º 42
0
    def _add_points(self, scene, name=None, new=None):

        scene.disable_render = True

        mlab.clf(figure=scene)
        x, y, z = np.random.rand(3, 50)
        mlab.points3d(x, y, z, figure=scene.mayavi_scene)
        mlab.axes()

        scene.disable_render = False
Exemplo n.º 43
0
 def draw_point_cloud(self, points3d):
     mlab.clf()
     mlab.points3d(points3d[:, 0],
                   points3d[:, 1],
                   points3d[:, 2],
                   color=(1., 0.25, 0.25),
                   opacity=0.75,
                   scale_factor=0.001)
     mlab.outline()
     mlab.axes()
Exemplo n.º 44
0
    def mesh(self, **kwargs):

        x = kwargs.get("x", self._obj.SCHISM_hgrid_node_x[:].values)
        y = kwargs.get("y", self._obj.SCHISM_hgrid_node_y[:].values)
        try:
            t = kwargs.get("t", self._obj.time.values)
        except:
            pass

        tri3 = kwargs.get("tes", self._obj.SCHISM_hgrid_face_nodes.values[:, :3].astype(int))

        dim = kwargs.get("dim", "2D")

        R = kwargs.get("R", 1.0)

        if dim == "3D":
            px, py, pz = to_3d(x, y, R=R)
        else:
            px = x
            py = y
            pz = np.zeros(x.shape[0])

        mlab.figure(1, size=(3840 / 2, 2160 / 2), bgcolor=(0, 0, 0), fgcolor=(1.0, 1.0, 1.0))
        mlab.clf()
        bcolor = kwargs.get("bcolor", (0.0, 0.0, 0.0))
        if dim == "3D":
            self.globe(R - 0.002, bcolor=bcolor)

        # 3D triangular mesh surface (like trisurf)
        grd = mlab.triangular_mesh(px, py, pz, tri3, representation="wireframe", opacity=1.0)
        #       grd.scalar.name = 'depth'

        coast = kwargs.get("coastlines", None)

        if coast is not None:
            try:
                del kwargs["coastlines"]
            except:
                pass
            try:
                del kwargs["R"]
            except:
                pass
            src, lines = self.c3d(coast, R=R, **kwargs)
            mlab.pipeline.surface(src, color=(1, 0, 0), line_width=10, opacity=0.8)

        engine = mlab.get_engine()
        scene = engine.scenes[0]
        scene.scene.z_plus_view()

        v = view(actors=grd, rotate=False, ui_collapsed=True)
        v.geometries = [v.geometries[0]]

        #        mlab.show()
        return v
Exemplo n.º 45
0
    def plot_surface(self, points=False, extent=None):
        """
        Plot a 3D view of the surface grid with mayavi.
        
        Parameters
        ----------
        points : bool, optional
            If True, surface points will be displayed.
            Default is False.
        extent : [xmin, xmax, ymin, ymax, zmin, zmax], optional
            Minimal and maximal coordinates to display.
            Default is the x, y, z arrays extent. 

        Returns
        -------
        mayavi scene
        """
        if self.Rgrid is not None:
            grid_size = self.Rgrid.shape[0]
            I = np.linspace(0, np.pi, grid_size + 1, endpoint=True)
            J = np.linspace(0, 2 * np.pi, grid_size + 1, endpoint=True)
            J, I = np.meshgrid(J, I)
            theta = I
            phi = J
            grid = np.zeros((grid_size + 1, grid_size + 1))
            grid[:-1, :-1] = self.Rgrid
            grid[-1] = grid[0]
            grid[:, -1] = grid[:, 0]

            x, y, z = tr.spherical_to_cart(1, theta, phi)
            mlab.clf()
            if extent is not None:
                mesh = mlab.mesh(x * np.abs(grid),
                                 y * np.abs(grid),
                                 z * np.abs(grid),
                                 scalars=grid,
                                 colormap='jet',
                                 extent=extent)
            else:
                mesh = mlab.mesh(x * np.abs(grid),
                                 y * np.abs(grid),
                                 z * np.abs(grid),
                                 scalars=grid,
                                 colormap='jet')
            if points:
                mesh = mlab.points3d(self.x,
                                     self.y,
                                     self.z,
                                     self.z,
                                     scale_mode='none',
                                     scale_factor=0.05)

            mesh.scene.background = (1, 1, 1)
            mesh.scene.magnification = 10
            return mesh.scene
Exemplo n.º 46
0
    def xmas_balls(connectivity,
                   node_data=None,
                   edge_data=True,
                   labels_data=True,
                   balls_colormap='Blues',
                   bgcolor=(1, 1, 1),
                   node_size=10.,
                   edge_color=(0.8, 0.8, 0.8),
                   edge_size=0.2,
                   text_size=0.042,
                   text_color=(0, 0, 0)):
        """
        Plots coloured balls at the region centres of connectivity, colour and
        size is determined by a vector of length number of regions (node_data).
        
        Optional: adds the connections between pair of nodes.
        
        """
        G = nx.from_numpy_matrix(numpy.matrix(connectivity.weights))

        mlab.figure(1, bgcolor=bgcolor)
        mlab.clf()
        # scalar colors
        if node_data is not None:
            scalars = node_data
            mlab.colorbar(orientation="vertical")
        else:
            scalars = numpy.array(G.nodes()) * 20

        pts = mlab.points3d(connectivity.centres[:, 0],
                            connectivity.centres[:, 1],
                            connectivity.centres[:, 2],
                            scalars,
                            scale_factor=node_size,
                            scale_mode='none',
                            colormap=balls_colormap,
                            resolution=20)

        if labels_data:
            for i, (x, y, z) in enumerate(connectivity.centres):
                label = mlab.text(x,
                                  y,
                                  connectivity.region_labels[i],
                                  z=z,
                                  width=text_size,
                                  name=str(connectivity.region_labels[i]),
                                  color=text_color)
                label.property.shadow = False

        if edge_data:
            pts.mlab_source.dataset.lines = numpy.array(G.edges())
            tube = mlab.pipeline.tube(pts, tube_radius=edge_size)
            mlab.pipeline.surface(tube, color=edge_color)

        mlab.show()
Exemplo n.º 47
0
def draw_graph3d(graph,  graph_colormap='winter',  bgcolor = (1,  1,  1), 
                 node_size=0.03, 
                 edge_color=(0.8,  0.8,  0.8),  edge_size=0.002, 
                 text_size=0.008,  text_color=(0,  0,  0)):

    H = nx.Graph()

    ## add edges
    #for node,  edges in graph.items():
    #    for edge,  val in edges.items():
    #        if val == 1:
    #            H.add_edge(node,  edge)
    
    # add edges
    for edge in graph:
        H.add_edge(edge[0],  edge[1])

    G = nx.convert_node_labels_to_integers(H)

    graph_pos = nx.spring_layout(G,  dim=3)

    # numpy array of x, y, z positions in sorted node order
    xyz = np.array([graph_pos[v] for v in sorted(G)])

    # scalar colors
    scalars = np.array(G.nodes())+5
    mlab.figure(1,  bgcolor=bgcolor)
    mlab.clf()

    pts = mlab.points3d(xyz[:,  0],  xyz[:,  1],  xyz[:,  2], 
                        scalars, 
                        scale_factor=node_size, 
                        scale_mode='none', 
                        colormap=graph_colormap, 
                        resolution=20)

    for i,  (x,  y,  z) in enumerate(xyz):
        label = mlab.text(x,  y,  str(i),  z=z, 
                          width=text_size,  name=str(i),  color=text_color)
        label.property.shadow = True

    print(np.array(G.edges))

    print(np.array(list(G.edges())))
    print(type(G.edges()))
    print(type(list(G.edges())))
    print(len(list(G.edges())))
    print(len(list(G.edges())))
    print(len(G.edges()))

    pts.mlab_source.dataset.lines = np.array(G.edges())
    tube = mlab.pipeline.tube(pts,  tube_radius=edge_size)
    mlab.pipeline.surface(tube,  color=edge_color)

    mlab.show()  # interactive window
Exemplo n.º 48
0
    def run(self):
        MayaviDaemon._viewers.append(self)
        
        mlab.clf()

        bounds = zeros((0, 6), 'l')
        
        self.cellsource = self.setup_source(self.cellfname)
        if self.cellsource is not None:
            tmp = [out.cell_data.scalars for out in self.cellsource.outputs \
                   if out.cell_data.scalars is not None]
            self.has_cell_scalars = (len(tmp) > 0)
            tmp = [out.cell_data.vectors for out in self.cellsource.outputs \
                   if out.cell_data.vectors is not None]
            self.has_cell_vectors = (len(tmp) > 0)
            tmp = [out.cell_data.tensors for out in self.cellsource.outputs \
                   if out.cell_data.tensors is not None]
            self.has_cell_tensors = (len(tmp) > 0)

            bounds = concatenate((bounds, 
                                  [out.bounds for out in self.cellsource.outputs]),
                                 axis=0)


        self.facesource = self.setup_source(self.facefname)
        if self.facesource is not None:
            tmp = [out.point_data.scalars for out in self.facesource.outputs \
                   if out.point_data.scalars is not None]
            self.has_face_scalars = (len(tmp) > 0)
            tmp = [out.point_data.vectors for out in self.facesource.outputs \
                   if out.point_data.vectors is not None]
            self.has_face_vectors = (len(tmp) > 0)
            tmp = [out.point_data.tensors for out in self.facesource.outputs \
                   if out.point_data.tensors is not None]
            self.has_face_tensors = (len(tmp) > 0)
            
            bounds = concatenate((bounds, 
                                  [out.bounds for out in self.facesource.outputs]),
                                 axis=0)
                                 
        boundsmin = bounds.min(axis=0)
        boundsmax = bounds.max(axis=0)
        
        bounds = (boundsmin[0], boundsmax[1], 
                  boundsmin[2], boundsmax[3], 
                  boundsmin[4], boundsmax[5])

        self.bounds = where(self.bounds == array((None,)),
                            bounds, 
                            self.bounds).astype(float)

        self.view_data()

        # Poll the lock file.
        self.timer = Timer(1000 / self.fps, self.poll_file)
Exemplo n.º 49
0
 def contourf(self,**kwargs):
                     
     x = kwargs.get('x',self._obj.SCHISM_hgrid_node_x[:].values)
     y = kwargs.get('y',self._obj.SCHISM_hgrid_node_y[:].values)
     try:
         t = kwargs.get('t',self._obj.time.values)
     except:
         pass
     
     tri3 = kwargs.get('tri3',self._obj.SCHISM_hgrid_face_nodes.values[:,:3].astype(int))
           
     it = kwargs.get('it', None)
   
     var = kwargs.get('var','depth')
     z = kwargs.get('z',self._obj[var].values[it,:].flatten())
     name = kwargs.get('name',self._obj[var].name)
             
     vmin = kwargs.get('vmin', z.min())
     vmax = kwargs.get('vmax', z.max())
     
     R = kwargs.get('R',1.)
     
     px=np.cos(y/180*np.pi)*np.cos(x/180*np.pi)*R
     py=np.cos(y/180*np.pi)*np.sin(x/180*np.pi)*R
     pz=np.sin(y/180*np.pi)*R
     
     rep=kwargs.get('representation','surface')
     
     cmap = kwargs.get('cmap','gist_earth')
     
     mlab.figure(1, size=(3840, 2160), bgcolor=(0, 0, 0), fgcolor=(1.,1.,1.))
     mlab.clf()
     
     bcolor=kwargs.get('bcolor',(0.,0.,0.))
     self.globe(R - .002, bcolor=bcolor)
     # 3D triangular mesh surface (like trisurf)
     grd = mlab.triangular_mesh(px,py,pz,tri3, representation=rep, opacity=1.0, scalars=z,  colormap=cmap,vmin=vmin,vmax=vmax)
                         
     grd.actor.mapper.scalar_visibility = True
     mlab.view(azimuth=0, distance=4)
     
     title = kwargs.get('title', '{}'.format(var))
     
     mlab.colorbar(grd, title=name, orientation='vertical')
     
     coast = kwargs.get('coastlines',None)
     
     if coast is not None :
         src, lines = self.c3d(coast,R=R)
         mlab.pipeline.surface(src, color=(1,0,0), line_width=10, opacity=0.8)
     
     
     mlab.show()
     return
Exemplo n.º 50
0
    def _plotbutton3_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)

        self.field = field
        self.labels()
        mlab.view(azimuth=0, elevation=0, distance='auto')
        mlab.show()
Exemplo n.º 51
0
def lvx_vis_3d(gt_annos,dt_annos,output_dir):
    root_path = dt_annos[0]["metadata"]["image_prefix"]
    fig = mlab.figure(figure=None, bgcolor=(0.85,0.85,0.85), fgcolor=None, engine=None, size=(1600, 1000))

    if gt_annos is not None:
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        vot = cv2.VideoWriter(os.path.join(output_dir,"bev_video_3d.mp4"),fourcc,10,(1600,1000),True)
        dataset = lvx_object(root_path)
        gt_image_idxes = [str(info["token"]) for info in gt_annos]

        for i in range(len(gt_annos)):
            print(gt_annos[i]['token'])
            points = dataset.get_lidar(gt_annos[i]['token'])
            points = points[points[:,2]>0.1,:]
            gt_annos[i] = remove_dontcare(gt_annos[i])
            fig = draw_lidar(points,color=None,fig=fig, pts_mode = 'sphere')
            gt_corners = center_to_corner_box3d(gt_annos[i]['location'],gt_annos[i]['dimensions'], gt_annos[i]['rotation_y'])
            fig = draw_gt_boxes3d(gt_corners, gt_annos[i]['id'],color=(0,0,1),fig=fig)
            dt_corners = center_to_corner_box3d(dt_annos[i]['location'],dt_annos[i]['dimensions'], dt_annos[i]['rotation_y'])
            fig = draw_gt_boxes3d(dt_corners, dt_annos[i]['track_id'],color=(0,1,0),fig=fig)
            img_path = os.path.join(output_dir,f"bev_imgs/lvx_{gt_annos[i]['token']}_3d.png")
            mlab.savefig(img_path)
            mlab.clf(figure=fig)
            img = cv2.imread(img_path)
            vot.write(img)
        vot.release()
    else:
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        vot = cv2.VideoWriter(os.path.join(output_dir,"beicao_video_3d.mp4"),fourcc,10,(1600,1000),True)
        dataset = lvx_object(root_path,split="testing")

        for i in range(len(dt_annos)):
            idx = dt_annos[i]['metadata']['token']
            print(idx)
            points = dataset.get_lidar(idx)
            plane = points[points[:,2]<0.1,:]
            points = points[points[:,2]>0.1,:]
            fig = draw_lidar(points,color=None,fig=fig, pts_mode = 'sphere')
            fig = draw_lidar(plane,color=None,fig=fig)
            dt_corners = center_to_corner_box3d(dt_annos[i]['location'],dt_annos[i]['dimensions'], dt_annos[i]['rotation_y'])
            color_list = np.zeros((dt_annos[i]['track_id'].shape[0],3))
            for j in range(dt_annos[i]['track_id'].shape[0]):
                np.random.seed(int(dt_annos[i]['track_id'][j]))
                color_list[j] = np.random.rand(3)

            view_setting = [180+30*np.sin(np.pi/100.*i),50+20*np.sin(np.pi/200.*i),60-20*np.sin(np.pi/100*i)]
            print(view_setting)
            fig = draw_gt_boxes3d(dt_corners, dt_annos[i]['track_id'],line_width=3,fig=fig,color_list=color_list,view_setting=view_setting)
            img_path = os.path.join(output_dir,f"beicao_imgs/lvx_{idx}_3d.png")
            mlab.savefig(img_path)
            mlab.clf(figure=fig)
            img = cv2.imread(img_path)
            vot.write(img)
        vot.release()
Exemplo n.º 52
0
    def volume_slice(self,
                     data,
                     save_name=None,
                     cmap='viridis',
                     vmin=None,
                     vmax=None,
                     show=False,
                     bgcolor=(1., 1., 1.)):
        '''Open Mayavi scene

        New function
        '''

        # Import mlab
        from mayavi import mlab

        # try:
        #    engine = mayavi.engine
        # except NameError:
        #    from mayavi.api import Engine
        #engine = Engine()
        # engine.start()

        if vmin is None:
            vmin = np.nanpercentile(data, 0.1)
        if vmax is None:
            vmax = np.nanpercentile(data, 99.9)

        # if len(engine.scenes) == 0:
        #    engine.new_scene()

        mlab.figure(size=(1000, 1000), bgcolor=bgcolor)
        mlab.clf()

        mlab.volume_slice(data.values, plane_orientation='x_axes')

        mlab.view(azimuth=azimuth,
                  elevation=elevation,
                  distance=distance,
                  roll=roll)

        #module_manager = engine.scenes[0].children[0].children[0]

        #module_manager.scalar_lut_manager.lut_mode = cmap
        #scene = engine.scenes[0]
        # scene.scene.x_minus_view()

        if save_name != None:
            mlab.savefig(save_name, size=(1000, 1000))

        if show_slice:
            mlab.show()

        return None
Exemplo n.º 53
0
    def anim():
        for i in range(T):
            plot.mlab_source.scalars = f(x, y, t=i * np.ones_like(x) / a)
            zeros = '0' * (pad - len(str(i)))
            filename = path + name + "_{}{}".format(zeros, i) + ext
            mlab.savefig(filename)
            print(i)
            yield

        mlab.clf()
        mlab.close(all=True)
Exemplo n.º 54
0
def test_bend_ends():
    thread = Thread()
    mlab.figure(3); mlab.clf()
    T = 16
    
    colors = colorSeq(25)
    
    for (t,cons) in enumerate(C.bend_ends(thread,1,.1)):
        thread.setConstraints(cons)
        x,y,z = thread.getXYZ()
        mlab.plot3d(x,y,z,tube_radius=.1,color=colors.next())
Exemplo n.º 55
0
def harmonic2(name):
    x = np.linspace(0, np.pi)
    y = np.linspace(0, np.pi)
    x, y = np.meshgrid(x, y, copy=False)
    z = np.sin(2 * x) * np.sin(2 * y)
    mlab.mesh(x, y, z)
    # Zoom in a bit.
    mlab.gcf().scene.camera.position = mlab.gcf().scene.camera.position / 1.3
    # Save the plot.
    mlab.savefig(name)
    mlab.clf()
 def make_exact(self):
     if(self.exact!=None):
         sol = self.exact(self.X,self.Y,0)
         for k in xrange(self.Nt):
             mlab.view(0, 0)
             mlab.mesh(self.X,self.Y,sol, color=(0.0, 0.3, 0.6))
             sol = self.exact(self.X, self.Y, self.t[k])
             mlab.savefig("wtmp%04d.png" %k)
             mlab.clf()
         filename = "exact_dt%2.1f.gif" %self.dt
         sci.movie("wtmp*.png",encoder='convert', fps=5, output_file=filename)
Exemplo n.º 57
0
    def grid(self,**kwargs):

        x = kwargs.get('x',self._obj.SCHISM_hgrid_node_x[:].values)
        y = kwargs.get('y',self._obj.SCHISM_hgrid_node_y[:].values)
        try:
            t = kwargs.get('t',self._obj.time.values)
        except:
            pass

        tri3 = kwargs.get('tri3',self._obj.SCHISM_hgrid_face_nodes.values[:,:3].astype(int))

        dim = kwargs.get('dim','2D')

        R = kwargs.get('R',1.)


        if dim == '3D':

            px=np.cos(y/180*np.pi)*np.cos(x/180*np.pi)*R
            py=np.cos(y/180*np.pi)*np.sin(x/180*np.pi)*R
            pz=np.sin(y/180*np.pi)*R

        else:

            px = x
            py = y
            pz = np.zeros(x.shape[0])

        mlab.figure(1, size=(3840/2, 2160/2), bgcolor=(0, 0, 0), fgcolor=(1.,1.,1.))
        mlab.clf()
        bcolor=kwargs.get('bcolor',(0.,0.,0.))
        if dim == '3D': self.globe(R - .002, bcolor=bcolor)

        # 3D triangular mesh surface (like trisurf)
        grd = mlab.triangular_mesh(px,py,pz,tri3, representation='wireframe', opacity=1.0)

        coast = kwargs.get('coastlines',None)

        if coast is not None :
            try:
                del kwargs['coastlines','R']
            except:
                pass

            src, lines = self.c3d(coast,R=R,**kwargs)
            mlab.pipeline.surface(src, color=(1,0,0), line_width=10, opacity=0.8)


        engine = mlab.get_engine()
        scene = engine.scenes[0]
        scene.scene.z_plus_view()

        mlab.show()
        return
Exemplo n.º 58
0
def draw_nucleus(v):
    mlab.clf()
    s = mlab.pipeline.triangular_mesh_source(x, y, z, triIndices)
    s.data.cell_data.scalars = np.cos(phaseAngle)
    surf = mlab.pipeline.surface(s)
    surf.contour.filled_contours = True
    surf.contour.minimum_contour = 0.0
    surf.contour.maximum_contour = 1.0
    surf.module_manager.scalar_lut_manager.data_range = (0, 1)
    mlab.view(v)
    mlab.draw()
Exemplo n.º 59
0
def myframe(time):
    global count
    """ Demo the bar chart plot with a 2D array.
    """
    print("generate barchar:", time)

    mlab.clf()
    tmp = t[:count + 1]
    mlab.plot3d(np.sin(tmp), np.cos(tmp), 0.1 * tmp, tmp)
    count += 1
    return mlab.screenshot(antialiased=False)
Exemplo n.º 60
0
    def update_density(self,ind):
        if ind >= len(self.figdensity):
            return
        ml = self.figdensity[ind]
        mon = self.monitors[ind]

        mlab.figure(ml)
        mlab.clf()
        if len(self.contours) > 0:
            self.curr_contours = self.contours
        self.curr_contours = plot_density(mon.M, self.curr_contours, self.levels)