def test_close(self): """ Various tests for mlab.close(). """ f = mlab.figure() self.assertTrue(f.running) mlab.close(f) self.assertFalse(f.running) f = mlab.figure(314) self.assertTrue(f.running) mlab.close(314) self.assertFalse(f.running) f = mlab.figure('test_figure') self.assertTrue(f.running) mlab.close('test_figure') self.assertFalse(f.running) f = mlab.figure() self.assertTrue(f.running) mlab.close() self.assertFalse(f.running) figs = [mlab.figure() for i in range(5)] for f in figs: self.assertTrue(f.running) mlab.close(all=True) for f in figs: self.assertFalse(f.running)
def test_empty(self): data=numpy.zeros((20,20,20)) mlab.figure( bgcolor=(0,0,0), size=(1000,845) ) ATMA.GUI.DataVisualizer.segmentation( data ) mlab.close()
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()
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()
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'])
def toggleshow3(self): if not self.show3On: self.show3On = True self.show3() elif self.show3On: mlab.close() self.show3On = False
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()
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 test_rawData(self): raw=numpy.uint32(numpy.random.rand(200,200,200)*255) mlab.figure( bgcolor=(0,0,0), size=(1000,845) ) ATMA.GUI.DataVisualizer.rawSlider( raw ) mlab.close()
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)
def close(self): """Close the figure and cleanup data structure.""" try: from mayavi import mlab except ImportError: from enthought.mayavi import mlab mlab.close(self._f)
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()
def new_func(test_case): try: func(test_case) finally: num_scenes = len(mlab.get_engine().scenes) test_case.assertNotEqual(num_scenes, 0, "No scene is opened") # close everything mlab.close(all=True)
def test_save_load_visualization_with_mlab(self): # test mlab.get_engine engine = mlab.get_engine() try: self.check_save_load_visualization(engine) finally: mlab.clf() mlab.close(all=True)
def mayavi_plt(): ml.test_plot3d() arr = ml.screenshot() ml.close() plt.imshow(arr) plt.axis('off') plt.show()
def close(self): for f in self.figures.itervalues(): plt.close(f) self.figures = {} self.figMslices.close() mlab.close(self.fig1) if self.show_grad: self.figdMslices.close()
def test_three_lines(self): data=numpy.zeros((200,200,160)) data[50,50,:]=1 data[150,150,:]=2 data[50,150,:]=3 mlab.figure( bgcolor=(0,0,0), size=(1000,845) ) ATMA.GUI.DataVisualizer.segmentation( data ) mlab.close()
def f(arr): from mayavi import mlab fig = mlab.figure(size=(800,800)) n_x = arr[0] n_y = arr[1] n_z = arr[2] name = arr[3] d = exponential(size=(n_x,n_y,n_z)) mlab.points3d(d[0], d[1], d[2], figure=fig) mlab.savefig(name+'.png', figure=fig) mlab.close(fig) return name
def save_figures(image_path, fig_count, gallery_conf): """Save all open matplotlib figures of the example code-block Parameters ---------- image_path : str Path where plots are saved (format string which accepts figure number) fig_count : int Previous figure number count. Figure number add from this number gallery_conf : dict Contains the configuration of Sphinx-Gallery Returns ------- images_rst : str rst code to embed the images in the document fig_num : int number of figures saved """ figure_list = [] for fig_num in plt.get_fignums(): # Set the fig_num figure as the current figure as we can't # save a figure that's not the current figure. fig = plt.figure(fig_num) kwargs = {} to_rgba = matplotlib.colors.colorConverter.to_rgba for attr in ['facecolor', 'edgecolor']: fig_attr = getattr(fig, 'get_' + attr)() default_attr = matplotlib.rcParams['figure.' + attr] if to_rgba(fig_attr) != to_rgba(default_attr): kwargs[attr] = fig_attr current_fig = image_path.format(fig_count + fig_num) fig.savefig(current_fig, **kwargs) figure_list.append(current_fig) if gallery_conf.get('find_mayavi_figures', False): from mayavi import mlab e = mlab.get_engine() last_matplotlib_fig_num = fig_count + len(figure_list) total_fig_num = last_matplotlib_fig_num + len(e.scenes) mayavi_fig_nums = range(last_matplotlib_fig_num + 1, total_fig_num + 1) for scene, mayavi_fig_num in zip(e.scenes, mayavi_fig_nums): current_fig = image_path.format(mayavi_fig_num) mlab.savefig(current_fig, figure=scene) # make sure the image is not too large scale_image(current_fig, current_fig, 850, 999) figure_list.append(current_fig) mlab.close(all=True) return figure_rst(figure_list, gallery_conf['src_dir'])
def save_frames(source, vertices, images_dir): print('Saving frames...') if not os.path.isdir(images_dir): os.makedirs(images_dir) bar = IncrementalBar(max=len(vertices)) angle_change = 360 // len(vertices) for i, v in enumerate(vertices): update(source, v, angle_change=angle_change) mlab.savefig(filename=os.path.join(images_dir, frame_fn(i))) bar.next() bar.finish() mlab.close()
def plot_forward_operator(subject, fnout_img=None): """"Reads in and plots the forward solution.""" # get name of inverse solution-file subjects_dir = os.environ.get('SUBJECTS_DIR') fname_dir_fwd = os.path.join(subjects_dir, subject) for files in os.listdir(fname_dir_fwd): if files.endswith(",cleaned_epochs_avg-7-src-fwd.fif"): fname_fwd = os.path.join(fname_dir_fwd, files) break try: fname_fwd except NameError: print "ERROR: No forward solution found!" sys.exit() # read inverse solution add_geom = True # include high resolution source space src = mne.read_source_spaces(fname_fwd, add_geom=add_geom) # 3D source space (high sampling) lh_points = src[0]['rr'] lh_faces = src[0]['tris'] rh_points = src[1]['rr'] rh_faces = src[1]['tris'] # create figure and plot results fig_forward = 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 image if desired if fnout_img is not None: mlab.savefig(fnout_img, figure=fig_forward, size=(1200, 1200)) mlab.close(all=True)
def test_full(self): data=numpy.zeros((200,200,160)) data[50:70,50:70,:]=1 data[150:170,150:200,:]=2 data[50:60,10:60,:]=3 raw=numpy.uint32(numpy.random.rand(200,200,200)*255) mlab.figure( bgcolor=(0,0,0), size=(1000,845) ) ATMA.GUI.DataVisualizer.segmentation( data ) ATMA.GUI.DataVisualizer.rawSlider( raw ) mlab.close(all=True)
def test_limits_to_control_points(): """Test functionality for determing control points """ sample_src = read_source_spaces(src_fname) vertices = [s['vertno'] for s in sample_src] n_time = 5 n_verts = sum(len(v) for v in vertices) stc_data = np.random.rand((n_verts * n_time)) stc_data.shape = (n_verts, n_time) stc = SourceEstimate(stc_data, vertices, 1, 1, 'sample') # Test for simple use cases from mayavi import mlab mlab.close() stc.plot(clim='auto', subjects_dir=subjects_dir) stc.plot(clim=dict(pos_lims=(10, 50, 90)), subjects_dir=subjects_dir) stc.plot(clim=dict(kind='value', lims=(10, 50, 90)), figure=99, subjects_dir=subjects_dir) with warnings.catch_warnings(record=True): # dep stc.plot(fmin=1, subjects_dir=subjects_dir) stc.plot(colormap='hot', clim='auto', subjects_dir=subjects_dir) stc.plot(colormap='mne', clim='auto', subjects_dir=subjects_dir) figs = [mlab.figure(), mlab.figure()] assert_raises(RuntimeError, stc.plot, clim='auto', figure=figs) # Test both types of incorrect limits key (lims/pos_lims) assert_raises(KeyError, plot_source_estimates, stc, colormap='mne', clim=dict(kind='value', lims=(5, 10, 15))) assert_raises(KeyError, plot_source_estimates, stc, colormap='hot', clim=dict(kind='value', pos_lims=(5, 10, 15))) # Test for correct clim values colormap = 'mne' assert_raises(ValueError, stc.plot, colormap=colormap, clim=dict(pos_lims=(5, 10, 15, 20))) assert_raises(ValueError, stc.plot, colormap=colormap, clim=dict(pos_lims=(5, 10, 15), kind='foo')) assert_raises(ValueError, stc.plot, colormap=colormap, clim=dict(kind='value', pos_lims=(5, 10, 15)), fmin=1) assert_raises(ValueError, stc.plot, colormap=colormap, clim='foo') assert_raises(ValueError, stc.plot, colormap=colormap, clim=(5, 10, 15)) assert_raises(ValueError, plot_source_estimates, 'foo', clim='auto') assert_raises(ValueError, stc.plot, hemi='foo', clim='auto') # Test that stc.data contains enough unique values to use percentages clim = 'auto' stc._data = np.zeros_like(stc.data) assert_raises(ValueError, plot_source_estimates, stc, colormap=colormap, clim=clim) mlab.close()
def plot_potential(grid, potential, along_axes=False, interactive=False, view=None, 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: if view is not None: mlab.surf(u, v, real(level), extent=view) else: 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)
def save_figures(image_path, fig_count, gallery_conf): """Save all open matplotlib figures of the example code-block Parameters ---------- image_path : str Path where plots are saved (format string which accepts figure number) fig_count : int Previous figure number count. Figure number add from this number Returns ------- list of strings containing the full path to each figure """ figure_list = [] fig_managers = matplotlib._pylab_helpers.Gcf.get_all_fig_managers() for fig_mngr in fig_managers: # Set the fig_num figure as the current figure as we can't # save a figure that's not the current figure. fig = plt.figure(fig_mngr.num) kwargs = {} to_rgba = matplotlib.colors.colorConverter.to_rgba for attr in ["facecolor", "edgecolor"]: fig_attr = getattr(fig, "get_" + attr)() default_attr = matplotlib.rcParams["figure." + attr] if to_rgba(fig_attr) != to_rgba(default_attr): kwargs[attr] = fig_attr current_fig = image_path.format(fig_count + fig_mngr.num) fig.savefig(current_fig, **kwargs) figure_list.append(current_fig) if gallery_conf.get("find_mayavi_figures", False): from mayavi import mlab e = mlab.get_engine() last_matplotlib_fig_num = len(figure_list) total_fig_num = last_matplotlib_fig_num + len(e.scenes) mayavi_fig_nums = range(last_matplotlib_fig_num, total_fig_num) for scene, mayavi_fig_num in zip(e.scenes, mayavi_fig_nums): current_fig = image_path.format(mayavi_fig_num) mlab.savefig(current_fig, figure=scene) # make sure the image is not too large scale_image(current_fig, current_fig, 850, 999) figure_list.append(current_fig) mlab.close(all=True) return figure_list
def calc(): """ The function that implements break-ups detection algorithm and write the data in a file. Input skeletons and graphs must correspond each other. """ #input graphs data_gr = glob.glob('/path/graphs_largedom/*_1.gpickle') data_gr.sort() #input skeletons data_sk = glob.glob('/path/skeletons_largedom/*.h5') data_sk.sort() for i, j, w in zip(data_gr[:-1][::-1], data_sk[:-1][::-1], data_sk[1:][::-1]): g = nx.read_gpickle(i) #We simplify the graph g1 = remove_terminal_br(g) g1 = remove_nodes(g1) #We use labeled branches arrays, skeletons, distans transfrom. All are of the same shape. d = tb.openFile(j, mode='r') bran1 = np.copy(d.root.branches1) skel1 = np.copy(d.root.skel) #this 'current' skeletons are used only for visualization. thick = np.copy(d.root.dist) d.close() #Skeletons shifted in time by one step. d = tb.openFile(w, mode='r') skel2 = np.copy(d.root.skel) d.close() b, pos = branches_map(g1, skel2, bran1, thick) #Visualization of break-ups if necessary. mlab.figure(1, bgcolor=(1,1,1), size=(1500,1500)) mlab.contour3d(skel1, colormap='hot') mask = np.zeros_like(skel1) for k in b: sl = b[k] mask[sl] = (bran1[sl] == k) mlab.contour3d(mask.astype('uint8')) np.save('/path/breakups/' + j[41:-3] + '_1.npy', b) #j[41:-3] must be replaced according to the path np.save('/path/breakups/' + j[41:-3] + '_pos.npy', pos) mlab.savefig('/path/breakups/' + j[41:-3] + '_1.png') mlab.close()
def test_plot_trans(): """Test plotting of -trans.fif files and MEG sensor layouts.""" from mayavi import mlab evoked = read_evokeds(evoked_fname)[0] with warnings.catch_warnings(record=True): # 4D weight tables bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True, preload=False).info infos = dict( Neuromag=evoked.info, CTF=read_raw_ctf(ctf_fname).info, BTi=bti, KIT=read_raw_kit(sqd_fname).info, ) for system, info in infos.items(): ref_meg = False if system == 'KIT' else True plot_trans(info, trans_fname, subject='sample', meg_sensors=True, subjects_dir=subjects_dir, ref_meg=ref_meg) mlab.close(all=True) # KIT ref sensor coil def is defined plot_trans(infos['KIT'], None, meg_sensors=True, ref_meg=True) mlab.close(all=True) info = infos['Neuromag'] assert_raises(ValueError, plot_trans, info, trans_fname, subject='sample', subjects_dir=subjects_dir, ch_type='bad-chtype') assert_raises(TypeError, plot_trans, 'foo', trans_fname, subject='sample', subjects_dir=subjects_dir) # no-head version plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head') mlab.close(all=True) # all coord frames for coord_frame in ('meg', 'head', 'mri'): plot_trans(info, meg_sensors=True, dig=True, coord_frame=coord_frame, trans=trans_fname, subject='sample', subjects_dir=subjects_dir) mlab.close(all=True) # EEG only with strange options evoked_eeg_ecog = evoked.copy().pick_types(meg=False, eeg=True) evoked_eeg_ecog.info['projs'] = [] # "remove" avg proj evoked_eeg_ecog.set_channel_types({'EEG 001': 'ecog'}) with warnings.catch_warnings(record=True) as w: plot_trans(evoked_eeg_ecog.info, subject='sample', trans=trans_fname, source='outer_skin', meg_sensors=True, skull=True, eeg_sensors=['original', 'projected'], ecog_sensors=True, brain='white', head=True, subjects_dir=subjects_dir) mlab.close(all=True) assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])
def plot_potential(grid, potential, sparsify=1, along_axes=False, view=None, interactive=False, path='.'): """Plot the potential :param iom: An :py:class:`IOManager` instance providing the simulation data. """ # The Grid u, v = grid.get_nodes(split=True, flat=False) u = real(u[::sparsify, ::sparsify]) v = real(v[::sparsify, ::sparsify]) # Create potential and evaluate eigenvalues potew = potential.evaluate_eigenvalues_at(grid) potew = [real(level).reshape(grid.get_number_nodes(overall=False))[::sparsify, ::sparsify] for level in potew] # Plot if not interactive: mlab.options.offscreen = True fig = mlab.figure(size=(800, 700)) for level in potew: # The energy surfaces of the potential src = mlab.pipeline.grid_source(u, v, level) # Clip to given view if view is not None: geometry_filter = mlab.pipeline.user_defined(src, filter='GeometryFilter') geometry_filter.filter.extent_clipping = True geometry_filter.filter.extent = view src = mlab.pipeline.user_defined(geometry_filter, filter='CleanPolyData') # Plot the surface normals = mlab.pipeline.poly_data_normals(src) mlab.pipeline.surface(normals) mlab.axes() fig.scene.parallel_projection = True fig.scene.isometric_view() # fig.scene.show_axes = True mlab.draw() if interactive: mlab.show() else: mlab.savefig(os.path.join(path, "potential_3D_view.png")) mlab.close(fig)
def animate(self): print "Animating...\n" end_counter = 0 for i in xrange(len(self.robots)): robot = self.robots[i] robot.update_pos() print robot.get_id(), robot.get_status() if robot.get_status() == RobotBall.STATUS_END or robot.get_status() == RobotBall.STATUS_DAMAGED: end_counter += 1 else: self.master_cmd.receive_keepalive(robot.get_id()) dead_r, alive_r = self.master_cmd.check_alive() print "dead", dead_r, "alive", alive_r, "n robots", len(self.robots), "end_counter", end_counter if len(dead_r) > 0: print "dead", dead_r, "alive", alive_r for r_id in dead_r: self.master_cmd.reallocate_path_of_robot(r_id) robot_index = None for i in xrange(len(self.robots)): if self.robots[i].get_id() == r_id: robot_index = i if robot_index is not None: print "Remove robot:", r_id, "index:", robot_index self.robots.pop(robot_index) self.master_cmd.remove_robot(r_id) else: if end_counter >= len(self.robots): print "Exiting path simulation..." # ------------------- with open("/tmp/exp_results.txt", "a") as myfile: end_time = int(time.time() * 1000) - self.start_time myfile.write(self.message + " " + str(end_time)) myfile.write("\n") # ------------------- self.animator.itimer.Stop() mlab.close(all=True)
def get_figure(*args, **kwargs): old_option = mlab.options.offscreen try: # offscreen on Windows works reliably if sys.platform == "win32": mlab.options.offscreen = True # Make sure a new figure is created figure = mlab.figure(*args, **kwargs) # if offscreen is True, this is set already figure.scene.off_screen_rendering = True yield figure finally: mlab.options.offscreen = old_option mlab.clf() mlab.close()
def plot_structures_gif(structures, outname, all_enrichments=None, colors=default_colors, radius=None, increment=10): if 360%increment != 0: print("Error. Increment must be factor of 360.") sys.exit(0) if radius is None: radius = calculateRadius(structures) mlab.figure(bgcolor=(1,1,1)) for i in range(0, 360, increment): for j, structure in enumerate(structures): coords = np.array(structure.getCoords()) if all_enrichments is not None: s = mlab.plot3d(coords[:,0], coords[:,1], coords[:,2], all_enrichments[j], tube_radius=radius) else: s = mlab.plot3d(coords[:,0], coords[:,1], coords[:,2], tube_radius=radius, color=colors[j]) mlab.view(i) mlab.savefig("{}_{:>03}.png".format(outname, i)) mlab.close() os.system("convert -loop 1 {}_*.png {}.gif".format(outname, outname)) os.system("rm {}_*.png".format(outname))
def omf_plot(x,y,z,mx,my,mz,img_bgcolor=(1,1,1),img_figsize=(1080,720),img_format='png',img_display='cone',img_view=np.array([0,90])\ ,img_line_scale=0.9,img_axis=False,fname=None,fdir=None): #create color map data=color1d(x,y,z,mx,my,mz,img_color,img_color_reverse) #计算箭头的长度 cal_step=lambda i:np.diff(np.sort(list(set(i)))[:2])[0] scale_factor=np.sqrt(cal_step(x)**2+cal_step(y)**2+cal_step(z)**2)*img_line_scale #开始画图 f=mlab.figure(bgcolor=img_bgcolor,size=img_figsize)#图片的 for i in range(len(data)):#循环画图class_color**3次 color,pf=data[i][0],data[i][1]#DataFrame,[x,y,z,mx,my,mz,lx,ly,lz] mlab.quiver3d(pf[0],pf[1],pf[2],pf[3],pf[4],pf[5],color=color,scale_factor=scale_factor,mode=img_display)#cone if img_axis: #创建三个坐标轴方向 maxx,maxy,maxz=np.max(x),np.max(y),np.max(z) #z mlab.quiver3d(0,1.0*maxy,1.3*maxz,0,0,1,color=(0,0,1),mode='arrow',scale_factor=scale_factor*2,) mlab.text3d(0,1.0*maxy,1.3*maxz+scale_factor*2,'z',color=(0,0,0),scale=scale_factor*0.8) #y mlab.quiver3d(0,1.0*maxy,1.3*maxz,0,1,0,color=(0,1,0),mode='arrow',scale_factor=scale_factor*2) mlab.text3d(0,1.0*maxy+scale_factor*2,1.3*maxz,'y',color=(0,0,0),scale=scale_factor*0.8) #x mlab.quiver3d(0,1.0*maxy,1.3*maxz,1,0,0,color=(1,0,0),mode='arrow',scale_factor=scale_factor*2,) mlab.text3d(scale_factor*2,1.0*maxy,1.3*maxz,'x',color=(0,0,0),scale=scale_factor*0.8) ######################################### for view in img_view: mlab.view(img_view[0],img_view[1])#观察角度 if isinstance(fname,str) and isinstance(fdir,str) and img_save: if GOODGPU: mlab.savefig(os.path.join(fdir,'%s-z%d-x%d.%s'%(fname,img_view[0],img_view[1],img_format)),magnification=5) else: mlab.savefig(os.path.join(fdir,'%s-z%d-x%d.%s'%(fname,img_view[0],img_view[1],img_format))) if img_show==True: #print u"需手动关掉图片,才会继续画图!!" print "Need to manually turn off the picture, will continue drawing!" mlab.show()#显示图片 if not img_show: mlab.close()#关闭画布
def save_result_images(subject_id, feature_space, reco_type, fig_size=(512, 512)): output_path = '/vol/atlas/pts08/cvpr/results/yaleb/{0}_{1}_{2}_{3}.png' # Left profile mlab.view(azimuth=-80, elevation=85, roll=-145, distance=840, focalpoint=np.array([288, 360, 64])) mlab.savefig(output_path.format(subject_id, feature_space, reco_type, 'left_profile'), size=fig_size) # Right profile mlab.view(azimuth=94, elevation=85, roll=-145, distance=840, focalpoint=np.array([288, 360, 64])) mlab.savefig(output_path.format(subject_id, feature_space, reco_type, 'right_profile'), size=fig_size) # Frontal mlab.view(azimuth=180, elevation=20, roll=-90, distance=810, focalpoint=np.array([300, 350, 67])) mlab.savefig(output_path.format(subject_id, feature_space, reco_type, 'frontal'), size=fig_size) mlab.close(all=True)
def plot_clusters_interactive(clusters, colors=default_colors, radius=None, cut=False): mlab.close(all=True) mlab.figure(bgcolor=(1, 1, 1)) if radius is None: radius = calculateRadius(clusters) for i, cluster in enumerate(clusters): coords = np.array(cluster.getCoords()) xs = coords[:, 0] ys = coords[:, 1] zs = coords[:, 2] if cut: midpoint = np.mean(xs) indices = np.where(xs > midpoint)[0] xs = xs[indices] ys = ys[indices] zs = zs[indices] mlab.plot3d(xs, ys, zs, tube_radius=radius, color=colors[i]) mlab.show()
def test_mayavi_viz(): # mayavi import adapted from mne: with warnings.catch_warnings(record=True): # traits from mayavi import mlab mlab.options.backend = 'test' clst2 = read_cluster(op.join(data_dir, 'temp_clst.hdf5'), src=fwd['src'], subjects_dir=data_dir) os.remove(op.join(data_dir, 'temp_clst.hdf5')) # mayavi plotting # --------------- # only smoke tests currently brain = clst2.plot(0, freq=[8, 9], set_light=False) fig = brain._figures[0][0] mlab.close(fig) brain = clst2.plot(1, freq=0.7, set_light=False) fig = brain._figures[0][0] mlab.close(fig)
def knn_plot(pc_path=''): f_list = [ base_path + '/' + i for i in os.listdir(base_path) if os.path.splitext(i)[1] == '.ply' ] for j, i in enumerate(f_list): if j < 4: pc = PointCloud(i) pc.down_sample(number_of_downsample=4096) pc.add_noise(factor=0.04) pc.add_outlier(factor=0.04) fig = pc.compute_key_points( percentage=0.02, resolution_control=1 / 15, rate=0.05, use_deficiency=False, show_result=True) # get the key points id f = mlab.gcf() # this two line for mlab.screenshot to work f.scene._lift() mlab.savefig(filename=str(j) + '_0.png') mlab.close() colorset = np.random.random((100, 3)) fig = pc.generate_k_neighbor(k=32, show_result=True, colorset=colorset) f = mlab.gcf() # this two line for mlab.screenshot to work f.scene._lift() mlab.savefig(filename=str(j) + '_1.png') mlab.close() fig = pc.generate_k_neighbor(k=64, show_result=True, colorset=colorset) f = mlab.gcf() # this two line for mlab.screenshot to work f.scene._lift() mlab.savefig(filename=str(j) + '_2.png') mlab.close() fig = pc.generate_k_neighbor(k=128, show_result=True, colorset=colorset) f = mlab.gcf() # this two line for mlab.screenshot to work f.scene._lift() mlab.savefig(filename=str(j) + '_3.png') mlab.close()
def visualize3Dcontour(xi, yi, zi, density): # Visualize the density estimate as isosurfaces out1 = mlab.contour3d(xi, yi, zi, density, opacity=0.2, contours=5, colormap='bwr') out2 = mlab.axes() #mlab.show(stop=False) #mayavi.mlab.savefig(filename, size=None, figure=None, magnification='auto', **kwargs) out3 = mlab.close(scene=None, all=False)
def ctmr_plot(subj_dir, subj, hem, elecs, weights=None, interactive=False): #need ctmr_brain_plot, mayavi, vtk import ctmr_brain_plot from mayavi import mlab from matplotlib import cm import scipy.io import numpy as np import matplotlib.pyplot as plt a = scipy.io.loadmat('%s/%s/Meshes/%s_pial_trivert.mat' % (subj_dir, subj, hem)) if weights == None: weights = np.ones((elecs.shape[0])) * -1. mesh, mlab = ctmr_brain_plot.ctmr_gauss_plot(a['tri'], a['vert'], elecs=elecs, weights=weights, color=(0.8, 0.8, 0.8), cmap='RdBu') mesh.actor.property.opacity = 1.0 # Make brain semi-transparent # View from the side if hem == 'lh': azimuth = 180 elif hem == 'rh': azimuth = 0 mlab.view(azimuth, elevation=90) arr = mlab.screenshot(antialiased=True) plt.figure(figsize=(20, 10)) plt.imshow(arr, aspect='equal') plt.axis('off') plt.show() if interactive: mlab.show() else: mlab.close() return mesh, mlab
def save(self, name=None, format='png', dirc=None): """Saves Bloch sphere to file of type ``format`` in directory ``dirc``. Parameters ---------- name : str Name of saved image. Must include path and format as well. i.e. '/Users/Paul/Desktop/bloch.png' This overrides the 'format' and 'dirc' arguments. format : str Format of output image. Default is 'png'. dirc : str Directory for output images. Defaults to current working directory. Returns ------- File containing plot of Bloch sphere. """ from mayavi import mlab import os self.make_sphere() mlab.view(azimuth=self.view[0], elevation=self.view[1], distance=5) if dirc: if not os.path.isdir(os.getcwd() + "/" + str(dirc)): os.makedirs(os.getcwd() + "/" + str(dirc)) if name is None: if dirc: mlab.savefig(os.getcwd() + "/" + str(dirc) + '/bloch_' + str(self.savenum) + '.' + format) else: mlab.savefig(os.getcwd() + '/bloch_' + str(self.savenum) + '.' + format) else: mlab.savefig(name) self.savenum += 1 if self.fig: mlab.close(self.fig)
def plot_grand_avg_stc_anim(ga_group, stc_animation, stc_animation_dilat, morph_to): ga_dict = ga_group.load_ga_source_estimate() for trial in ga_dict: brain = ga_dict[trial].plot(subject=morph_to, subjects_dir=ga_group.subjects_dir, size=(1600, 800), title=f'{ga_group.name}-{trial}', hemi='split', views='lat') brain.title = f'{ga_group.name}-{trial}' print('Saving Video') save_path = join( ga_group.figures_path, 'grand_averages/source_space/stc_movie', f'{ga_group.name}_{trial}_{ga_group.pr.p_preset}-stc_movie.mp4') brain.save_movie(save_path, time_dilation=stc_animation_dilat, tmin=stc_animation[0], tmax=stc_animation[1], framerate=30) mlab.close()
def display_rgb(pos, color, filename): N = pos.shape[0] s = np.arange(N) lut = np.zeros((N, 4), dtype=np.uint8) lut[:, :3] = (color * 255).astype(np.uint8) lut[:, -1] = 255 mlab.figure() x = pos[:, 0] y = pos[:, 1] z = pos[:, 2] points3d = mlab.points3d(x, y, z, s, mask_points=10, colormap='jet', scale_factor=0.025, scale_mode='none') points3d.module_manager.scalar_lut_manager.lut.table = lut # mlab.show() mlab.savefig(filename, magnification=2) mlab.close()
def plot_cluster_gif(cluster, outname, color=(1, 0, 0), radius=None, increment=10): if 360 % increment != 0: print "Error. Increment must be factor of 360." sys.exit(0) if radius is None: radius = calculateRadius([cluster]) coords = np.array(cluster.getCoords()) for i in range(0, 360, increment): mlab.figure(bgcolor=(1, 1, 1)) s = mlab.plot3d(coords[:, 0], coords[:, 1], coords[:, 2], tube_radius=radius, color=color) mlab.view(i) mlab.savefig("{}_{:>03}.png".format(outname, i)) mlab.close() os.system("convert {}_*.png -loop 1 {}.gif".format(outname, outname)) os.system("rm {}_*.png".format(outname))
def plot_structures_interactive(structures, all_enrichments=None, colors=default_colors, radius=None, cut=False, out_path=None, colormap="bwr"): mlab.close(all=True) mlab.figure(bgcolor=(1,1,1)) if radius is None: radius = calculateRadius(structures) for i, structure in enumerate(structures): coords = np.array(structure.getCoords()) xs = coords[:,0] ys = coords[:,1] zs = coords[:,2] if cut: midpoint = np.mean(xs) indices = np.where(xs > midpoint)[0] xs = xs[indices] ys = ys[indices] zs = zs[indices] if all_enrichments is not None: mlab.plot3d(xs, ys, zs, all_enrichments[i], tube_radius=radius, colormap=colormap) else: mlab.plot3d(xs, ys, zs, [0 for x in xs], tube_radius=radius, color=colors[i]) if out_path: mlab.savefig(out_path) mlab.show()
def key_points_plot(flist): for i in flist: Pc = PointCloud(i) Pc.down_sample(4096) fig = Pc.compute_key_points(percentage=0.1, resolution_control=None, show_result=True) f = mlab.gcf() # this two line for mlab.screenshot to work f.scene._lift() img = mlab.screenshot() mlab.savefig(filename=str(i) + 'key_points.png') mlab.close() fig = Pc.compute_key_points(percentage=0.1, resolution_control=0.01, show_result=True) f = mlab.gcf() # this two line for mlab.screenshot to work f.scene._lift() img = mlab.screenshot() mlab.savefig(filename=str(i) + 'key_points_with_resolution_ctrl.png') mlab.close()
def noise_outliers(pointclous, noise=0.05, outliers=0.05): fig = plt.figure(figsize=(38, 20), dpi=600, facecolor='w') for j, i in enumerate(pointclous): pc = PointCloud(i) pc.down_sample(number_of_downsample=1024) for k in range(4): if k == 3: k = 4 pc.add_noise(factor=k * noise) pc.add_outlier(factor=k * outliers) m_fig = mlab.figure(bgcolor=(1, 1, 1)) mlab.points3d(pc.position[:, 0], pc.position[:, 1], pc.position[:, 2], pc.position[:, 2] * 10**-2 + 1, colormap='Spectral', scale_factor=2, figure=m_fig) # mlab.gcf().scene.parallel_projection = True # parallel projection f = mlab.gcf() # this two line for mlab.screenshot to work f.scene._lift() # mlab.show() # for testing img = mlab.screenshot(figure=m_fig) mlab.close() if k == 4: k = 3 ax = fig.add_subplot(4, 8, (j + 1) + k * 8) ax.imshow(img) ax.set_axis_off() plt.subplots_adjust(wspace=0, hspace=0) plt.show()
def visualize_3d(self): if self.pt == '3d.isosurface': fig = mlab.figure(1, size=(400, 400), bgcolor=(1, 1, 1)) # density self.plot_pm_isosurface_3d() # molecule if self.mol: self.plot_atoms_3d(fig, self.mol[1], self.mol[2], self.mol[3], self.mol[4]) # orientation axes self.set_orientation_axes() if self.mode == 'show': mlab.show() elif self.mode == 'save' and self.out: # unless you change DISPLAY=:1, the mayavi window will pop up for a second... # but fig will be saved correctly mlab.savefig(self.out) mlab.close(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()
len(temp_conds) + 1, figsize=(12, 8)) for tl_idx, this_label in enumerate(these_labels): mfig = mlab.figure() hemi = "lh" if "lh" in this_label.name else "rh" brain = Brain('fsaverage', hemi, 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', size=(800, 600), figure=mfig) brain.add_label(this_label) axes[tl_idx, 0].imshow(mlab.screenshot(figure=mfig)) axes[tl_idx, 0].axis("off") mlab.close() for ax_idx, ax in enumerate(axes[tl_idx, 1:]): ax.imshow(XXX[ax_idx, :, tl_idx, v[0]:v[1]], vmin=vmin, vmax=vmax, cmap="seismic") ax.set_title(temp_conds[ax_idx]) plt.sca(ax) if ax_idx == len(temp_conds) - 1: plt.yticks(ticks=np.arange(len(subjs_t)), labels=subjs_t) ax.yaxis.tick_right() else: ax.yaxis.set_visible(False) plt.xticks(ticks=np.arange(v[1] - v[0]), labels=all_f[v[0]:v[1]]) plt.xlabel("Hz")
def visualize_labels(config, labels_fname, outname, fps=300): try: scheme = config['labeling']['scheme'] except KeyError: scheme = [] data = pd.read_csv(labels_fname) cols = [x for x in data.columns if '_error' in x] if len(scheme) == 0: bodyparts = [c.replace('_error', '') for c in cols] else: bodyparts = sorted(set([x for dx in scheme for x in dx])) bp_dict = dict(zip(bodyparts, range(len(bodyparts)))) all_points = np.array([ np.array(data.loc[:, (bp + '_x', bp + '_y', bp + '_z')]) for bp in bodyparts ], dtype='float64') all_errors = np.array( [np.array(data.loc[:, bp + '_error']) for bp in bodyparts], dtype='float64') all_scores = np.array( [np.array(data.loc[:, bp + '_score']) for bp in bodyparts], dtype='float64') if config['triangulation']['optim']: all_errors[np.isnan(all_errors)] = 0 else: all_errors[np.isnan(all_errors)] = 10000 good = (all_errors < 100) all_points[~good] = np.nan all_points_flat = all_points.reshape(-1, 3) check = ~np.isnan(all_points_flat[:, 0]) if np.sum(check) < 10: print('too few points to plot, skipping...') return low, high = np.percentile(all_points_flat[check], [5, 95], axis=0) nparts = len(bodyparts) framedict = dict(zip(data['fnum'], data.index)) writer = skvideo.io.FFmpegWriter( outname, inputdict={ # '-hwaccel': 'auto', '-framerate': str(fps), }, outputdict={ '-vcodec': 'h264', '-qp': '28', '-pix_fmt': 'yuv420p' }) cmap = get_cmap('tab10') points = np.copy(all_points[:, 20]) points[0] = low points[1] = high s = np.arange(points.shape[0]) good = ~np.isnan(points[:, 0]) fig = mlab.figure(bgcolor=(1, 1, 1), size=(500, 500)) fig.scene.anti_aliasing_frames = 2 low, high = np.percentile(points[good, 0], [10, 90]) scale_factor = (high - low) / 12.0 mlab.clf() pts = mlab.points3d(points[:, 0], points[:, 1], points[:, 2], s, color=(0.8, 0.8, 0.8), scale_mode='none', scale_factor=scale_factor) lines = connect_all(points, scheme, bp_dict, cmap) mlab.orientation_axes() view = list(mlab.view()) mlab.view(focalpoint='auto', distance='auto') for framenum in trange(data.shape[0], ncols=70): fig.scene.disable_render = True if framenum in framedict: points = all_points[:, framenum] else: points = np.ones((nparts, 3)) * np.nan s = np.arange(points.shape[0]) good = ~np.isnan(points[:, 0]) new = np.vstack([points[:, 0], points[:, 1], points[:, 2]]).T pts.mlab_source.points = new update_all_lines(lines, points, scheme, bp_dict) fig.scene.disable_render = False img = mlab.screenshot() mlab.view(*view, reset_roll=False) writer.writeFrame(img) mlab.close(all=True) writer.close()
for value in values: plot(squeeze(x), squeeze(value)) grid(True) xlabel(r"$x$") ylabel(r"$\lambda_i\left(x\right)$") xlim(min(x), max(x)) savefig(potdef["name"] + ".png") elif len(potdef["variables"]) == 2: values = P.evaluate_eigenvalues_at(G) f = mlab.figure() for value in values: mlab.surf(x2, y2, real(value.reshape(Nx, Ny))) mlab.savefig(potdef["name"] + ".png") mlab.close(f) # The latex code ls = [] l = "Potential ``" + str(potdef["name"]) + "``\n" ls.append(l) ls.append((len(l) - 1) * "^") ls.append("\n\n") ls.append("* Formula: :math:`V(x) = " + potformula + "`\n") ls.append("\n") ls.append("* Variables: " + potvars + "\n") ls.append("\n") if len(potdefaults) > 0: ls.append("* Default values:\n") ls.append("\n")
def plot(self, x, y, z, mx, my, mz, scalars, fname, savefig=True): ''' x,y,z,mx,my,mz为xyzdxdydz方式的数据 scalars:标量数据,可能用于标记颜色 fname:str,文件的名字 ''' figure = mlab.figure(bgcolor=self.bgcolor, size=self.size) #图片的 mlab.quiver3d(x, y, z, mx, my, mz, scalars=scalars, colormap=self.colormap, scale_mode=self.scale_mode, scale_factor=self.scale_factor) if self.show_colorbar: mlab.colorbar( title='Mz', #color 的名字 orientation='vertical', #垂直方向 nb_labels=5, #显示五个标签 label_fmt='%.1f') #保留一位小数 #坐标轴: if self.show_axes: #线宽,显示五个标签 mlab.axes(xlabel='x', ylabel='y', zlabel='z', line_width=3.0, nb_labels=5) if self.show_outline: #线宽2.0 ,有一点透明 mlab.outline(line_width=2.0, opacity=0.5) for view in self.view: mlab.view(view[0], view[1]) #观察角度 if isinstance(fname, str) and isinstance(self.save_path, str) and savefig: print('savefig in ', self.save_path) if self.gpu: mlab.savefig(os.path.join( self.save_path, '%s-z%d-x%d.%s' % (fname, view[0], view[1], self.fig_format)), magnification=3) else: mlab.savefig( os.path.join( self.save_path, '%s-z%d-x%d.%s' % (fname, view[0], view[1], self.fig_format))) if self.show_fig: print( "Need to manually turn off the picture, will continue drawing!" ) mlab.show() #显示图片 if not self.show_fig: mlab.close(all=True) #关闭画布
def save_figures(image_path, fig_count, gallery_conf): """Save all open matplotlib figures of the example code-block Parameters ---------- image_path : str Path where plots are saved (format string which accepts figure number) fig_count : int Previous figure number count. Figure number add from this number gallery_conf : dict Contains the configuration of Sphinx-Gallery Returns ------- figure_list : list of str strings containing the full path to each figure images_rst : str rst code to embed the images in the document """ figure_list = [] fig_numbers = plt.get_fignums() for fig_num in fig_numbers: # Set the fig_num figure as the current figure as we can't # save a figure that's not the current figure. fig = plt.figure(fig_num) kwargs = {} to_rgba = matplotlib.colors.colorConverter.to_rgba for attr in ['facecolor', 'edgecolor']: fig_attr = getattr(fig, 'get_' + attr)() default_attr = matplotlib.rcParams['figure.' + attr] if to_rgba(fig_attr) != to_rgba(default_attr): kwargs[attr] = fig_attr current_fig = image_path.format(fig_count + fig_num) fig.savefig(current_fig, **kwargs) figure_list.append(current_fig) if gallery_conf.get('find_mayavi_figures', False): from mayavi import mlab e = mlab.get_engine() last_matplotlib_fig_num = fig_count + len(figure_list) total_fig_num = last_matplotlib_fig_num + len(e.scenes) mayavi_fig_nums = range(last_matplotlib_fig_num + 1, total_fig_num + 1) for scene, mayavi_fig_num in zip(e.scenes, mayavi_fig_nums): current_fig = image_path.format(mayavi_fig_num) mlab.savefig(current_fig, figure=scene) # make sure the image is not too large scale_image(current_fig, current_fig, 850, 999) figure_list.append(current_fig) mlab.close(all=True) # Depending on whether we have one or more figures, we're using a # horizontal list or a single rst call to 'image'. images_rst = "" if len(figure_list) == 1: figure_name = os.path.relpath(figure_list[0], gallery_conf['src_dir']) images_rst = SINGLE_IMAGE % figure_name.lstrip('/') elif len(figure_list) > 1: images_rst = HLIST_HEADER for figure_name in figure_list: figure_name = os.path.relpath(figure_name, gallery_conf['src_dir']) images_rst += HLIST_IMAGE_TEMPLATE % figure_name.lstrip('/') return figure_list, images_rst
def visualize_labels(config, labels_fname, outname, fps=300): try: scheme = config['labeling']['scheme'] except KeyError: scheme = [] data = pd.read_csv(labels_fname) cols = [x for x in data.columns if '_error' in x] if len(scheme) == 0: bodyparts = [c.replace('_error', '') for c in cols] else: bodyparts = sorted(set([x for dx in scheme for x in dx])) bp_dict = dict(zip(bodyparts, range(len(bodyparts)))) nparts = len(bodyparts) framenums = np.array(data['fnum']) framedict = dict(zip(data['fnum'], data.index)) writer = skvideo.io.FFmpegWriter( outname, inputdict={ # '-hwaccel': 'auto', '-framerate': str(fps), }, outputdict={ '-vcodec': 'h264', '-qp': '30' }) cmap = get_cmap('tab10') dx = data.iloc[20] points = get_points(dx, bodyparts) s = np.arange(points.shape[0]) good = ~np.isnan(points[:, 0]) fig = mlab.figure(bgcolor=(1, 1, 1), size=(500, 500)) fig.scene.anti_aliasing_frames = 2 ## TODO: estimate scale_factor from the spead of points mlab.clf() pts = mlab.points3d(points[:, 0], -points[:, 1], points[:, 2], s, scale_mode='none', scale_factor=0.05) lines = connect_all(points, scheme, bp_dict, cmap) mlab.orientation_axes() view = list(mlab.view()) for framenum in trange(data.shape[0], ncols=70): fig.scene.disable_render = True if framenum in framedict: ix = framedict[framenum] dx = data.iloc[ix] points = get_points(dx, bodyparts) else: points = np.ones((nparts, 3)) * np.nan s = np.arange(points.shape[0]) good = ~np.isnan(points[:, 0]) new = np.vstack([points[:, 0], -points[:, 1], points[:, 2]]).T pts.mlab_source.points = new update_all_lines(lines, points, scheme, bp_dict) fig.scene.disable_render = False img = mlab.screenshot() view[0] += -0.2 mlab.view(*view, reset_roll=False) writer.writeFrame(img) mlab.close(all=True) writer.close()
def plot(self, filename): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(1, 2, 1, projection="3d") for i in range(0, len(self.stellarator.coils)): ax = self.stellarator.coils[i].plot(ax=ax, show=False, color=["b", "g", "r", "c", "m", "y"][i%len(self.stellarator._base_coils)]) self.ma.plot(ax=ax, show=False, closed_loop=False) ax.view_init(elev=90., azim=0) ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_zlim(-1, 1) ax = fig.add_subplot(1, 2, 2, projection="3d") for i in range(0, len(self.stellarator.coils)): ax = self.stellarator.coils[i].plot(ax=ax, show=False, color=["b", "g", "r", "c", "m", "y"][i%len(self.stellarator._base_coils)]) self.ma.plot(ax=ax, show=False, closed_loop=False) ax.view_init(elev=0., azim=0) ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_zlim(-1, 1) plt.savefig(self.outdir + filename, dpi=300) plt.close() if "DISPLAY" in os.environ: try: import mayavi.mlab as mlab except ModuleNotFoundError: raise ModuleNotFoundError( "\n\nPlease install mayavi first. On a mac simply do \n" + " pip3 install mayavi PyQT5\n" + "On Ubuntu run \n" + " pip3 install mayavi\n" + " sudo apt install python3-pyqt4\n\n" ) mlab.options.offscreen = True colors = [ (0.2980392156862745, 0.4470588235294118, 0.6901960784313725), (0.8666666666666667, 0.5176470588235295, 0.3215686274509804), (0.3333333333333333, 0.6588235294117647, 0.40784313725490196), (0.7686274509803922, 0.3058823529411765, 0.3215686274509804), (0.5058823529411764, 0.4470588235294118, 0.7019607843137254), (0.5764705882352941, 0.47058823529411764, 0.3764705882352941), (0.8549019607843137, 0.5450980392156862, 0.7647058823529411), (0.5490196078431373, 0.5490196078431373, 0.5490196078431373), (0.8, 0.7254901960784313, 0.4549019607843137), (0.39215686274509803, 0.7098039215686275, 0.803921568627451) ] mlab.figure(bgcolor=(1, 1, 1)) for i in range(0, len(self.stellarator.coils)): gamma = self.stellarator.coils[i].gamma gamma = np.concatenate((gamma, [gamma[0,:]])) mlab.plot3d(gamma[:, 0], gamma[:, 1], gamma[:, 2], color=colors[i%len(self.stellarator._base_coils)]) gamma = self.ma.gamma theta = 2*np.pi/self.ma.nfp rotmat = np.asarray([ [cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]]).T gamma0 = gamma.copy() for i in range(1, self.ma.nfp): gamma0 = gamma0 @ rotmat gamma = np.vstack((gamma, gamma0)) mlab.plot3d(gamma[:, 0], gamma[:, 1], gamma[:, 2], color=colors[len(self.stellarator._base_coils)]) mlab.view(azimuth=0, elevation=0) mlab.savefig(self.outdir + "mayavi_top_" + filename, magnification=4) mlab.view(azimuth=0, elevation=90) mlab.savefig(self.outdir + "mayavi_side1_" + filename, magnification=4) mlab.view(azimuth=90, elevation=90) mlab.savefig(self.outdir + "mayavi_side2_" + filename, magnification=4) mlab.view(azimuth=45, elevation=45) mlab.savefig(self.outdir + "mayavi_angled_" + filename, magnification=4) mlab.close()
def __init__(self,random_minerals=True,random_location=True, mineral_location= Location.CENTER, reward = Reward.RELATIVE, grayscale = False, flat = False, mineral_scale = 1.5, start_shift = 0, camera_height = 4, actions = [Action.LEFT,Action.RIGHT,Action.FORWARDS,Action.BACKWARDS,Action.CW,Action.CCW], decorations = False, camera_tilt = 0,start_pos=-23.5, width = 900, height = (500-46),resize_scale=15, x_collision_scale = 1,y_collision_scale = 1,k=5,silver=(.5,.5,.7), random_colors = False,random_lighting=False): self.random_minerals = random_minerals self.random_location = random_location self.mineral_location = mineral_location self.reward = reward self.grayscale = grayscale self.flat = flat self.actions = actions.copy() self.actions_index_dict = self.get_action_index_dictionary() self.camera_height = camera_height self.decorations = decorations self.camera_tilt = camera_tilt self.start_pos = start_pos self.resize_scale = resize_scale mlab.close(all=True) self.width = width self.height = height + 46 self.f = mlab.figure(size=(self.width,self.height),bgcolor = (1,1,1)) self.f.scene._lift() self.square_width = 23.5 self.start_shift = start_shift self.x_collision_scale = x_collision_scale self.y_collision_scale = y_collision_scale self.k = k self.k_max_iterations = 10 self.silver = silver self.random_colors = random_colors self.random_lighting = random_lighting visual.set_viewer(self.f) a_side = 34.5 tape_height = .2 #distance between minerals self.d = 14.5 / np.sqrt(2) #color for silver #silver = (.8,.8,.8) floor_color = (.4,.4,.4) #reate field self.floor_3_3 = visual.box(x=0,y=0,z=-1, length = 23.5*3,height = 23.5*3,width = 2,color = floor_color) #get mineral location locations = self.get_mineral_locations() #self.gold_mineral = visual.box(x=locations[0][0],y=locations[0][1],z=1, length=4,height=4,width=4, color = (1,1,0)) mineral_radius = 2.75 * mineral_scale self.gold_mineral = visual.sphere(x=locations[0][0],y=locations[0][1],z=mineral_radius,radius =mineral_radius,color = (1,1,0) ) self.silver_mineral_1 = visual.sphere(x=locations[1][0],y=locations[1][1],z=mineral_radius,radius =mineral_radius,color = self.silver) self.silver_mineral_2 = visual.sphere(x=locations[2][0],y=locations[2][1],z=mineral_radius,radius =mineral_radius,color = self.silver) #randomly pick the red or blue side r = np.round(np.random.random(1)[0]) b = 1 - r tape_color = (r,0,b) #23.5 is the diameter of a square #place the crater tape self.vertical_lander_tape = visual.box(x=-self.square_width*3/2 + 1,y=a_side/2 - self.square_width*3/2,z=tape_height,length = 2, height = a_side, width = tape_height,color=tape_color) self.h_lander_tape = visual.box(x=-self.square_width*3/2 + a_side/2,y=-a_side/2,z=tape_height,length = 2, height = a_side * np.sqrt(2), width = tape_height,color=tape_color) self.h_lander_tape.rotate(45,axis = [0,0,1],origin = [self.h_lander_tape.x,self.h_lander_tape.y,self.h_lander_tape.z]) self.marker_left = visual.box(x=self.square_width/2 + 1, y =self.square_width,z=tape_height,length=2,height = self.square_width,width=tape_height,color=tape_color) self.marker_right = visual.box(x=3*self.square_width/2 -1, y =self.square_width,z=tape_height,length=2,height = self.square_width,width=tape_height,color=tape_color) self.marker_bottom = visual.box(x=self.square_width,y=self.square_width/2 + 1, z = tape_height,length=self.square_width,height=2,width=tape_height,color=tape_color) self.marker_top = visual.box(x=self.square_width,y=3*self.square_width/2 - 1, z = tape_height,length=self.square_width,height=2,width=tape_height,color=tape_color) #add bars if self.decorations: bar_width = 1.5 bar_height = 1 middle_height = 12 - bar_height*2 middle_color = floor_color bar_length = self.square_width * 3 bar_color = (0,0,0) self.bar1 = visual.box(x=self.square_width*1.5-bar_width/2,y=0,z=tape_height, width= bar_width, height=bar_height,length=bar_length, color = bar_color) self.bar1.rotate(90,axis=[0,0,1],origin=self.bar1.pos) self.bar1m = visual.box(x=self.square_width*1.5-bar_width/2,y=0,z=bar_height+middle_height/2, width= middle_height, height=bar_width,length=bar_length, color = middle_color) self.bar1m.rotate(90,axis=[0,0,1],origin=self.bar1m.pos) self.bar1t = visual.box(x=self.square_width*1.5-bar_width/2,y=0,z=bar_height+middle_height, width= bar_height, height=bar_width,length=bar_length, color = bar_color) self.bar1t.rotate(90,axis=[0,0,1],origin=self.bar1t.pos) self.bar2 = visual.box(x=-self.square_width*1.5+bar_width/2,y=0,z=tape_height, width= bar_width, height=bar_height,length=bar_length, color = bar_color) self.bar2.rotate(90,axis=[0,0,1],origin=self.bar2.pos) self.bar2m = visual.box(x=-self.square_width*1.5+bar_width/2,y=0,z=bar_height+middle_height/2, width= middle_height, height=bar_width,length=bar_length, color = middle_color) self.bar2m.rotate(90,axis=[0,0,1],origin=self.bar2m.pos) self.bar2t = visual.box(x=-self.square_width*1.5+bar_width/2,y=0,z=bar_height+middle_height, width= bar_height, height=bar_width,length=bar_length, color = bar_color) self.bar2t.rotate(90,axis=[0,0,1],origin=self.bar2t.pos) self.bar3 = visual.box(x=0,y=self.square_width*1.5-bar_width/2,z=tape_height, width= bar_width, height=bar_height,length=bar_length, color = bar_color) self.bar3m = visual.box(x=0,y=self.square_width*1.5-bar_width/2,z=bar_height+middle_height/2, width= middle_height, height=bar_width,length=bar_length, color = middle_color) self.bar3t = visual.box(x=0,y=self.square_width*1.5-bar_width/2,z=bar_height+middle_height, width= bar_height, height=bar_width,length=bar_length, color = bar_color) self.bar4 = visual.box(x=0,y=-self.square_width*1.5+bar_width/2,z=tape_height, width= bar_width, height=bar_height,length=bar_length, color = bar_color) self.bar4m = visual.box(x=0,y=-self.square_width*1.5+bar_width/2,z=bar_height+middle_height/2, width= middle_height, height=bar_width,length=bar_length, color = middle_color) self.bar4t = visual.box(x=0,y=-self.square_width*1.5+bar_width/2,z=bar_height+middle_height, width= bar_height, height=bar_width,length=bar_length, color = bar_color) if self.random_colors: height_scale = 40 new_height = bar_height * height_scale self.bar1t.width= new_height self.bar1t.rotate(90,axis=[0,0,1],origin=self.bar1t.pos) self.bar2t.width= new_height self.bar2t.rotate(90,axis=[0,0,1],origin=self.bar2t.pos) self.bar3t.width = new_height self.bar4t.width = new_height self.randomize_colors() self.x, self.y, self.pos_angle = self.get_start_position() self.init_position() if self.random_lighting: self.randomize_lighting() self.move_distance = 2 self.turn_angle = 5
jac=lambda x: lib.ml.fun(N, mp, x)[0:-1] / la.norm(lib.ml.fun(N, mp, x)[0:-1]),\ hess=lambda x: Jac(N, mp, x)[0:-1],\ constraints = sciop.NonlinearConstraint(\ lambda x: (lib.ml.fun(N, mp, x)[-1] - b[-1]*C0), 0, 0))#, jac=lambda x: lib.ml.Jac(N, mp, x)[-1]) ) xn = sol2.x #sol3 = sciop.root(\ # lambda x: np.array(lib.ml.fun(N, mp, x).T)[0][llsq_active] - b.T[0][llsq_active] * C0, \ # x0, \ # method='lm', \ # jac=lambda x: np.array(lib.ml.Jac(N, mp, x)[llsq_active]), \ # options = {'ftol':1e-4, 'xtol':1e-10} ) #xn = sol3.x mlab.close(all=True) mlab.figure() mlab.points3d(x0[0], x0[1], x0[2], scale_mode='none', scale_factor=5e3, color=(0, 1, 1)) mlab.text(x0[0], x0[1], "Init x0", z=x0[2], width=0.13) mlab.points3d(xn[0], xn[1], xn[2], scale_mode='none', scale_factor=5e3, color=(0, 1, 0))
op.join(subjects_dir, subject, 'bem', '%s-oct6-src.fif' % subject)) aln = mne.viz.plot_alignment( raw.info, fname_trans, subject=subject, subjects_dir=subjects_dir, src=src, surfaces=['outer_skin', 'inner_skull'], dig=True, coord_frame='meg') aln.scene.parallel_projection = True fig, axes = plt.subplots(1, 3, figsize=(6.5, 2.5), facecolor='k') from mayavi import mlab # noqa: E402 for ai, angle in enumerate((180, 90, 0)): mlab.view(angle, 90, focalpoint=(0., 0., 0.), distance=0.6) view = mlab.screenshot() mask_w = (view == 0).all(axis=-1).all(axis=1) mask_h = (view == 0).all(axis=-1).all(axis=0) view = view[~mask_w][:, ~mask_h] axes[ai].set_axis_off() axes[ai].imshow(view, interpolation='bicubic') mlab.close(aln) fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0.05, hspace=0) fig.savefig(op.join('..', 'figures', '%s_alignment.pdf' % subject), dpi=150, facecolor=fig.get_facecolor(), edgecolor='none') ############################################################################### # Faces :ref:`sphx_glr_auto_scripts_13-make_inverse.py`. def plot_stc(cond, figure=None): fname = op.join(subject_dir, 'mne_dSPM_inverse_highpass-%sHz-%s' % (l_freq, cond)) stc = mne.read_source_estimate(fname, subject).magnitude() brain = stc.plot(subject=subject, subjects_dir=subjects_dir, views=['ven'], hemi='both', initial_time=0.17, time_unit='s', figure=figure)
def _close_all(): from mayavi import mlab mlab.close(all=True)
def _close_3d_figure(figure): from mayavi import mlab mlab.close(figure)