def update(chset): mlab.get_engine().scenes[0].children[-1].remove() new = numpy.array([estimate[chset['new']]]) pnew = vis.plot_prism_mesh(new, style='surface', xy2ne=True) neighbors = numpy.array([setden(e, chset['dens']) for e in [estimate[n] for n in chset['nn']]]) pnn = vis.plot_prism_mesh(neighbors, style='wireframe', xy2ne=True) pnn.actor.property.color = neighborcolor pnn.actor.property.line_width = 1 pos = 0 scale = 800 Z = numpy.reshape(data['value'] - chset['res'], dshape) ct = mlab.contour_surf(X, Y, Z, contours=10, colormap='jet') ct.contour.filled_contours = True ct.actor.actor.position = (0,0,pos) ct.actor.actor.scale = (1,1,scale)
def __init__(self, objects, objectsOverlay, objectInputOverlay, outputdir): self.objects = objects self.objectsOverlay = objectsOverlay self.objectsInputOverlay = objectInputOverlay self.outputdir = outputdir self.counter = 0 self.max_spread_x = 0 self.max_spread_y = 0 self.max_spread_z = 0 for iobj in self.objects.values(): spread_x = max(iobj[0])-min(iobj[0]) if self.max_spread_x < spread_x: self.max_spread_x = spread_x spread_y = max(iobj[1])-min(iobj[1]) if self.max_spread_y < spread_y: self.max_spread_y = spread_y spread_z = max(iobj[2])-min(iobj[2]) if self.max_spread_z < spread_z: self.max_spread_z = spread_z self.max_spread_x = self.max_spread_x/2+10 self.max_spread_y = self.max_spread_y/2+10 self.max_spread_z = self.max_spread_z/2 from enthought.mayavi import mlab # Returns the current scene. self.scene = mlab.figure(size = (2*self.max_spread_x, 2*self.max_spread_y), bgcolor = (1., 1., 1.)) self.engine = mlab.get_engine()
def __init__(self, objects, objectsOverlay, objectInputOverlay, outputdir): self.objects = objects self.objectsOverlay = objectsOverlay self.objectsInputOverlay = objectInputOverlay self.outputdir = outputdir self.counter = 0 self.max_spread_x = 0 self.max_spread_y = 0 self.max_spread_z = 0 for iobj in self.objects.values(): spread_x = max(iobj[0]) - min(iobj[0]) if self.max_spread_x < spread_x: self.max_spread_x = spread_x spread_y = max(iobj[1]) - min(iobj[1]) if self.max_spread_y < spread_y: self.max_spread_y = spread_y spread_z = max(iobj[2]) - min(iobj[2]) if self.max_spread_z < spread_z: self.max_spread_z = spread_z self.max_spread_x = self.max_spread_x / 2 + 10 self.max_spread_y = self.max_spread_y / 2 + 10 self.max_spread_z = self.max_spread_z / 2 from enthought.mayavi import mlab # Returns the current scene. self.scene = mlab.figure(size=(2 * self.max_spread_x, 2 * self.max_spread_y), bgcolor=(1., 1., 1.)) self.engine = mlab.get_engine()
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 test_figure(self): """ Various tests for mlab.figure(). """ # Test when specifying figure instances f1 = mlab.figure() e = mlab.get_engine() self.assert_(e.current_scene is f1) f2 = mlab.figure() self.assert_(e.current_scene is f2) mlab.figure(f1) self.assert_(e.current_scene is f1) # Test when specifying figure numbers f1 = mlab.figure(3) self.assert_(e.current_scene is f1) f2 = mlab.figure(4) self.assert_(e.current_scene is f2) mlab.figure(3) self.assert_(e.current_scene is f1) # Test when specifying figure names f1 = mlab.figure('Test 1') self.assert_(e.current_scene is f1) f2 = mlab.figure('Test 2') self.assert_(e.current_scene is f2) mlab.figure('Test 1') self.assert_(e.current_scene is f1)
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 plot_sln_mayavi(x, y, mesh, sln_values, colorbar=False): """ Plot a solution using mayavi. Example: >>> from numpy import array >>> from femhub.plot import plot_sln_mayavi >>> f = plot_sln_mayavi([0, 1, 1], [0, 0, 1], [1, 2, 3]) >>> f.savefig("a.png") """ from enthought.mayavi import mlab #mlab.options.offscreen = True mlab.clf() #mlab.options.show_scalar_bar = False z = [0] * len(x) mlab.triangular_mesh(x, y, z, mesh, scalars=sln_values) 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") mlab.view(0, 0) return mlab
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 tearDown(self): # Check that the NullEngine is still the mlab engine if not mlab.get_engine() is self.e: raise AssertionError, \ "The NullEngine has been overridden" engine_manager.current_engine = None # Unregistering the engine, to avoid side-effects between tests self.e.stop() registry.unregister_engine(self.e)
def serve_udp(engine=None, port=9007, logto=sys.stdout): """Serve the `M2UDP` protocol using the given `engine` on the specified `port` logging messages to given `logto` which is a file-like object. This function will block till the service is closed. There is no need to call `mlab.show()` after or before this. The Mayavi UI will be fully responsive. **Parameters** :engine: Mayavi engine to use. If this is `None`, `mlab.get_engine()` is used to find an appropriate engine. :port: int: port to serve on. :logto: file : File like object to log messages to. If this is `None` it disables logging. **Examples** Here is a very simple example:: from enthought.mayavi import mlab from enthought.mayavi.tools import server mlab.test_plot3d() server.serve_udp() Test it like so:: import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', 9008)) s.sendto('camera.azimuth(10)', ('', 9007)) **Warning** Data sent is exec'd so this is a security hole. """ from enthought.mayavi import mlab e = engine or mlab.get_engine() # Setup the protocol with the right attributes. proto = M2UDP() proto.engine = e proto.scene = e.current_scene.scene proto.mlab = mlab if logto is not None: log.startLogging(logto) log.msg('Serving Mayavi2 UDP server on port', port) log.msg('Using Engine', e) # Register the running wxApp. reactor.registerWxApp(wx.GetApp()) # Listen on port 9007 using above protocol. reactor.listenUDP(port, proto) # Run the server + app. This will block. reactor.run()
def tearDown(self): # Check that the NullEngine was not set as the default mlab engine. if not mlab.get_engine() is self._non_null_engine: raise AssertionError, \ "The NullEngine has overridden the default one" engine_manager.current_engine = None # Unregistering all unused engines. registry.unregister_engine(self._non_null_engine) for engine in registry.engines.keys(): registry.unregister_engine(engine)
def view(src): """ Open up a mayavi scene and display the dataset in it. """ from enthought.mayavi import mlab mayavi = mlab.get_engine() fig = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0),) mayavi.add_source(src) mlab.pipeline.surface(src, opacity=0.1) mlab.pipeline.surface(mlab.pipeline.extract_edges(src), color=(0, 0, 0), )
def close_scenes(self): """ Closes all scenes for this render manager """ from enthought.mayavi import mlab eng = mlab.get_engine() try: # Uncomment to activate again #eng.close_scene(self.scene2d) eng.close_scene(self.scene3d) except Exception: pass
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 view(src): """ Open up a mayavi scene and display the dataset in it. """ from enthought.mayavi import mlab mayavi = mlab.get_engine() fig = mlab.figure( bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), ) mayavi.add_source(src) mlab.pipeline.surface(src, opacity=0.1) mlab.pipeline.surface( mlab.pipeline.extract_edges(src), color=(0, 0, 0), )
def init(changes, ns): for chset in changes[0:ns]: seed = numpy.array([estimate[chset['new']]]) pnew = vis.plot_prism_mesh(seed, style='surface', xy2ne=True) mlab.get_engine().scenes[0].children[-1].children[0].children[0].children[0].scalar_lut_manager.data_range = [0,1000] neighbors = numpy.array([setden(e, chset['dens']) for e in [estimate[n] for n in chset['nn']]]) pnn = vis.plot_prism_mesh(neighbors, style='wireframe', xy2ne=True) pnn.actor.property.color = neighborcolor pnn.actor.property.line_width = 1 pos = 0 scale = 800 Z = numpy.reshape(data['value'] - changes[ns-1]['res'], dshape) ct = mlab.contour_surf(X, Y, Z, contours=10, colormap='jet') ct.contour.filled_contours = True ct.actor.actor.position = (0,0,pos) ct.actor.actor.scale = (1,1,scale)
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 __init__(self, network, **traits): super(RenderManager, self).__init__(**traits) from enthought.mayavi import mlab logger.info('Initalize RenderManager...') # set the datasource manager self.datasourcemanager = network.datasourcemanager # getting mlab engine self.engine = mlab.get_engine() # store reference to managed network self.network = network # create the scene instances self._create_scenes() # use nice trackball camera interactor # self.scene3d.scene.interactor.interactor_style = tvtk.InteractorStyleTrackballCamera() # otherwise just use tvtk.InteractorStyleSwitch() # create my node picker inclusive the NodePickHandler self.nodepicker = NodePicker(renwin=self.scene3d.scene) # add custom picker for the scene3d self.scene3d.scene.picker = self.nodepicker # adding observers to capture key events self.scene3d.scene.interactor.add_observer('KeyPressEvent', self.nodepicker.key_pressed) # add the callback function after a pick event self.scene3d.scene.picker.pointpicker.add_observer('EndPickEvent', self._nodepicked_callback) # initialize node_labels self.node_labels = {} logger.info('RenderManager created.')
def doit(): global s global iter if iter == 0: print "plotting the triangular mesh..." s = mlab.triangular_mesh(x, y, z, triangles, scalars=t) print " done." print "adjusting view..." mlab.view(0, 0) print " done." else: print "changing the source..." # This doesn't work due to a bug in mayavi/VTK: # http://github.com/certik/mhd-hermes/issues#issue/1 #s.mlab_source.reset(x=x, y=y, z=z, triangles=triangles, scalars=t) # so until this is fixed, let's call triangular_mesh and delete the # old mesh (this is slow but works): scene = mlab.gcf().scene scene.disable_render = True s = mlab.triangular_mesh(x, y, z, triangles, scalars=t) mlab.get_engine().scenes[0].children[:1] = [] scene.disable_render = False print " done." iter += 1
def make_plots(plots,argd=None,figs=None,save=False,overwrite=True,showfigs=True): """ Generate plots and maybe save them. :param plots: A comma-seperated string of plots to show :param argd: The dictionary to use to find the arguments of the plot function. If None, global variables will be used. :param figs: A list of figure numbers to use for each of the figures in `plots`. If None, the current figure will be used as the starting point. :param str save: A directory in which to save the plots. If False, they will not be saved, if True, the current directory will be used. :param bool overwrite: If True and plots are being saved, any existing plot will be overwritten. Otherwise, the figure will not be saved. :parm bool showfigs: If True, the figures will be shown (in whatever GUI is the correct one for the type). """ import os,shutil,inspect,subprocess if save is True: save='.' if isinstance(save,basestring) and not save.endswith(os.sep): save+=os.sep if plots is None: plots = _plotreg.keys() elif isinstance(plots,basestring): if '*' in plots: import re plots = plots.replace('*','.*') regex = re.compile(plots) plots = [p for p in plot_names()[0] if regex.match(p)] else: plots = plots.split(',') if figs is None: figs = arange(len(plots))+1 if len(figs) != len(plots): raise ValueError("plots don't match figs") if argd is None: argd = globals() plotd={} for p,fnum in zip(plots,figs): if p not in _plotreg: raise KeyError('plotname %s not found'%p) plotd[p] = (_plotreg[p][0],fnum,_plotreg[p][1],_plotreg[p][2],_plotreg[p][3]) isinter = plt.isinteractive() plt.ioff() anympl = False try: for fname,(figf,fignum,figsize,ftype,tweakbbox) in plotd.iteritems(): print 'figure',fname if 'mpl' in ftype: anympl = True if isinter: plt.ion() plt.close(fignum) plt.figure(fignum,figsize=figsize) plt.ioff() elif 'mayavi' in ftype: from enthought.mayavi import mlab as M if len(M.get_engine().scenes) > 0: M.gcf().parent.close_scene(M.gcf()) f=M.figure(fignum,size=figsize) #this is buggy #f.scene.set_size(figsize) #M.clf() else: raise ValueError('unrecognized figtype') argsp = inspect.getargspec(figf) if argsp[2] is not None: figf(**argd) else: args=[] for arg in argsp[0]: args.append(argd[arg]) figf(*args) if save: epsconv = False if ftype=='mpltoeps': epsconv = 'png' savefunc = plt.savefig saveexts = ['png'] elif ftype.startswith('mpl'): savefunc = plt.savefig saveexts = ftype[3:].strip() if saveexts=='': saveexts = ['eps','pdf'] else: saveexts = saveexts.split(',') elif ftype.startswith('mayavi'): savefunc = M.savefig saveexts = ftype[6:].strip() if saveexts=='': saveexts = ['png'] else: saveexts = saveexts.split(',') if 'eps' in saveexts: saveexts.remove('eps') if 'png' not in saveexts: saveexts.append('png') epsconv = 'png' else: raise ValueError('unrecognized figtype') for saveext in saveexts: fn = '%s%s.%s'%(save,fname,saveext) epsfns = None if not overwrite and os.path.exists(fn): print fn,'exists, skipping (use -o at command line to overwrite)' else: print 'saving',fn savefunc(fn) if saveext == epsconv: epsfns = (fn,'%s%s.%s'%(save,fname,'eps')) if epsfns is not None: from os import system fn,epsfn = epsfns print 'converting',fn,'to',epsfn retcode = subprocess.call('convert %s %s'%(fn,epsfn),shell=True) if retcode is not 0: raise ValueError('convert failed to convert %s to %s'%(fn,epsfn)) if tweakbbox is not None: print 'updating eps bounding box on',epsfn,'to',tweakbbox with open(epsfn+'.tmpwrite','w') as fw: with open(epsfn,'r') as fr: for l in fr: if 'BoundingBox' in l and 'Page' not in l: newline = l.split(':')[0]+(': %s %s %s %s\n'%tweakbbox) fw.write(newline) else: fw.write(l) shutil.move(epsfn+'.tmpwrite',epsfn) finally: if isinter: plt.ion() if showfigs and anympl: plt.draw()
def serve_tcp(engine=None, port=8007, logto=sys.stdout, max_connect=1): """Serve the `M2TCP` protocol using the given `engine` on the specified `port` logging messages to given `logto` which is a file-like object. This function will block till the service is closed. There is no need to call `mlab.show()` after or before this. The Mayavi UI will be fully responsive. **Parameters** :engine: Mayavi engine to use. If this is `None`, `mlab.get_engine()` is used to find an appropriate engine. :port: int: port to serve on. :logto: file: File like object to log messages to. If this is `None` it disables logging. :max_connect: int: Maximum number of simultaneous connections to support. **Examples** Here is a very simple example:: from enthought.mayavi import mlab from enthought.mayavi.tools import server mlab.test_plot3d() server.serve_tcp() The TCP server will listen on port 8007 by default in the above. Any data sent to the server is simply exec'd, meaning you can do pretty much anything you want. The `engine`, `scene`, `camera` and `mlab` are all available and can be used. For example after running the above you can do this:: $ telnet localhost 8007 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. scene.camera.azimuth(45) mlab.clf() mlab.test_contour3d() scene.camera.zoom(1.5) **Warning** Data sent is exec'd so this is a security hole. """ from enthought.mayavi import mlab e = engine or mlab.get_engine() # Setup the factory with the right attributes. factory = Factory() factory.protocol = M2TCP factory.maxConnect = max_connect factory.numConnect = 0 factory.engine = e factory.scene = e.current_scene.scene factory.mlab = mlab if logto is not None: log.startLogging(logto) log.msg('Serving Mayavi2 TCP server on port', port) log.msg('Using Engine', e) # Register the running wxApp. reactor.registerWxApp(wx.GetApp()) # Listen on port 9007 using above protocol. reactor.listenTCP(port, factory) # Run the server + app. This will block. reactor.run()
height = 0 for area in sorted(regions.keys()): pulses = regions[area] if len(pulses) == 0 or area < 280 or area > 300: continue values = [crh.get_value(p) for p in pulses] height_diff = max(values) - min(values) value_maxes.append(height_diff) centre = height + height_diff / 2.0 pulse_values = np.zeros_like(img) for p in pulses: crh.set_array(pulse_values, p, crh.get_value(p)) y, x = np.where(pulse_values) s = pulse_values[y, x] mlab.barchart(x, y, [height + centre] * len(s), s, opacity=1.0, scale_factor=1.5) height += height_diff + 0.5 scene = mlab.get_engine().scenes[0] scene.scene.parallel_projection = True mlab.show()
def close(): """Close the scene.""" f = mlab.gcf() e = mlab.get_engine() v = e.get_viewer(f) v.close()
def close(): """Close the scene.""" f = mlab.gcf() e = mlab.get_engine() e.window.close()
with open("res.pickle") as f: res = pickle.load(f) with open("seeds.pickle") as f: seeds = pickle.load(f) with open("model.pickle") as f: model = pickle.load(f) extent = view.extent ranges = view.ranges scene = mlab.figure(size=view.size) scene.scene.background = (1, 1, 1) p = vis.plot_prism_mesh(res, style='surface', xy2ne=True) p.actor.property.line_width = 2 mlab.get_engine().scenes[0].children[-1].children[0].children[0].children[0].scalar_lut_manager.data_range = [0,1200] p = vis.plot_prism_mesh(seeds, style='surface', xy2ne=True) p.actor.property.line_width = 2 mlab.get_engine().scenes[0].children[-1].children[0].children[0].children[0].scalar_lut_manager.data_range = [0,1200] p = vis.plot_prism_mesh(model, style='surface', xy2ne=True) p.actor.property.line_width = 2 p = vis.plot_prism_mesh(mesh.vfilter(model,1100,1201), style='wireframe', xy2ne=True) p.actor.property.color = (0,0,0) p.actor.property.line_width = 3 mlab.outline(color=(0,0,0), extent=extent) a = mlab.axes(p, nb_labels=5, extent=extent, ranges=ranges, color=(0,0,0))
from gpaw import * basename = 'CO' # load nc binary file and get calculator atoms, calc = restart(basename + '.gpw') # write atomic positions to xyz-file write(basename + '.xyz', atoms) # loop over all wfs and write their cube files nbands = calc.get_number_of_bands() wf = calc.get_pseudo_wave_function(band=0) from enthought.mayavi import mlab #mlab.figure(1, bgcolor=(0, 0, 0), size=(350, 350)) mlab.clf() data = wf source = mlab.pipeline.scalar_field(data) mlab.view(132, 54, 45, [21, 20, 21.5]) engine = mlab.get_engine() from enthought.mayavi.modules.scalar_cut_plane import ScalarCutPlane scalar_cut_plane = ScalarCutPlane() engine.add_module(scalar_cut_plane, obj=None) scene = engine.scenes[0] scene.scene.render() mlab.show()
def _engine_default(self): return m2_mlab.get_engine()
def chcolor(): mlab.get_engine().scenes[0].children[-3].children[0].children[0].children[0].scalar_lut_manager.data_range = [0,1000]
points[:, 2], faces, color=(1, 1, 0), opacity=0.3) # show one cortical surface mlab.triangular_mesh(lh_points[:, 0], lh_points[:, 1], lh_points[:, 2], lh_faces, color=(0.7, ) * 3) # show dipole as small cones dipoles = mlab.quiver3d(pos[:, 0], pos[:, 1], pos[:, 2], ori[:, 0], ori[:, 1], ori[:, 2], opacity=1., scale_factor=4e-4, scalars=time, mode='cone', colormap='RdBu') # revert colormap dipoles.module_manager.scalar_lut_manager.reverse_lut = True mlab.colorbar(dipoles, title='Dipole fit time (ms)') # proper 3D orientation mlab.get_engine().scenes[0].scene.x_plus_view()
def plot_map(map, affine, cut_coords=None, anat=None, anat_affine=None, figure=None, axes=None, title=None, threshold=None, annotate=True, draw_cross=True, do3d=False, threshold_3d=None, view_3d=(38.5, 70.5, 300, (-2.7, -12, 9.1)), black_bg=False, **kwargs): """ Plot three cuts of a given activation map (Frontal, Axial, and Lateral) Parameters ---------- map : 3D ndarray The activation map, as a 3D image. affine : 4x4 ndarray The affine matrix going from image voxel space to MNI space. cut_coords: 3-tuple of floats or None The MNI coordinates of the point where the cut is performed, in MNI coordinates and order. If None is given, the cut point is calculated automaticaly. anat : 3D ndarray or False, optional The anatomical image to be used as a background. If None, the MNI152 T1 1mm template is used. If False, no anat is displayed. anat_affine : 4x4 ndarray, optional The affine matrix going from the anatomical image voxel space to MNI space. This parameter is not used when the default anatomical is used, but it is compulsory when using an explicite anatomical image. figure : integer or matplotlib figure, optional Matplotlib figure used or its number. If None is given, a new figure is created. axes : matplotlib axes or 4 tuple of float: (xmin, xmax, ymin, ymin), optional The axes, or the coordinates, in matplotlib figure space, of the axes used to display the plot. If None, the complete figure is used. title : string, optional The title dispayed on the figure. threshold : a number, None, or 'auto' If None is given, the maps are not thresholded. If a number is given, it is used to threshold the maps: values below the threshold are plotted as transparent. If auto is given, the threshold is determined magically by analysis of the map. annotate: boolean, optional If annotate is True, positions and left/right annotation are added to the plot. draw_cross: boolean, optional If draw_cross is True, a cross is drawn on the plot to indicate the cut plosition. do3d: {True, False or 'interactive'}, optional If True, Mayavi is used to plot a 3D view of the map in addition to the slicing. If 'interactive', the 3D visualization is displayed in an additional interactive window. threshold_3d: The threshold to use for the 3D view (if any). Defaults to the same threshold as that used for the 2D view. view_3d: tuple, The view used to take the screenshot: azimuth, elevation, distance and focalpoint, see the docstring of mlab.view. black_bg: boolean, optional If True, the background of the image is set to be black. If you whish to save figures with a black background, you will need to pass "facecolor='k', edgecolor='k'" to pylab's savefig. kwargs: extra keyword arguments, optional Extra keyword arguments passed to pylab.imshow Notes ----- Arrays should be passed in numpy convention: (x, y, z) ordered. Use masked arrays to create transparency: import numpy as np map = np.ma.masked_less(map, 0.5) plot_map(map, affine) """ map, affine = _xyz_order(map, affine) nan_mask = np.isnan(np.asarray(map)) if np.any(nan_mask): map = map.copy() map[nan_mask] = 0 # Deal with automatic settings of plot parameters if threshold == 'auto': # Threshold epsilon above a percentile value, to be sure that some # voxels are indeed threshold threshold = _fast_abs_percentile(map) + 1e-5 if cut_coords is None: x_map, y_map, z_map = find_cut_coords(map, activation_threshold=threshold) cut_coords = coord_transform(x_map, y_map, z_map, affine) if do3d: try: from enthought.mayavi import version if not int(version.version[0]) > 2: raise ImportError except ImportError: warnings.warn('Mayavi > 3.x not installed, plotting only 2D') do3d = False # Make sure that we have a figure if not isinstance(figure, Figure): if do3d: size = (10, 2.6) else: size = (6.6, 2.6) facecolor = 'k' if black_bg else 'w' figure = pl.figure(figure, figsize=size, facecolor=facecolor) else: if isinstance(axes, Axes): assert axes.figure is figure, ("The axes passed are not " "in the figure") # Use Mayavi for the 3D plotting if do3d: from .maps_3d import plot_map_3d, m2screenshot from enthought.tvtk.api import tvtk version = tvtk.Version() offscreen = True if (version.vtk_major_version, version.vtk_minor_version) < (5, 2): offscreen = False if do3d == 'interactive': offscreen = False cmap = kwargs.get('cmap', pl.cm.cmap_d[pl.rcParams['image.cmap']]) # Computing vmin and vmax is costly in time, and is needed # later, so we compute them now, and store them for future # use vmin = kwargs.get('vmin', map.min()) kwargs['vmin'] = vmin vmax = kwargs.get('vmax', map.max()) kwargs['vmax'] = vmax from enthought.mayavi import mlab if threshold_3d is None: threshold_3d = threshold plot_map_3d(np.asarray(map), affine, cut_coords=cut_coords, anat=anat, anat_affine=anat_affine, offscreen=offscreen, cmap=cmap, threshold=threshold_3d, view=view_3d, vmin=vmin, vmax=vmax) ax = figure.add_axes((0.001, 0, 0.29, 1)) ax.axis('off') m2screenshot(mpl_axes=ax) axes = (0.3, 0, .7, 1.) if offscreen: # Clean up, so that the offscreen engine doesn't become the # default mlab.clf() engine = mlab.get_engine() from enthought.mayavi.core.registry import registry for key, value in registry.engines.iteritems(): if value is engine: registry.engines.pop(key) break if threshold: map = np.ma.masked_inside(map, -threshold, threshold, copy=False) ortho_slicer = plot_anat(anat, anat_affine, cut_coords=cut_coords, figure=figure, axes=axes, title=title, annotate=annotate, draw_cross=draw_cross, black_bg=black_bg) ortho_slicer.plot_map(map, affine, **kwargs) return ortho_slicer
"""Example of how to generate 3D ellipsoids in mayavi, using glyphs. Adapted from Gael Varoquaux""" from enthought.tvtk.api import tvtk from enthought.mayavi import mlab #from enthought.mayavi.sources.vtk_data_source import VTKDataSource import numpy as np point = np.array([0, 0, 0]) tensor = np.array([20, 0, 0, 0, 20, 0, 0, 0, 20]) engine = mlab.get_engine() engine.start() scene = engine.new_scene() scene.scene.disable_render = True # for speed glyphs = [] for i in range(10): data = tvtk.PolyData(points=[point]) data.point_data.tensors = [tensor] data.point_data.tensors.name = 'some_name' data.point_data.scalars = [i] #data.point_data.scalars.name = 'some_other_name' #mlab.clf() #src = VTKDataSource(data=data) #e = mlab.get_engine() #e.add_source(src) glyph = mlab.pipeline.tensor_glyph(data)
regions = lulu.decompose(img) value_maxes = [] height = 0 for area in sorted(regions.keys()): pulses = regions[area] if len(pulses) == 0 or area < 280 or area > 300: continue values = [crh.get_value(p) for p in pulses] height_diff = max(values) - min(values) value_maxes.append(height_diff) centre = height + height_diff / 2.0 pulse_values = np.zeros_like(img) for p in pulses: crh.set_array(pulse_values, p, crh.get_value(p)) y, x = np.where(pulse_values) s = pulse_values[y, x] mlab.barchart(x, y, [height + centre] * len(s), s, opacity=1.0, scale_factor=1.5) height += height_diff + 0.5 scene = mlab.get_engine().scenes[0] scene.scene.parallel_projection = True mlab.show()
try: from enthought.mayavi import mlab except: from mayavi import mlab lh_points = src[0]['rr'] lh_faces = src[0]['use_tris'] mlab.figure(size=(600, 600), bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) # show brain surface after proper coordinate system transformation points = brain_surface['rr'] faces = brain_surface['tris'] coord_trans = fwd['mri_head_t']['trans'] points = np.dot(coord_trans[:3,:3], points.T).T + coord_trans[:3,-1] mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2], faces, color=(1, 1, 0), opacity=0.3) # show one cortical surface mlab.triangular_mesh(lh_points[:, 0], lh_points[:, 1], lh_points[:, 2], lh_faces, color=(0.7, ) * 3) # show dipole as small cones dipoles = mlab.quiver3d(pos[:,0], pos[:,1], pos[:,2], ori[:,0], ori[:,1], ori[:,2], opacity=1., scale_factor=4e-4, scalars=time, mode='cone') mlab.colorbar(dipoles, title='Dipole fit time (ms)') # proper 3D orientation mlab.get_engine().scenes[0].scene.x_plus_view()
from fatiando import mesh, vis, utils with open("mesh.pickle") as f: res = pickle.load(f) x1, x2 = 0, 3000 y1, y2 = 0, 3000 z1, z2 = 0, 3000 extent = [x1, x2, y1, y2, -z2, -z1] # Plot the adjusted model plus the skeleton of the synthetic model fig = mlab.figure(size=(600, 730)) fig.scene.background = (1, 1, 1) p = vis.plot_prism_mesh(res, style='surface') mlab.get_engine().scenes[0].children[-1].children[0].children[0].children[ 0].scalar_lut_manager.lut_mode = "Greys" scene = fig scene.scene.camera.position = [ 5617.6246210610589, 9378.6744914189112, 1832.0425527256102 ] scene.scene.camera.focal_point = [ 1435.8921050117997, 1598.1461572098237, -1715.9026272606379 ] scene.scene.camera.view_angle = 30.0 scene.scene.camera.view_up = [ -0.18883236854009863, -0.3216128720649955, 0.92785101019163696 ] scene.scene.camera.clipping_range = [4531.9434654515926, 15755.396726380868] scene.scene.camera.compute_view_plane_normal() scene.scene.render()
from fatiando import mesh, vis, utils with open("mesh.pickle") as f: res = pickle.load(f) x1, x2 = 0, 3000 y1, y2 = 0, 3000 z1, z2 = 0, 3000 extent = [x1, x2, y1, y2, -z2, -z1] # Plot the adjusted model plus the skeleton of the synthetic model fig = mlab.figure(size=(600,730)) fig.scene.background = (1, 1, 1) p = vis.plot_prism_mesh(mesh.vfilter(res,900,2001), style='surface', opacity=1) mlab.get_engine().scenes[0].children[-1].children[0].children[0].children[0].scalar_lut_manager.data_range = [0,2000] #a = mlab.axes(p, nb_labels=0, extent=extent, color=(0,0,0)) #a.label_text_property.color = (0,0,0) #a.title_text_property.color = (0,0,0) #a.axes.label_format = "" #a.axes.x_label, a.axes.y_label, a.axes.z_label = "", "", "" #a.property.line_width = 1 mlab.outline(p, extent=extent, color=(0,0,0)) scene = fig scene.scene.camera.position = [5617.6246210610589, 9378.6744914189112, 1832.0425527256102] scene.scene.camera.focal_point = [1435.8921050117997, 1598.1461572098237, -1715.9026272606379] scene.scene.camera.view_angle = 30.0 scene.scene.camera.view_up = [-0.18883236854009863, -0.3216128720649955, 0.92785101019163696]
import cPickle as pickle from enthought.mayavi import mlab from fatiando import mesh, vis, utils with open("mesh.pickle") as f: res = pickle.load(f) x1, x2 = 0, 3000 y1, y2 = 0, 3000 z1, z2 = 0, 3000 extent = [x1, x2, y1, y2, -z2, -z1] # Plot the adjusted model plus the skeleton of the synthetic model fig = mlab.figure(size=(600,730)) fig.scene.background = (1, 1, 1) p = vis.plot_prism_mesh(res, style='surface') mlab.get_engine().scenes[0].children[-1].children[0].children[0].children[0].scalar_lut_manager.lut_mode = "Greys" scene = fig scene.scene.camera.position = [5617.6246210610589, 9378.6744914189112, 1832.0425527256102] scene.scene.camera.focal_point = [1435.8921050117997, 1598.1461572098237, -1715.9026272606379] scene.scene.camera.view_angle = 30.0 scene.scene.camera.view_up = [-0.18883236854009863, -0.3216128720649955, 0.92785101019163696] scene.scene.camera.clipping_range = [4531.9434654515926, 15755.396726380868] scene.scene.camera.compute_view_plane_normal() scene.scene.render() mlab.show()