def mcrtmv(frames, mvname, dt, Lx, Ly, Nx, Ny): x = np.linspace(0, Lx, Nx) y = np.linspace(0, Ly, Ny) X, Y = np.meshgrid(x, y) size = 500, 500 fig = ml.figure(size=size, bgcolor=(1., 1., 1.)) #fig.scene.anti_aliasing_frames=07 #extent = [0,Nx-1,0,Ny-1,-30,30] ml.clf(figure=fig) u = np.loadtxt('test.d%07d' % 1) fname = '_tmp%07d.png' % 1 s = ml.surf(x, y, u, figure=fig, vmin=-0, vmax=1) ml.axes(extent=[0, Lx, 0, Ly, -2, 2]) ml.colorbar() ml.xlabel('x position') ml.ylabel('y position') ml.zlabel('wave amplitude') """ pl.ion() arr = ml.screenshot() img = pl.imshow(arr) pl.axis('off') """ for i in range(2, frames): #arr = ml.screenshot() #img.set_array(arr) u = np.loadtxt('test.d%07d' % i) s.mlab_source.scalars = u fname = '_tmp%07d.png' % i
def plot3D(name, X, Y, Z, zlabel): """ Plots a 3d surface plot of Z using the mayavi mlab.mesh function. Parameters ---------- name: string The name of the figure. X: 2d ndarray The x-axis data. Y: 2d ndarray The y-axis data. Z: 2d nd array The z-axis data. zlabel: The title that appears on the z-axis. """ mlab.figure(name) mlab.clf() plotData = mlab.mesh(X/(np.max(X) - np.min(X)), Y/(np.max(Y) - np.min(Y)), Z/(np.max(Z) - np.min(Z))) mlab.outline(plotData) mlab.axes(plotData, ranges=[np.min(X), np.max(X), np.min(Y), np.max(Y), np.min(Z), np.max(Z)]) mlab.xlabel('Space ($x$)') mlab.ylabel('Time ($t$)') mlab.zlabel(zlabel)
def plot_3D( self ): x = self.compute3D_plot[0] y = self.compute3D_plot[1] z = self.compute3D_plot[2] # print x_axis, y_axis, z_axis if self.autowarp_bool: x = x / x[-1] y = y / y[-1] z = z / z[-1] * self.z_scale mlab.surf( x, y , z, representation = 'wireframe' ) engine = Engine() engine.start() if len( engine.scenes ) == 75.5: engine.new_scene() surface = engine.scenes[0].children[0].children[0].children[0].children[0].children[0] surface.actor.mapper.scalar_range = np.array( [ 6.97602671, 8.8533387 ] ) surface.actor.mapper.scalar_visibility = False scene = engine.scenes[0] scene.scene.background = ( 1.0, 1.0, 1.0 ) surface.actor.property.specular_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.diffuse_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.ambient_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.color = ( 0.0, 0.0, 0.0 ) surface.actor.property.line_width = 1. scene.scene.isometric_view() mlab.xlabel( self.x_name3D ) mlab.ylabel( self.y_name3D ) mlab.outline() mlab.show()
def labels(xlabel="x", ylabel="y", zlabel="z", obj=None): if xlabel: mlab.xlabel(xlabel, obj) if ylabel: mlab.ylabel(ylabel, obj) if zlabel: mlab.zlabel(zlabel, obj)
def plot_mayavi(self): """Use mayavi to plot a phenotype phase plane in 3D. The resulting figure will be quick to interact with in real time, but might be difficult to save as a vector figure. returns: mlab figure object""" from mayavi import mlab figure = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) figure.name = "Phenotype Phase Plane" max = 10.0 xmax = self.reaction1_fluxes.max() ymax = self.reaction2_fluxes.max() zmax = self.growth_rates.max() xgrid, ygrid = meshgrid(self.reaction1_fluxes, self.reaction2_fluxes) xgrid = xgrid.transpose() ygrid = ygrid.transpose() xscale = max / xmax yscale = max / ymax zscale = max / zmax mlab.surf(xgrid * xscale, ygrid * yscale, self.growth_rates * zscale, representation="wireframe", color=(0, 0, 0), figure=figure) mlab.mesh(xgrid * xscale, ygrid * yscale, self.growth_rates * zscale, scalars=self.shadow_prices1 + self.shadow_prices2, resolution=1, representation="surface", opacity=0.75, figure=figure) # draw axes mlab.outline(extent=(0, max, 0, max, 0, max)) mlab.axes(opacity=0, ranges=[0, xmax, 0, ymax, 0, zmax]) mlab.xlabel(self.reaction1_name) mlab.ylabel(self.reaction2_name) mlab.zlabel("Growth rates") return figure
def main(argv): if ( len(argv) != 1 ): print ("Usage: python visualizeField.py <datafile.json>") return # Read input file try: infile = open( argv[0], 'r' ) except: print ("Error when opening file %s"%(argv[0])) return data = json.load( infile ) infile.close() y = np.array( data["points"]["y"] ) z = np.array( data["points"]["z"] ) x = np.zeros( len(y) ) Ex = np.array( data["field"]["x"] ) pts = mlab.points3d( y, z, x, Ex, scale_mode="scalar", scale_factor=0.0, mode="point") mesh = mlab.pipeline.delaunay2d( pts ) surf = mlab.pipeline.surface( mesh ) fname = "Figures/fieldyzPlane.png" mlab.view(0.0,0.0,1.0, (0.0,0.0,0.0)) mlab.scalarbar() mlab.xlabel( "y" ) mlab.ylabel( "z" ) mlab.show()
def draw_min_cost_surface(graph): graph = sim.graph X = [] Y = [] Z = [] for day,sizes in graph.items(): for size,days_const in sizes.items(): days_const, node = sorted(days_const.items())[0] X.append(day) Y.append(size/10.) Z.append(node.min_cost) pts = mlab.points3d(X, Y, Z, Z) mesh = mlab.pipeline.delaunay2d(pts) # Remove the point representation from the plot pts.remove() # Draw a surface based on the triangulation surf = mlab.pipeline.surface(mesh) mlab.xlabel("time") mlab.ylabel("size") mlab.zlabel("cost") mlab.show()
def draw_min_feed_surface(graph): graph = sim.graph X = [] Y = [] Z = [] for day,sizes in graph.items(): for size,days_const in sizes.items(): days_const, node = sorted(days_const.items())[-1] X.append(day) Y.append(size/10.) Z.append(node.min_rate*10) # for i in range(len(X)): # print ("%d,%f,%f" % (X[i], Y[i], Z[i])) pts = mlab.points3d(X, Y, Z, Z) mesh = mlab.pipeline.delaunay2d(pts) # Remove the point representation from the plot pts.remove() # Draw a surface based on the triangulation surf = mlab.pipeline.surface(mesh) mlab.xlabel("time") mlab.ylabel("size") mlab.zlabel("rate") mlab.show()
def mcrtmv(frames, dt, mesh, d_nodes, map, savemovie=False, mvname='test', vmin=-1, vmax=1): """ Creates move from numpyfied results in 2d, using mencoder. Prolly does not work on mac! """ size = 500, 500 fig = ml.figure(size=size, bgcolor=(1., 1., 1.)) #fig.scene.anti_aliasing_frames=07 #extent = [0,Nx-1,0,Ny-1,-30,30] xaxis = np.linspace(0, 1, d_nodes[0] + 1) yaxis = np.linspace(0, 1, d_nodes[1] + 1) ml.clf(figure=fig) u = np.load('solution_%06d.npy' % 1) u = numpyfy(u, mesh, d_nodes, map) fname = '_tmp%07d.png' % 1 s = ml.imshow(xaxis, yaxis, u, figure=fig, vmin=vmin, vmax=vmax) #scale = 1./np.max(np.abs(u)) u = u ml.axes(extent=[0, 1, 0, 1, 0, 2]) ml.colorbar() ml.xlabel('x position') ml.ylabel('y position') ml.zlabel('wave amplitude') if savemovie == True: pl.ion() arr = ml.screenshot() img = pl.imshow(arr) pl.axis('off') for i in range(2, frames): u = np.load('solution_%06d.npy' % i) u = numpyfy(u, mesh, d_nodes, map) s.mlab_source.scalars = u fname = '_tmp%07d.png' % i if savemovie == True: arr = ml.screenshot() img.set_array(arr) pl.savefig(filename=fname) #,figure=fig) print 'Saving frame', fname pl.draw() fig.scene.disable_render = False if savemovie: os.system( "mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname)
def setLabels(self, xlabel="", ylabel="", zlabel=""): """ sets the label input: - xlabel - ylabel - zlabel """ mlab.xlabel(xlabel) mlab.ylabel(ylabel) mlab.zlabel(zlabel)
def mcrtmv(frames, dt,mesh, d_nodes, map, savemovie=False, mvname='test', vmin=-1, vmax=1): """ Creates move from numpyfied results in 2d, using mencoder. Prolly does not work on mac! """ size = 500,500 fig = ml.figure(size= size, bgcolor=(1.,1.,1.)); #fig.scene.anti_aliasing_frames=07 #extent = [0,Nx-1,0,Ny-1,-30,30] xaxis = np.linspace(0,1,d_nodes[0]+1) yaxis = np.linspace(0,1,d_nodes[1]+1) ml.clf(figure=fig) u = np.load('solution_%06d.npy'%1); u = numpyfy(u, mesh, d_nodes, map) fname = '_tmp%07d.png' % 1 s = ml.imshow(xaxis, yaxis, u,figure=fig,vmin=vmin, vmax=vmax) #scale = 1./np.max(np.abs(u)) u = u ml.axes(extent=[0,1,0,1,0,2]) ml.colorbar() ml.xlabel('x position') ml.ylabel('y position') ml.zlabel('wave amplitude') if savemovie == True: pl.ion() arr = ml.screenshot() img = pl.imshow(arr) pl.axis('off') for i in range(2,frames): u = np.load('solution_%06d.npy'%i); u = numpyfy(u, mesh, d_nodes, map) s.mlab_source.scalars = u fname = '_tmp%07d.png' % i if savemovie == True: arr = ml.screenshot() img.set_array(arr) pl.savefig(filename=fname)#,figure=fig) print 'Saving frame', fname pl.draw() fig.scene.disable_render = False if savemovie: os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname);
def plot_cartesian(traj, xaxis=None, yaxis=None, zaxis=None, color='b',label='_nolegend_', linewidth=2, scatter_size=10, plot_velocity=False): import matplotlib_util.util as mpu import arm_trajectories as at #if traj.__class__ == at.JointTrajectory: if isinstance(traj,at.JointTrajectory): traj = joint_to_cartesian(traj) pts = np.matrix(traj.p_list).T label_list = ['X coord (m)', 'Y coord (m)', 'Z coord (m)'] x = pts[xaxis,:].A1.tolist() y = pts[yaxis,:].A1.tolist() if plot_velocity: vels = np.matrix(traj.v_list).T xvel = vels[xaxis,:].A1.tolist() yvel = vels[yaxis,:].A1.tolist() if zaxis == None: mpu.plot_yx(y, x, color, linewidth, '-', scatter_size, label, axis = 'equal', xlabel = label_list[xaxis], ylabel = label_list[yaxis],) if plot_velocity: mpu.plot_quiver_yxv(y, x, np.matrix([xvel,yvel]), width = 0.001, scale = 1.) mpu.legend() else: from numpy import array from enthought.mayavi.api import Engine engine = Engine() engine.start() if len(engine.scenes) == 0: engine.new_scene() z = pts[zaxis,:].A1.tolist() time_list = [t-traj.time_list[0] for t in traj.time_list] mlab.plot3d(x,y,z,time_list,tube_radius=None,line_width=4) mlab.axes() mlab.xlabel(label_list[xaxis]) mlab.ylabel(label_list[yaxis]) mlab.zlabel(label_list[zaxis]) mlab.colorbar(title='Time') # ------------------------------------------- axes = engine.scenes[0].children[0].children[0].children[1] axes.axes.position = array([ 0., 0.]) axes.axes.label_format = '%-#6.2g' axes.title_text_property.font_size=4
def plot_cartesian(traj, xaxis=None, yaxis=None, zaxis=None, color='b',label='_nolegend_', linewidth=2, scatter_size=10, plot_velocity=False): import arm_trajectories as at #if traj.__class__ == at.JointTrajectory: if isinstance(traj,at.JointTrajectory): traj = joint_to_cartesian(traj) pts = np.matrix(traj.p_list).T label_list = ['X coord (m)', 'Y coord (m)', 'Z coord (m)'] x = pts[xaxis,:].A1.tolist() y = pts[yaxis,:].A1.tolist() if plot_velocity: vels = np.matrix(traj.v_list).T xvel = vels[xaxis,:].A1.tolist() yvel = vels[yaxis,:].A1.tolist() if zaxis == None: mpu.plot_yx(y, x, color, linewidth, '-', scatter_size, label, axis = 'equal', xlabel = label_list[xaxis], ylabel = label_list[yaxis],) if plot_velocity: mpu.plot_quiver_yxv(y, x, np.matrix([xvel,yvel]), width = 0.001, scale = 1.) mpu.legend() else: from numpy import array from enthought.mayavi.api import Engine engine = Engine() engine.start() if len(engine.scenes) == 0: engine.new_scene() z = pts[zaxis,:].A1.tolist() time_list = [t-traj.time_list[0] for t in traj.time_list] mlab.plot3d(x,y,z,time_list,tube_radius=None,line_width=4) mlab.axes() mlab.xlabel(label_list[xaxis]) mlab.ylabel(label_list[yaxis]) mlab.zlabel(label_list[zaxis]) mlab.colorbar(title='Time') # ------------------------------------------- axes = engine.scenes[0].children[0].children[0].children[1] axes.axes.position = array([ 0., 0.]) axes.axes.label_format = '%-#6.2g' axes.title_text_property.font_size=4
def plot_2D( points, a=0, b=301 ): ''' Perfom a 2D plot. INPUTS: - points: numpy array of points to plot in the order of (x, y, z). - a : placeholder for now - b : placeholder for now OUTPUT: - No return; generates a 2D plot. ''' x, y = points # Store data into arrays z = np.zeros_like(x) # We don't want th scene = mlab.figure( size= (1000, 800), # Create scene fgcolor=(0, 0, 0), # Set foreground color bgcolor=(1, 1, 1) ) # Set background color nodes = mlab.points3d( x, y, z, # ... figure = scene, # Insert collected data to plot scale_factor=5.0 ) # ... xlab = mlab.xlabel( "x" ) # Set x-axis label ylab = mlab.ylabel( "y" ) # Set y-axis label mlab.axes( extent = [0, b-1, 0, b-1, 0, 0.5], # Set extent of axes figure = scene, # The figure to populate y_axis_visibility=False) # Remove the z-axis (designated y for some MayaVi reason) scene.scene.z_plus_view() # Look at it from the top! scene.scene.parallel_projection = True # 2D projection of 3D plane mlab.show()
def drawSurfaceDelaunay(point_list): x = [i[0] for i in point_list] y = [i[1] for i in point_list] z = [i[2] for i in point_list] pts = mlab.points3d(x, y, z, z) mesh = mlab.pipeline.delaunay2d(pts) pts.remove() surf = mlab.pipeline.surface(mesh) mlab.xlabel('x') mlab.ylabel('y') mlab.zlabel('z') mlab.show()
def plot_fiber_voltage(filename,fibertype): data = pickle.load( open(filename, "rb" ) ) decimate_s = 1 decimate_t = 1 nproc = len(data) data_plot = [] ddata2dx2 = [] ddata2dx2_plot = [] dx = 1 dt = 1 for proc in range(len(data)): data_plot.append(data[proc][fibertype][::decimate_s, ::decimate_t]) ddata2dx2.append(np.gradient(data[proc][fibertype],dx)) ddata2dx2_plot.append(ddata2dx2[proc][0][::decimate_t, ::decimate_s]) nseg, nsamp = ddata2dx2_plot[0].shape x = np.arange(nseg) t_plot = [] t_plot.append(data[0]['tvec'][::decimate_t]) y = t_plot[0] X,Y = np.meshgrid(x, y) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) s = mlab.surf(data_plot[0], warp_scale="auto", extent = [0,1,0,5,0,1]) #pdb.set_trace() ax=mlab.axes(s, ranges = [0, 43.306, np.min(y), np.max(y), np.min(data_plot[0]), np.max(data_plot[0])]) # ax.axes.label_format='%.2f' ax.label_text_property.font_family = 'arial' mlab.xlabel('Distance along axon (mm)') mlab.ylabel('Time (msec)') mlab.zlabel('Membrane voltage (mV)') ax.axes.font_factor=0.9 mlab.savefig('3d_voltage.png', size=(1920, 1080)) #pdb.set_trace() bla = input()
def mcrtmv(frames, dt, Lx, Ly, Nx, Ny, savemovie=False, mvname='test'): x = np.linspace(0, Lx, Nx) y = np.linspace(0, Lx, Nx) X, Y = np.meshgrid(x, y) size = 500, 500 fig = ml.figure(size=size, bgcolor=(1., 1., 1.)) #fig.scene.anti_aliasing_frames=07 #extent = [0,Nx-1,0,Ny-1,-30,30] ml.clf(figure=fig) u = np.loadtxt('solution_%06d.txt' % 1) fname = '_tmp%07d.png' % 1 s = ml.surf(x, y, u, figure=fig, vmin=-1, vmax=1) ml.axes(extent=[0, Lx, 0, Ly, -2, 2]) ml.colorbar() ml.xlabel('x position') ml.ylabel('y position') ml.zlabel('wave amplitude') if savemovie == True: pl.ion() arr = ml.screenshot() img = pl.imshow(arr) pl.axis('off') for i in range(2, frames): u = np.loadtxt('solution_%06d.txt' % i) s.mlab_source.scalars = u fname = '_tmp%07d.png' % i if savemovie == True: arr = ml.screenshot() img.set_array(arr) pl.savefig(filename=fname) #,figure=fig) print 'Saving frame', fname pl.draw() fig.scene.disable_render = False os.system( "mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname)
def sigma_m( m ): dataname = "sigmaOPT25_with_m{}.npy".format( m ) res = np.load( dataname ) print 'max', np.max( res ), 'min', np.min( res ) from mayavi.api import Engine engine = Engine() engine.start() if len( engine.scenes ) == 0: engine.new_scene() mlab.surf( x_axis1 , y_axis1 , res , representation = 'wireframe' ) surface = engine.scenes[0].children[0].children[0].children[0].children[0].children[0] surface.actor.mapper.scalar_range = np.array( [ 6.97602671, 8.8533387 ] ) surface.actor.mapper.scalar_visibility = False scene = engine.scenes[0] scene.scene.background = ( 1.0, 1.0, 1.0 ) surface.actor.property.specular_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.diffuse_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.ambient_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.color = ( 0.0, 0.0, 0.0 ) surface.actor.property.line_width = 0. warp_scalar = engine.scenes[0].children[0].children[0] module_manager = engine.scenes[0].children[0].children[0].children[0].children[0] warp_scalar.filter.normal = np.array( [ 0. , 0. , 0.8] ) module_manager.scalar_lut_manager.scalar_bar.global_warning_display = 1 module_manager.scalar_lut_manager.scalar_bar.position2 = np.array( [ 0.8 , 0.17] ) module_manager.scalar_lut_manager.scalar_bar.position = np.array( [ 0.1 , 0.01] ) module_manager.scalar_lut_manager.data_range = np.array( [ 6.97602671, 8.8533387 ] ) module_manager.scalar_lut_manager.default_data_range = np.array( [ 6.97602671, 8.8533387 ] ) module_manager.vector_lut_manager.scalar_bar.global_warning_display = 1 module_manager.vector_lut_manager.scalar_bar.position2 = np.array( [ 0.8 , 0.17] ) module_manager.vector_lut_manager.scalar_bar.position = np.array( [ 0.1 , 0.01] ) module_manager.vector_lut_manager.data_range = np.array( [ 0., 1.] ) module_manager.vector_lut_manager.default_data_range = np.array( [ 0., 1.] ) scene.scene.isometric_view() # mlab.surf( x_axis2, y_axis2, res2 ) mlab.xlabel( "rand tau" ) mlab.ylabel( "rand r" ) mlab.zlabel( "z" ) mlab.show()
def mcrtmv(frames, dt,Lx,Ly,Nx,Ny,savemovie=False, mvname='test'): x = np.linspace(0,Lx,Nx); y = np.linspace(0,Lx,Nx); X,Y = np.meshgrid(x,y); size = 500,500 fig = ml.figure(size= size, bgcolor=(1.,1.,1.)); #fig.scene.anti_aliasing_frames=07 #extent = [0,Nx-1,0,Ny-1,-30,30] ml.clf(figure=fig) u = np.loadtxt('solution_%06d.txt'%1); fname = '_tmp%07d.png' % 1 s = ml.surf(x,y,u,figure=fig,vmin=-1,vmax=1) ml.axes(extent=[0,Lx,0,Ly,-2,2]) ml.colorbar() ml.xlabel('x position') ml.ylabel('y position') ml.zlabel('wave amplitude') if savemovie == True: pl.ion() arr = ml.screenshot() img = pl.imshow(arr) pl.axis('off') for i in range(2,frames): u = np.loadtxt('solution_%06d.txt'%i); s.mlab_source.scalars = u fname = '_tmp%07d.png' % i if savemovie == True: arr = ml.screenshot() img.set_array(arr) pl.savefig(filename=fname)#,figure=fig) print 'Saving frame', fname pl.draw() fig.scene.disable_render = False os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname);
def mayavi_version(X,Y,Z): from mayavi import mlab # Define the points in 3D space # including color code based on Z coordinate. pts = mlab.points3d(X, Y, Z, Z) # Triangulate based on X, Y with Delaunay 2D algorithm. # Save resulting triangulation. mesh = mlab.pipeline.delaunay2d(pts) # Remove the point representation from the plot pts.remove() # Draw a surface based on the triangulation surf = mlab.pipeline.surface(mesh) # Simple plot. mlab.xlabel("x") mlab.ylabel("y") mlab.zlabel("z") mlab.show()
def mayavi_version(X, Y, Z): from mayavi import mlab # Define the points in 3D space # including color code based on Z coordinate. pts = mlab.points3d(X, Y, Z, Z) # Triangulate based on X, Y with Delaunay 2D algorithm. # Save resulting triangulation. mesh = mlab.pipeline.delaunay2d(pts) # Remove the point representation from the plot pts.remove() # Draw a surface based on the triangulation surf = mlab.pipeline.surface(mesh) # Simple plot. mlab.xlabel("x") mlab.ylabel("y") mlab.zlabel("z") mlab.show()
def show_net(): """ Visualizes the current Q(s,a_1) and Q(s,a_2) values of neural net Use BlueSky command SHOW_NET """ mlab.clf() x = np.linspace(-180, 180, 100) y = np.linspace(-180, 180, 100) X, Y = np.meshgrid(x, y) Z_Left = [] Z_Right = [] Z_Contour = [] for _x in x: Z_Left.append([]) Z_Right.append([]) Z_Contour.append([]) for _y in y: nn_input = tensor([_x, 7.0, _y]) nn_output = atc_net.forward(nn_input) Z_Left[-1].append(float(nn_output[0])) Z_Right[-1].append(float(nn_output[2])) Z_Contour[-1].append(nn_output.max(0)[1]) Z_Left = np.array(Z_Left) Z_Right = np.array(Z_Right) Z_Contour = np.array(Z_Contour) mlab.surf(x, y, Z_Left, colormap="Greens") mlab.surf(x, y, Z_Right, colormap="Reds") mlab.xlabel('qdr + self_hdg') mlab.ylabel('rel_hdg') mlab.title("Values for LEFT (g) and RIGHT (r)") mlab.show()
def show_point_cloud(self,fig): X,Y = np.meshgrid(self.X,self.Y) mesh = mlab.mesh(X, Y, self.Z,figure = fig,color=(0.3, 0.3, 0.3)) mlab.xlabel('x') mlab.ylabel('y')
# including color code based on Z coordinate. pts = mlab.points3d(X, Y, Z, Z) # Triangulate based on X, Y with Delaunay 2D algorithm. # Save resulting triangulation. mesh = mlab.pipeline.delaunay2d(pts) # Remove the point representation from the plot pts.remove() # Draw a surface based on the triangulation surf = mlab.pipeline.surface(mesh) # Simple plot. mlab.xlabel("x") mlab.ylabel("y") mlab.zlabel("z") mlab.show() print x print y print s
j=mlab.quiver3d(xs,ys,zs,jx,jy,jz, scale_factor=.002,color=(1,0,0),name='J') m=mlab.quiver3d(xs,ys,zs,baryX,baryY,baryZ, scale_factor=.013,color=(0,0,1),name='Mb') t=mlab.quiver3d(xs,ys,zs,tx,ty,tz, scale_factor=.1,color=(0,1,0),name='T/W') pt=mlab.quiver3d(xs,ys,zs,us,vs,ws, scale_factor=.01,color=(1,1,1),name='projT/W') mlab.text(.01,.2,'J ',color=(1,0,0),width=0.1) mlab.text(.01,.4,'Mb ',color=(0,0,1),width=0.1) mlab.text(.01,.5,'T/W ',color=(0,1,0),width=0.1) mlab.text(.01,.6,'-projT/W',color=(1,1,1),width=0.1) mlab.title("Gradients along track") mlab.axes(color=(.7,.7,.7),xlabel='a') mlab.xlabel('a') mlab.ylabel('edMax') mlab.zlabel('rpoe') mlab.show() exit() ############################### # TEST plotting and stepDown function def func(a,T): return -2*(a*a + T*T/2. -a*T/2.) + (a*a*a*a*.7 + T*T*T*T*.34) p0=(.10,.10,.15) p1=(.30,.20,.10)
except TypeError: a_result = np.NaN delta = np.NaN delta_dspace = np.append(delta_dspace, [delta]) print(i) #Kw_zspace_sap = Kw_zspace_sap * 10**1 #Ka2_yspace_sap = Ka2_yspace_sap * 10**-2 #Ka1_xspace_sap = Ka1_xspace_sap * 10**-2 #use for wrong scaling correction figure = mlab.figure('DensityPlot') pts = mlab.points3d(Ka1_xspace_sap, Ka2_yspace_sap, Kw_zspace_sap, delta_dspace, scale_mode='none', scale_factor=0.0005) #scale_factor = 0.0000001 or 0.001 mlab.xlabel('Ka1,unit : 10^2') mlab.ylabel('Ka2,unit : 10^2') mlab.zlabel('Kw,unit : 10^-1') mlab.axes(None, extent=[0, 0.1, 0, 0.1, 0, 0.1]) #use for wrong scaling correction too #mlab.axes() mlab.show()
u_y=numpy.zeros((N,N), dtype=float) v_x=numpy.zeros((N,N), dtype=float) omega=numpy.zeros((N,N), dtype=float) # Initial conditions for i in range(len(x)): for j in range(len(y)): u[i][j]=numpy.sin(2*math.pi*x[i])*numpy.cos(2*math.pi*y[j]) v[i][j]=-numpy.cos(2*math.pi*x[i])*numpy.sin(2*math.pi*y[j]) u_y[i][j]=-2*math.pi*numpy.sin(2*math.pi*x[i])*numpy.sin(2*math.pi*y[j]) v_x[i][j]=2*math.pi*numpy.sin(2*math.pi*x[i])*numpy.sin(2*math.pi*y[j]) omega[i][j]=v_x[i][j]-u_y[i][j] src = mlab.imshow(xx,yy,omega,colormap='jet') mlab.scalarbar(object=src) mlab.xlabel('x',object=src) mlab.ylabel('y',object=src) # Wavenumber k_x = 2*math.pi*numpy.array([complex(0,1)*n for n in range(0,N/2) \ + [0] + range(-N/2+1,0)]) k_y=k_x kx=numpy.zeros((N,N), dtype=complex) ky=numpy.zeros((N,N), dtype=complex) kxx=numpy.zeros((N,N), dtype=complex) kyy=numpy.zeros((N,N), dtype=complex) for i in xrange(N): for j in xrange(N): kx[i,j] = k_x[i]
def plotWithCondition(self, condition): assert isinstance(condition,str), "must enter a condition!" cursor=self.dbConnection.cursor() xname = self.independentVars[0] yname = self.independentVars[1] xs=[] for i in cursor.execute("SELECT DISTINCT " + xname + " FROM models ORDER BY " + xname): val = i[0] if xname == "edMax": val = val#/1.0e15 xs.append(val) ys=[] for i in cursor.execute("SELECT DISTINCT " + yname + " FROM models ORDER BY " + yname): val = i[0] if yname == "edMax": val = val#/1.0e15 ys.append(val) #print xs #print ys ##### # xs, ys = meshgrid(xs,ys) # reverse order since mlab uses mgrid format which returns transpose of matrices in meshgrid style xs = xs.transpose() ys = ys.transpose() # ##### def lookup(x,y): assert x >= 0., "Lookup only well defined for x >=0" assert y >= 0., "Lookup only well defined for y >=0" tolerance = 1.0001 additionalConditions=[] if not x == 0: additionalConditions.append( xname + ">" + str(x/tolerance) ) additionalConditions.append( xname + "<" + str(x*tolerance) ) else: additionalConditions.append(xname + "=" + str(x)) if not y == 0: additionalConditions.append(yname + ">" + str(y/tolerance)) additionalConditions.append( yname + "<" + str(y*tolerance)) else: additionalConditions.append(yname + "=" + str(y)) additionalConditions.append(condition) #print additionalConditions value= queryDBGivenParams(self.dependentVar, {}, cursor,"models", tuple( additionalConditions )) #print x,y, value if value: if len(value[0]) > 1 : print "WARNING MORE THAN ONE VALUE FOUND!!!" return value[0][0] else: print "WARNING: no value" return 0.0 zs = zeros(xs.shape) for i in range(len(xs)): row = xs[i] #print row for j in range(len(row)): #print xs[i][j], ys[i][j] zs[i][j] = lookup(xs[i][j], ys[i][j] ) if xname == "edMax": xs = array(xs*1e-15) else: xs = array(xs) if yname == "edMax": ys=array(ys*1e-15) else: ys = array(ys) zs = array(zs) #print xs #print ys #print zs #print size(xs) #print size(ys) #print size(zs) fig=mlab.figure(bgcolor=(.5,.5,.5)) extents=[xs.min(),xs.max(), ys.min(),ys.max(), zs.min(),zs.max()] mlab.surf(xs,ys,zs, colormap="bone",representation='wireframe', extent=extents ) mlab.axes(extent=extents,nb_labels=6) mlab.outline(extent=extents) mlab.xlabel(xname) mlab.ylabel(yname) mlab.zlabel(self.dependentVar)
forceY = [] forceZ = [] originX = [] originY = [] originZ = [] i = 0 with open("forceOnObject.txt", "r") as f: for line in f: vect = line.split('[')[1].split(']')[0].split(',') # Parse list forceX.append(float(vect[0])) forceY.append(float(vect[1])) forceZ.append(float(vect[2])) originX.append(0.0) originY.append(time[i]) originZ.append(0.0) i += 1 m.quiver3d(originX, originY, originZ, forceX, forceY, forceZ) # m.title('Force applied on the house over time') m.vectorbar(orientation='vertical') m.ylabel('time (s)') m.axes() m.show()
thetag = np.linspace(0.,2.*pi,ntheta) phi, theta = np.meshgrid(phig,thetag) rho = np.zeros_like(phi) sinphi = sin(phi); cosphi = cos(phi); sinth = sin(theta); costh = cos(theta) m = 0 for k in range(K): for j in range(J): for i in range(I): rho += (c[m]*np.power(sinphi,i+j) * np.power(cosphi,k) * np.power(sinth,j) * np.power(costh,i)) m += 1 xs = rho * sin(phi) * cos(theta) ys = rho * sin(phi) * sin(theta) zs = rho * cos(phi) import mayavi.mlab as mylab fig=mylab.figure(1,bgcolor=(0,0,0)) mylab.clf() ps = 1.*np.ones_like(x) mylab.points3d(x,y,z,(ps), scale_factor=0.025,colormap='Spectral',opacity=1.) mylab.mesh(xs, ys, zs, colormap="bone",opacity=0.5) mylab.outline(); mylab.xlabel('X'); mylab.ylabel('Y'); mylab.zlabel('Z')
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- import numpy as np from mayavi import mlab X = np.array([0, 1, 0, 1, 0.75]) Y = np.array([0, 0, 1, 1, 0.75]) Z = np.array([1, 1, 1, 1, 2]) # Define the points in 3D space # including color code based on Z coordinate. pts = mlab.points3d(X, Y, Z, Z) # Triangulate based on X, Y with Delaunay 2D algorithm. # Save resulting triangulation. mesh = mlab.pipeline.delaunay2d(pts) # Remove the point representation from the plot pts.remove() # Draw a surface based on the triangulation surf = mlab.pipeline.surface(mesh) # Simple plot. mlab.xlabel("x") mlab.ylabel("y") mlab.zlabel("z") mlab.show()
def plot3(history, *args, title=None, give=False, plot_style='default', axis_label=None, make_square=True, figsize=None,backend='matplotlib', **kwargs): ''' Parameters: > *args,**kwargs : are passed to matplotlib's pyplot.plot function > FIG_TITLE: the title given to the figure. Only used is a figure is not given to plot on > GIVE : this command makes the method return the figure after the path data is plotted. > BACKEND: either matplotlib or mayavi. ''' if backend == 'matplotlib': # setting style style.use(plot_style) # creating figure if figsize: fig = plt.figure(figsize=figsize) else: fig = plt.figure() ax = fig.gca(projection='3d') ax.set_aspect('equal') # makes history a numpy array history = array(history) # getting motion history X = history[:, 0] Y = history[:, 1] Z = history[:, 2] # To Do add optional label to the first point # Plots the 3 past printer positions on figure ax.plot(X, Y, Z, *args, **kwargs) # Keeps aspect ratio square but can be computationally expensive for large GCODE if make_square: # Keeps aspect ratio square # http://stackoverflow.com/questions/13685386 # numpy array max_range = array([X.max()-X.min(), Y.max()-Y.min(), Z.max()-Z.min()]).max() / 2.0 mean_x = X.mean() mean_y = Y.mean() mean_z = Z.mean() ax.set_xlim(mean_x - max_range, mean_x + max_range) ax.set_ylim(mean_y - max_range, mean_y + max_range) ax.set_zlim(mean_z - max_range, mean_z + max_range) # labeling figure axes if axis_label: ax.set_xlabel(axis_label[0]) ax.set_ylabel(axis_label[1]) ax.set_zlabel(axis_label[2]) # sets the figure title if title: ax.set_title(title) # determines whether to show the figure or to return it if give: return ax else: # showing figure plt.show() elif backend == 'mayavi': # getting the needing import to plot in mayavi from mayavi import mlab # makes history a numpy array history = array(history) # getting x,y,z coordinates x = history[:,0] y = history[:,1] z = history[:,2] # changin the figure size if figsize: mlab.figure(size=figsize) else: mlab.figure() # plotting the line plot fig = mlab.plot3d(x,y,z, *args, **kwargs) # setting label corrdinates # labeling figure axes if axis_label: mlab.xlabel(axis_label[0]) mlab.ylabel(axis_label[1]) mlab.zlabel(axis_label[2]) # sets the figure title if title: mlab.title(title) # showing the figure if give: return fig, mlab else: mlab.show() # end of view return
import numpy as np from mayavi import mlab X = np.array([.49,.98,1.47,1.96,2.45,.49,.98,1.47,1.96,2.45,.49,.98,1.47,1.96,2.45,.49,.98,1.47,1.96,2.45,.49,.98,1.47,1.96,2.45]) Y = np.array([.49,.49,.49,.49,.49,.98,.98,.98,.98,.98,1.47,1.47,1.47,1.47,1.47,1.96,1.96,1.96,1.96,1.96,2.45,2.45,2.45,2.45,2.45]) Z = np.array([0,.0078,.0245,.0485,.0784,.0230,.0235,.0358,.0578,.0887,.0583,.0505,.0573,.0760,.1034,.1005,.0892,.0916,.1078,.1318,.1593,.1507,.1421,.1504,.1715]) #X = np.array([0,1,0,1,.75]) #Y = np.array([0,0,1,1,.75]) #Z = np.array([1,1,1,1,2]) pts = mlab.points3d(X,Y,Z,Z) mesh = mlab.pipeline.delaunay2d(pts) pts.remove() surf = mlab.pipeline.surface(mesh) mlab.xlabel("Fx (N)") mlab.ylabel("Fy (N)") mlab.zlabel("Delta Potential (J)") mlab.show()
sinth = sin(theta) costh = cos(theta) m = 0 for k in range(K): for j in range(J): for i in range(I): rho += (c[m] * np.power(sinphi, i + j) * np.power(cosphi, k) * np.power(sinth, j) * np.power(costh, i)) m += 1 xs = rho * sin(phi) * cos(theta) ys = rho * sin(phi) * sin(theta) zs = rho * cos(phi) import mayavi.mlab as mylab fig = mylab.figure(1, bgcolor=(0, 0, 0)) mylab.clf() ps = 1. * np.ones_like(x) mylab.points3d(x, y, z, (ps), scale_factor=0.025, colormap='Spectral', opacity=1.) mylab.mesh(xs, ys, zs, colormap="bone", opacity=0.5) mylab.outline() mylab.xlabel('X') mylab.ylabel('Y') mylab.zlabel('Z')
una = numpy.zeros((Nx, Ny), dtype=complex) unb = numpy.zeros((Nx, Ny), dtype=complex) v = numpy.zeros((Nx, Ny), dtype=complex) vna = numpy.zeros((Nx, Ny), dtype=complex) vnb = numpy.zeros((Nx, Ny), dtype=complex) mass = numpy.zeros((Nx, Ny), dtype=complex) test = numpy.zeros((numplots - 1), dtype=float) tdata = numpy.zeros((numplots - 1), dtype=float) u = numpy.exp(-(xx**2 + yy**2)) v = numpy.fft.fftn(u) usquared = abs(u)**2 src = mlab.surf(xx, yy, usquared, colormap='YlGnBu', warp_scale='auto') mlab.scalarbar() mlab.xlabel('x', object=src) mlab.ylabel('y', object=src) mlab.zlabel('abs(u)^2', object=src) # initial mass usquared = abs(u)**2 mass = numpy.fft.fftn(usquared) ma = numpy.real(mass[0, 0]) print(ma) maO = ma t = 0.0 tdata[0] = t plotnum = 0 #solve pde and plot results for nt in xrange(numplots - 1): for n in xrange(plotgap): vna = v * numpy.exp(complex(0, 0.5) * dt * (k2xm + k2ym))
def plotWithCondition(self, condition): assert isinstance(condition, str), "must enter a condition!" cursor = self.dbConnection.cursor() xname = self.independentVars[0] yname = self.independentVars[1] xs = [] for i in cursor.execute("SELECT DISTINCT " + xname + " FROM models ORDER BY " + xname): val = i[0] if xname == "edMax": val = val #/1.0e15 xs.append(val) ys = [] for i in cursor.execute("SELECT DISTINCT " + yname + " FROM models ORDER BY " + yname): val = i[0] if yname == "edMax": val = val #/1.0e15 ys.append(val) #print xs #print ys ##### # xs, ys = meshgrid(xs, ys) # reverse order since mlab uses mgrid format which returns transpose of matrices in meshgrid style xs = xs.transpose() ys = ys.transpose() # ##### def lookup(x, y): assert x >= 0., "Lookup only well defined for x >=0" assert y >= 0., "Lookup only well defined for y >=0" tolerance = 1.0001 additionalConditions = [] if not x == 0: additionalConditions.append(xname + ">" + str(x / tolerance)) additionalConditions.append(xname + "<" + str(x * tolerance)) else: additionalConditions.append(xname + "=" + str(x)) if not y == 0: additionalConditions.append(yname + ">" + str(y / tolerance)) additionalConditions.append(yname + "<" + str(y * tolerance)) else: additionalConditions.append(yname + "=" + str(y)) additionalConditions.append(condition) #print additionalConditions value = queryDBGivenParams(self.dependentVar, {}, cursor, "models", tuple(additionalConditions)) #print x,y, value if value: if len(value[0]) > 1: print "WARNING MORE THAN ONE VALUE FOUND!!!" return value[0][0] else: print "WARNING: no value" return 0.0 zs = zeros(xs.shape) for i in range(len(xs)): row = xs[i] #print row for j in range(len(row)): #print xs[i][j], ys[i][j] zs[i][j] = lookup(xs[i][j], ys[i][j]) if xname == "edMax": xs = array(xs * 1e-15) else: xs = array(xs) if yname == "edMax": ys = array(ys * 1e-15) else: ys = array(ys) zs = array(zs) #print xs #print ys #print zs #print size(xs) #print size(ys) #print size(zs) fig = mlab.figure(bgcolor=(.5, .5, .5)) extents = [xs.min(), xs.max(), ys.min(), ys.max(), zs.min(), zs.max()] mlab.surf(xs, ys, zs, colormap="bone", representation='wireframe', extent=extents) mlab.axes(extent=extents, nb_labels=6) mlab.outline(extent=extents) mlab.xlabel(xname) mlab.ylabel(yname) mlab.zlabel(self.dependentVar)
mlab.figure() xmin = qx[0] * 1E0 xmax = qx[-1] * 1E0 ymin = qy[0] * 1E0 ymax = qy[-1] * 1E0 zmin = qz[0] * 1E0 zmax = qz[-1] * 1E0 obj = mlab.contour3d(plot_data, contours=10, opacity=0.5, transparent=False, extent=[qz[0], qz[-1], qy[0], qy[-1], qx[0], qx[-1]]) # , vmin=0, vmax=0.8) mlab.axes(ranges=[xmin, xmax, ymin, ymax, zmin, zmax]) mlab.xlabel('$Q_z$ [$\AA^{-1}$]') mlab.ylabel('$Q_y$ [$\AA^{-1}$]') mlab.zlabel('$Q_z$ [$\AA^{-1}$]') #C:\Users\Sanna\Documents\Beamtime\NanoMAX062017\Analysis_ptypy\scan461_\bragg_peak_stacking\InP\ #mlab.savefig('pos_'+ str(pos) +'.jpg') # Another way to maka an iso surface. Can also be combined with cut planes position = 0 def iso_pipeline_plot(): src = mlab.pipeline.scalar_field( plot_data) # this creates a regular space data mlab.pipeline.iso_surface(src, contours=[ diff_data[position].min() + 0.1 * diff_data[position].ptp(),
obj = mlab.pipeline.surface(normals, colormap='gist_ncar') mlab.outline(extent=[ np.min(x1), np.max(x1), np.min(x2), np.max(x2), v0, v1 ]) #WARNING: the z-axis will include the warp factor and is highly misleading #mlab.axes(src,z_axis_visibility=False,extent=ext,xlabel=plot_dict['xlabel'],ylabel=plot_dict['ylabel'],zlabel=plotter.name) mlab.view(azimuth=90, elevation=60, distance=5 * np.max(sizes), focalpoint=origin) s = s0 * len(slices[1]) + s1 mlab.xlabel(plot_dict['xlabel']) mlab.ylabel(plot_dict['ylabel']) mlab.zlabel(plot_dict['blabel']) mlab.savefig('tempfile{:03d}.png'.format(s)) # 3D PLOTS if num_slice_axes == 1: for s in slices[0]: print('Rendering frame', s, '...') data_slice, plot_dict = plotter.volume3d(slicing_spec, s, dyn_range) data_slice = data_slice.astype(np.double) ext = plot_dict['extent'] dims = plot_dict['dims'] x1 = np.einsum('i,j,k', plot_dict['xpts'], np.ones(dims[1]), np.ones(dims[2])).astype(np.double) x2 = np.einsum('i,j,k', np.ones(dims[0]), plot_dict['ypts'],
def Apply(db_tested, db_train, sysnames, alpha=0.05, N=50): """ Inputs: A data frame of objects to be tested, a training data set, and a list of ratios to use Outputs: An array of booleans of indices in the test data frame which have passed the filter """ #Reconstruct element names from ratio names el_list = [] for r in sysnames: el_list.extend(DecomposeR(r)) #Get matrices for the tested and training datasets print("ApplyLOF: Normalise & take logarithms") dTest = LogRatioMatrix(db_tested, el_list, stripNaNs=False) dTrain = LogRatioMatrix(db_train, el_list, stripNaNs=True) #Compute extents of training data for each dimension, renormalise all data dTrain, midpts, extents = Renormalise(dTrain) dTest = Renormalise(dTest, midpts, extents)[0] #Fill in missing data print("ApplyLOF: Interpolate missing values") dTest = FillNaNs(dTrain, dTest, N) print("ApplyLOF: Compute testing set factors") LOF_test = ComputeLOF(dTest, dTrain, N) print("ApplyLOF: Compute training set factors") LOF_ref = ComputeLOF2(dTrain, N) #Prepare the rejections filter Filter = np.full(dTest.shape[0], True, dtype=np.bool) #Find cutoff LOF value for the training set c = np.percentile(LOF_ref, 100 * (1 - alpha)) passing_samples = (LOF_test < c) Filter = (Filter & passing_samples) print("ApplyLOF: Evaluate with c=" + str(c)) # DEBUG: Plot results with mayavi if _debugVisualise: from mayavi import mlab dTest[np.isinf(dTest)] = 1000 LOF_test[np.isinf(LOF_test)] = 1000 mlab.figure('RSV ') mlab.points3d(dTrain.T[-3], dTrain.T[-2], dTrain.T[-1], LOF_ref, scale_mode='none', scale_factor=0.01) mlab.axes() mlab.xlabel(sysnames[-3]) mlab.ylabel(sysnames[-2]) mlab.zlabel(sysnames[-1]) mlab.show() mlab.figure('RSV ') mlab.points3d(dTrain.T[-6], dTrain.T[-5], dTrain.T[-4], LOF_ref, scale_mode='none', scale_factor=0.01) mlab.axes() mlab.xlabel(sysnames[-6]) mlab.ylabel(sysnames[-5]) mlab.zlabel(sysnames[-4]) mlab.show() #Return boolean mask for test data frame return Filter
# Loop over the values of the slice array, to produce an image of the vector # field for each slice for i in range(len(slice_arr)): # Create a new figure fig = mlab.figure(size = (800,700)) # Create an image of the vector field for this slice of the array mlab.quiver3d(X[slice_arr[i],::8,::8], Y[slice_arr[i],::8,::8],\ Z[slice_arr[i],::8,::8], mag_x[slice_arr[i],::8,::8],\ mag_y[slice_arr[i],::8,::8],mag_z[slice_arr[i],::8,::8],scalars =\ B_mag[slice_arr[i],::8,::8], vmax=vmax,vmin=vmin) # Make the co-ordinate axes appear on the plot mlab.xlabel('x-axis') mlab.ylabel('y-axis') mlab.zlabel('z-axis') # Rotate the camera so that it is face on mlab.view(azimuth=0, elevation = 90) # Add a colourbar to the figure mlab.colorbar(orientation='vertical') # Save the figure mlab.savefig(data_loc + 'B_vectors_slice_{}.jpg'.format(slice_arr[i])) # Close the figure mlab.close() # Print a line to the screen to show that the figure has been saved
# Loop over the values of the slice array, to produce an image of the vector # field for each slice for i in range(len(slice_arr)): # Create a new figure fig = mlab.figure(size=(800, 700)) # Create an image of the vector field for this slice of the array mlab.quiver3d(X[slice_arr[i],::8,::8], Y[slice_arr[i],::8,::8],\ Z[slice_arr[i],::8,::8], mag_x[slice_arr[i],::8,::8],\ mag_y[slice_arr[i],::8,::8],mag_z[slice_arr[i],::8,::8],scalars =\ B_mag[slice_arr[i],::8,::8], vmax=vmax,vmin=vmin) # Make the co-ordinate axes appear on the plot mlab.xlabel('x-axis') mlab.ylabel('y-axis') mlab.zlabel('z-axis') # Rotate the camera so that it is face on mlab.view(azimuth=0, elevation=90) # Add a colourbar to the figure mlab.colorbar(orientation='vertical') # Save the figure mlab.savefig(data_loc + 'B_vectors_slice_{}.jpg'.format(slice_arr[i])) # Close the figure mlab.close() # Print a line to the screen to show that the figure has been saved
from mayavi import mlab import numpy as np from numpy import pi, sin, cos phi, theta = np.mgrid[0:pi:20j, 0:2 * pi:20j] x = sin(phi) * cos(theta) y = sin(phi) * sin(theta) z = cos(phi) mlab.clf() mlab.mesh(x, y, z, scalars=z, representation='wireframe') mlab.colorbar(orientation='vertical') mlab.title('Sphere') mlab.outline() mlab.axes() mlab.xlabel('X') mlab.ylabel('Y') mlab.savefig('sphere.png') mlab.show()
mlab.view(azimuth=38, elevation=63, distance=distance) else: mlab.view(azimuth=38, elevation=63, distance=np.sqrt(qx.max()**2 + qz.max()**2 + qy.max()**2)) # azimut is the rotation around z axis of mayavi (x) mlab.roll(0) if crop_symmetric: ax = mlab.axes(line_width=2.0, nb_labels=2 * half_labels + 1) else: ax = mlab.axes(line_width=2.0, nb_labels=4) mlab.xlabel('Qx (1/nm)') mlab.ylabel('Qz (1/nm)') mlab.zlabel('-Qy (1/nm)') mlab.savefig(savedir + 'S' + str(scan) + comment + '_labels.png', figure=myfig) ax.label_text_property.opacity = 0.0 ax.title_text_property.opacity = 0.0 mlab.savefig(savedir + 'S' + str(scan) + comment + '_axes.png', figure=myfig) ax.axes.x_axis_visibility = False ax.axes.y_axis_visibility = False ax.axes.z_axis_visibility = False mlab.savefig(savedir + 'S' + str(scan) + comment + '.png', figure=myfig) mlab.draw(myfig) if make_movie: if output_format == 'mp4': animation = mpy.VideoClip(rotate_scene, duration=duration).resize(width=fig_size[0],
import tables as tb import mayavi.mlab as ml f = tb.openFile('/Users/fpaolo/data/gps/amery_gps_all.h5') t = f.root.time[:] x = f.root.x[:] y = f.root.y[:] h = f.root.h[:] f.close() ml.figure(1, size=(700, 600), fgcolor=(1, 1, 1), bgcolor=(0.5, 0.5, 0.5)) ml.points3d(x, y, h, t.round(1), mode='point') #ml.plot3d(x, y, h, t.round(1), tube_radius=.3) ml.colorbar(title='campaigns', orientation='vertical', nb_labels=5, label_fmt='%.0f', nb_colors=5) ml.outline() ml.axes(nb_labels=4).axes.label_format = '%.0f' ml.title('Amery GPS', size=.7) ml.xlabel('x (km)') ml.ylabel('y (km)') ml.zlabel('h (m)') ml.show()
rho[i + 1] = rho[i] + h * f(rho[i], u[i], v[i], w) u[i + 1] = u[i] + h * g1(rho[i], u[i], v[i]) v[i + 1] = v[i] + h * g2(rho[i], u[i], v[i]) time[i + 1] = time[i] + h ux, vx, rhox = np.mgrid[-2:2:50j, -2:2:50j, -1.5:1.5:50j] values = -(rhox**3 - rhox) * (3.0 * rhox**2 - 1) - ux * (rhox + 1) - vx * rhox - w * (rhox - 1) mlab.contour3d(ux, vx, rhox, values, contours=[0], opacity=0.5) # values_u = a*(1.0 - ux) - eta(rhox+1, c1) # mlab.contour3d(ux, vx, rhox, values_u, color = (0.7, 0.4, 0.4), contours=[0], opacity = 0.5) # values_v = b*(1.0 - vx) - eta(rhox, c1) # mlab.contour3d(ux, vx, rhox, values_v, color = (0.7, 0.4, 0.4), contours=[0], opacity = 0.5) mlab.axes() mlab.xlabel('u') mlab.ylabel('v') mlab.zlabel('rho') mlab.plot3d(u, v, rho, tube_radius=0.02, line_width=2.0) print('Mean u: ', np.mean(u)) print('Mean v: ', np.mean(v)) fig, ax = plt.subplots(1, 2) ax[0].plot(time, u, label='u') ax[0].plot(time, v, label='v') ax[0].legend() ax[0].set_xlabel('time') ax[1].plot(time, rho) ax[1].set_ylabel('rho') ax[1].set_xlabel('time')
def main_function(file): # Process the data to arrays # file = "HP_1a1.csv" data = pd.read_csv(file) data = np.array(data) # x: Retention time # y: m/z ratio # z: Intensity x = data[:, 0] y = data[:, 1] z = data[:, 2] # Retrieve scaling scalars from scale function x_scale, y_scale, z_scale = scale_function(data) # Retrieve rate to downsample data rate = rate_downsampling(file) # Begin full downsampling of data # These lists store the final data of each axis xnew = [] ynew = [] znew = [] # These lists are temporary placeholders for each section/bucket of each axis data_BucketX = [] data_BucketY = [] data_BucketZ = [] index = 0 for item in x: # Ignore the first line if index == 0: index += 1 continue # Retention values are the same, grouped into same bucket if item == x[index - 1]: data_BucketX.append(item) data_BucketY.append(y[index]) data_BucketZ.append(z[index]) # Different bucket else: # Ignore buckets with fewer than 100 data points if len(data_BucketX) < 100: index += 1 continue xn = [] yn = [] zn = [] # Downsample length of each bucket # TODO: Fix the rate error # An error like the one below may occur with regards to rate: # ERROR: In C:\VPP\standalone-build\VTK-source\Filters\Core\vtkDelaunay2D.cxx, line 819 # vtkDelaunay2D (0000027AE2A2ACF0): ERROR: Edge [118461 118462] is non-manifold!!! sample = int(len(data_BucketX) / rate) xn.extend(signal.resample(data_BucketX, sample)) yn.extend(signal.resample(data_BucketY, sample)) zn.extend(signal.resample(data_BucketZ, sample)) i = 0 for foo in zn: # Rescaled each axis xnew.append(xn[i] * x_scale) ynew.append(yn[i] / y_scale) znew.append(zn[i] / z_scale) i += 1 data_BucketX.clear() data_BucketY.clear() data_BucketZ.clear() index += 1 # From here, continue to remove data, specifically intensity values, that are too small and irrelevant # Temporary list to store indices foo = [] # Set a max z-axis threshold z_threshold = max(znew) * 0.01 # Loop through intensity list for i in range(len(znew)): # Append to the temporary list the indices of intensity values that are less than the threshold if znew[i] < z_threshold: foo.append(i) # Removes all corresponding elements from each array # Must remove from all three lists to preserve uniformity xnew = np.delete(xnew, foo) ynew = np.delete(ynew, foo) znew = np.delete(znew, foo) # From here, we are ready to get our plots set up # Dummy object to get accurate and original intensity values for colorbar label original = mlab.points3d(x, y, z, z, mode='point') original.remove() # Visualize the points pts = mlab.points3d(xnew, ynew, znew, znew, mode='point') # Create and visualize the mesh mesh = mlab.pipeline.delaunay2d(pts) surf = mlab.pipeline.surface(mesh) pts.remove() # Simple plot axis info rendering mlab.xlabel("Retention") mlab.ylabel("m/z") mlab.zlabel("Intensity") # Add text to plot indicating how each axis was rescaled mlab.text(0.5, 0.80, 'Retention scaled up by %.2f' % x_scale, width=0.8) mlab.text(0.5, 0.85, 'm/z scaled down by %.2f' % y_scale, width=0.8) mlab.text(0.5, 0.90, 'Intensity scaled down by %.2f' % z_scale, width=1.0) # Colorbar with original intensity values colorbar = mlab.colorbar(object=original, title='Intensity', orientation='vertical') colorbar.scalar_bar_representation.position = [0.85, 0.18] # Show the final plot scene mlab.show()
def drawGraph(self, colormap='jet', mapping=None, surfaceOnly=False): """ """ self.figure = mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1), size=(1200, 900)) self.gcf = mlab.gcf() # mlab.clf() self.figure.scene.disable_render = True self.crds = {} print("root information:",self.root_wcrd, self.root) # create drawables for bifurcations and endpoints self.narray = np.zeros((len(self.nodes), 3), dtype=np.float32) nodeSize = np.zeros((len(self.nodes),)) labels = [] for i in range(self.narray.shape[0]): n = self.nodes[i] self.narray[i, :] = n[1]['wcrd'] dg = self.og.degree(n[0]) if(dg == 1): tmp = (self.narray[i, 0], self.narray[i, 1], self.narray[i, 2]) nodeSize[i] = 1 if tuple(map(int, tmp)) != self.root_wcrd else 1.5 labels.append((n[0], tmp)) else: nodeSize[i] = 0.5 # # create random mapping if mapping is None: mapping = {} for e in self.edges: clr = random.randint(0, 1) mapping[(e[0], e[1])] = clr # now draw self.lines = {} surface = None self.surfaces = None x = np.array([0, 0]) y = np.array([0, 0]) z = np.array([0, 0]) s = np.array([0, 4]) for e in self.edges: try: mp = e[2]["mappedPoints"] x = np.concatenate((x, mp[::4, 0])) y = np.concatenate((y, mp[::4, 1])) z = np.concatenate((z, mp[::4, 2])) clr = mapping[(e[0], e[1])] # clr_t = clr, clr, clr s = np.concatenate((s, np.linspace(clr, clr, len(mp[::4, 0])))) #print "%s->%s mapping=%s"%(e[0],e[1],clr) if surface is None: surface = e[2]['mappedPoints'] else: try: surface = np.concatenate((surface, mp), axis=0) except ValueError: pass sp = e[2]['d0'] if(sp): if not surfaceOnly: self.lines[(e[0], e[1])] = mlab.plot3d(sp[0], sp[1], sp[2], color=(0, 0, 0), # color=clrt, tube_radius=.3) except KeyError as error: print("KeyError", error) except IndexError as error: print("IndexError", error) self.surfaces = mlab.points3d(x, y, z, s, # colormap="Greys", colormap="jet", scale_mode='none', scale_factor=.4, opacity=0.5) if not surfaceOnly: self.npts = mlab.points3d(self.narray[:, 0], self.narray[:, 1], self.narray[:, 2], nodeSize, colormap="jet", scale_factor=4.0) x = surface[::1, 0] y = surface[::1, 1] z = surface[::1, 2] minx = min(x) maxx = max(x) miny = min(y) maxy = max(y) minz = min(z) maxz = max(z) X, Y, Z = np.mgrid[minx:maxx:100j, miny:maxy:100j, minz:maxz:100j] # Visualize the points3d clr = (1, 0, 0) # Labels and legends if(self.showAxes): mlab.xlabel("x") mlab.ylabel("y") mlab.xlabel("z") mlab.title(self.title, size=.5, height=.90) for label in labels: l = label[1] fl = tuple(map(int, l)) if fl == self.root_wcrd: mlab.text(l[0], l[1], repr(label[0]) + " (root)", z=l[2], width=.2, color=(0, 0, 0)) else: mlab.text(l[0], l[1], repr(label[0]), z=l[2], width=.15, color=(0, 0, 0)) #adjust lut transparency lut = self.surfaces.module_manager.scalar_lut_manager.lut.table.to_array() lut[:, -1] = np.linspace(110, 110, 256) self.surfaces.module_manager.scalar_lut_manager.lut.table = lut # add scale bar if self.surfaces is not None: mlab.scalarbar(title="scale", orientation='vertical', nb_labels=5) self.figure.scene.disable_render = False mlab.view(0, 180, 400, roll=180) #saveFileName = os.path.join(os.path.expanduser("~"), "desktop", self.title + ".png") #mlab.savefig(saveFileName) #mlab.close() mlab.show()
foo = [] # set a max z-axis threshold z_threshold = max(znew) * 0.01 for i in range(len(znew)): # append to a list the indices of z-axis values that are less than the threshold if znew[i] < z_threshold: foo.append(i) # removes all corresponding elements from each array xnew = np.delete(xnew, foo) ynew = np.delete(ynew, foo) znew = np.delete(znew, foo) # Visualize the points # pts = mlab.points3d(x_3d, y_3d, z_3d, z_3d, mode='point') pts = mlab.points3d(xnew, ynew, znew, znew, mode='point') # pts = mlab.points3d(xnew, ynew, znew, znew, mode='point', scale_factor=3.0) # Create and visualize the mesh mesh = mlab.pipeline.delaunay2d(pts) surf = mlab.pipeline.surface(mesh) pts.remove() # Simple plot axis info rendering mlab.xlabel("Retention") mlab.ylabel("m/z") mlab.zlabel("Intensity") mlab.show()
def plotter(profiles, smsh): """ Mesh and profiles plotter. :param profiles: A list of :class:`openquake.hazardlib.geo.line.Line` instances :param smsh: A :class:`numpy.ndarray` instance """ # if MAYAVI: _ = mlab.figure(size=(600, 400)) # scl = -0.01 delta = 0.1 wdt = 0.001 # initialize extremes xmi = +1e10 ymi = +1e10 zmi = +1e10 xma = -1e10 yma = -1e10 zma = -1e10 # plotting profiles for l in profiles: coo = [[p.longitude, p.latitude, p.depth * scl] for p in l] coo = np.array(coo) mlab.plot3d(coo[:, 0], coo[:, 1], coo[:, 2], color=(0, 1, 0), line_width=wdt, opacity=0.2) mlab.points3d(coo[0, 0], coo[0, 1], coo[0, 2], color=(1., 0.5, 0.), line_width=wdt, scale_factor=0.1) xmi = min(xmi, np.amin(coo[:, 0]) - delta) xma = max(xma, np.amax(coo[:, 0]) + delta) ymi = min(ymi, np.amin(coo[:, 1]) - delta) yma = max(yma, np.amax(coo[:, 1]) + delta) zmi = min(zmi, np.amin(coo[:, 2]) - delta) zma = max(zma, np.amax(coo[:, 2]) + delta) # plotting mesh smsh[:, :, 2] *= scl for i in range(smsh.shape[0]): k = np.isfinite(smsh[i, :, 0]) if np.any(k): _ = mlab.plot3d(smsh[i, k, 0], smsh[i, k, 1], smsh[i, k, 2], color=(1, 0, 0), line_width=wdt, tube_radius=0.01) for i in range(smsh.shape[1]): k = np.isfinite(smsh[:, i, 0]) if sum(k): _ = mlab.plot3d(smsh[k, i, 0], smsh[k, i, 1], smsh[k, i, 2], color=(1, 0, 0), line_width=wdt, tube_radius=0.01) # decoration axes = mlab.axes(extent=[xmi, xma, ymi, yma, zmi, zma]) axes.label_text_property.font_size = 6 axes.axes.font_factor = 1.0 mlab.xlabel('Longitude\n') mlab.ylabel('Latitude\n') mlab.zlabel('Depth\n [km*0.01]') mlab.show()
def drawGraph(self, colormap='jet', mapping=None, surfaceOnly=False): """ """ self.figure = mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1), size=(1200, 900)) self.gcf = mlab.gcf() # mlab.clf() self.figure.scene.disable_render = True self.crds = {} print("root information:", self.root_wcrd, self.root) # create drawables for bifurcations and endpoints self.narray = np.zeros((len(self.nodes), 3), dtype=np.float32) nodeSize = np.zeros((len(self.nodes), )) labels = [] for i in range(self.narray.shape[0]): n = self.nodes[i] self.narray[i, :] = n[1]['wcrd'] dg = self.og.degree(n[0]) if (dg == 1): tmp = (self.narray[i, 0], self.narray[i, 1], self.narray[i, 2]) nodeSize[i] = 1 if tuple(map(int, tmp)) != self.root_wcrd else 1.5 labels.append((n[0], tmp)) else: nodeSize[i] = 0.5 # # create random mapping if mapping is None: mapping = {} for e in self.edges: clr = random.randint(0, 1) mapping[(e[0], e[1])] = clr # now draw self.lines = {} surface = None self.surfaces = None x = np.array([0, 0]) y = np.array([0, 0]) z = np.array([0, 0]) s = np.array([0, 4]) for e in self.edges: try: mp = e[2]["mappedPoints"] x = np.concatenate((x, mp[::4, 0])) y = np.concatenate((y, mp[::4, 1])) z = np.concatenate((z, mp[::4, 2])) clr = mapping[(e[0], e[1])] # clr_t = clr, clr, clr s = np.concatenate((s, np.linspace(clr, clr, len(mp[::4, 0])))) #print "%s->%s mapping=%s"%(e[0],e[1],clr) if surface is None: surface = e[2]['mappedPoints'] else: try: surface = np.concatenate((surface, mp), axis=0) except ValueError: pass sp = e[2]['d0'] if (sp): if not surfaceOnly: self.lines[(e[0], e[1])] = mlab.plot3d( sp[0], sp[1], sp[2], color=(0, 0, 0), # color=clrt, tube_radius=.3) except KeyError as error: print("KeyError", error) except IndexError as error: print("IndexError", error) self.surfaces = mlab.points3d( x, y, z, s, # colormap="Greys", colormap="jet", scale_mode='none', scale_factor=.4, opacity=0.5) if not surfaceOnly: self.npts = mlab.points3d(self.narray[:, 0], self.narray[:, 1], self.narray[:, 2], nodeSize, colormap="jet", scale_factor=4.0) x = surface[::1, 0] y = surface[::1, 1] z = surface[::1, 2] minx = min(x) maxx = max(x) miny = min(y) maxy = max(y) minz = min(z) maxz = max(z) X, Y, Z = np.mgrid[minx:maxx:100j, miny:maxy:100j, minz:maxz:100j] # Visualize the points3d clr = (1, 0, 0) # Labels and legends if (self.showAxes): mlab.xlabel("x") mlab.ylabel("y") mlab.xlabel("z") mlab.title(self.title, size=.5, height=.90) for label in labels: l = label[1] fl = tuple(map(int, l)) if fl == self.root_wcrd: mlab.text(l[0], l[1], repr(label[0]) + " (root)", z=l[2], width=.2, color=(0, 0, 0)) else: mlab.text(l[0], l[1], repr(label[0]), z=l[2], width=.15, color=(0, 0, 0)) #adjust lut transparency lut = self.surfaces.module_manager.scalar_lut_manager.lut.table.to_array( ) lut[:, -1] = np.linspace(110, 110, 256) self.surfaces.module_manager.scalar_lut_manager.lut.table = lut # add scale bar if self.surfaces is not None: mlab.scalarbar(title="scale", orientation='vertical', nb_labels=5) self.figure.scene.disable_render = False mlab.view(0, 180, 400, roll=180) #saveFileName = os.path.join(os.path.expanduser("~"), "desktop", self.title + ".png") #mlab.savefig(saveFileName) #mlab.close() mlab.show()