def anim(s, d, *args, **kwargs): """ Animate graph s with data d[nt,nx,ny] optional argument s1 -> additional bundled graph optional kargument 'save = False' -> save png files for creating movie """ if len(args) == 1: s1 = args[0] else: s1=None try: save = kwargs['save'] except: save = False nt=d.shape[0] print('animating for ',nt,'timesteps') if save == True : print('Saving pics in folder Movie') if not os.path.exists('Movie'): os.makedirs('Movie') for i in range(nt): s.mlab_source.scalars = d[i,:,:] if s1 != None : s1.mlab_source.scalars = d[i,:,:] title="t="+np.string0(i) mlab.title(title,height=1.1, size=0.26) if save == True : mlab.savefig('Movie/anim%d.png'%i) yield
def rotate(): mlab.figure(3) for tt in linspace(30,160,14): mlab.view(0,tt) mlab.draw() mlab.savefig('sphere-rotate%s.png' % str(int(tt)).zfill(3)) os.system("convert sphere-rotate*.png sphere.gif")
def anim(s, d, *args, **kwargs): """ Animate graph s with data d[nt,nx,ny] optional argument s1 -> additional bundled graph optional kargument 'save = False' -> save png files for creating movie """ if len(args) == 1: s1 = args[0] else: s1 = None try: save = kwargs['save'] except: save = False nt = d.shape[0] print('animating for ', nt, 'timesteps') if save == True: print('Saving pics in folder Movie') if not os.path.exists('Movie'): os.makedirs('Movie') for i in range(nt): s.mlab_source.scalars = d[i, :, :] if s1 != None: s1.mlab_source.scalars = d[i, :, :] title = "t=" + np.string0(i) mlab.title(title, height=1.1, size=0.26) if save == True: mlab.savefig('Movie/anim%d.png' % i) yield
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. 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)
def sln2png(sln, filename): """ Creates a nice png image of the Solution sln. """ plot_sln_mayavi(sln) from enthought.mayavi.mlab import savefig savefig(filename)
def plotsln(mesh, z=None, sln=None, colorbar=False, view=(0,0), filename="a.png"): """ Plot a solution for the mesh editor in the online lab. """ x = [n[0] for n in mesh.nodes] y = [n[1] for n in mesh.nodes] if z == None: try: z = [n[2] for n in mesh.nodes] except IndexError: z = [0]*len(y) from enthought.mayavi import mlab mlab.options.offscreen = True mlab.clf() #mlab.options.show_scalar_bar = False mlab.triangular_mesh(x, y, z, mesh.elems, scalars=sln) engine = mlab.get_engine() image = engine.current_scene image.scene.background = (1.0, 1.0, 1.0) image.scene.foreground = (0.0, 0.0, 0.0) if colorbar: mlab.colorbar(orientation="vertical") if view: mlab.view(view[0], view[1]) mlab.savefig(filename)
def move_cam(outpath): """ Example to record a stream of images moving the camera around (using offscreen rendering) Usage: move_cam(out_path) Input: outpath - (String) output path to save images Output: -NONE- but stream of images is saved in outpath """ import os.path import tf_format from enthought.mayavi import mlab mlab.options.offscreen = True mlab.test_contour3d() # Example motion: rotate clockwise around an object step = 15 # degrees of change between views for i, angle in enumerate(range(0, 360, step)): view = mlab.view(azimuth=angle) imgname = os.path.join(outpath, 'example' + str(i) + '.png') mlab.savefig(imgname)
def show(self, sln, show=True, lib="mpl", notebook=False, filename="a.png", **options): """ Shows the solution. show ... should it actually plot the window? Set to False in tests. lib .... which library to use for the plotting? either "mpl" or "mayavi" notebook ... are we running inside Sage notebook? If True, just save the image to a.png filename ... the name of the filename if we are saving the image (e.g. notebook == False) """ self._lib = lib self._notebook = notebook if lib == "mpl": plot_sln_mpl(sln, **options) import pylab if show: if notebook: pylab.savefig(filename) else: pylab.ion() pylab.draw() pylab.ioff() elif lib == "mayavi": plot_sln_mayavi(sln, notebook=notebook) from enthought.mayavi import mlab if show: if notebook: mlab.savefig(filename) else: mlab.show() else: raise NotImplementedError("Unknown library '%s'" % lib)
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: 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: from enthought.mayavi import mlab e = mlab.get_engine() if len(e.scenes) > 0: mlab.savefig(image_file) 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()
def sln2png(sln, filename, offscreen=False): """ Creates a nice png image of the Solution sln. """ plot_sln_mayavi(sln, offscreen=offscreen) from enthought.mayavi.mlab import savefig savefig(filename)
def topo(j_data, file_name=None, size=(600,600)): u"""Creates the topological view of the molecule. ** Parameters ** j_data : dict Data on the molecule, as deserialized from the scanlog format. file_name : str, optional Base name of the file in which to save the image. size : tuple(int, int), optional The size of the image to save. ** Returns ** figure : mayavi.core.scene.Scene The MayaVi scene containing the visualization. """ figure, normal = _init_scene(j_data) geom = np.array(j_data["results"]["geometry"]["elements_3D_coords_converged"]).reshape((-1,3))/A_to_a0 ## Show labels and numbers ( = indices + 1 ) for i, atom in enumerate(j_data["molecule"]["atoms_Z"]): P, label = geom[i], tab[atom][1] mlab.text3d(P[0] - normal[0], P[1] - normal[1], P[2] - normal[2], label + str(i + 1), color=(0,0,0), scale=0.5, figure=figure) if file_name is not None: mlab.savefig("{}-TOPO.png".format(file_name), figure=figure, size=size) return figure
def ChargeDensityFog3D(directory, save_file=None , DrawAtoms=True, DrawCell=True, opacity_range=[0,1]): # Get data from calculation files with jasp(directory) as calc: atoms = calc.get_atoms() x, y, z, cd = calc.get_charge_density() mlab.figure(bgcolor=(0,0,0), size=(640,480)) # Draw atoms if DrawAtoms == True: for atom in atoms: mlab.points3d(atom.x, atom.y, atom.z, scale_factor=vdw_radii[atom.number]/10., resolution=16, color=tuple(cpk_colors[atom.number]), scale_mode='none') # Draw unit cell if DrawCell == True: a1, a2, a3 = atoms.get_cell() origin = [0,0,0] cell_matrix = [[origin, a1], [origin, a2], [origin, a3], [a1, a1+a2], [a1, a1+a3], [a2, a2+a1], [a2, a2+a3], [a3, a1+a3], [a3, a2+a3], [a1+a2, a1+a2+a3], [a2+a3, a1+a2+a3], [a1+a3, a1+a3+a2]] # contains all points on the box for p1, p2 in cell_matrix: mlab.plot3d([p1[0], p2[0]], # x-coords of box [p1[1], p2[1]], # y-coords [p1[2], p2[2]]) # z-coords # Plot the charge density src = mlab.pipeline.scalar_field(x, y, z, cd) #Source data vmin = cd.min() #find minimum and maximum value of CD data vmax = cd.max() vol = mlab.pipeline.volume(src) # Make a volumetric representation of the data # Set opacity transfer function from tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() otf.add_point(vmin, opacity_range[0]) #Transparency at zero electron density otf.add_point(vmax*1, opacity_range[1]) #Transparency at max electron density vol._otf=otf vol._volume_property.set_scalar_opacity(otf) #Show a legend mlab.colorbar(title="e- density\n(e/Ang^3)", orientation="vertical", nb_labels=5, label_fmt='%.2f') mlab.view(azimuth=-90, elevation=90, distance='auto') # Set viewing angle mlab.show() if save_file != None: mlab.savefig(save_file)
def show(self, sln, show=True, lib="mayavi", notebook=None, filename="scalar.png", **options): """ Shows the solution. show ... should it actually plot the window? Set to False in tests. lib .... which library to use for the plotting? either "mpl" or "mayavi" notebook ... are we running inside Sage notebook? If True, just save the image to a.png filename ... the name of the filename if we are saving the image (e.g. notebook == False) Example: >>> 1 + 1 2 >>> 1 + 2 3 """ if notebook is None: try: from sagenb.misc.support import EMBEDDED_MODE except ImportError: EMBEDDED_MODE = False notebook = EMBEDDED_MODE self._lib = lib self._notebook = notebook if lib == "glut": if self._glut_view is None: from _hermes2d import ScalarView self._glut_view = ScalarView(self._name) self._glut_view.show(sln) elif lib == "mpl": plot_sln_mpl(sln, **options) import pylab if show: if notebook: pylab.savefig(filename) else: pylab.ion() pylab.draw() pylab.ioff() elif lib == "mayavi": plot_sln_mayavi(sln, notebook=notebook) from enthought.mayavi import mlab if show: engine = mlab.get_engine() image = engine.current_scene image.scene.background = (1.0, 1.0, 1.0) image.scene.foreground = (0.0, 0.0, 0.0) #mlab.colorbar(orientation="vertical") if notebook: mlab.savefig(filename) else: mlab.show() else: raise NotImplementedError("Unknown library '%s'" % lib)
def capture_image(func, filename): """ Runs a function doing some mayavi drawing and save the resulting scene to a file. """ mlab.clf() func() if not filename[-4:] in ('.jpg', '.png'): filename = '%s.jpg' % filename mlab.savefig(filename , size=(400, 400) ) os.system('convert %s -trim %s' % (filename, filename))
def capture_image(func, filename): """ Runs a function doing some mayavi drawing and save the resulting scene to a file. """ mlab.clf() func() if not filename[-4:] in ('.jpg', '.png'): filename = '%s.jpg' % filename mlab.savefig(filename, size=(400, 400)) os.system('convert %s -trim %s' % (filename, filename))
def poll_file(self): if os.path.isfile(self.lockfname): self.update_pipeline(self.cellsource) self.update_pipeline(self.facesource) lock = file(self.lockfname, 'r') filename = lock.read() lock.close() if len(filename) > 0: mlab.savefig(filename) os.unlink(self.lockfname)
def viz_EDD(data, X, Y, Z, j_data, file_name=None, labels=None, size=(600, 600)): u"""Visualizes the electron density differences for the transitions of the molecule. ** Parameters ** data : list(numpy.ndarray) Voxels containing the scalar values of the electron density differences to plot. X, Y, Z : numpy.ndarray Meshgrids as generated by numpy.mgrid, for positioning the voxels. j_data : dict Data on the molecule, as deserialized from the scanlog format. file_name : str, optional Base name of the files in which to save the images. labels : list(str), optional Labels to append to `file_name` for each series in `data`. If None, the position of the series is appended. size : tuple(int, int), optional The size of the image to save. ** Returns ** figure : mayavi.core.scene.Scene The MayaVi scene containing the visualization. """ figure = _init_scene(j_data)[0] for i, series in enumerate(data): D_data = mlab.pipeline.scalar_field(X, Y, Z, series, figure=figure) Dp = mlab.pipeline.iso_surface(D_data, figure=figure, contours=[0.0035], color=(0.0, 0.5, 0.5)) Dn = mlab.pipeline.iso_surface(D_data, figure=figure, contours=[-0.0035], color=(0.95, 0.95, 0.95)) #Dn.actor.property.representation = 'wireframe' #Dn.actor.property.line_width = 0.5 if file_name is not None: mlab.savefig("{}-EDD-{}.png".format( file_name, labels[i] if labels is not None else i), figure=figure, size=size) Dp.remove() Dn.remove() return figure
def viz_MO(data, X, Y, Z, j_data, file_name=None, labels=None, size=(600, 600)): u"""Visualizes the molecular orbitals of the molecule. ** Parameters ** data : list(numpy.ndarray) List of series of voxels containing the scalar values of the molecular orbitals to plot. X, Y, Z Meshgrids as generated by numpy.mgrid, for positioning the voxels. j_data : dict Data on the molecule, as deserialized from the scanlog format. file_name : str, optional Base name of the files in which to save the images. labels : list(str), optional Labels to append to `file_name` for each series in `data`. If None, the position of the series is appended. size : tuple(int, int), optional The size of the image to save. ** Returns ** figure : mayavi.core.scene.Scene The MayaVi scene containing the visualization. """ figure = _init_scene(j_data)[0] for i, series in enumerate(data): MO_data = mlab.pipeline.scalar_field(X, Y, Z, series, figure=figure) Cutoff = CalcCutOffP(series, i=i) print Cutoff MOp = mlab.pipeline.iso_surface(MO_data, figure=figure, contours=[Cutoff], color=(0.4, 0, 0.235)) MOn = mlab.pipeline.iso_surface(MO_data, figure=figure, contours=[-Cutoff], color=(0.95, 0.90, 0.93)) if file_name is not None: mlab.savefig("{}-MO-{}.png".format( file_name, labels[i] if labels is not None else i), figure=figure, size=size) MOp.remove() MOn.remove() return figure
def make_all_frames(figno): frames = range(85) plotfiles = [] for frameno in frames: plotframe(frameno) frstring = str(int(frameno)).zfill(3) name = "monai-%s-frame%s.png" % (figno, frstring) plotfiles.append(name) mlab.savefig("monai-%s-frame%s.png" % (figno, frstring)) make_movie(plotfiles, moviename='monai-%s.html' % figno)
def example(): """ Example to run offscreen rendering with mayavi. If you see an 'int64' error, you will need to patch 'figure.py' to '... = int(magnification)'. This example saves a file called 'example.png' in the current folder, with some shapes. Usage: example() """ from enthought.mayavi import mlab mlab.options.offscreen = True mlab.test_contour3d() mlab.savefig('example.png')
def make_all_frames(water_opacity): fortqfiles = glob.glob(os.path.join(outdir,'fort.q*')) frames = range(len(fortqfiles)) print "Will make %s frames" % len(fortqfiles) plotfiles = [] for frameno in frames: plotframe(frameno,1,water_opacity) frstring = str(int(frameno)).zfill(3) name = "movie-frame%s.png" % frstring plotfiles.append(name) mlab.savefig("movie-frame%s.png" % frstring) make_movie(plotfiles, moviename='movie.html')
def viz_Fukui(data, X, Y, Z, j_data, file_name=None, labels=None, size=(600, 600)): u"""Visualizes the fukui density differences for the molecule. ** Parameters ** data : list(numpy.ndarray) Voxels containing the scalar values of the electron density difference to plot. X, Y, Z : numpy.ndarray Meshgrids as generated by numpy.mgrid, for positioning the voxels. j_data : dict Data on the optimized state of the molecule, as deserialized from the scanlog format. file_name : str, optional Base name of the files in which to save the images. label : text Label to append to `file_name` for each series in `data`. "plus" for sp_plus - opt; "minus" for opt - sp_minus. size : tuple(int, int), optional The size of the image to save. ** Returns ** figure : mayavi.core.scene.Scene The MayaVi scene containing the visualization. """ figure = _init_scene(j_data)[0] F_data = mlab.pipeline.scalar_field(X, Y, Z, data, figure=figure) Fp = mlab.pipeline.iso_surface(F_data, figure=figure, contours=[0.0035], color=(0.0, 0.5, 0.5)) Fn = mlab.pipeline.iso_surface(F_data, figure=figure, contours=[-0.0035], color=(0.95, 0.95, 0.95)) #Fn.actor.property.representation = 'wireframe' #Fn.actor.property.line_width = 0.5 if file_name is not None: mlab.savefig("{}-fukui-{}.png".format(file_name, labels), figure=figure, size=size) Fp.remove() Fn.remove() return figure
def viz_BARY(data, j_data, file_name=None, labels=None, size=(600, 600)): u"""Visualizes the barycenters of the electron density difference (for visualizing dipole moments). ** Parameters ** data : tuple(numpy.ndarray((3,N)), numpy.ndarray((3,N))) Pair of column-major matrices containing the coordinates of the positive and negative barycenters, in that order. j_data : dict Data on the molecule, as deserialized from the scanlog format. file_name : str, optional Base name of the files in which to save the images. labels : list(str), optional Labels to append to `file_name` for each datum in `data`. If None, the position of the datum is appended. size : tuple(int, int), optional The size of the image to save. ** Returns ** figure : mayavi.core.scene.Scene The MayaVi scene containing the visualization. """ figure = _init_scene(j_data)[0] for i, D in enumerate(data): #Pp = mlab.points3d(D[0][0], D[0][1], D[0][2], figure=figure, mode='axes', scale_factor=0.3, color=(0.0, 0.5, 0.5)) #Pm = mlab.points3d(D[1][0], D[1][1], D[1][2], figure=figure, mode='axes', scale_factor=0.3, color=(0.95, 0.95, 0.95)) ## Chemistry convention (from negative to positive) Mu = mlab.quiver3d(D[1][0], D[1][1], D[1][2], D[0][0] - D[1][0], D[0][1] - D[1][1], D[0][2] - D[1][2], figure=figure, mode='arrow', scale_factor=1.0, color=(0.0, 0.5, 0.5)) if file_name is not None: mlab.savefig("{}-BARY-{}.png".format( file_name, labels[i] if labels is not None else i), figure=figure, size=size) #Pp.remove() #Pm.remove() Mu.remove() return figure
def make_all_frames(figno): frames = range(85) plotfiles = [] for frameno in frames: plotframe(frameno) frstring = str(int(frameno)).zfill(3) name = "monai-%s-frame%s.png" % (figno,frstring) plotfiles.append(name) mlab.savefig("monai-%s-frame%s.png" % (figno,frstring)) make_movie(plotfiles, moviename='monai-%s.html' % figno) #os.system("convert island-%s-frame%s.png island-%s-frame%s.eps" \ # % (figno,frstring,figno,frstring))
def save(self,it): msh = self.__msh w = (self.__eqn).get(self.__var)() mlab.clf() mlab.points3d(msh.x[:,0], msh.x[:,1], zeros(w.shape), w, scale_factor=self.__scale, scale_mode=self.__mode) mlab.outline(extent=[msh.BB[0,0],msh.BB[1,0],msh.BB[0,1],msh.BB[1,1], 0,0]) mlab.view(0,0,self.__zoom,self.__xView) mlab.colorbar() fSol = ''.join([self.__figDir,'/',self.__name,'%04d.png'% it]) #print fSol mlab.savefig(fSol)
def run_mlab_file(filename, image_file): ## XXX: Monkey-patch mlab.show, so that we keep control of the ## the mainloop old_show = mlab.show def my_show(func=None): pass mlab.show = my_show mlab.clf() e = mlab.get_engine() e.close_scene(mlab.gcf()) execfile(filename, {'__name__': '__main__'}) mlab.savefig(image_file) size = mlab.gcf().scene.get_size() for scene in e.scenes: e.close_scene(scene) mlab.show = old_show
def createVideo(filename, renderers, tMin, tMax, framerate=25, resolution=None): """ Create a video of a 3D visualisation. The video is created using the current MayaVi figure, which should be setup beforehand to correctly position the camera and any other elements that should be rendered. @param filename: Name of the video file to create. @param renderers: List of L{AnimatedRenderer} objects to use. @param tMin: Time from which to begin rendering. @param tMax: Time at which to stop rendering. @param framerate: Framerate of the video in frames per second. @param resolution: Resolution of the video (width, height). If not specified, the resolution of the current figure is used. """ if not isinstance(renderers, collections.Iterable): renderers = [renderers] figure = mlab.gcf() if resolution is not None: originalResolution = figure.scene.get_size() figure.scene.set_size(resolution) figure.scene.off_screen_rendering = True figure.scene.disable_render = True frameTimes = np.arange(tMin, tMax, 1.0/framerate) try: imageDir = tempfile.mkdtemp() for f,t in enumerate(frameTimes): for r in renderers: r.renderUpdate(t) framefile = os.path.join(imageDir, '%06d.png'%(f)) mlab.savefig(framefile, size=resolution) assert os.path.exists(framefile) retval = subprocess.call(['ffmpeg', '-f','image2', '-r', str(framerate), '-i', '%s'%os.path.join(imageDir,'%06d.png'), '-sameq', filename, '-pass','2']) finally: shutil.rmtree(imageDir) figure.scene.disable_render = False figure.scene.off_screen_rendering = False if resolution is not None: figure.scene.set_size(originalResolution)
def plot_connections(data_file, min, max, bins, params=None, output=''): print("Creating connection profile graphs.") # Read data points from file f = open(data_file, 'r') # Ignore first line f.readline() data = [] for line in f: temp = line.split(' ') if params != None: if check_node([int(temp[1])], params): data.append([float(temp[4]), float(temp[5])]); else: data.append([float(temp[4]), float(temp[5])]); # Create histogram data based on the retrieved data. histogram_data = histogram2d(data, min, max, bins) # Open a new Mayavi2 figure f = mlab.figure() # Convert histogram bin count to relative densities. m = np.max(histogram_data[2].max(axis=0)) histogram_data[2] = histogram_data[2]/float(m) # Plot histogram data mlab.mesh(histogram_data[0], histogram_data[1], histogram_data[2]) #surf(histogram_data[0], histogram_data[1], histogram_data[2]) # Create and save various viewpoints of histogram figure mlab.axes(z_axis_visibility=False) mlab.view(azimuth=0, elevation=90) # X mlab.savefig(output+"xaxis.eps", size=[600,400]) mlab.view(azimuth=90, elevation=270) # Y mlab.savefig(output+"yaxis.eps", size=[600,400]) mlab.view(azimuth=45, elevation=45) # Perspective mlab.savefig(output+"perspective.eps", size=[600,400]) mlab.colorbar(orientation="vertical") mlab.view(azimuth=0, elevation=0) # Z mlab.savefig(output+"above.eps", size=[600,400])
def plot_connections(data_file, min, max, bins, params=None, output=''): print("Creating connection profile graphs.") # Read data points from file f = open(data_file, 'r') # Ignore first line f.readline() data = [] for line in f: temp = line.split(' ') if params != None: if check_node([int(temp[1])], params): data.append([float(temp[4]), float(temp[5])]) else: data.append([float(temp[4]), float(temp[5])]) # Create histogram data based on the retrieved data. histogram_data = histogram2d(data, min, max, bins) # Open a new Mayavi2 figure f = mlab.figure() # Convert histogram bin count to relative densities. m = np.max(histogram_data[2].max(axis=0)) histogram_data[2] = histogram_data[2] / float(m) # Plot histogram data mlab.mesh(histogram_data[0], histogram_data[1], histogram_data[2]) #surf(histogram_data[0], histogram_data[1], histogram_data[2]) # Create and save various viewpoints of histogram figure mlab.axes(z_axis_visibility=False) mlab.view(azimuth=0, elevation=90) # X mlab.savefig(output + "xaxis.eps", size=[600, 400]) mlab.view(azimuth=90, elevation=270) # Y mlab.savefig(output + "yaxis.eps", size=[600, 400]) mlab.view(azimuth=45, elevation=45) # Perspective mlab.savefig(output + "perspective.eps", size=[600, 400]) mlab.colorbar(orientation="vertical") mlab.view(azimuth=0, elevation=0) # Z mlab.savefig(output + "above.eps", size=[600, 400])
def make_3d_graph(scalarfield, filename): mlab.figure(bgcolor=(1,1,1),fgcolor=(0,0,0)) #mlab.options.offscreen = True #win = e.new_scene() #src = mlab.pipeline.scalar_scatter(Phi_graph) #e.add_source(src) #e.add_module(IsoSurface()) #e.add_module( #win.scene.isometric_view() #win.scene.save(filename,size=(800,600)) mlab.clf() mlab.contour3d(scalarfield,opacity=.5,transparent=True)#,contours=[1.0]) # mlab.outline() mlab.zlabel('Z') mlab.xlabel('X') mlab.ylabel('Y') print 'saving %s' % filename mlab.savefig(filename)
def meshplot(mesh, labels=None, vert=False, elm=False, ed=False, \ scale=[1,1,1], elm_ids=[], offscreen=False, savefig=None, is2D=False): '''Function to plot the mesh, with various labelling options @param mesh A mesh object @param labels One interface fo labeling. labels is a list of size 3 of type bool. Then entries in labels corresponds to labels = [vert, elm, ed] (See below) @param vert (\c bool) Flags wether or not to plot vertex labels. False by default. @param elm (\c bool) Flags wether or not to plot element labels. False by default. @param ed (\c bool) Flags wether or not to plot edge labels. False by default. @param scale (\c int) List indicating the scaling of the vertices -- this is used to scale the z-direction for a thin mesh. By default, there is no scaling, i.e. scale = [1, 1, 1] @param elm_ids Numpy array of elements that will be plotted. If left empty, all elements are plotted. This is closely used with the labels inputs -- labels are expensive (memory-wise) to plot in 3D, so only a limited number of elements can be comfortably plotted with labels in 3D. @param offscreen ? @param savefig ? @param is2D ? ''' if offscreen: mlab.options.offscreen = True if savefig == None: savefig = 'out.png' if labels == None: labels = [vert, elm, ed] if mesh.dim == 2: if any(labels) or is2D: mshplot2D(mesh.elm, mesh.vert, mesh.ed2ed, labels) else: mshplot3D(mesh) elif mesh.dim == 3: mshplot3D(mesh, scale, elm_ids, labels) if savefig != None: mlab.savefig(savefig)
def anim(s, d, *args, **kwargs): """Animate graph with mayavi Parameters ---------- s : mayavi axis object Axis to animate data on d : array_like 3-D array to animate s1 : mayavi axis object, optional Additional bundled graph (first item in *args) save : bool, optional Save png files for creating movie (default: False) """ if len(args) == 1: s1 = args[0] else: s1=None try: save = kwargs['save'] except: save = False nt=d.shape[0] print('animating for ',nt,'timesteps') if save == True : print('Saving pics in folder Movie') if not os.path.exists('Movie'): os.makedirs('Movie') for i in range(nt): s.mlab_source.scalars = d[i,:,:] if s1 is not None : s1.mlab_source.scalars = d[i,:,:] title="t="+np.string0(i) mlab.title(title,height=1.1, size=0.26) if save == True : mlab.savefig('Movie/anim%d.png'%i) yield
def make_multiple_3d_graphs(data, filename): '''data is a list of 3d scalar fields. filename is a string, probably ending in .png''' mlab.figure(bgcolor=(1,1,1),fgcolor=(0,0,0),size=(1000,600)) # f = mlab.gcf() # camera = f.scene.camera # cam.parallel_scale = 9 # view = mlab.view() # roll = mlab.roll() # print 'camera view is:',view # print 'camera roll is:',roll #mlab.options.offscreen = True #win = e.new_scene() #src = mlab.pipeline.scalar_scatter(Phi_graph) #e.add_source(src) #e.add_module(IsoSurface()) #e.add_module( #win.scene.isometric_view() #win.scene.save(filename,size=(800,600)) i=0 # print 'mean is: ',data[i].mean() # print 'min is: ',data[i].min() for contourpercent in [.232,]: # [.16, .20,.22,.232,.25,.28,.32,.36,.40,.44,.48,.52,.56,.60,.64,.68,.72]: mlab.clf() # contourpercent = .232 # .28, .24 is good value = (data[i].max()-data[i].min())*contourpercent+data[i].min() print 'graphing contours at',contourpercent,'of min-max distance, where value is ',value,'(versus a max of',data[i].max(),'and a min of',data[i].min(),', and a range of ',data[i].max()-data[i].min(),').' # print 'graphing data[%i].shape='%i,data[i].shape mlab.contour3d(data[i],contours=[value],opacity=.36,transparent=True,colormap='bone') for i in range(1,len(data)): # print data[i] # print 'graphing data[%i].shape='%i,data[i].shape mlab.contour3d(data[i],contours=[(data[i].max()-data[i].min())*contourpercent+data[i].min()],opacity=.56,transparent=True) # mlab.view(distance=36.0) # mlab.outline() # mlab.zlabel('Z') # mlab.xlabel('X') # mlab.ylabel('Y') tosave = filename + '%.03f'%contourpercent + '.png' print 'saving %s' % tosave mlab.savefig(tosave)
def save_image(self, fname): """Save current view to disk Only mayavi image types are supported: (png jpg bmp tiff ps eps pdf rib oogl iv vrml obj Parameters ---------- filename: string path to new image file """ from enthought.mayavi import mlab ftype = fname[fname.rfind('.') + 1:] good_ftypes = ['png', 'jpg', 'bmp', 'tiff', 'ps', 'eps', 'pdf', 'rib', 'oogl', 'iv', 'vrml', 'obj'] if not ftype in good_ftypes: raise ValueError("Supported image types are %s" % " ".join(good_ftypes)) mlab.savefig(fname)
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 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)
def show(self, sln, show=True, lib="mpl", notebook=False, filename="a.png", **options): """ Shows the solution. show ... should it actually plot the window? Set to False in tests. lib .... which library to use for the plotting? either "mpl" or "mayavi" notebook ... are we running inside Sage notebook? If True, just save the image to a.png filename ... the name of the filename if we are saving the image (e.g. notebook == False) """ self._lib = lib self._notebook = notebook if lib == "mpl": plot_sln_mpl(sln, **options) import pylab if show: if notebook: pylab.savefig(filename) else: pylab.ion() pylab.draw() pylab.ioff() elif lib == "mayavi": plot_sln_mayavi(sln, notebook=notebook) from enthought.mayavi import mlab if show: engine = mlab.get_engine() image = engine.current_scene image.scene.background = (1.0, 1.0, 1.0) image.scene.foreground = (0.0, 0.0, 0.0) c = mlab.colorbar(orientation="vertical") c.position = (0.000, 0.035) if notebook: mlab.savefig(filename) else: mlab.show() else: raise NotImplementedError("Unknown library '%s'" % lib)
def saveVTKFilesAsImages_2D(sourceFolder, destinationFolder): if not os.path.isdir(sourceFolder) or not os.path.isdir( destinationFolder): return vtkFiles = [] for f in sorted(os.listdir(sourceFolder)): if f.endswith(".vtk"): vtkFiles.append(f) if len(vtkFiles) == 0: return figure = mlab.figure(size=(800, 600)) figure.scene.disable_render = True vtkSource = VTKFileReader() vtk_file = os.path.join(sourceFolder, vtkFiles[0]) vtkSource.initialize(vtk_file) surface = mlab.pipeline.surface(vtkSource) axes = mlab.axes() colorbar = mlab.colorbar(object=surface, orientation='horizontal') mlab.view(0, 0) figure.scene.disable_render = False mlab.draw() png_file = os.path.join(destinationFolder, vtkFiles[0]).replace('.vtk', '.png') mlab.savefig(png_file) for f in vtkFiles[1:-1]: vtk_file = os.path.join(sourceFolder, f) vtkSource.initialize(vtk_file) png_file = os.path.join(destinationFolder, f).replace('.vtk', '.png') mlab.savefig(png_file) app = QtCore.QCoreApplication.instance() if app: app.processEvents()
index_edges.add(frozenset([index, neighbor_index])) return index_edges def add_tree(): # construct the matrices to be used for the eigendecomposition lfdo = ProofDecoration.tree_string_to_LFDO(g_tree_string) lfdi = ProofDecoration.LFDO_to_LFDI(lfdo) # we need the ordered ids themselves to to construct the edges tree = NewickIO.parse(g_tree_string, FelTree.NewickTree) ordered_ids = ProofDecoration.tree_to_leaf_first_ids(tree) index_edges = get_index_edges(tree, ordered_ids) # define the points X, Y, Z = get_grant_proposal_points_b(lfdi) # draw the image draw_3d_tree(X, Y, Z, index_edges) draw_crossings(X, Y, Z, index_edges) # try to not pop up an annoying window mlab.options.offscreen = True add_yz_plane() add_zx_plane() add_xy_plane() add_tree() #mlab.show() mlab.savefig('myfig.png', size=(640, 480)) #mlab.savefig('mymodel.vrml', size=(640, 480))
visio.draw_model() time = man.groups['t'] for i, indx in enumerate(total_time_index_array): # Creating the dirs path_animation = os.path.join(dir, animation_dir) path_screenshots = os.path.join(dir, screenshot_dir) if not os.path.exists(path_animation): os.mkdir(path_animation) if not os.path.exists(path_screenshots): os.mkdir(path_screenshots) time_point = time[indx] figure_filename_screenshot = '%s_%s_%09d.png' % (condition, time_point, i) figure_filename_animation = '%s%09d.png' % (condition, i) file = os.path.join(path_animation, figure_filename_animation) path_animation_file = os.path.join(path_animation, figure_filename_animation) path_screenshot_file = os.path.join(path_screenshots, figure_filename_screenshot) if not os.path.exists(path_animation_file): visio.show_variable_timecourse(var, indx, start_value, end_value) print "Saving %s" % path_animation_file mlab.savefig(os.path.join(path_animation_file), size=(1280, 1024)) copyfile(path_animation_file, path_screenshot_file)
""" Use Mayavi to visualize the structure of a VolumeImg """ from enthought.mayavi import mlab import numpy as np x, y, z = np.mgrid[-5:5:64j, -5:5:64j, -5:5:64j] data = x*x*0.5 + y*y + z*z*2.0 mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) mlab.clf() src = mlab.pipeline.scalar_field(x, y, z, data) mlab.pipeline.surface(src, opacity=0.4) src2 = mlab.pipeline.scalar_field(x[::9, ::9, ::9], y[::9, ::9, ::9], z[::9, ::9, ::9], data[::9, ::9, ::9]) mlab.pipeline.surface(mlab.pipeline.extract_edges(src2), color=(0, 0, 0)) mlab.pipeline.glyph(src2, mode='cube', scale_factor=0.4, scale_mode='none') mlab.savefig('viz_volume_structure.png') mlab.show()
mlab.text(280, 300, '300', z=6560, color=(0, 0, 0), width=0.05) mlab.text(-320, 300, '-300', z=6560, color=(0, 0, 0), width=0.05) # Finally, add some tick lines in the middle of the top-front-side panels mlab.plot3d([-300, 300], [0, 0], [np.min(vs), np.min(vs)], color=(0, 0, 0), tube_radius=1) mlab.plot3d([0, 0], [-300, 300], [np.min(vs), np.min(vs)], color=(0, 0, 0), tube_radius=1) mlab.plot3d([0, 0], [np.max(decs), np.max(decs)], [6671.3, 7643.7], color=(0, 0, 0), tube_radius=1) mlab.plot3d([-300, 300], [np.max(decs), np.max(decs)], [7157.5, 7157.5], color=(0, 0, 0), tube_radius=1) mlab.plot3d([np.min(ras), np.min(ras)], [0, 0], [6671.3, 7643.7], color=(0, 0, 0), tube_radius=1) mlab.plot3d([np.min(ras), np.min(ras)], [-300, 300], [7157.5, 7157.5], color=(0, 0, 0), tube_radius=1) # All done ! # Save it & export the diagram mlab.savefig(plot_loc + 'HCG91.x3d') mlab.savefig(plot_loc + 'HCG91.png') # Show it ! mlab.show()
temperature[i,j,k] = (f[:,i,j,k]* v[2:-2]**2).sum() / f.sum(axis=0)[i,j,k] return temperature for frame in range(len(fileh.root.Time[:])): # 3D Movie frame = 4*frame mlab.clf(figure=fig3d) scene = mlab.contour3d(Temperature(fileh.root.Phasespace[:,:,:,:,frame], fileh.root.Phasespace.attrs.v), contours=50) # Density profile #scene = mlab.contour3d(fileh.root.Phasespace[:,:,:,:,frame].sum(axis=0), contours=50) #source = mlab.pipeline.scalar_field(Temperature(fileh.root.Phasespace[:,:,:,:,frame], fileh.root.Phasespace.attrs.v)) #vol = mlab.pipeline.volume(source) angle = 50. mlab.view(azimuth=angle%360, distance=72.0) #mlab.axes(color=(0.0,0.0,0.),extent=ext,xlabel='X',ylabel='Y',zlabel='Z') #a = array(gradient(fileh.root.Phi[:,:,:,frame]))**2 #mlab.quiver3d(a[0],a[1],a[2]) mlab.colorbar(orientation='vertical')#, label_fmt="%.2f", nb_labels=3) mlab.outline() mlab.savefig("Rho_" + string.zfill(frame, 4) + ".jpg")#, size=(600,600)) print "[", string.zfill(frame, 4),"/", len(fileh.root.Time[:]), "]" #mencoder "mf://*.jpg" -mf fps=10 -ovc lavc -o mymovie.av
#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
subplot(1, 2, 2) pcolor(image2, cmap=cm.jet, vmin=-1, vmax=1, shading='faceted') xticks(()) yticks(()) savefig('laplacien.eps') show() from enthought.mayavi import mlab mlab.figure(1, size=(720, 300)) mlab.clf() import numpy as np x_, y_ = np.indices(image.shape) mlab.barchart(x_, y_ - 3, 2 * image, vmin=-1, vmax=1) mlab.barchart(x_, y_ + 3, 2 * image2, vmin=-1, vmax=1) mlab.view(0, 63, 8.5, (3, 2, 1)) mlab.savefig('laplacien.jpg') import os os.system('mogrify -trim laplacien.jpg') from numpy import zeros image = zeros((size, size)) image[size / 2, size / 2] = 1 def laplacien_numpy(): image[1:-1, 1:-1] = (image[:-2, 1:-1] - image[2:, 1:-1] + image[1:-1, :-2] - image[1:-1, 2:]) * 0.25 # speed of laplacien_numpy, measured throught %timeit, on epsilon: # size = 5, 38us
mlab.clf() mlab.points3d(center.T[0], center.T[1], center.T[2], colors_, scale_factor=0.05, scale_mode='none', colormap='RdBu', vmin=colors_.min(), vmax=colors_.max()) #mlab.quiver3d(center.T[0],center.T[1],center.T[2],normal.T[0],normal.T[1],normal.T[2],colormap='spectral',scale_mode='none') mlab.colorbar() if i >= 1: vx,vy,vz = center.T[0]-old_center.T[0],\ center.T[1]-old_center.T[1],\ center.T[2]-old_center.T[2] v = np.sqrt(vx**2 + vy**2 + vz**2) mlab.quiver3d(center.T[0],center.T[1],center.T[2],\ vx,vy,vz,scalars=v,colormap='spectral',scale_mode='scalar') #mlab.show() old_center = center.copy() mlab.view(distance=5, azimuth=-90, elevation=90) mlab.savefig('pulsation_lm%d%d_k%03d_%03d.png' % (l, m, k, i)) mlab.close() multimedia.make_movie( 'pulsation_lm%d%d_k%03d_*.png' % (l, m, k), output='pulsation_lm%d%d_k%03d.avi' % (l, m, k))
atoms=atoms) calc.set_nbands(f=2) calc.stop_if(calc.potential_energy is None) x, y, z, lp = calc.get_local_potential() x, y, z, cd = calc.get_charge_density() mlab.figure(1, bgcolor=(1, 1, 1)) # make a white figure # plot the atoms as spheres for atom in atoms: mlab.points3d( atom.x, atom.y, atom.z, scale_factor=vdw_radii[atom.number] / 5., resolution=20, # a tuple is required for the color color=tuple(cpk_colors[atom.number]), scale_mode='none') # plot the bonds. We want a line from C-Br, C-F, etc... # We create a bond matrix showing which atoms are connected. bond_matrix = [[0, 1], [0, 2], [0, 3], [0, 4]] for a1, a2 in bond_matrix: mlab.plot3d( atoms.positions[[a1, a2], 0], # x-positions atoms.positions[[a1, a2], 1], # y-positions atoms.positions[[a1, a2], 2], # z-positions [2, 2], tube_radius=0.02, colormap='Reds') mlab.contour3d(x, y, z, lp) mlab.savefig('images/halogen-ep.png') mlab.show()
m.axes( s, color=(0.7, 0.7, 0.7), extent=(-1, 1, 0, 1, 0, 1), ranges=(-0.21, 0.21, 0.1, 20, 0, max_mu_q), xlabel="x", ylabel="Lr", zlabel="Force", ) m.view(-60.0, 70.0, focalpoint=[0.0, 0.45, 0.45]) # Store the information view = m.view() roll = m.roll() print "view", view print "roll", roll print n_mu_q_arr.shape[2] ms = s.mlab_source for i in range(1, n_mu_q_arr.shape[0]): ms.scalars = n_mu_q_arr[i, :, :] fname = "x%02d.jpg" % i print "saving", fname m.savefig(fname) sleep(0.1) # m.surf( n_e_arr[0], n_e_arr[1], n_mu_q_arr + n_std_q_arr ) # m.surf( n_e_arr[0], n_e_arr[1], n_mu_q_arr - n_std_q_arr ) m.show()
def make_all_frames(): for frameno in range(4): plotframe(frameno) mlab.savefig("sphere-frame%i.png" % frameno) os.system("convert sphere-frame%i.png sphere-frame%i.eps" \ % (frameno,frameno))
#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(list(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(list(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
### Setup calculators benzene = molecule('C6H6') benzene.set_cell([10, 10, 10]) benzene.center() calc1 = Vasp('molecules/benzene', xc='PBE', nbands=18, encut=350, atoms=benzene) calc1.set(lcharg=True) chlorobenzene = molecule('C6H6') chlorobenzene.set_cell([10, 10, 10]) chlorobenzene.center() chlorobenzene[11].symbol = 'Cl' calc2 = Vasp('molecules/chlorobenzene', xc='PBE', nbands=22, encut=350, atoms=chlorobenzene) calc2.set(lcharg=True) calc2.stop_if(None in (calc1.potential_energy, calc2.potential_energy)) x1, y1, z1, cd1 = calc1.get_charge_density() x2, y2, z2, cd2 = calc2.get_charge_density() cdiff = cd2 - cd1 print(cdiff.min(), cdiff.max()) ########################################## ##### set up visualization of charge difference from enthought.mayavi import mlab mlab.contour3d(x1, y1, z1, cdiff, contours=[-0.02, 0.02]) mlab.savefig('images/cdiff.png')
#mlab.orientation_axes() mlab.xlabel("phi") mlab.ylabel("theta") mlab.zlabel("centroid\ndistance") #mlab.colorbar(nb_labels=2,nb_colors=2,label_fmt='') mlab.colorbar() #mlab.text(0.1,0.1,"attraction",color=(0,0,1),width=0.1) #mlab.text(0.8,0.1,"repulsion",color=(1,0,0),width=0.1) mlab.text(0.1,0.8,"%s-%s (n=%i; x=%i); (%s)"%(res1,res2,ndata,countNone,pdblistfile),width=0.8) mlab.title("Free Energy (%s,%s)"%(res1,res2),size=0.3,height=0.7,figure=fig1) viewdist = 120 elevation = 60 # angle or 'rotate' azimuth = 180+45 # angle or 'rotate' mlab.view(distance=viewdist,elevation=elevation, azimuth=azimuth) mlab.savefig(pdblistfile+"_%s_%s_r_theta_phi.png"%(res1,res2)) mlab.show() #sys.exit() ############## for i in xrange(len(bins[0])): tmp = [] for j in xrange(len(bins[1])): sum_P = 0.0 for k in xrange(len(bins[2])): if (i,j,k) in histogram: n = histogram[(i,j,k)] else: n = 0
#scale = 800 #Z = utils.extract_matrices(adj)[-1] #p = mlab.contour_surf(X, Y, Z, contours=10, colormap='jet') #p.contour.filled_contours = True #p.actor.actor.position = (0,0,pos) #p.actor.actor.scale = (1,1,scale) pos = 1300 field = 'gz' scale = 800 Z = utils.extract_matrices(data)[-1] p = mlab.contour_surf(X, Y, Z, contours=10, colormap='jet') p.contour.filled_contours = True p.actor.actor.position = (0,0,pos) p.actor.actor.scale = (1,1,scale) setview(scene) mlab.savefig("chset%04d.png" % (0)) ns = 2 init(changes, ns) setview(scene) mlab.savefig("chset%04d.png" % (1)) for i, chset in enumerate(changes[ns:]): update(chset) setview(scene) mlab.savefig("chset%04d.png" % (i+2)) chcolor() mlab.show()
mlab.figure(bgcolor=(1, 1, 1)) # plot the atoms as spheres for atom in atoms: mlab.points3d( atom.x, atom.y, atom.z, scale_factor=vdw_radii[atom.number] / 5., resolution=20, # a tuple is required for the color color=tuple(cpk_colors[atom.number]), scale_mode='none') # draw the unit cell - there are 8 corners, and 12 connections a1, a2, a3 = atoms.get_cell() origin = [0, 0, 0] cell_matrix = [[origin, a1], [origin, a2], [origin, a3], [a1, a1 + a2], [a1, a1 + a3], [a2, a2 + a1], [a2, a2 + a3], [a3, a1 + a3], [a3, a2 + a3], [a1 + a2, a1 + a2 + a3], [a2 + a3, a1 + a2 + a3], [a1 + a3, a1 + a3 + a2]] for p1, p2 in cell_matrix: mlab.plot3d( [p1[0], p2[0]], # x-positions [p1[1], p2[1]], # y-positions [p1[2], p2[2]], # z-positions tube_radius=0.02) # Now plot the charge density mlab.contour3d(x, y, z, cd, transparent=True) # this view was empirically found by iteration mlab.view(azimuth=-90, elevation=90, distance='auto') mlab.savefig('images/co-centered-cd.png') mlab.show()
scene = mlab.contour3d((fileh.root.Phi[2:-2, 2:-2, 2:-2, frame]**2), contours=50, extent=ext, vmax=fmax, vmin=fmin) #, colormap='ylgn') # Cutplane #E = gradient(fileh.root.Phi[:,:,:,frame]) #mlab.quiver3d(E[0], E[1], E[2]) #src = mlab.pipeline.vector_field(E[2], E[1], E[0]) #mlab.pipeline.vectors(src, mask_points=20, scale_factor=3.) #mlab.pipeline.vector_cut_plane(src, mask_points=1, scale_factor=5) #src = mlab.pipeline.vector_field(E[0], E[1], E[2]) #magnitude = mlab.pipeline.extract_vector_norm(src) #flow = mlab.pipeline.streamline(magnitude, seedtype='plane', seed_visible=False, seed_scale=1.0, seed_resolution=100, linetype='line',integration_direction='both') #$mlab.axes(color=(0.0,0.0,0.),extent=ext,xlabel='X',ylabel='Y',zlabel='Z') #source = mlab.pipeline.scalar_field(fileh.root.Phi[:,:,:,frame]**2) #vol = mlab.pipeline.volume(source) #a = array(gradient(fileh.root.Phi[:,:,:,frame]))**2 #mlab.quiver3d(a[0],a[1],a[2]) # mlab.view(azimuth=angle%360, distance=128.0) mlab.view(azimuth=angle % 360, distance=10.0) angle += 1.0 mlab.colorbar(orientation='vertical', label_fmt="%.2e", nb_labels=5) mlab.outline() mlab.savefig("Phi3D_" + filename + "_" + string.zfill(frame, 4) + ".jpg") #, size=(600,600)) print "[", string.zfill(frame, 4), "/", len(fileh.root.Time[:]), "]" #mencoder "mf://*.jpg" -mf fps=10 -ovc lavc -o mymovie.av
# left hemisphere f = mlab.figure(bgcolor=(.05, 0, .1), size=(400, 400)) mlab.clf() plot_retino_image(lmesh_path_inflated, name="LeftHemisphere", mask=lmask, tf=None, tex=ltex, curv=lcurv, vmin=-np.pi, vmax=np.pi) #plot_retino_image(lmesh_path_inflated, name="LeftHemisphere", mask=lmask, # tf=None, tex=ltex, curv=lcurv, vmin=-np.pi, vmax=0) mlab.view(280, 120) mlab.savefig(op.join(func_path, '%s_%s.png') % (subject, 'left')) # right hemisphere f = mlab.figure(bgcolor=(.05, 0, .1), size=(400, 400)) mlab.clf() plot_retino_image(rmesh_path_inflated, name="RightHemisphere", mask=rmask, tf=None, tex=rtex, curv=rcurv, vmin=-np.pi, vmax=np.pi) #plot_retino_image(rmesh_path_inflated, name="RightHemisphere", mask=rmask, # tf=None, tex=rtex, curv=rcurv, vmin=0, vmax=np.pi) mlab.view(250, 120)