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 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 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 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, 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 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 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 anims(time): nc = get_grid_from_dda(time) ref = nc.variables['reflectivity'][:] u = nc.variables['eastward_wind'][:] v = nc.variables['northward_wind'][:] w = nc.variables['upward_air_velocity'][:] zh = nc.variables['z'][:] xh = nc.variables['x'][:] yh = nc.variables['y'][:] u = np.ma.squeeze(u) v = np.ma.squeeze(v) w = np.ma.squeeze(w) ref = np.squeeze(ref) grid_y, grid_z, grid_x = np.meshgrid(yh, zh, xh) ref = np.array(ref) bca = get_bca(grid_x, grid_y) ## Mask region outside dual doppler lobes and u = np.ma.masked_where( np.logical_or(bca < math.pi / 6, bca > 5 * math.pi / 6), u) no_mask = np.where(u.mask == False) no_mask_r = np.where(ref > 1) ## Apply mask grid_xm = grid_x[no_mask[0][0::10], no_mask[1][0::10], no_mask[2][0::10]] / 1e3 grid_ym = grid_y[no_mask[0][0::10], no_mask[1][0::10], no_mask[2][0::10]] / 1e3 grid_zm = grid_z[no_mask[0][0::10], no_mask[1][0::10], no_mask[2][0::10]] / 1e3 um = u[no_mask[0][0::10], no_mask[1][0::10], no_mask[2][0::10]] vm = v[no_mask[0][0::10], no_mask[1][0::10], no_mask[2][0::10]] wm = w[no_mask[0][0::10], no_mask[1][0::10], no_mask[2][0::10]] grid_xmr = grid_x[no_mask_r[0][0::2], no_mask_r[1][0::2], no_mask_r[2][0::2]] / 1e3 grid_ymr = grid_y[no_mask_r[0][0::2], no_mask_r[1][0::2], no_mask_r[2][0::2]] / 1e3 grid_zmr = grid_z[no_mask_r[0][0::2], no_mask_r[1][0::2], no_mask_r[2][0::2]] / 1e3 refm = ref[no_mask_r[0][0::2], no_mask_r[1][0::2], no_mask_r[2][0::2]] ## Regrid data for contour plot refm_gridded = griddata((grid_xmr, grid_ymr, grid_zmr), refm, (grid_x / 1e3, grid_y / 1e3, grid_z / 1e3)) um_gridded = griddata((grid_xm, grid_ym, grid_zm), um, (grid_x / 1e3, grid_y / 1e3, grid_z / 1e3)) vm_gridded = griddata((grid_xm, grid_ym, grid_zm), vm, (grid_x / 1e3, grid_y / 1e3, grid_z / 1e3)) wm_gridded = griddata((grid_xm, grid_ym, grid_zm), wm, (grid_x / 1e3, grid_y / 1e3, grid_z / 1e3)) #mlab.options.offscreen = True f = mlab.figure(bgcolor=(0, 0, 0), size=(1500, 1500)) q = mlab.quiver3d(grid_xm, grid_ym, grid_zm, um, vm, wm, extent=[-40, 40, -30, 30, 0, 20]) colorbar = mlab.colorbar(q, title='m/s', orientation='vertical') colorbar.label_text_property.font_size = 5 #mlab.flow(np.transpose(grid_x)/1e3, # np.transpose(grid_y)/1e3, # np.transpose(grid_z)/1e3, # np.transpose(um_gridded), # np.transpose(vm_gridded), # np.transpose(wm_gridded)) mlab.contour3d(np.transpose(grid_x) / 1e3, np.transpose(grid_y) / 1e3, np.transpose(grid_z) / 1e3, np.transpose(wm_gridded), colormap='blue-red', contours=[-4, 4], opacity=0.5, extent=[-40, 40, -30, 30, 0, 20]) mlab.view(azimuth=72.608457142284237, elevation=73.373132558239334, distance=201.83739701316438, focalpoint=(-0.05410797, -0.34705752, 10.27633847)) mlab.title( str(time.month) + '-' + str(time.day) + ' ' + str(time.hour) + ':' + str(time.minute)) axes = mlab.axes(extent=[-40, 40, -30, 30, 0, 20]) axes.label_text_property.font_family = 'courier' axes.label_text_property.font_size = 5 xlabel = mlab.xlabel('E of CPOL [km]') ylabel = mlab.ylabel('N of CPOL [km]') zlabel = mlab.zlabel('z [km]') xlabel.label_text_property.font_size = 5 ylabel.label_text_property.font_size = 5 zlabel.label_text_property.font_size = 5 mlab.show()
# 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 print 'Figure saved for slice number {}'.format(i)
EnStr=numpy.zeros((numplots), dtype=float) En=numpy.zeros((numplots), dtype=float) Enchange=numpy.zeros((numplots-1),dtype=float) tdata=numpy.zeros((numplots), dtype=float) nonlin=numpy.zeros((Nx,Ny), dtype=float) nonlinhat=numpy.zeros((Nx,Ny), dtype=complex) u=0.1*numpy.exp(-(xx**2 + yy**2))*numpy.sin(10*xx+12*yy) uold=u v=numpy.fft.fft2(u) vold=numpy.fft.fft2(uold) src = mlab.surf(xx,yy,u,colormap='YlGnBu',warp_scale='auto') mlab.scalarbar(object=src) mlab.xlabel('x',object=src) mlab.ylabel('y',object=src) mlab.zlabel('u',object=src) # initial energy vx=0.5*kxm*(v+vold) vy=0.5*kym*(v+vold) ux=numpy.fft.ifft2(vx) uy=numpy.fft.ifft2(vy) Kineticenergy=0.5*((u-uold)/dt)**2 Strainenergy=0.5*(ux)**2 + 0.5*(uy)**2 Potentialenergy=0.5*(0.5*(u+uold))**2 - Es*0.25*(0.5*(u+uold))**4 Kineticenergy=numpy.fft.fft2(Kineticenergy) Strainenergy=numpy.fft.fft2(Strainenergy) Potentialenergy=numpy.fft.fft2(Potentialenergy) EnKin[0]=numpy.real(Kineticenergy[0,0]) EnPot[0]=numpy.real(Potentialenergy[0,0]) EnStr[0]=numpy.real(Strainenergy[0,0]) En[0]=EnStr[0]+EnPot[0]+EnKin[0]
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], height=fig_size[1])
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(), ],
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()
colormap='YlGnBu', opacity=0.01) mlab.pipeline.image_plane_widget(src, plane_orientation='y_axes', slice_index=Ny / 2, colormap='YlGnBu', opacity=0.01) mlab.pipeline.image_plane_widget(src, plane_orientation='x_axes', slice_index=Nx / 2, colormap='YlGnBu', opacity=0.01) mlab.scalarbar() mlab.xlabel('x', object=src) mlab.ylabel('y', object=src) mlab.zlabel('z', object=src) # initial energy vx = 0.5 * kxm * (v + vold) vy = 0.5 * kym * (v + vold) vz = 0.5 * kzm * (v + vold) ux = numpy.fft.ifftn(vx) uy = numpy.fft.ifftn(vy) uz = numpy.fft.ifftn(vz) Kineticenergy = 0.5 * ((u - uold) / dt)**2 Strainenergy = 0.5 * (ux)**2 + 0.5 * (uy)**2 + 0.5 * (uz)**2 Potentialenergy = 0.5 * (0.5 * (u + uold))**2 - Es * 0.25 * (0.5 * (u + uold))**4 Kineticenergy = numpy.fft.fftn(Kineticenergy) Strainenergy = numpy.fft.fftn(Strainenergy) Potentialenergy = numpy.fft.fftn(Potentialenergy)
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
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) xs=[]
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()
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 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
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)
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
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()
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')
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)) una = numpy.fft.ifftn(vna)
#!/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()
# 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 print 'Figure saved for slice number {}'.format(i)
EnStr = numpy.zeros((numplots), dtype=float) En = numpy.zeros((numplots), dtype=float) Enchange = numpy.zeros((numplots - 1), dtype=float) tdata = numpy.zeros((numplots), dtype=float) nonlin = numpy.zeros((Nx, Ny), dtype=float) nonlinhat = numpy.zeros((Nx, Ny), dtype=complex) u = 0.1 * numpy.exp(-(xx**2 + yy**2)) * numpy.sin(10 * xx + 12 * yy) uold = u v = numpy.fft.fft2(u) vold = numpy.fft.fft2(uold) src = mlab.surf(xx, yy, u, colormap='YlGnBu', warp_scale='auto') mlab.scalarbar(object=src) mlab.xlabel('x', object=src) mlab.ylabel('y', object=src) mlab.zlabel('u', object=src) # initial energy vx = 0.5 * kxm * (v + vold) vy = 0.5 * kym * (v + vold) ux = numpy.fft.ifft2(vx) uy = numpy.fft.ifft2(vy) Kineticenergy = 0.5 * ((u - uold) / dt)**2 Strainenergy = 0.5 * (ux)**2 + 0.5 * (uy)**2 Potentialenergy = 0.5 * (0.5 * (u + uold))**2 - Es * 0.25 * (0.5 * (u + uold))**4 Kineticenergy = numpy.fft.fft2(Kineticenergy) Strainenergy = numpy.fft.fft2(Strainenergy) Potentialenergy = numpy.fft.fft2(Potentialenergy) EnKin[0] = numpy.real(Kineticenergy[0, 0]) EnPot[0] = numpy.real(Potentialenergy[0, 0]) EnStr[0] = numpy.real(Strainenergy[0, 0])
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)) una=numpy.fft.ifftn(vna)
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)
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)
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'], np.ones(dims[2])).astype(np.double)
def read_seismic(): try: t0 = time.time() data = segy_dir_path.get() #use obspy to read data stream = _read_segy(data, headonly=True) #create stream object num_trace = len(stream.traces) #get ns from binary header ns = stream.binary_file_header.number_of_samples_per_data_trace min_il = int(min_inline.get()) max_il = int(int(max_inline.get()) + 1) il_step = int(inline_step.get()) min_xl = int(min_xline.get()) max_xl = int(int(max_xline.get()) + 1) xl_step = int(xline_step.get()) inline_range = np.arange(min_il, max_il, il_step) xline_range = np.arange(min_xl, max_xl, xl_step) total_traces_calculated = (len(inline_range) * len(xline_range)) total_missing_traces = int(total_traces_calculated - num_trace) lines = [ "Total no of traces read : {}".format(num_trace), "Total number of calculated traces :{}".format( total_traces_calculated), "Total traces to pad: {}".format(total_missing_traces) ] tkinter.messagebox.showinfo("INFO", "\n".join(lines)) data = np.stack(t.data for t in stream.traces) #get z dim bounds, nt = data.shape data_t = data.T #Pad data with zero traces data_padded = np.pad(data_t, [(0, 0), (0, total_missing_traces)], mode='constant') data_padded = data_padded.T #Reshape data to a 3d cube shaped_data = np.reshape(data_padded, (inline_range.size, xline_range.size, nt)) #calculate the right colorbar scale vm = np.percentile(shaped_data, 99) #Define the mayavi data source source = mlab.pipeline.scalar_field(shaped_data) source.spacing = [il_step, xl_step, -4] for axis in ['x', 'y', 'z']: plane = mlab.pipeline.image_plane_widget( source, plane_orientation='{}_axes'.format(axis), colormap="gray", vmin=-vm, vmax=vm, slice_index=20) plane.module_manager.scalar_lut_manager.reverse_lut = True mlab.xlabel("XLINE") mlab.ylabel("INLINE") mlab.zlabel("TIME/DEPTH") #mlab.title("3D Seismic Cube : {}".format(str(segy_dir_path.get()))) #mlab.colorbar() mlab.show() except ValueError: tk.messagebox.showinfo("ERROR", "Please check your input bounds") close_window() except FileNotFoundError: tk.messagebox.showinfo("ERROR", "Please check your input File") close_window()
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') plt.show(block=False)
def ckplot(kmod=None, kmod2=None, labels=False, show=True, xlabel='x',ylabel='y',zlabel='z'): ''' This function plots 2D and 3D models :param labels: :param show: If True, the plots are displayed at the end of this call. If False, plt.show() should be called outside this function :return: ''' if kmod.k == 3: import mayavi.mlab as mlab predictFig = mlab.figure(figure='predict') # errorFig = mlab.figure(figure='error') if kmod.testfunction: truthFig = mlab.figure(figure='test') dx = 1 pts = 25j X, Y, Z = np.mgrid[0:dx:pts, 0:dx:pts, 0:dx:pts] scalars = np.zeros(X.shape) scalars2= np.zeros(X.shape) errscalars = np.zeros(X.shape) for i in range(X.shape[0]): for j in range(X.shape[1]): for k1 in range(X.shape[2]): # errscalars[i][j][k1] = kmod.predicterr_normalized([X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) scalars[i][j][k1] = kmod.predict_normalized([X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) scalars2[i][j][k1] = kmod2.predict([X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) if kmod.testfunction: tfscalars = np.zeros(X.shape) for i in range(X.shape[0]): for j in range(X.shape[1]): for k1 in range(X.shape[2]): tfplot = tfscalars[i][j][k1] = kmod.testfunction([X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) plot = mlab.contour3d(tfscalars, contours=15, transparent=True, figure=truthFig) plot.compute_normals = False # obj = mlab.contour3d(scalars, contours=10, transparent=True) mlab.contour3d(scalars2, contours=15, transparent=True, figure=predictFig) plot = mlab.contour3d(scalars, contours=15, transparent=True, figure=predictFig) plot.compute_normals = False # errplt = mlab.contour3d(errscalars, contours=15, transparent=True, figure=errorFig) # errplt.compute_normals = False mlab.xlabel(xlabel) mlab.ylabel(ylabel) mlab.zlabel(zlabel) if show: mlab.show() if kmod.k==2: fig = pylab.figure(figsize=(8,6)) samplePoints = list(zip(*kmod.X)) # Create a set of data to plot plotgrid = 61 x = np.linspace(kmod.normRange[0][0], kmod.normRange[0][1], num=plotgrid) y = np.linspace(kmod.normRange[1][0], kmod.normRange[1][1], num=plotgrid) # x = np.linspace(0, 1, num=plotgrid) # y = np.linspace(0, 1, num=plotgrid) X, Y = np.meshgrid(x, y) # Predict based on the optimized results zs = np.array([kmod.predict([x,y]) for x,y in zip(np.ravel(X), np.ravel(Y))]) Z = zs.reshape(X.shape) # Z = (Z*(kmod.ynormRange[1]-kmod.ynormRange[0]))+kmod.ynormRange[0] #Calculate errors zse = np.array([kmod.predict_var([x,y]) for x,y in zip(np.ravel(X), np.ravel(Y))]) Ze = zse.reshape(X.shape) spx = (kmod.X[:,0] * (kmod.normRange[0][1] - kmod.normRange[0][0])) + kmod.normRange[0][0] spy = (kmod.X[:,1] * (kmod.normRange[1][1] - kmod.normRange[1][0])) + kmod.normRange[1][0] contour_levels = 25 ax = fig.add_subplot(222) CS = pylab.contourf(X,Y,Ze, contour_levels) pylab.colorbar() pylab.plot(spx, spy,'ow') ax = fig.add_subplot(221) if kmod.testfunction: # Setup the truth function zt = kmod.testfunction( np.array(list(zip(np.ravel(X), np.ravel(Y)))) ) ZT = zt.reshape(X.shape) CS = pylab.contour(X,Y,ZT,contour_levels ,colors='k',zorder=2) # contour_levels = np.linspace(min(zt), max(zt),50) if kmod.testfunction: contour_levels = CS.levels delta = np.abs(contour_levels[0]-contour_levels[1]) contour_levels = np.insert(contour_levels, 0, contour_levels[0]-delta) contour_levels = np.append(contour_levels, contour_levels[-1]+delta) CS = plt.contourf(X,Y,Z,contour_levels,zorder=1) pylab.plot(spx, spy,'ow', zorder=3) pylab.colorbar() ax = fig.add_subplot(212, projection='3d') # fig = plt.gcf() #ax = fig.gca(projection='3d') ax.plot_surface(X, Y, Z, rstride=3, cstride=3, alpha=0.4) if kmod.testfunction: ax.plot_wireframe(X, Y, ZT, rstride=3, cstride=3) if show: pylab.show()
colormap='YlGnBu',opacity=0.85) mlab.pipeline.iso_surface(src, contours=[usquared.max()-0.1*usquared.ptp(), ], colormap='YlGnBu',opacity=1.0) mlab.pipeline.image_plane_widget(src,plane_orientation='z_axes', slice_index=Nz/2,colormap='YlGnBu', opacity=0.01) mlab.pipeline.image_plane_widget(src,plane_orientation='y_axes', slice_index=Ny/2,colormap='YlGnBu', opacity=0.01) mlab.pipeline.image_plane_widget(src,plane_orientation='x_axes', slice_index=Nx/2,colormap='YlGnBu', opacity=0.01) mlab.scalarbar() mlab.xlabel('x',object=src) mlab.ylabel('y',object=src) mlab.zlabel('z',object=src) # initial mass usquared=abs(u)**2 mass=numpy.fft.fftn(usquared) ma=numpy.real(mass[0,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+k2zm)) una=numpy.fft.ifftn(vna)
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')
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()