Esempio n. 1
0
def example():
    # setup movie
    m = movie(frame_rate=22.5)
    
    # setup example
    from mayavi import mlab
    mlab.options.offscreen = True
    mlab.test_contour3d()
    f = mlab.gcf() 

    # save frames
    for i in range(36*3):
        f.scene.camera.azimuth(10) # rotate
        f.scene.render()
        mlab.savefig(m.next_frame(), figure=f)
    
    # encode frames
    encoded = m.encode()

    # remove tempdir
    del m
    
    if not encoded:
        # report error
        exit(m.output)
Esempio n. 2
0
def m2screenshot(mayavi_fig=None, mpl_axes=None, autocrop=True):
    """ Capture a screeshot of the Mayavi figure and display it in the
        matplotlib axes.
    """
    import pylab as pl
    # Late import to avoid triggering wx imports before needed.
    try:
        from mayavi import mlab
    except ImportError:
        # Try out old install of Mayavi, with namespace packages
        from enthought.mayavi import mlab

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

    filename = tempfile.mktemp('.png')
    mlab.savefig(filename, figure=mayavi_fig)
    image3d = pl.imread(filename)
    if autocrop:
        bg_color = mayavi_fig.scene.background
        image3d = autocrop_img(image3d, bg_color)
    pl.imshow(image3d)
    pl.axis('off')
    os.unlink(filename)
Esempio n. 3
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)
def vis_breakups():
    """
    This function allows to visualize break-ups as the highlighted branches in
    the original skeleton.
    """
    data_sk = glob.glob('/backup/yuliya/vsi05/skeletons_largdom/*.h5')
    data_sk.sort()
    
    data_br = glob.glob('/backup/yuliya/vsi05/breakups_con_correction/dict/*.npy')
    data_br.sort()
    
    for i,j in zip(data_sk[27:67][::-1], data_br[19:][::-1]):
        d = tb.openFile(i, mode='r')
        bran1 = np.copy(d.root.branches)
        skel1 = np.copy(d.root.skel)
        d.close() 

        br = np.load(j).item()
        
        mlab.figure(1, bgcolor=(1,1,1), size=(1200,1200))
        surf_skel = mlab.contour3d(skel1, colormap='hot')
        surf_skel.actor.property.representation = 'points'
        surf_skel.actor.property.line_width = 2.3
        mask = np.zeros_like(skel1)
        for k in br:
            sl = br[k]            
            mask[sl] = (bran1[sl] == k)
        surf_mask = mlab.contour3d(mask.astype('uint8'))
        surf_mask.actor.property.representation = 'wireframe'
        surf_mask.actor.property.line_width = 5
        
        mlab.savefig('/backup/yuliya/vsi05/breakups_con_correction/video_hot/' + i[39:-3] + '.png')
        mlab.close()
def run_plots(DataDirectory,Base_file):

    root = DataDirectory+Base_file
    filenames = get_filenames(root)
    counter = 0

    # create the plot for the initial raster
    initial_file = filenames[0]

    # read in the raster
    raster = IO.ReadRasterArrayBlocks(initial_file)

    f = mlab.figure(size=(1000,1000), bgcolor=(0.5,0.5,0.5))
    s = mlab.surf(raster, warp_scale=0.4, colormap='gist_earth', vmax=100)
    #mlab.outline(color=(0,0,0))

    #mlab.axes(s, color=(1,1,1), z_axis_visibility=True, y_axis_visibility=False, xlabel='', ylabel='', zlabel='', ranges=[0,500,0,1000,0,0])

    #@mlab.animate(delay=10)
    #def anim():
    # now loop through each file and update the z values
    for fname in filenames:
        this_rast = IO.ReadRasterArrayBlocks(fname)
        s.mlab_source.scalars = this_rast
        #f.scene.render()
        #
        mlab.savefig(fname[:-4]+'_3d.png')
Esempio n. 6
0
def savefig(filename,mlabview=[],magnification = 3):
    """
    Save mayavi figure

    Parameters
    ----------

    name : str
        name of the figure
    mlabview : [] | (x,y,z, np.array([ xroll,yroll,zroll]))
        specifyy angle of camera view ( see mayavi.view )
    magnification : int
        resolution of the generated image ( see mayavi.savefig)

    """
    import os


    path = os.path.dirname(filename)
    if not mlabview == []:
        mlab.view(mlabview)
    if os.path.exists(path):
        mlab.savefig(filename+'.png',magnification=magnification )
    else:
        os.mkdir(path)
        mlab.savefig(filename+'.png',magnification=magnification )
    mlab.close()
Esempio n. 7
0
    def plot_mcontour(self, ndim0, ndim1, z, show_mode):
        "use mayavi.mlab to plot contour."
        if not mayavi_installed:
            self.__logger.info("Mayavi is not installed on your device.")
            return
        #do 2d interpolation
        #get slice object
        s = np.s_[0:ndim0:1, 0:ndim1:1]
        x, y = np.ogrid[s]
        mx, my = np.mgrid[s]
        #use cubic 2d interpolation
        interpfunc = interp2d(x, y, z, kind='cubic')
        newx = np.linspace(0, ndim0, 600)
        newy = np.linspace(0, ndim1, 600)
        newz = interpfunc(newx, newy)
        #mlab
        face = mlab.surf(newx, newy, newz, warp_scale=2)
        mlab.axes(xlabel='x', ylabel='y', zlabel='z')
        mlab.outline(face)
        #save or show
        if show_mode == 'show':
            mlab.show()
        elif show_mode == 'save':
            mlab.savefig('mlab_contour3d.png')
        else:
            raise ValueError('Unrecognized show mode parameter : ' +
                             show_mode)

        return
Esempio n. 8
0
 def plot_channel(self,fn_hist,fn_corrvec,fn_arrows):
     list_channel = self.list_channel
     import matplotlib.pyplot as plt
     # plot vecs
     plt.figure()
     #vecs = np.array((3,len(list_channel)))
     for i in range(3):
         vecs = [chan.vec[i] for chan in list_channel]
         plt.hist(vecs,bins=100)
     plt.savefig(fn_hist)
     # plot corr vecs
     plt.figure()
     v0 = [chan.vec[0] for chan in list_channel]
     v1 = [chan.vec[1] for chan in list_channel]
     v2 = [chan.vec[2] for chan in list_channel]
     plt.plot(v0,v1,"o")
     plt.plot(v0,v2,"o")
     plt.plot(v1,v2,"o")
     plt.savefig(fn_corrvec)
     # cluster
     import matplotlib.pyplot as plt
     import mayavi.mlab as mlab
     #from mlab import quiver3d
     mlab.options.backend = 'envisage'         # one way to save visualization
     #f = mlab.figure()
     mlab.figure()
     x = [np.zeros(v.shape) for v in v0]
     mlab.quiver3d(x,x,x,v0,v1,v2)
     mlab.savefig(fn_arrows)
Esempio n. 9
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!
def short_branches():
    """
    Visualization of short branches of the skeleton.
    
    """
    data1_sk = glob.glob('/backup/yuliya/vsi05/skeletons_largdom/*.h5')
    data1_sk.sort()

    for i,j, k in zip(d[1][37:47], data1_sk[46:56], ell[1][37:47]):
        g = nx.read_gpickle(i)
        dat = tb.openFile(j)
        skel = np.copy(dat.root.skel)
        bra = np.copy(dat.root.branches)
        mask = np.zeros_like(skel)    
        dat.close()
    
        length = nx.get_edge_attributes(g, 'length')
        number = nx.get_edge_attributes(g, 'number')
        num_dict = {}
        for m in number:
            for v in number[m]:
                num_dict.setdefault(v, []).append(m)
        find_br = ndimage.find_objects(bra)
        for l in list(length.keys()):
            if length[l]<0.5*k: #Criteria
                for b in number[l]:
                    mask[find_br[b-1]] = bra[find_br[b-1]]==b
        mlab.figure(bgcolor=(1,1,1), size=(1200,1200))
        mlab.contour3d(skel, colormap='hot')
        mlab.contour3d(mask)
        mlab.savefig('/backup/yuliya/vsi05/skeletons/short_bran/'+ i[42:-10] + '.png')
        mlab.close()
Esempio n. 11
0
def mayavi_scraper(block, block_vars, gallery_conf):
    """Scrape Mayavi images.

    Parameters
    ----------
    block : tuple
        A tuple containing the (label, content, line_number) of the block.
    block_vars : dict
        Dict of block variables.
    gallery_conf : dict
        Contains the configuration of Sphinx-Gallery

    Returns
    -------
    rst : str
        The ReSTructuredText that will be rendered to HTML containing
        the images. This is often produced by
        :func:`sphinx_gallery.gen_rst.figure_rst`.
    """
    from mayavi import mlab
    image_path_iterator = block_vars['image_path_iterator']
    image_paths = list()
    e = mlab.get_engine()
    for scene, image_path in zip(e.scenes, image_path_iterator):
        mlab.savefig(image_path, figure=scene)
        # make sure the image is not too large
        scale_image(image_path, image_path, 850, 999)
        image_paths.append(image_path)
    mlab.close(all=True)
    return figure_rst(image_paths, gallery_conf['src_dir'])
Esempio n. 12
0
def make_fractal_movie(seed="X", iter=6):
    """
    """
    f = hilbert.VoxelisedFractal.fromSeed(seed, iter)
    f.center_fractal()
    pos = np.array([vox.pos for vox in f.fractal])
    max_pos = np.max(pos, axis=0)
    mask = lambda x: np.sum((x[0:3]/max_pos[0:3])**2) <= 1
    f = f.to_pretty_plot(refine=5, mayavi=True, mask=mask)
    fig = mlab.gcf()
    fig.scene.set_size([1024, 768])
    fig.scene.render()
    mlab.savefig("example/img/fractal_rotate0000.png")
    step = 5
    for ii in range(1, int(720/step)):
        fig.scene.camera.azimuth(step)
        fig.scene.render()
        mlab.savefig("example/img/fractal_rotate{:04d}.png".format(ii))

    mlab.savefig("example/img/fractal_zoom0000.png")
    nsteps = 200
    for ii in range(nsteps):
        fig.scene.camera.zoom(1.02)
        fig.scene.render()
        mlab.savefig("example/img/fractal_zoom{:04d}.png".format(ii))

    for ii in range(nsteps, nsteps + int(720/step)):
        fig.scene.camera.azimuth(step)
        fig.scene.render()
        mlab.savefig("example/img/fractal_zoom{:04d}.png".format(ii))
    return None
Esempio n. 13
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()
Esempio n. 14
0
def Main(outputFolder, isData, normalized = True):
    assert isinstance(outputFolder, str)
    min, max = 0., 1.
    if os.path.splitext(args.file)[1] == '.arff':
        datasets, targets, targetMap = loadFromArff(args.file)
    elif os.path.splitext(args.file)[1] == '.npy':
        datasets = numpy.load(args.file)
        min = -1.
    else:
        assert False

    datasets = (lambda x : histogramEqualization(x, min=min, max=max) if normalized else x)(datasets)
    if normalized : assert (datasets.min(), datasets.max()) == (min, max)

    if not os.path.isdir("%s/Pictures" % outputFolder):
        os.makedirs("%s/Pictures" % outputFolder)

    global listIndex
    if listIndex is None or (len(listIndex) >= len(datasets)):
        listIndex = xrange(len(datasets))

    for index in listIndex:
        assert 0 <= index < len(datasets)
        mlab.figure("Index : %d" % index, bgcolor=(1,1,1))
        showArray(datasets[index], isData)
        mlab.savefig("%s/Pictures/Index_%d.png" % (outputFolder, index))
        if isData:
            saveData('%s/Pictures/%s_Index_%d.txt' % (outputFolder, targetMap.reverse_mapping[targets[index]], index), datasets[index])
        else:
            saveData('%s/Pictures/Index_%d.txt' % (outputFolder, index), datasets[index])
        mlab.close()
Esempio n. 15
0
def draw_volume(scalars):
    # filts out low data
    nmax = np.amax(scalars)
    nmin = np.amin(scalars)
    #nptp = nmax - nmin
    #lowBound = nmin + nptp*0
    #for i in np.nditer(scalars, op_flags=['readwrite']):
    #    if i<lowBound: i[...] = 0
        
    # Get the shape of axes
    shape = scalars.shape
    
    # draw
    fig = mlab.figure(bgcolor=(0,0,0), size=(800,800) )
    src = mlab.pipeline.scalar_field(scalars)
    src.update_image_data = True
    #src.spacing = [1, 1, 1]
    
    vol = mlab.pipeline.volume(src)
    
    change_volume_property(vol)
    #change_test(vol)
    
    #vol = mlab.pipeline.image_plane_widget(src,plane_orientation='z_axes', slice_index=shape[2]/2)
    ax = mlab.axes(nb_labels=5, ranges=(0,shape[0],0,shape[1],0,shape[2]))
    
    mlab.savefig("result.jpg")
    print "nmax =", nmax
    print "nmin =", nmin
    
    viewkeeper = mlab.view()
    print "View", mlab.view()
    draw_map(shape[0],shape[1])
    mlab.view(viewkeeper[0],viewkeeper[1],viewkeeper[2],viewkeeper[3])
Esempio n. 16
0
def plot_isosurface(crystal):
    filename = './output/potentialfield.txt'
    data = np.genfromtxt(filename, delimiter='\t')
    size = np.round((len(data))**(1/3))
    X = np.reshape(data[:,0], (size,size,size))
    Y = np.reshape(data[:,1], (size,size,size))
    Z = np.reshape(data[:,2], (size,size,size))
    DeltaU = np.reshape(data[:,3], (size,size,size))
    average = np.average(crystal.coordinates[:,0])
    start = average - crystal.a
    end = average + crystal.a
    coords1 = np.array([[start, start, start]])
    coords2 = np.array([[end, end, end]])
    array1 = np.repeat(coords1,len(crystal.coordinates),axis=0)
    array2 = np.repeat(coords2,len(crystal.coordinates),axis=0)
    basefilter1 = np.greater(crystal.coordinates,array1)
    basefilter2 = np.less(crystal.coordinates,array2)
    basefilter = np.nonzero(np.all(basefilter1*basefilter2, axis=1))
    base = crystal.coordinates[basefilter]   

    mlab.figure(bgcolor=(1, 1, 1), fgcolor=(1, 1, 1), size=(2048,2048))
    dataset = mlab.contour3d(X, Y, Z, DeltaU, contours=[3.50],color=(1,0.25,0))
    scatter = mlab.points3d(base[:,0], 
                            base[:,1], 
                            base[:,2],
                            color=(0.255,0.647,0.88),
                            resolution=24, 
                            scale_factor=1.0, 
                            opacity=0.40)
    mlab.view(azimuth=17, elevation=90, distance=10, focalpoint=[average,average-0.2,average])
    mlab.draw()
    savename = './output/3Dpotential.png'
    mlab.savefig(savename, size=(2048,2048))
    mlab.show()
Esempio n. 17
0
def snapshot(cuds, filename):
    """ Save a snapshot of the cuds object using the default visualisation.

     Parameters
     ----------
     cuds :
         A top level cuds object (e.g. a mesh). The method will detect
         the type of object and create the appropriate visualisation.

     filename : string
         The filename to use for the output file.

    """
    # adapt to CUDSSource
    if isinstance(cuds, (ABCMesh, ABCParticles, ABCLattice)):
        source = CUDSSource(cuds=cuds)
    else:
        msg = 'Provided object {} is not of any known cuds type'
        raise TypeError(msg.format(type(cuds)))

    # set image size
    size = 800, 600

    with get_figure(size=size):
        # add source
        mlab.pipeline.add_dataset(source)

        modules = default_module(source)

        # add default modules
        for module in modules:
            source.add_module(module)

        mlab.savefig(filename, size=size)
    def setUp(self):
        # set up source
        sgrid = datasets.generateStructuredGrid()
        source = VTKDataSource(data=sgrid)

        self.engine = mlab.get_engine()

        # set up scene, first scene is empty
        # second scene has the settings we want to restore
        for _ in range(2):
            fig = mlab.figure()
            fig.scene.off_screen_rendering = True

        # add source
        self.engine.add_source(source)

        # add more modules
        self.engine.add_module(IsoSurface())
        self.engine.add_module(Text3D())
        self.modules = source.children[0].children

        # set camera
        self.view = (25., 14., 20., [0., 0., 2.5])
        mlab.view(*self.view)

        # save the visualisation
        self.temp_dir = tempfile.mkdtemp()
        self.filename = os.path.join(self.temp_dir, "test_vis.mv2")
        self.engine.save_visualization(self.filename)

        # save the scene as an image for comparison later
        self.ref_saved_filename = os.path.join(self.temp_dir, "ref_saved.png")
        mlab.savefig(self.ref_saved_filename)
    def test_restore_scene(self):
        # create a new scene with new data source
        fig = mlab.figure()
        fig.scene.off_screen_rendering = True

        sgrid_2 = datasets.generateStructuredGrid()
        source = VTKDataSource(data=sgrid_2)
        self.engine.add_source(source)

        # when
        restore_scene(self.filename, scene_index=1)

        # then
        modules = source.children[0].children

        self.check_items_same_types(modules, self.modules)
        self.check_items_not_same_object(modules, self.modules)
        self.check_camera_view(mlab.view(), self.view)

        # save the scene to a file
        saved_filename = os.path.join(self.temp_dir, "test_restore.png")
        mlab.savefig(saved_filename)

        # compare the pixels to the desired one
        self.check_images_almost_identical(saved_filename,
                                           self.ref_saved_filename)
Esempio n. 20
0
def plot_inverse_operator(subject, fnout_img=None, verbose=None):
    """"Reads in and plots the inverse solution."""

    # get name of inverse solution-file
    subjects_dir = os.environ.get('SUBJECTS_DIR')
    fname_dir_inv = os.path.join(subjects_dir,
                                 subject)

    for files in os.listdir(fname_dir_inv):
        if files.endswith(",cleaned_epochs_avg-7-src-meg-inv.fif"):
            fname_inv = os.path.join(fname_dir_inv,
                                     files)
            break

    try:
        fname_inv
    except NameError:
        print "ERROR: No forward solution found!"
        sys.exit()


    # read inverse solution
    inv = min_norm.read_inverse_operator(fname_inv)

    # print some information if desired
    if verbose is not None:
        print "Method: %s" % inv['methods']
        print "fMRI prior: %s" % inv['fmri_prior']
        print "Number of sources: %s" % inv['nsource']
        print "Number of channels: %s" % inv['nchan']


    # show 3D source space
    lh_points = inv['src'][0]['rr']
    lh_faces = inv['src'][0]['tris']
    rh_points = inv['src'][1]['rr']
    rh_faces = inv['src'][1]['tris']

    # create figure and plot results
    fig_inverse = mlab.figure(size=(1200, 1200),
                              bgcolor=(0, 0, 0))

    mlab.triangular_mesh(lh_points[:, 0],
                         lh_points[:, 1],
                         lh_points[:, 2],
                         lh_faces)

    mlab.triangular_mesh(rh_points[:, 0],
                         rh_points[:, 1],
                         rh_points[:, 2],
                         rh_faces)

    # save result
    if fnout_img is not None:
        mlab.savefig(fnout_img,
                     figure=fig_inverse,
                     size=(1200, 1200))

    mlab.close(all=True)
Esempio n. 21
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()
Esempio n. 22
0
 def anim():
     f = mlab.gcf()
     for count, i in enumerate(range(2,361,2)):
     #while 1:
         f.scene.camera.azimuth(degree_step)
         f.scene.render()
         mlab.savefig('/Users/jessebrown/Desktop/mayavi_figs/r_hipp_network%03d.png' %count)
         yield
def beach(x,y):
    q = x*(Lx - x)*y*(Ly - y)
    q = 0.5*x**2 + 0.5*y
    q += (q.min() + 0.1) 
    q /= (q.max() + 0.1)
    s = mlab.mesh(x, y, q)
    mlab.savefig("beach.png")
    return q
Esempio n. 24
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!
Esempio n. 25
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()
Esempio n. 26
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=0.15)
    mlab.savefig("points3d.png", size=png_size)
    mlab.clf()
Esempio n. 27
0
def field(potential, outfile=None, title="BEM Calculation (field)", cmap="spectral"):
    from mayavi import mlab

    u,v,w = np.gradient(potential)
    obj = mlab.quiver3d(u,v,w, colormap=cmap, vmax=10)
    mlab.colorbar()
    if outfile:
        mlab.savefig(outfile)
    return obj
Esempio n. 28
0
    def snapshot(self,params):
        res=np.ceil(500*params.dpi/8000*111)	#TODO this resolution is too hi

        from mayavi import __version__ as mayavi_version
        if float(mayavi_version[:3]) >= 4.3:
            mlab.savefig(params.savefile,figure=self.scene.mayavi_scene,
                size=(res,res))
        else:
            self.hack_mlabsavefig(params.savefile,size=(res,res))
Esempio n. 29
0
def surfacePlot(
    Hmap,
    nrows,
    ncols,
    xyspacing,
    zscale,
    name,
    hRange,
    file_path,
    lutfromfile,
    lut,
    lut_file_path,
    colorbar_on,
    save,
    show,
):

    # Create a grid of the x and y coordinates corresponding to each pixel in the height matrix
    x, y = np.mgrid[0 : ncols * xyspacing : xyspacing, 0 : nrows * xyspacing : xyspacing]

    # Create a new figure
    mlab.figure(size=(1000, 1000))

    # Set the background color if desired
    # bgcolor=(0.16, 0.28, 0.46)

    # Create the surface plot of the reconstructed data
    plot = mlab.surf(x, y, Hmap, warp_scale=zscale, vmin=hRange[0], vmax=hRange[1], colormap=lut)

    # Import the LUT from a file if necessary
    if lutfromfile:
        plot.module_manager.scalar_lut_manager.load_lut_from_file(lut_file_path)

    # Draw the figure with the new LUT if necessary
    mlab.draw()

    # Zoom in to fill the entire window
    f = mlab.gcf()
    f.scene.camera.zoom(1.05)

    # Change the view to a top-down perspective
    mlab.view(270, 0)

    # Add a colorbar if indicated by colorbar_on (=True)
    if colorbar_on:
        # mlab.colorbar(title='Height (nm)', orientation='vertical')
        mlab.colorbar(orientation="vertical")

    # Save the figure if indicated by save (=True)
    if save:
        mlab.savefig(file_path, size=(1000, 1000))
        if show == False:
            mlab.close()

    # Keep the figure open if indicated by show (=True)
    if show:
        mlab.show()
Esempio n. 30
0
def anim():
    from mayavi import mlab as M
    M.options.offscreen = True
    M.test_mesh()
    f = M.figure()
    print f
    for i in range(36):
        f.scene.camera.azimuth(10)
        M.savefig('img%02i.png'%i)
    cen = np.vstack((cen, [0, 0, 0, 1]))
    mlab.points3d(cen[:, 0],
                  cen[:, 1],
                  cen[:, 2],
                  color=(1, 0, 0),
                  scale_factor=0.5)

    velo = filter_ground(velo, cen, th=1000)

    # draw annotated objects
    filled_idx = np.zeros((velo.shape[0], ), dtype=bool)
    for j, box in enumerate(tracklet_rects[i]):
        draw_class.draw_box(box, tracklet_ids[i][j])
        idx = in_hull(velo[:, :3], box[:3, :].T)
        draw_class.draw_cluster(velo[idx, :], tracklet_ids[i][j])
        filled_idx |= idx

    # print other points
    draw_class.draw_cluster(velo[~filled_idx, :])

    mlab.view(azimuth=180, elevation=0, distance=30,
              focalpoint=[0., 0., 0.])  # tracking-view
    # mlab.view(azimuth=180, elevation=0, distance=70, roll=90, focalpoint=[0., 0., 0.]) # over-view

    plt_img = imayavi_return_inline(fig=fig)
    plt.imshow(plt_img)
    plt_fig.canvas.draw()

    mlab.savefig('./output/%s_%s/test_%03d.png' % (date, drive, i))
    print('./output/%s_%s/test_%03d.png' % (date, drive, i), plt_img.shape)
Esempio n. 32
0
def plotIsosurfaces3D(x3D,
                      y3D,
                      z3D,
                      surface3Dlist,
                      contourList,
                      slice3Dlist=(None, ),
                      boundSurface=(None, ),
                      customColors=(None, ),
                      figDir='./',
                      name='UntitledIsosurface',
                      sliceOriantations=(None, ),
                      sliceOffsets=(None, ),
                      boundSlice=(None, ),
                      sliceValRange=(None, )):
    from mayavi import mlab
    from mayavi.modules.contour_grid_plane import ContourGridPlane
    from mayavi.modules.outline import Outline
    from mayavi.api import Engine
    import numpy as np
    from warnings import warn

    x3D, y3D, z3D = np.array(x3D), np.array(y3D), np.array(z3D)

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

    if customColors[0] is not None:
        customColors = iter(customColors)
    else:
        customColors = iter(
            ('inferno', 'viridis', 'coolwarm', 'Reds', 'Blues') * 2)

    contourList = iter(contourList)
    if sliceOriantations[0] is not None:
        sliceOriantations = iter(sliceOriantations)
    else:
        sliceOriantations = iter(('z_axes', ) * len(slice3Dlist))

    if boundSurface[0] is None:
        boundSurface = (x3D.min(), x3D.max(), y3D.min(), y3D.max(), z3D.min(),
                        z3D.max())

    if boundSlice[0] is None:
        boundSlice = (x3D.min(), x3D.max(), y3D.min(), y3D.max(), z3D.min(),
                      z3D.max())

    if sliceOffsets[0] is None:
        sliceOffsets = iter((0, ) * len(slice3Dlist))
    else:
        sliceOffsets = iter(sliceOffsets)

    if sliceValRange[0] is None:
        sliceValRange = iter((None, None) * len(slice3Dlist))
    else:
        sliceValRange = iter(sliceValRange)

    mlab.figure(name,
                engine=engine,
                size=(1200, 900),
                bgcolor=(1, 1, 1),
                fgcolor=(0.5, 0.5, 0.5))

    for surface3D in surface3Dlist:
        color = next(customColors)
        # If a colormap given
        if isinstance(color, str):
            mlab.contour3d(x3D,
                           y3D,
                           z3D,
                           surface3D,
                           contours=next(contourList),
                           colormap=color,
                           extent=boundSurface)
        # If only one color of (0-1, 0-1, 0-1) given
        else:
            mlab.contour3d(x3D,
                           y3D,
                           z3D,
                           surface3D,
                           contours=next(contourList),
                           color=color,
                           extent=boundSurface)

        # cgp = ContourGridPlane()
        # engine.add_module(cgp)
        # cgp.grid_plane.axis = 'y'
        # cgp.grid_plane.position = x3D.shape[1] - 1
        # cgp.contour.number_of_contours = 20
        # # contour_grid_plane2.actor.mapper.scalar_range = array([298., 302.])
        # # contour_grid_plane2.actor.mapper.progress = 1.0
        # # contour_grid_plane2.actor.mapper.scalar_mode = 'use_cell_data'
        # cgp.contour.filled_contours = True
        # cgp.actor.property.lighting = False

    for slice3D in slice3Dlist:
        sliceOriantation = next(sliceOriantations)
        sliceOffset = next(sliceOffsets)
        if sliceOriantation == 'z_axes':
            origin = np.array([boundSlice[0], boundSlice[2], sliceOffset])
            point1 = np.array([boundSlice[1], boundSlice[2], sliceOffset])
            point2 = np.array([boundSlice[0], boundSlice[3], sliceOffset])
        elif sliceOriantation == 'x_axes':
            origin = np.array([sliceOffset, boundSlice[2], boundSlice[4]])
            point1 = np.array([sliceOffset, boundSlice[3], boundSlice[4]])
            point2 = np.array([sliceOffset, boundSlice[2], boundSlice[5]])
        else:
            origin = np.array([boundSlice[0], sliceOffset, boundSlice[4]])
            point1 = np.array([boundSlice[1], sliceOffset, boundSlice[4]])
            point2 = np.array([boundSlice[0], sliceOffset, boundSlice[5]])

        image_plane_widget = mlab.volume_slice(
            x3D,
            y3D,
            z3D,
            slice3D,
            plane_orientation=sliceOriantation,
            colormap=next(customColors),
            vmin=next(sliceValRange),
            vmax=next(sliceValRange))
        image_plane_widget.ipw.reslice_interpolate = 'cubic'
        image_plane_widget.ipw.origin = origin
        image_plane_widget.ipw.point1 = point1
        image_plane_widget.ipw.point2 = point2
        # image_plane_widget.ipw.slice_index = 2
        image_plane_widget.ipw.slice_position = sliceOffset

    # Contour grid plane at last y if the last slice is in xy plane
    if sliceOriantation == 'z_axes':
        cgp2 = ContourGridPlane()
        engine.add_module(cgp2)
        cgp2.grid_plane.axis = 'y'
        cgp2.grid_plane.position = x3D.shape[1] - 1
        cgp2.contour.number_of_contours = 20
        cgp2.contour.filled_contours = True
        cgp2.actor.property.lighting = False

    outline = Outline()
    engine.add_module(outline)
    outline.actor.property.color = (0.2, 0.2, 0.2)
    outline.bounds = np.array(boundSurface)
    outline.manual_bounds = True

    mlab.view(azimuth=270, elevation=45)
    mlab.move(-500, 0, 0)
    mlab.savefig(figDir + '/' + name + '.png', magnification=3)
    print('\nFigure ' + name + ' saved at ' + figDir)
    mlab.show()
scene = engine.scenes[0]
scene.scene.background = (1.0, 1.0, 1.0)  # white background

scene.scene.camera.position = [
    -62.711753438810604, -53.97895685490163, 35.505462783605786
]
scene.scene.camera.focal_point = [
    -85.78755652469613, -4.492737440904958, -3.103982951529997
]
scene.scene.camera.view_angle = 15.36
scene.scene.camera.view_up = [
    -0.24399876718044772, 0.5232570448142633, 0.8164965809277254
]
scene.scene.camera.clipping_range = [39.987551578962204, 100.87872165042502]
scene.scene.camera.compute_view_plane_normal()
scene.scene.render()

col_options += ["elevation"]
for col_type in col_options:
    meshes[col_type].visible = True
    scene.scene.camera.compute_view_plane_normal()
    scene.scene.render()
    meshes[col_type].visible = True
    if args.nolight:
        meshes[col_type].actor.property.edge_visibility = True
        meshes[col_type].actor.property.line_width = 1.5
    filename = save_path / f"{col_type}.png"
    mlab.savefig(str(filename), magnification=1)
    meshes[col_type].visible = False
    meshes[col_type].actor.property.edge_visibility = False
Esempio n. 34
0
        #scan_dir = f'data/kitti/object/training/velodyne_reduced/{file_id}.bin'
        scan_dir = f'velodyne_reduced_reduced/{file_id}.bin'
        if not os.path.exists(scan_dir):
            print("skip %s for pc" % file_id)
            continue
        scan = np.fromfile(scan_dir, dtype=np.float32).reshape(-1, 4)

        # load labels
        #label_dir = f'data/kitti/object/training/label_2/{file_id}.txt'
        label_dir = f'label_2_reduced/{file_id}.txt'
        with open(label_dir, 'r') as f:
            labels = f.readlines()

        # draw point cloud
        plot = mlab.points3d(scan[:, 0],
                             scan[:, 1],
                             scan[:, 2],
                             mode="point",
                             figure=fig,
                             color=(1, 0, 0))

        for line in labels:
            draw_box(line, colors)
        mlab.view(azimuth=230, distance=100)
        mlab.savefig(filename='reduced_output/%s_GT.png' % file_id)
        print("Saved %s_GT.png" % file_id)

        mlab.clf(fig)

    mlab.close(all=True)
Esempio n. 35
0
brain = stc.plot(
    subject='fsaverage',
    hemi='both',
    background='white',
    foreground='black',
    time_label='',
    initial_time=0,
    smoothing_steps=5,
    figure=fig,
)
brain.scale_data_colormap(0, 1, stc.data.max(), True)
brain.add_annotation('aparc', borders=2)

# Save some views
mlab.view(0, 90, 450, [0, 0, 0])
mlab.savefig('../paper/figures/degree_rh.png', magnification=4)
mlab.view(180, 90, 450, [0, 0, 0])
mlab.savefig('../paper/figures/degree_lh.png', magnification=4)
mlab.view(180, 0, 450, [0, 10, 0])
mlab.savefig('../paper/figures/degree_top.png', magnification=4)
mlab.view(180, 180, 480, [0, 10, 0])
mlab.savefig('../paper/figures/degree_bottom.png', magnification=4)

# Plot the connectivity diagram
fig, _ = con_parc.plot(title='Parcel-wise Connectivity',
                       facecolor='white',
                       textcolor='black',
                       node_edgecolor='white',
                       colormap='plasma_r',
                       vmin=0,
                       show=False)
Esempio n. 36
0
def rotat_visu():
    hours = np.tile(np.repeat(range(0, 24), 5), 3)
    azimuths = np.arange(0, 360)
    distances = np.append(np.linspace(20000, 6000, 120), np.repeat(6000, 240))
    for azimuth, hour, distance in zip(azimuths[234:], hours[234:],
                                       distances[234:]):
        print(hour)
        T = concat_dfs(inpath, column=hour, regex="TPC")
        Q = concat_dfs(inpath, column=hour, regex="QPC")
        U = concat_dfs(inpath, column=hour, regex="UPC")
        V = concat_dfs(inpath, column=hour, regex="VPC")

        # Sum the PCs
        T = T.sum(axis=1)
        Q = Q.sum(axis=1)
        U = U.sum(axis=1)
        V = V.sum(axis=1)

        T = T.values.reshape(239, 244)
        Q = Q.values.reshape(239, 244)
        U = U.values.reshape(239, 244)
        V = V.values.reshape(239, 244)
        W = np.zeros(U.shape)
        s = np.ones(U.shape)

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

        # # Surface plot
        pts = mlab.quiver3d(x,
                            y,
                            z,
                            s,
                            s,
                            s,
                            scalars=T,
                            mode='cube',
                            scale_factor=0,
                            colormap='bwr')
        pts.glyph.color_mode = "color_by_scalar"
        pts.glyph.glyph_source.glyph_source.center = [0, 0, 0]

        # pts.module_manager.scalar_lut_manager.lut.table = T
        # draw()

        mesh = mlab.pipeline.delaunay2d(pts)  # Create and visualize the mesh
        surf = mlab.pipeline.surface(mesh, colormap='bwr', vmin=12, vmax=26)
        # surf.module_manager.scalar_lut_manager.reverse_lut = True # reverse colormap
        sc = mlab.scalarbar(surf, title="Temperature (C)", label_fmt="%.0f")

        sc.scalar_bar_representation.position = [0.1, 0.9]
        sc.scalar_bar_representation.position2 = [0.8, 0.05]

        # Quiver plot
        mask_point = 4
        quiver3d(x[::mask_point, ::mask_point],
                 y[::mask_point, ::mask_point],
                 z[::mask_point, ::mask_point] + 50,
                 U[::mask_point, ::mask_point],
                 V[::mask_point, ::mask_point],
                 W[::mask_point, ::mask_point],
                 opacity=0.8,
                 mode='2darrow',
                 color=(0.3, 0.3, 0.3),
                 scale_factor=150,
                 transparent=True)

        # mlab.axes()

        mlab.text(0.45,
                  0.97,
                  "Time: " + str(hour).zfill(3) + "H",
                  width=0.1,
                  line_width=0.01,
                  color=(0, 0, 0))

        mlab.view(azimuth=azimuth,
                  elevation=60,
                  distance=distance,
                  focalpoint=np.array([3500, 2500, 0]))
        mlab.savefig(outpath + str(azimuth).zfill(3) + ".png",
                     size=(1420, 1080),
                     magnification='auto')
        mlab.close()
Esempio n. 37
0

coil_data_fil, params_fil = get_all_coil_data("../../tests/w7x/w7x_fil.hdf5")
_, _, r_fil, _ = CoilSet.get_outputs(coil_data_fil, params_fil)
centroid_fil = CoilSet.get_r_centroid(coil_data_fil, params_fil)
coil_data_fb, params_fb = get_all_coil_data("../../tests/w7x/w7x_fb.hdf5")
_, _, r_fb, _ = CoilSet.get_outputs(coil_data_fb, params_fb)
centroid_fb = CoilSet.get_r_centroid(coil_data_fb, params_fb)
coil_data_rot, params_rot = get_all_coil_data("../../tests/w7x/w7x_rot.hdf5")
_, _, r_rot, _ = CoilSet.get_outputs(coil_data_rot, params_rot)
centroid_rot = CoilSet.get_r_centroid(coil_data_rot, params_rot)

r_surf, nn, sg, _ = read_w7x_data()
mlab.options.offscreen = True
mlab.figure(size=(2400, 2400), bgcolor=(1, 1, 1))
p = plot_surface(r_surf)
#r_c = compute_r_centroid(NS, fc_init)
#p = plot_coils(r_fil, color=(0.8,0.0,0.0))
#p = plot_coils(r_fb, color=(0.0,0.0,0.8))
p = plot_coils(r_rot, color=(0.0, 0.0, 0.8))
mlab.view(azimuth=0.0,
          elevation=180,
          distance=26.5,
          focalpoint=(0.0, 0.0, 0.0),
          roll=None,
          reset_roll=True)
mlab.savefig('w7x.png', figure=mlab.gcf())
#mlab.savefig('w7x.pdf', figure=mlab.gcf())
#mlab.savefig('w7x.eps', figure=mlab.gcf())
mlab.clf()
Esempio n. 38
0
#H=nx.krackhardt_kite_graph()
#H=nx.Graph();H.add_edge('a','b');H.add_edge('a','c');H.add_edge('a','d')
#H=nx.grid_2d_graph(4,5)
H=nx.cycle_graph(20)

# reorder nodes from 0,len(G)-1
G=nx.convert_node_labels_to_integers(H)
# 3d spring layout
pos=nx.spring_layout(G,dim=3)
# numpy array of x,y,z positions in sorted node order
xyz=np.array([pos[v] for v in sorted(G)])
# scalar colors
scalars=np.array(G.nodes())+5

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

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

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

mlab.savefig('mayavi2_spring.png')
mlab.show() # interactive window
Esempio n. 39
0
    def cross_section(self,
                      axis,
                      pct=0.5,
                      show_axis=True,
                      show=True,
                      save=None,
                      startup=True):
        """
        Plot a cross-section of the model, with the Y-axis plotting depth

        If axis == X, the slice is normal to the Y-axis
        if axis == Y, the slice is normal to the X-axis

        :type axis: str
        :param axis: axis of axis to slice along, 'X', 'Y'
        :type pct: float
        :param pct: percentage to slice the model at based on the model range.
            defaults to 50%, or the middle of the model
        :type show_axis: bool
        :param show_axis: show the axis of the plot
        :type save: str
        :param save: save the figure with a unique generic identifier
        :type show: bool
        :param show: show the figure after making it
        :type startup: bool
        :param startup: run the _startup() function which closes all instances
            of mlab and creates a new mlab figure and engine. Normally the
            necessary thing to do so defaults to True
        """
        src_color = self.kwargs.get("src_color", "g")
        src_marker = self.kwargs.get("src_marker", "sphere")
        rcv_color = self.kwargs.get("rcv_color", "w")
        rcv_marker = self.kwargs.get("rcv_marker", "2ddiamond")

        if startup:
            self._startup()

        axis = axis.upper()

        def slice_range(ranges_):
            """
            Convenience function to calculate where to slice by checking the
            min and max of the range and multiplying by a percentage

            :type ranges_: list
            :param ranges_: [xmin, xmax, ymin, ymax, zmin, zmax]
            """
            if axis == "X":
                return pct * (ranges_[1] - ranges_[0]) + ranges_[0]
            elif axis == "Y":
                return pct * (ranges_[3] - ranges_[2]) + ranges_[2]

        # Determine what part of the axis we are slicing
        slice_val = slice_range(self.ranges)
        tag = slice_range(self.axes_ranges)

        logger.info(
            f"Cross section [{axis}] of '{self.fid}'  at {slice_val*1E-3}")
        if show_axis:
            set_axes(xyz=[True, True, False],
                     ranges=self.axes_ranges,
                     **self.kwargs)

        self._cut_plane(axis=axis, slice_at=slice_val)

        # Differentiate which way were slicing to put the sources and receivers
        slice_x, slice_y = None, None
        if axis == "X":
            slice_x = slice_val
        elif axis == "Y":
            slice_y = slice_val

        # Plot the sources and receivers along a given slice
        if self.rcvs is not None:
            srcrcv(self.rcvs,
                   color=rcv_color,
                   x_value=slice_x,
                   y_value=slice_y,
                   marker=rcv_marker)
        if self.srcs is not None:
            # Sources default to spheres because I didn't want to figure out how
            # to rotate 2d glyphs
            srcrcv(self.srcs,
                   color=src_color,
                   x_value=slice_x,
                   y_value=slice_y,
                   marker=src_marker)

        # Set the camera with a side on view. No preset so set to the preset and
        # rotate to get to the proper frame of reference
        scene = self.engine.scenes[0]
        if axis == "X":
            scene.scene.x_plus_view()
        elif axis == "Y":
            scene.scene.y_plus_view()
            scene.scene.camera.roll(90)

        # Plot extras
        colorscale(orientation="horizontal", **self.kwargs)

        # Annotation location changes based on which axis you slice
        anno_tag = f"{axis.lower()}={pct*1E2}%={tag:.2f}km"
        if axis == "X":
            annotate(x=.2, y=.3, s=anno_tag, c="k", width=0.15)
        elif axis == "Y":
            annotate(x=.27, y=.3, s=anno_tag, c="k", width=0.15)

        # Finalize
        save_tag = None
        if save:
            save_tag = save.format(tag=f"{tag:.0f}km")
            mlab.savefig(save_tag)
        if show:
            mlab.show()
        else:
            mlab.close(self.fig)

        return save_tag
Esempio n. 40
0
    def depth_slice(self,
                    depth_km="surface",
                    save=None,
                    show=True,
                    startup=True,
                    anno_text=None):
        """
        Plot a topdown view of the model, either with a surface projection
        (map view) or at some depth slice determined by `depth_km`

        :type depth_km: float or None
        :param depth_km: depth to show the model at in units of km, by default
            plots a map view of the 'surface'
        :type save: str
        :param save: save the figure with a unique generic identifier
        :type show: bool
        :param show: show the figure after making it
        :type startup: bool
        :param startup: run the _startup() function which closes all instances
            of mlab and creates a new mlab figure and engine. Normally the
            necessary thing to do so defaults to True
        :type anno_text: str
        :param anno_text: text to annotate into the corner of the figure, 
            defaults to annotating the depth value
        """
        src_color = self.kwargs.get("src_color", "g")
        src_marker = self.kwargs.get("src_marker", "2dcircle")
        rcv_color = self.kwargs.get("rcv_color", "w")
        rcv_marker = self.kwargs.get("rcv_marker", "2ddiamond")

        if startup:
            self._startup()

        logger.info(f"Depth Slice (Z) of '{self.fid}' at {depth_km} [km]")
        coastline_z = self.ranges[-1]

        if depth_km != "surface":
            depth_m = -1 * abs(depth_km) * 1E3
            coastline_z = depth_m

        # Put the coastline at some height above the topography, or at depth
        if self.coast is not None:
            coastline(self.coast, coastline_z)

        # Plot the stations and receivers
        if self.rcvs is not None:
            srcrcv(self.rcvs,
                   color=rcv_color,
                   z_value=coastline_z,
                   marker=rcv_marker)
        if self.srcs is not None:
            srcrcv(self.srcs,
                   color=src_color,
                   z_value=coastline_z,
                   marker=src_marker)

        # Plot the model at the given height
        # Axes behave weirdly when cutting planes so turn off Y-axis, not sure
        # why this works... sorry
        if depth_km == "surface":
            # Show a surface projection
            self.engine.add_filter(Surface(), self.vtkfr)
            tag = depth_km
            set_axes(xyz=[True, True, False],
                     ranges=self.axes_ranges,
                     **self.kwargs)
        else:
            # Show a slice (plane) at a given depth
            self._cut_plane(axis="Z", slice_at=depth_m)
            tag = f"depth_{int(abs(depth_km))}km"
            set_axes(xyz=[True, False, True],
                     ranges=self.axes_ranges,
                     **self.kwargs)

        # Set the camera with top down view
        scene = self.engine.scenes[0]
        scene.scene.z_plus_view()

        # Plot extras
        colorscale(orientation="vertical", **self.kwargs)
        if anno_text is None:
            anno_text = tag.replace("_", " ")
        annotate(s=anno_text, c="k", width=0.175)  # was 0.2

        # Finalize
        save_tag = None
        if save:
            mlab.savefig(save.format(tag=tag))
            save_tag = save.format(tag=tag)
        if show:
            mlab.show()
        else:
            mlab.close(self.fig)

        return save_tag
    all_boxes = np.concatenate(all_box)

    draw_gt_boxes3d(all_boxes,
                    conf,
                    thres=thres,
                    color=(0, 1, 0),
                    fig=fig,
                    engine=e)

    #mlab.view(azimuth=0, elevation=45, focalpoint='auto', roll=90, figure=fig)
    #mlab.savefig("new6.png", figure=fig)
    scene = e.scenes[-1]
    cam = scene.scene.camera

    mlab.savefig('/home/manojpc/PointRCNN/imagelist/{}_0.png'.format(PC_ID),
                 size=(1920, 1080),
                 magnification=3)

    scene.scene.x_plus_view()
    cam.zoom(2.8)
    # scene.scene.save('/home/manojpc/snapshotx.png',size=(1600,1400))
    mlab.savefig('/home/manojpc/PointRCNN/imagelist/{}_1.png'.format(PC_ID),
                 size=(1920, 1080),
                 magnification=3)
    # mlab.savefig("myfigurex.jpg", size=(1600,1400),figure=fig)
    scene.scene.y_plus_view()
    cam.zoom(1.9)
    mlab.savefig('/home/manojpc/PointRCNN/imagelist/{}_2.png'.format(PC_ID),
                 size=(1920, 1080),
                 magnification=3)
    # mlab.savefig("myfigurey.jpg", size=(1600,1400),figure=fig)
Esempio n. 42
0
import numpy as np
from particle.pipeline import Sand
from mayavi import mlab

# data = np.load("output/geometry/generatedParticles/vae.npy")
# initInd = 281
# for i, particle in enumerate(data[initInd:initInd+30]):
#     Sand(particle).visualize()
#     mlab.savefig(f"/home/chuan/obj/{i+1:02d}.obj")
#     mlab.close(all=True)

data = np.load("data/liutao/v1/particles.npz")["trainSet"]
print(data.shape)
initInd = 114
for i, particle in enumerate(data[initInd:initInd+30]):
    Sand(particle[0]).visualize()
    mlab.savefig(f"/home/chuan/obj/{i+1:02d}.obj")
    mlab.savefig(f"/home/chuan/obj/{i+1:02d}.png")
    mlab.close(all=True)
Esempio n. 43
0
                foreground='black',
                time_label='',
                initial_time=0,
                smoothing_steps=5,
                figure=fig,
                colormap="jet",  # others "bwr"
                subjects_dir=mri_dir,
            )
            brain.scale_data_colormap(fmin, fmid / 4, fmax, True,
                                      center=0)  # optimize these values !!
            brain.add_annotation('HCPMMP1_combined', borders=1, alpha=0.9)

            # Save some views
            mlab.view(0, 90, 450, [0, 0, 0])
            mlab.savefig('{d}{cont}_connectivity_{f}_hcp_sum_rh.png'.format(
                d=save_dir, cont=contrast, f=freq),
                         magnification=4)
            mlab.view(180, 90, 450, [0, 0, 0])
            mlab.savefig('{d}{cont}_connectivity_{f}_hcp_sum_lh.png'.format(
                d=save_dir, cont=contrast, f=freq),
                         magnification=4)
            mlab.view(180, 0, 450, [0, 10, 0])
            mlab.savefig('{d}{cont}_connectivity_{f}_hcp_sum_top.png'.format(
                d=save_dir, cont=contrast, f=freq),
                         magnification=4)
            mlab.view(180, 180, 480, [0, 10, 0])
            mlab.savefig(
                '{d}{cont}_connectivity_{f}_hcp_sum_bottom.png'.format(
                    d=save_dir, cont=contrast, f=freq),
                magnification=4)
            # mlab.close(fig)
Esempio n. 44
0
def plot_potential(grid, potential, along_axes=False, interactive=False, size=(800,700)):
    # The Grid
    u, v = grid.get_nodes(split=True, flat=False)
    u = real(u)
    v = real(v)

    # Create potential and evaluate eigenvalues
    potew = potential.evaluate_eigenvalues_at(grid)
    potew = [ level.reshape(grid.get_number_nodes(overall=False)) for level in potew ]

    # Plot the energy surfaces of the potential
    fig = mlab.figure(size=size)

    for level in potew:
        mlab.surf(u, v, real(level))

    fig.scene.parallel_projection = True
    fig.scene.isometric_view()
    fig.scene.show_axes = True

    mlab.savefig("potential_3D_view.png")

    # Parallele views
    if along_axes is True:
        fig.scene.x_minus_view()
        mlab.savefig("potential_xm_view.png")

        fig.scene.x_plus_view()
        mlab.savefig("potential_xp_view.png")

        fig.scene.y_minus_view()
        mlab.savefig("potential_ym_view.png")

        fig.scene.y_plus_view()
        mlab.savefig("potential_yp_view.png")

        fig.scene.z_minus_view()
        mlab.savefig("potential_zm_view.png")

        fig.scene.z_plus_view()
        mlab.savefig("potential_zp_view.png")

    if interactive is True:
        # Enable interactive plot
        mlab.show()
    else:
        mlab.close(fig)
Esempio n. 45
0
        model = minkunet(args.model, pretrained=True)
    elif 'SPVCNN' in args.model:
        model = spvcnn(args.model, pretrained=True)
    elif 'SPVNAS' in args.model:
        model = spvnas_specialized(args.model, pretrained=True)
    else:
        raise NotImplementedError

    model = model.to(device)

    input_point_clouds = sorted(os.listdir(args.velodyne_dir))
    for point_cloud_name in input_point_clouds:
        if not point_cloud_name.endswith('.bin'):
            continue
        label_file_name = point_cloud_name.replace('.bin', '.label')
        vis_file_name = point_cloud_name.replace('.bin', '.png')
        gt_file_name = point_cloud_name.replace('.bin', '_GT.png')

        pc = np.fromfile('%s/%s' % (args.velodyne_dir, point_cloud_name),
                         dtype=np.float32).reshape(-1, 4)
        label = np.fromfile('%s/%s' % (args.velodyne_dir, label_file_name),
                            dtype=np.int32)
        feed_dict = process_point_cloud(pc, label)
        inputs = feed_dict['lidar'].to(device)
        outputs = model(inputs)
        predictions = outputs.argmax(1).cpu().numpy()
        predictions = predictions[feed_dict['inverse_map']]
        fig = draw_lidar(feed_dict['pc'], predictions.astype(np.int32))
        mlab.savefig('%s/%s' % (output_dir, vis_file_name))
        fig = draw_lidar(feed_dict['pc'], feed_dict['targets_mapped'])
        mlab.savefig('%s/%s' % (output_dir, gt_file_name))
def show_selected_grasps_with_color(m, ply_name_, title, obj_):
    m_good = m[m[:, 1] <= 0.4]
    if len(m_good) > 25:
        m_good = m_good[np.random.choice(len(m_good), size=25, replace=True)]
    m_bad = m[m[:, 1] >= 1.8]
    if len(m_bad) > 25:
        m_bad = m_bad[np.random.choice(len(m_bad), size=25, replace=True)]
    collision_grasp_num = 0

    if save_fig or show_fig:
        # fig 1: good grasps
        mlab.figure(bgcolor=(1, 1, 1),
                    fgcolor=(0.7, 0.7, 0.7),
                    size=(1000, 1000))
        mlab.pipeline.surface(mlab.pipeline.open(ply_name_))
        for a in m_good:
            # display_gripper_on_object(obj, a[0])  # real gripper
            collision_free = display_grasps(a[0], obj_,
                                            color='d')  # simulated gripper
            if not collision_free:
                collision_grasp_num += 1

        if save_fig:
            mlab.savefig("good_" + title + ".png")
            mlab.close()
        elif show_fig:
            mlab.title(title, size=0.5)

        # fig 2: bad grasps
        mlab.figure(bgcolor=(1, 1, 1),
                    fgcolor=(0.7, 0.7, 0.7),
                    size=(1000, 1000))
        mlab.pipeline.surface(mlab.pipeline.open(ply_name_))

        for a in m_bad:
            # display_gripper_on_object(obj, a[0])  # real gripper
            collision_free = display_grasps(a[0], obj_, color=(1, 0, 0))
            if not collision_free:
                collision_grasp_num += 1

        if save_fig:
            mlab.savefig("bad_" + title + ".png")
            mlab.close()
        elif show_fig:
            mlab.title(title, size=0.5)
            mlab.show()
    elif generate_new_file:
        # only to calculate collision:
        collision_grasp_num = 0
        ind_good_grasp_ = []
        for i_ in range(len(m)):
            collision_free = display_grasps(m[i_][0], obj_, color=(1, 0, 0))
            if not collision_free:
                collision_grasp_num += 1
            else:
                ind_good_grasp_.append(i_)
        collision_grasp_num = str(collision_grasp_num)
        collision_grasp_num = (
            4 - len(collision_grasp_num)) * " " + collision_grasp_num
        print("collision_grasp_num =", collision_grasp_num, "| object name:",
              title)
        return ind_good_grasp_
Esempio n. 47
0
                 color=(1,1,0), scale_factor=10, opacity=1)
    mlab.quiver3d(x_sats[co_orb], y_sats[co_orb], z_sats[co_orb],\
                  vx_sats[co_orb], vy_sats[co_orb], vz_sats[co_orb],\
                  color=(1,1,0), scale_factor=30, opacity=1)

    mlab.points3d(x_sats[counter_orb], y_sats[counter_orb], z_sats[counter_orb],\
                 color=(1,0,1), scale_factor=10, opacity=1)
    mlab.quiver3d(x_sats[counter_orb], y_sats[counter_orb], z_sats[counter_orb],\
                  vx_sats[counter_orb], vy_sats[counter_orb], vz_sats[counter_orb],\
                  color=(1,0,1), scale_factor=30, opacity=1)


    mlab.points3d(0, 0, 0, 20,  mode='2dcircle', color=(1,1,1),\
                 scale_factor=1.0, opacity=1, resolution=100)

    mlab.savefig('mw_satellites_3d.png', size=(200, 200))

#mlab.close()
#Function that reads the N-body simulation orbit
"""
def reading_Nbody(snap_name):
    data = np.loadtxt(snap_name)
    #time = data[:,0]
    #Rgal = data[:,1]
    x_sat= data[:,6]
    y_sat = data[:,7]
    z_sat = data[:,8]
    x_gal = data[:,0]
    y_gal = data[:,1]
    z_gal = data[:,2]
    #Vgal = data[:,8]
Esempio n. 48
0
def generate_file_rst(fname, target_dir, src_dir, plot_gallery):
    """ Generate the rst file for a given example.
    """
    image_name = fname[:-2] + 'png'
    global rst_template, plot_rst_template
    this_template = rst_template
    last_dir = os.path.split(src_dir)[-1]
    # to avoid leading . in file names
    if last_dir == '.': last_dir = ''
    else: last_dir += '_'
    short_fname = last_dir + fname
    src_file = os.path.join(src_dir, fname)
    example_file = os.path.join(target_dir, fname)
    shutil.copyfile(src_file, example_file)
    if plot_gallery and fname.startswith('plot'):
        # generate the plot as png image if file name
        # starts with plot and if it is more recent than an
        # existing image.
        if not os.path.exists(os.path.join(target_dir, 'images')):
            os.makedirs(os.path.join(target_dir, 'images'))
        image_file = os.path.join(target_dir, 'images', image_name)
        if (not os.path.exists(image_file)
                or os.stat(image_file).st_mtime <= os.stat(src_file).st_mtime):
            print 'plotting %s' % fname
            import matplotlib.pyplot as plt
            plt.close('all')
            try:
                try:
                    from mayavi import mlab
                except ImportError:
                    from enthought.mayavi import mlab
                mlab.close(all=True)
            except:
                pass

            try:
                execfile(example_file, {'pl': plt})
                facecolor = plt.gcf().get_facecolor()  # hack to keep black bg
                if facecolor == (0.0, 0.0, 0.0, 1.0):
                    plt.savefig(image_file, facecolor='black')
                else:
                    plt.savefig(image_file)

                try:
                    try:
                        from mayavi import mlab
                    except ImportError:
                        from enthought.mayavi import mlab

                    e = mlab.get_engine()
                    if len(e.scenes) > 0:
                        mlab.savefig(image_file, size=(400, 400))
                except:
                    pass

            except:
                print 80 * '_'
                print '%s is not compiling:' % fname
                traceback.print_exc()
                print 80 * '_'
        this_template = plot_rst_template

    docstring, short_desc, end_row = extract_docstring(example_file)

    f = open(os.path.join(target_dir, fname[:-2] + 'rst'), 'w')
    f.write(this_template % locals())
    f.flush()
Esempio n. 49
0
def UV_PCs(nbpc=0, use_U=False, scale_factor=150):
    # Get reconstructed variables field
    inpath = "/home/thomas/phd/framework/model/out/local_downscaling/ribeirao_articleII/pres_obs_3d/"

    if use_U:
        outpath = "/home/thomas/phd/framework/visu/res/pres/U/" + "PC" + str(
            nbpc + 1) + "/"
    else:
        outpath = "/home/thomas/phd/framework/visu/res/pres/V/" + "PC" + str(
            nbpc + 1) + "/"

    # 360 numbers between 0 and 24h
    hours = range(0, 23)
    for hour in hours:

        print(hour)
        # T = concat_dfs(inpath, column = hour, regex="TPC")
        # Q = concat_dfs(inpath, column = hour, regex="QPC")
        U = concat_dfs(inpath, column=hour, regex="UPC")
        V = concat_dfs(inpath, column=hour, regex="VPC")

        # Sum the PCs
        # T = T.iloc[:,nbpc]
        # Q = Q.sum(axis=1)

        if use_U == False:
            U = U.iloc[:, 0]
            V = V.iloc[:, nbpc]
        else:
            U = U.iloc[:, nbpc]
            V = V.iloc[:, 0]

        # T = T.values.reshape(239,244)
        # Q = Q.values.reshape(239,244)
        U = U.values.reshape(239, 244)
        V = V.values.reshape(239, 244)

        if use_U == False:
            U = np.zeros(U.shape)
        else:
            V = np.zeros(V.shape)

        W = np.zeros(U.shape)
        s = np.ones(U.shape)
        T = np.ones(U.shape)

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

        # # # Surface plot
        pts = mlab.quiver3d(x,
                            y,
                            z,
                            s,
                            s,
                            s,
                            scalars=T,
                            mode='cube',
                            scale_factor=0,
                            colormap='bwr')
        pts.glyph.color_mode = "color_by_scalar"
        pts.glyph.glyph_source.glyph_source.center = [0, 0, 0]

        pts.module_manager.scalar_lut_manager.lut.table = T
        draw()

        mesh = mlab.pipeline.delaunay2d(pts)  # Create and visualize the mesh
        surf = mlab.pipeline.surface(mesh, colormap='Greys', vmin=-3, vmax=10)
        # surf.module_manager.scalar_lut_manager.reverse_lut = True # reverse colormap
        # sc = mlab.scalarbar(surf, title="Temperature (C)", label_fmt="%.0f")
        #
        # sc.scalar_bar_representation.position = [0.1, 0.9]
        # sc.scalar_bar_representation.position2 = [0.8, 0.05]
        #
        #
        # Quiver plot
        mask_point = 4
        quiver3d(x[::mask_point, ::mask_point],
                 y[::mask_point, ::mask_point],
                 z[::mask_point, ::mask_point] + 100,
                 U[::mask_point, ::mask_point],
                 V[::mask_point, ::mask_point],
                 W[::mask_point, ::mask_point],
                 opacity=0.8,
                 line_width=3,
                 mode='2darrow',
                 color=(0.1, 0.1, 0.1),
                 scale_factor=scale_factor,
                 transparent=True)
        #
        # mlab.axes()
        #
        # mlab.text(0.45, 0.97, "Time: "+str(hour).zfill(2) + "H", width=0.1, line_width=0.01, color=(0,0,0))

        mlab.view(azimuth=255,
                  elevation=40,
                  distance=6500,
                  focalpoint=np.array([3500, 2600, 0]))
        mlab.savefig(outpath + str(hour).zfill(2) + ".png",
                     size=(1420, 1080),
                     magnification='auto')
        mlab.close()
Esempio n. 50
0
mlab.text3d(x[0] - 0.075*nX, y[0] - 0.075*nY, ZOffset/2, "gE", orientation=[0, 0, 0],
        orient_to_camera=True, color=(0, 0, 0), line_width=3, scale=textScale)

mlab.text3d(x[1] + 0.075*nX, y[1] + 0.075*nY, ZOffset/2, "gI", orientation=[0, 0, 0],
        orient_to_camera=True, color=(0, 0, 0), line_width=3, scale=textScale)

# Neuron labels
startLabelOffset = 1
labelScale = 1.5
mlab.text3d(-startLabelOffset, -startLabelOffset, ZOffset - 1,
        str(nX), orientation=[0, 0, 0], orient_to_camera=True, color=(0, 0, 0),
        line_width=3, scale=labelScale)
mlab.text3d(nX, -startLabelOffset, ZOffset - 1,
        "1", orientation=[0, 0, 0], orient_to_camera=True, color=(0, 0, 0),
        line_width=3, scale=labelScale)
mlab.text3d(nX - 1, nY + 1, ZOffset + 0.5,
        str(nY), orientation=[0, 0, 0], orient_to_camera=True, color=(0, 0, 0),
        line_width=3, scale=labelScale)

roll = 177.9584710619396
view = (-20.96663248113742,
         107.30927449790735,
          94.066015884153884,
           np.array([ 17.14404891,  16.30124532,   9.85753332]))
mlab.view(*view)
mlab.roll(roll)


fname = outputDir + "/network_layers.png"
mlab.savefig(fname)
Esempio n. 51
0
def T_PCs(nbpc=0, vmin=None, vmax=None):
    # Get reconstructed variables field
    inpath = "/home/thomas/phd/framework/model/out/local_downscaling/ribeirao_articleII/pres_obs_3d/"
    outpath = "/home/thomas/phd/framework/visu/res/pres/T/PC" + str(nbpc +
                                                                    1) + "/"

    # 360 numbers between 0 and 24h
    hours = range(0, 23)
    for hour in hours:

        print(hour)
        T = concat_dfs(inpath, column=hour, regex="TPC")
        # Q = concat_dfs(inpath, column = hour, regex="QPC")
        # U = concat_dfs(inpath, column = hour, regex="UPC")
        # V = concat_dfs(inpath, column = hour, regex="VPC")

        # Sum the PCs
        T = T.iloc[:, nbpc]
        # Q = Q.sum(axis=1)
        # U = U.sum(axis=1)
        # V = V.sum(axis=1)

        T = T.values.reshape(239, 244)
        # Q = Q.values.reshape(239,244)
        # U = U.values.reshape(239,244)
        # V = V.values.reshape(239,244)
        # W = np.zeros(U.shape)
        s = np.ones((239, 244))

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

        # # Surface plot
        pts = mlab.quiver3d(x,
                            y,
                            z,
                            s,
                            s,
                            s,
                            scalars=T,
                            mode='cube',
                            scale_factor=0,
                            colormap='bwr')
        pts.glyph.color_mode = "color_by_scalar"
        pts.glyph.glyph_source.glyph_source.center = [0, 0, 0]

        # pts.module_manager.scalar_lut_manager.lut.table = T
        # draw()

        mesh = mlab.pipeline.delaunay2d(pts)  # Create and visualize the mesh
        surf = mlab.pipeline.surface(mesh,
                                     colormap='coolwarm',
                                     vmin=vmin,
                                     vmax=vmax)
        # surf.module_manager.scalar_lut_manager.reverse_lut = True # reverse colormap
        # sc = mlab.scalarbar(surf, title="Temperature (C)", label_fmt="%.1f")

        # sc.scalar_bar_representation.position = [0.2, 0.85]
        # sc.scalar_bar_representation.position2 = [0.6, 0.08]

        # sc.scalar_bar_representation.position = [0.2, 0]
        # sc.scalar_bar_representation.position2 = [0.6, 0.08]
        #
        #
        # # Quiver plot
        # mask_point=4
        # quiver3d(x[::mask_point,::mask_point],y[::mask_point,::mask_point],z[::mask_point,::mask_point]+100,
        #          U[::mask_point,::mask_point], V[::mask_point,::mask_point], W[::mask_point,::mask_point],
        #          opacity=0.8,
        #          mode='2darrow', color=(0.3,0.3,0.3), scale_factor=150, transparent=True)

        # mlab.axes()

        # mlab.text(0.78, 0.13, "Time: "+str(hour).zfill(2) + "H", width=0.2, line_width=0.01, color=(0,0,0))

        mlab.view(azimuth=255,
                  elevation=40,
                  distance=6500,
                  focalpoint=np.array([3500, 2600, 0]))
        # mlab.view(azimuth=260, elevation=45, distance=7000, focalpoint=np.array([3250,2000,0]))

        mlab.savefig(outpath + str(hour).zfill(2) + ".png",
                     size=(1420, 1080),
                     magnification='auto')
        mlab.close()
Esempio n. 52
0
})
vecomp.widget.widget.set_transform(vecomp._transform)
vecomp.widget.update_implicit_function()
vecomp.render()
vecomp.widget.widget.enabled = False
# vecomp.filter.inside_out = True

# Surface with z as colormap
surf = mlab.pipeline.surface(vecomp, vmax=1, vmin=-1, colormap='RdYlBu')
surf.actor.property.interpolation = 'flat'

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

# Set the view (coordinates from Mayavi GUI)
fig.scene.camera.position = [
    225.79348206790564, -65.35463216386151, 152.22309264982135
]
fig.scene.camera.focal_point = [
    89.481086187422022, 89.317925608749434, 9.359478555383852
]
fig.scene.camera.view_angle = 30.0
fig.scene.camera.view_up = [
    -0.39936240943471379, 0.40687820822779919, 0.82155936462305368
]
fig.scene.camera.clipping_range = [21.185478265041723, 538.96253637184236]
fig.scene.camera.compute_view_plane_normal()

mlab.savefig('system_3d_cylinder.png')

mlab.show()
Esempio n. 53
0
def creator(name, curDir):
    saveName = name.split('.')[0]
    data = np.load(curDir+'/'+name)
    plotter = np.array([data[0]]).reshape(160,160)*255
    mlab.barchart(plotter, auto_scale=False, reset_zoom=False)
    mlab.savefig('../../mayaHist/'+saveName+'.png')
Esempio n. 54
0
fig1 = mlab.figure(size=(300, 300))
fig2 = mlab.figure(size=(300, 300))
brain1 = stc_face.plot(
    subject='sub002',
    hemi='split',
    views='med',
    background='white',
    foreground='black',
    time_label='',
    initial_time=1,
    figure=[fig1, fig2],
)
brain1.scale_data_colormap(1e-23, 1.5e-23, 2.4e-23, True)

mlab.savefig('../paper/figures/power_face_lh.png',
             figure=fig1,
             magnification=4)
mlab.savefig('../paper/figures/power_face_rh.png',
             figure=fig2,
             magnification=4)

fig3 = mlab.figure(size=(300, 300))
fig4 = mlab.figure(size=(300, 300))
brain2 = stc_scrambled.plot(
    subject='fsaverage',
    hemi='split',
    views='med',
    background='white',
    foreground='black',
    time_label='',
    initial_time=1,
Esempio n. 55
0
def plot_surf_views(surfin, hemi, pngoutdir, cmapout, colorbarflag):

    s1 = dfsio.readdfs(surfin)
    pex = np.max(np.abs(s1.attributes))
    cdict = cm.Colormap.create_bidirectional_logpvalues_cmap_dict(pex)

    cdict_orig = deepcopy(cdict)
    # Scale the attribute values in cdict from 0 to 1
    for i in range(0, len(cdict['red'])):
        cdict['red'][i] = ((cdict['red'][i][0] + pex) / (2 * pex),
                           cdict['red'][i][1], cdict['red'][i][2])
    for i in range(0, len(cdict['green'])):
        cdict['green'][i] = ((cdict['green'][i][0] + pex) / (2 * pex),
                             cdict['green'][i][1], cdict['green'][i][2])
    for i in range(0, len(cdict['blue'])):
        cdict['blue'][i] = ((cdict['blue'][i][0] + pex) / (2 * pex),
                            cdict['blue'][i][1], cdict['blue'][i][2])

    my_cmap = mpl_colors.LinearSegmentedColormap('my_bi_cmap', cdict, 256)
    my_cmap._init()

    # my_cmap, cdict_orig = cm.create_bidirectional_log_colormap(pminneg,pmaxneg,pminpos,pmaxpos,pIDneg,pIDpos)

    head, tail = os.path.split(surfin)
    cmap_png_filename = pngoutdir + '/' + os.path.splitext(
        tail)[0] + '_colormap' + '.png.eps'
    try:
        os.mkdir(pngoutdir)
    except OSError:
        pass

    if cmapout is not None:
        cmapfilename = os.path.join(pngoutdir, 'colormap')
        cm.Colormap.exportParaviewCmap(cdict_orig, cmapfilename + '.xml')
        # cm.Colormap.exportMayavi2LUT(-1*pex, 1*pex, cmapfilename)

    if colorbarflag:
        cm.Colormap.show_and_save_colorbar(s1.attributes, my_cmap, cdict_orig,
                                           cmap_png_filename)

    mlab.figure(size=(1200, 800), bgcolor=(1, 1, 1))
    tmesh = mlab.triangular_mesh(s1.vertices[:, 0],
                                 s1.vertices[:, 1],
                                 s1.vertices[:, 2],
                                 s1.faces,
                                 colormap='hot',
                                 scalars=s1.attributes,
                                 vmin=cdict_orig['red'][0][0],
                                 vmax=cdict_orig['red'][-1][0])

    lut = tmesh.module_manager.scalar_lut_manager.lut.table.to_array()
    tmesh.module_manager.scalar_lut_manager.lut.table = ((
        my_cmap._lut[0:256, :] * 255).astype('uint32'))

    #    if colorbaronlyflag:
    #        mlab.colorbar(orientation='vertical',nb_labels=14,nb_colors=256)
    #        pngfilename = pngoutdir + '/' + os.path.splitext(tail)[0] +'_colobar' +'.png'
    #        mlab.savefig(pngfilename)
    #        img = imcrop.autoCrop(pngfilename)
    #        img = imcrop.imTrans(img)
    #        img.save(pngfilename,'PNG')
    #        return

    if hemi == 'lh':
        vs = np.array([[170, 65], [0, 90], [90, 100], [-90, 85], [-90, 180],
                       [-90, 0]])
        rollvar = [75, -75, None, None, 0, 0]
    else:
        vs = np.array([[10, 75], [180, 90], [90, 100], [-90, 85], [-90, 180],
                       [-90, 0]])
        rollvar = [-75, 75, None, None, 0, 0]

    for i in np.arange(0, len(vs)):
        mlab.view(vs[i][0], vs[i][1], roll=rollvar[i])
        pngfilename = pngoutdir + '/' + os.path.splitext(
            tail)[0] + '_view' + str(i + 1) + '.png'
        mlab.savefig(pngfilename)
        #         img = imcrop.autoCrop(pngfilename)
        #         img = imcrop.imTrans(img)
        #         img.save(pngfilename,'PNG')
        sys.stdout.write(str(i) + ' ')
        sys.stdout.flush()
Esempio n. 56
0
    '''
    num = len(gt_boxes3d)
    for n in range(num):
        b = gt_boxes3d[n]
        if color_list is not None:
            color = color_list[n]
        if draw_text: mlab.text3d(b[4, 0], b[4, 1], b[4, 2], '%d' % n, scale=text_scale, color=color, figure=fig)
        for k in range(0, 4):
            # http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html
            i, j = k, (k + 1) % 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=None,
                        line_width=line_width, figure=fig)

            i, j = k + 4, (k + 1) % 4 + 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=None,
                        line_width=line_width, figure=fig)

            i, j = k, k + 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=None,
                        line_width=line_width, figure=fig)
    # mlab.show(1)
    # mlab.view(azimuth=180, elevation=70, focalpoint=[ 12.0909996 , -1.04700089, -2.03249991], distance=62.0, figure=fig)
    return fig


if __name__ == '__main__':
    pc = np.loadtxt('mayavi/kitti_sample_scan.txt')
    fig = draw_lidar(pc)
    mlab.savefig('pc_view.jpg', figure=fig)
raw_input()
Esempio n. 57
0
    print "el volumen haciendo la suma de los voxels de la mask es:", nGFPfinal
    intensidadmedia = float((fGmascarafinal).sum()) / nGFPfinal
    print "la intensidad media con la suma de voxels de la mask es:", intensidadmedia

    return mask3d


"""mostramos las imágenes 3d"""
vol = volumen_voxels(data_0)
vol = np.multiply(vol, data_0)
"""fig1 = mlab.figure(figure='Superficie',bgcolor=(0, 0, 0), size=(400, 500))
fig1.scene.disable_render = True
src1= mlab.pipeline.scalar_field(vol)
representacion_1=mlab.pipeline.iso_surface(src1,color=(1,0,0))
fig2 = mlab.figure(figure='Volumen',bgcolor=(0, 0, 0), size=(400, 500))
fig2.scene.disable_render = True
src2= mlab.pipeline.scalar_field(vol)
representacion_0=mlab.pipeline.volume(src2,color=(0,1,0))
fig3 = mlab.figure(figure='Superficie y Volumen',bgcolor=(0, 0, 0), size=(400, 500))
fig3.scene.disable_render = True
src3= mlab.pipeline.scalar_field(vol)
representacion_2=mlab.pipeline.iso_surface(src3,color=(1,0,0))
representacion_3=mlab.pipeline.volume(src3,color=(0,1,0))"""
mlab.options.offscreen = True
mlab.pipeline.iso_surface(mlab.pipeline.scalar_field(vol),
                          color=(1, 0, 0),
                          opacity=0.5)
mlab.savefig(sys.argv[1])
"""mlab.close(all=True)
mlab.show()"""
Esempio n. 58
0
            xp = 2 * linewidth * np.sin(phi) * np.cos(theta) + x[pos]
            yp = 2 * linewidth * np.sin(phi) * np.sin(theta) + y[pos]
            zp = 2 * linewidth * np.cos(phi) + z[pos]
            mlab.mesh(xp + shift, yp, zp, opacity=1, color=(0.07, 0.68, 0.37))

    if "Pv" in args.filename:
        begin = end
        continue

    ind = int(cent.mean() / resolution / length * m)
    xp = 2 * linewidth * np.sin(phi) * np.cos(theta) + x[ind]
    yp = 2 * linewidth * np.sin(phi) * np.sin(theta) + y[ind]
    zp = 2 * linewidth * np.cos(phi) + z[ind]
    mlab.mesh(xp + shift, yp, zp, opacity=1, color=(0.67, 0.77, 0.93))

    begin = end

if args.outfile is None:
    outfile = args.filename.replace("results",
                                    "images").replace(".txt", ".png")
else:
    outfile = args.outfile

try:
    os.makedirs(os.path.dirname(outfile))
except OSError:
    pass
mlab.savefig(outfile, magnification=4)
if args.show:
    mlab.show()
Esempio n. 59
0
    def saveFigure(self, name=None):
        '''
        Similar to plot, except that figures are saved to file
        :param name: the file name of the plot image
        '''
        if self.k == 3:
            import mayavi.mlab as mlab

            mlab.options.offscreen = True
            predictFig = mlab.figure(figure='predict')
            mlab.clf(figure='predict')
            errorFig = mlab.figure(figure='error')
            mlab.clf(figure='error')
            if self.testfunction:
                truthFig = mlab.figure(figure='test')
                mlab.clf(figure='test')
            dx = 1
            pts = 75j
            X, Y, Z = np.mgrid[0:dx:pts, 0:dx:pts, 0:dx:pts]
            scalars = np.zeros(X.shape)
            errscalars = np.zeros(X.shape)
            for i in range(X.shape[0]):
                for j in range(X.shape[1]):
                    for k1 in range(X.shape[2]):
                        errscalars[i][j][k1] = self.predicterr_normalized(
                            [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]])
                        scalars[i][j][k1] = self.predict_normalized(
                            [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]])

            if self.testfunction:
                tfscalars = np.zeros(X.shape)
                for i in range(X.shape[0]):
                    for j in range(X.shape[1]):
                        for k1 in range(X.shape[2]):
                            tfscalars[i][j][k1] = self.testfunction(
                                [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]])
                mlab.contour3d(tfscalars,
                               contours=15,
                               transparent=True,
                               figure=truthFig,
                               compute_normals=False)

            # obj = mlab.contour3d(scalars, contours=10, transparent=True)
            pred = mlab.contour3d(scalars,
                                  contours=15,
                                  transparent=True,
                                  figure=predictFig)
            pred.compute_normals = False
            errpred = mlab.contour3d(errscalars,
                                     contours=15,
                                     transparent=True,
                                     figure=errorFig)
            errpred.compute_normals = False
            mlab.savefig('%s_prediction.wrl' % name, figure=predictFig)
            mlab.savefig('%s_error.wrl' % name, figure=errorFig)
            if self.testfunction:
                mlab.savefig('%s_actual.wrl' % name, figure=truthFig)
            mlab.close(all=True)
        if self.k == 2:
            samplePoints = zip(*self.X)
            # Create a set of data to plot
            plotgrid = 61
            x = np.linspace(0, 1, num=plotgrid)
            y = np.linspace(0, 1, num=plotgrid)
            X, Y = np.meshgrid(x, y)

            # Predict based on the optimized results

            zs = np.array([
                self.predict_normalized([x, y])
                for x, y in zip(np.ravel(X), np.ravel(Y))
            ])
            Z = zs.reshape(X.shape)
            Z = (
                Z *
                (self.ynormRange[1] - self.ynormRange[0])) + self.ynormRange[0]

            # Calculate errors
            zse = np.array([
                self.predicterr_normalized([x, y])
                for x, y in zip(np.ravel(X), np.ravel(Y))
            ])
            Ze = zse.reshape(X.shape)

            if self.testfunction:
                # Setup the truth function
                zt = self.testfunction(
                    np.array(
                        zip(
                            np.ravel((X * (self.normRange[0][1] -
                                           self.normRange[0][0])) +
                                     self.normRange[0][0]),
                            np.ravel((Y * (self.normRange[1][1] -
                                           self.normRange[1][0])) +
                                     self.normRange[1][0]))))
                ZT = zt.reshape(X.shape)

            # Plot real world values
            X = (X * (self.normRange[0][1] - self.normRange[0][0])
                 ) + self.normRange[0][0]
            Y = (Y * (self.normRange[1][1] - self.normRange[1][0])
                 ) + self.normRange[1][0]
            spx = (self.X[:, 0] * (self.normRange[0][1] - self.normRange[0][0])
                   ) + self.normRange[0][0]
            spy = (self.X[:, 1] * (self.normRange[1][1] - self.normRange[1][0])
                   ) + self.normRange[1][0]
            fig = plt.figure(figsize=(8, 6))
            # contour_levels = np.linspace(min(zt), max(zt),50)
            contour_levels = 15
            plt.plot(spx, spy, 'ow')
            cs = plt.colorbar()

            if self.testfunction:
                pass
            plt.plot(spx, spy, 'ow')

            cs = plt.colorbar()
            plt.plot(spx, spy, 'ow')

            ax = fig.add_subplot(212, projection='3d')
            ax.plot_surface(X, Y, Z, rstride=3, cstride=3, alpha=0.4)

            if self.testfunction:
                ax.plot_wireframe(X, Y, ZT, rstride=3, cstride=3)
        if name:
            plt.savefig(name)
        else:
            plt.savefig('pyKrigingResult.png')
Esempio n. 60
0
    # data2[45,45:56,55]=m1;
    # data2[55,45:56,45]=m1;
    # data2[45,55,45:56]=m1;
    # data2[55,45,45:56]=m1;
    field=mlab.pipeline.scalar_field(x, y, z,(data))
    # field2=mlab.pipeline.scalar_field(x, y, z,data2)
    vol=mlab.pipeline.volume(field)#, contours=10, transparent=True)
    vol._ctf = ctf
    vol.update_ctf = True
    # vol._otf = otf
    # vol._volume_property.set_scalar_opacity(otf)


    # vol2=mlab.pipeline.volume(field2, vmax=0)
    # vol2._volume_property.set_color(ctf)
    # # vol2._ctf = ctf
    # # vol2.update_ctf = True
    # vol2._otf = otf
    # vol2._volume_property.set_scalar_opacity(otf)

    mlab.view(azimuth=(-150+(i*5)), elevation=60, distance=500, focalpoint=(49,49,49))
    # mlab.move(right=30)
    mlab.savefig(filename='./anim/fig%03d.png'%i)
    # mlab.show()
    mlab.close()


# mlab.show()
#ffmpeg -r 10 -i fig%03d.png -c:v libx264 -vf fps=60 -pix_fmt yuv420p out.mp4
#ffmpeg -f concat -i list.txt -c copy output.mp4