def plot(self): "绘制场景" # 产生三维网格 x, y, z = np.mgrid[self.x0:self.x1:1j * self.points, self.y0:self.y1:1j * self.points, self.z0:self.z1:1j * self.points] # 根据函数计算标量场的值 scalars = eval(self.function) mlab.clf() # 清空当前场景 # 绘制等值平面 g = mlab.contour3d(x, y, z, scalars, contours=8, transparent=True) g.contour.auto_contours = self.autocontour mlab.axes() # 添加坐标轴 # 添加一个X-Y的切面 s = mlab.pipeline.scalar_cut_plane(g) cutpoint = (self.x0 + self.x1) / 2, (self.y0 + self.y1) / 2, ( self.z0 + self.z1) / 2 s.implicit_plane.normal = (0, 0, 1) # x cut s.implicit_plane.origin = cutpoint self.g = g self.scalars = scalars # 计算标量场的值的范围 self.v0 = np.min(scalars) self.v1 = np.max(scalars)
def newSurface(self): processes = self.plotter.getProcesses() if not self._cv_dlg: self._cv_dlg = daeChooseVariable(daeChooseVariable.plot3D) self._cv_dlg.updateProcessesList(processes) self._cv_dlg.setWindowTitle('Choose variable for 3D plot') if self._cv_dlg.exec_() != QtWidgets.QDialog.Accepted: return False variable, domainIndexes, domainPoints, xAxisLabel, yAxisLabel, zAxisLabel, xPoints, yPoints, zPoints, currentTime = self._cv_dlg.getPlot3DData( ) xPoints = numpy.array(xPoints) yPoints = numpy.array(yPoints) xmax = numpy.max(xPoints) ymax = numpy.max(yPoints) zmax = numpy.max(zPoints) xmin = numpy.min(xPoints) ymin = numpy.min(yPoints) zmin = numpy.min(zPoints) warp = 'auto' #if((xmax == xmin) or (ymax == ymin) or (zmax == zmin)): # warp = 'auto' #else: # warp = math.sqrt( (xmax-xmin)*(ymax-ymin) ) / (zmax-zmin) # colormap='gist_earth', 'RdBu' stype = 'surface' mlab.figure() if (stype == 'surface'): #print "warp=", warp #print "[xmin, xmax, ymin, ymax, zmin, zmax]=", [xmin, xmax, ymin, ymax, zmin, zmax] mlab.surf(xPoints, yPoints, zPoints, warp_scale=warp, representation='surface') mlab.colorbar(orientation='vertical') #mlab.title('polar mesh') #mlab.outline() mlab.axes(ranges=[xmin, xmax, ymin, ymax, zmin, zmax], nb_labels=3) mlab.xlabel(xAxisLabel) mlab.ylabel(yAxisLabel) mlab.zlabel(zAxisLabel) elif (stype == 'map'): mlab.imshow(zPoints) mlab.colorbar(orientation='vertical') #mlab.title('polar mesh') #mlab.outline() mlab.axes(ranges=[xmin, xmax, ymin, ymax], nb_labels=3) mlab.xlabel(xAxisLabel) mlab.ylabel(yAxisLabel) mlab.zlabel(zAxisLabel) mlab.show()
def getData(self, data_D, data_H, name): """ plot passed in data as a surface """ #plotting fig = mlab.figure(size=(512, 512)) cl.enqueue_read_buffer(lbm.queue, data_D, data_H).wait() # retrieve mid cell points from cell node data Nx = lbm.X.size - 1 Ny = lbm.Y.size - 1 x = np.zeros((Nx)) y = np.zeros((Ny)) for i in range(1, lbm.X.size): x[i - 1] = (lbm.X[i] - lbm.X[i - 1]) / 2.0 + lbm.X[i - 1] for i in range(1, lbm.Y.size): y[i - 1] = (lbm.Y[i] - lbm.Y[i - 1]) / 2.0 + lbm.Y[i - 1] s = mlab.surf(x, y, data_H, warp_scale='auto', colormap="jet") mlab.axes(s) sb = mlab.scalarbar(s, title=name) self.s = s self.data_D = data_D self.data_H = data_H
def plot(self): "绘制场景" # 产生三维网格 x, y, z = np.mgrid[ self.x0 : self.x1 : 1j * self.points, self.y0 : self.y1 : 1j * self.points, self.z0 : self.z1 : 1j * self.points, ] # 根据函数计算标量场的值 scalars = eval(self.function) mlab.clf() # 清空当前场景 # 绘制等值平面 g = mlab.contour3d(x, y, z, scalars, contours=8, transparent=True) g.contour.auto_contours = self.autocontour mlab.axes() # 添加坐标轴 # 添加一个X-Y的切面 s = mlab.pipeline.scalar_cut_plane(g) cutpoint = (self.x0 + self.x1) / 2, (self.y0 + self.y1) / 2, (self.z0 + self.z1) / 2 s.implicit_plane.normal = (0, 0, 1) # x cut s.implicit_plane.origin = cutpoint self.g = g self.scalars = scalars # 计算标量场的值的范围 self.v0 = np.min(scalars) self.v1 = np.max(scalars)
def plot_connections(data_file, min, max, bins, params=None, output=''): print("Creating connection profile graphs.") # Read data points from file f = open(data_file, 'r') # Ignore first line f.readline() data = [] for line in f: temp = line.split(' ') if params != None: if check_node([int(temp[1])], params): data.append([float(temp[4]), float(temp[5])]); else: data.append([float(temp[4]), float(temp[5])]); # Create histogram data based on the retrieved data. histogram_data = histogram2d(data, min, max, bins) # Open a new Mayavi2 figure f = mlab.figure() # Convert histogram bin count to relative densities. m = np.max(histogram_data[2].max(axis=0)) histogram_data[2] = histogram_data[2]/float(m) # Plot histogram data mlab.mesh(histogram_data[0], histogram_data[1], histogram_data[2]) #surf(histogram_data[0], histogram_data[1], histogram_data[2]) # Create and save various viewpoints of histogram figure mlab.axes(z_axis_visibility=False) mlab.view(azimuth=0, elevation=90) # X mlab.savefig(output+"xaxis.eps", size=[600,400]) mlab.view(azimuth=90, elevation=270) # Y mlab.savefig(output+"yaxis.eps", size=[600,400]) mlab.view(azimuth=45, elevation=45) # Perspective mlab.savefig(output+"perspective.eps", size=[600,400]) mlab.colorbar(orientation="vertical") mlab.view(azimuth=0, elevation=0) # Z mlab.savefig(output+"above.eps", size=[600,400])
def plot_connections(data_file, min, max, bins, params=None, output=''): print("Creating connection profile graphs.") # Read data points from file f = open(data_file, 'r') # Ignore first line f.readline() data = [] for line in f: temp = line.split(' ') if params != None: if check_node([int(temp[1])], params): data.append([float(temp[4]), float(temp[5])]) else: data.append([float(temp[4]), float(temp[5])]) # Create histogram data based on the retrieved data. histogram_data = histogram2d(data, min, max, bins) # Open a new Mayavi2 figure f = mlab.figure() # Convert histogram bin count to relative densities. m = np.max(histogram_data[2].max(axis=0)) histogram_data[2] = histogram_data[2] / float(m) # Plot histogram data mlab.mesh(histogram_data[0], histogram_data[1], histogram_data[2]) #surf(histogram_data[0], histogram_data[1], histogram_data[2]) # Create and save various viewpoints of histogram figure mlab.axes(z_axis_visibility=False) mlab.view(azimuth=0, elevation=90) # X mlab.savefig(output + "xaxis.eps", size=[600, 400]) mlab.view(azimuth=90, elevation=270) # Y mlab.savefig(output + "yaxis.eps", size=[600, 400]) mlab.view(azimuth=45, elevation=45) # Perspective mlab.savefig(output + "perspective.eps", size=[600, 400]) mlab.colorbar(orientation="vertical") mlab.view(azimuth=0, elevation=0) # Z mlab.savefig(output + "above.eps", size=[600, 400])
def plot_cartesian(traj, xaxis=None, yaxis=None, zaxis=None, color='b', label='_nolegend_', linewidth=2, scatter_size=20): ''' xaxis - x axis for the graph (0,1 or 2) zaxis - for a 3d plot. not implemented. ''' 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 zaxis == None: pl.plot(x, y, c=color, linewidth=linewidth, label=label) pl.scatter( x, y, c=color, s=scatter_size, label='_nolegend_', linewidths=0) pl.xlabel(label_list[xaxis]) pl.ylabel(label_list[yaxis]) pl.legend(loc='best') pl.axis('equal') 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_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 animateVTKFiles_2D(folder): if not os.path.isdir(folder): return vtkFiles = [] for f in sorted(os.listdir(folder)): if f.endswith(".vtk"): vtkFiles.append(os.path.join(folder, f)) if len(vtkFiles) == 0: return figure = mlab.figure(size=(800, 600)) figure.scene.disable_render = True vtkSource = VTKFileReader() vtk_file = vtkFiles[0] vtkSource.initialize(vtk_file) surface = mlab.pipeline.surface(vtkSource) axes = mlab.axes() colorbar = mlab.colorbar(object=surface, orientation='horizontal') mlab.view(0, 0) figure.scene.disable_render = False mlab.draw() a = animateVTKFiles(figure, vtkSource, vtkFiles)
def read(name): from enthought.tvtk.api import tvtk from enthought.mayavi import mlab import numpy gridreader = tvtk.XMLStructuredGridReader() gridreader.file_name = name gridreader.update() grid = gridreader.output data = grid.point_data points = grid.points dims = grid.dimensions dims = dims.tolist() dims.reverse() phase = numpy.array(data.get_array("Phase")) velocity = numpy.array(data.get_array("Velocity")) velx = velocity[:, 0] vely = velocity[:, 1] velz = velocity[:, 2] phase_numpy = phase.reshape(dims) velx_numpy = velx.reshape(dims) vely_numpy = vely.reshape(dims) velz_numpy = velz.reshape(dims) fig = mlab.figure() src = mlab.pipeline.scalar_field(phase_numpy) mlab.axes() v = mlab.pipeline.vector_field(velx_numpy, vely_numpy, velz_numpy) vx = mlab.pipeline.scalar_field(velx_numpy) vy = mlab.pipeline.scalar_field(vely_numpy) vz = mlab.pipeline.scalar_field(velz_numpy) extract = mlab.pipeline.extract_grid(src) extract.set(z_min=1, z_max=dims[2] - 2, y_min=1, y_max=dims[1] - 2) surf = mlab.pipeline.contour_surface(extract) mlab.pipeline.image_plane_widget(vx, plane_orientation='x_axes', slice_index=250) #mlab.pipeline.vectors(v, mask_points=20, scale_factor=3.) mlab.pipeline.vector_cut_plane(v, mask_points=2, scale_factor=3) mlab.show()
def showVTKFile_2D(filename): figure = mlab.figure(size=(800, 600)) vtkSource = VTKFileReader() vtkSource.initialize(filename) surface = mlab.pipeline.surface(vtkSource) axes = mlab.axes() colorbar = mlab.colorbar(object=surface, orientation='horizontal') mlab.view(0, 0) 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('data/solution_%06d.txt' % 1) fname = 'data/_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('data/solution_%06d.txt' % i) s.mlab_source.scalars = u fname = 'data/_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://data/_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname)
def plot3d(self,ix=0,iy=1,iz=2,clf=True): """ Generates a 3-dimensional plot of the data set and principle components using mayavi. ix, iy, and iz specify which of the input p-dimensions to place on each of the x,y,z axes, respectively (0-indexed). """ import enthought.mayavi.mlab as M if clf: M.clf() z3=np.zeros(3) v=(self.getEigenvectors()*self.getEigenvalues()) M.quiver3d(z3,z3,z3,v[ix],v[iy],v[iz],scale_factor=5) M.points3d(self.N[:,ix],self.N[:,iy],self.N[:,iz],scale_factor=0.3) if self.names: M.axes(xlabel=self.names[ix]+'/sigma',ylabel=self.names[iy]+'/sigma',zlabel=self.names[iz]+'/sigma') else: M.axes()
def cutPlanes(volume, colormap='gist_ncar'): '''Display a 3D volume of scalars with two cut planes. volume: a three dimensional array of scalars ''' scalarField = mlab.pipeline.scalar_field(volume) mlab.pipeline.image_plane_widget(scalarField, plane_orientation='z_axes', slice_index=10, colormap=colormap) mlab.pipeline.image_plane_widget(scalarField, plane_orientation='y_axes', slice_index=10, colormap=colormap) mlab.outline() mlab.axes() mlab.colorbar(orientation='vertical')
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('data/solution_%06d.txt'%1); fname = 'data/_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('data/solution_%06d.txt'%i); s.mlab_source.scalars = u fname = 'data/_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://data/_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname);
def main(self): from enthought.mayavi import mlab self._iter = 1 self.density = mlab.pipeline.scalar_field(self.sim.rho.transpose()) self.vx = mlab.pipeline.scalar_field((self.sim.vx**2 + self.sim.vy**2 + self.sim.vz**2).transpose()) self.velocity = mlab.pipeline.vector_field(self.sim.vx.transpose(), self.sim.vy.transpose(), self.sim.vz.transpose()) self.trc = mlab.points3d(self.sim.tracer_x, self.sim.tracer_y, self.sim.tracer_z, scale_factor=0.75) mlab.pipeline.image_plane_widget(self.vx, plane_orientation='x_axes', slice_index=10) mlab.pipeline.image_plane_widget(self.vx, plane_orientation='y_axes', slice_index=10) mlab.pipeline.image_plane_widget(self.vx, plane_orientation='z_axes', slice_index=10) mlab.axes() # mlab.pipeline.vector_cut_plane(self.velocity, mask_points=2, scale_factor=3, plane_orientation='y_axes') # mlab.pipeline.vectors(self.velocity, mask_points=20, scale_factor=3.) mlab.outline() while 1: self.visualize()
def cutPlanes( volume, colormap='gist_ncar' ): '''Display a 3D volume of scalars with two cut planes. volume: a three dimensional array of scalars ''' scalarField = mlab.pipeline.scalar_field( volume ) mlab.pipeline.image_plane_widget(scalarField, plane_orientation='z_axes', slice_index=10, colormap = colormap ) mlab.pipeline.image_plane_widget(scalarField, plane_orientation='y_axes', slice_index=10, colormap = colormap ) mlab.outline() mlab.axes() mlab.colorbar(orientation='vertical')
def generate_mayavi_point_plot(self, srcid_sciclasses_list): """ Generate a Mayavi mlab 3D plot which summarizes iterative classification of a TUTOR source over the number of epochs used/added. """ # # # # # # # # # # TODO: I should label which science class by color, as Y axis labels from enthought.mayavi.scripts import mayavi2 mayavi2.standalone(globals()) from enthought.mayavi import mlab epoch_ids = [0] # x class_groups = [0] # y probs = [0] # z styles = [0] # numbers used for coloring & glyph sizes for src_id,sci_classes in srcid_sciclasses_list: #print 'src_id:', src_id i = 0 for class_name, class_dict in sci_classes.class_dict.iteritems(): epoch_ids.extend(class_dict['epoch_ids']) class_groups.extend([1]*len(class_dict['epoch_ids'])) probs.extend(class_dict['probs']) styles.extend([i + 1]*len(class_dict['epoch_ids'])) i += 1 mlab.points3d(numpy.array(epoch_ids), numpy.array(class_groups), numpy.array(probs)*100.0, numpy.array(styles), colormap="Paired", scale_mode="none", scale_factor=2.0) mlab.axes(xlabel='N of epochs', ylabel='science class', zlabel='% Prob.')
def plot(self): "绘制场景" # ball.up.x = 5 # ball.up.y = 6 # ball.up.z = 7 # ball.up.x = -4 # ball.up.y = -3 # ball.up.z = -2 x = [[-1,1,1,-1,-1], [-1,1,1,-1,-1]] y = [[-1,-1,-1,-1,-1], [1,1,1,1, 1]] z = [[1,1,-1,-1,1], [1,1,-1,-1,1]] # s = mlab.mesh(x, y, z, representation="wireframe", line_width=1.0 ) # mlab.show() pl = mlab.surf(x,y,z,warp_scale="auto") mlab.axes(xlabel = 'x',ylabel= 'y',zlabel= 'z') mlab.outline(pl)
def image(): #print getcwd() fig = mlab.figure() fig.scene.background = (1.,1.,1.) fig.scene.jpeg_quality = 100 src = mlab.pipeline.open('/home/jakub/simdata/global_enrichement/eps_f0nodes_1.vtk') tc = mlab.pipeline.extract_tensor_components(src) tc.filter.scalar_mode = 'component' ws = mlab.pipeline.warp_scalar(tc, warp_scale = 2.) #mlab.pipeline.surface(ws) cp = mlab.pipeline.cut_plane(ws) cp.filters[0].widget.enabled = False cp.filters[0].plane.normal = (0.,1.,0.) su = mlab.pipeline.surface(cp) su.actor.property.color = (0.75294117647058822, 0.75294117647058822, 0.75294117647058822) su.actor.property.line_width = 4. su.actor.mapper.scalar_visibility = False #print cp.filters src2 = mlab.pipeline.open('/home/jakub/simdata/global_enrichement/eps_m0nodes_1.vtk') tc2 = mlab.pipeline.extract_tensor_components(src2) tc2.filter.scalar_mode = 'component' ws2 = mlab.pipeline.warp_scalar(tc2, warp_scale = 2.) #mlab.pipeline.surface(ws) cp2 = mlab.pipeline.cut_plane(ws2) cp2.filters[0].widget.enabled = False cp2.filters[0].plane.normal = (0.,1.,0.) su2 = mlab.pipeline.surface(cp2) su2.actor.property.color = (0.,0.,0.) su2.actor.property.line_width = 4. su2.actor.mapper.scalar_visibility = False ax = mlab.axes(color = (0.,0.,0.), xlabel = 'x', ylabel = '', zlabel = 'strain', extent = [0., 3.1, 0., 0., 0., 2.], ranges = [1., 0., 0., 0., 0., 1.], y_axis_visibility = False) ax.title_text_property.color = (0.0, 0.0, 0.0) ax.label_text_property.color = (0.0, 0.0, 0.0) ax.title_text_property.bold = False ax.label_text_property.bold = False mlab.view(90., 90., 6.0, 'auto')
def saveVTKFilesAsImages_2D(sourceFolder, destinationFolder): if not os.path.isdir(sourceFolder) or not os.path.isdir( destinationFolder): return vtkFiles = [] for f in sorted(os.listdir(sourceFolder)): if f.endswith(".vtk"): vtkFiles.append(f) if len(vtkFiles) == 0: return figure = mlab.figure(size=(800, 600)) figure.scene.disable_render = True vtkSource = VTKFileReader() vtk_file = os.path.join(sourceFolder, vtkFiles[0]) vtkSource.initialize(vtk_file) surface = mlab.pipeline.surface(vtkSource) axes = mlab.axes() colorbar = mlab.colorbar(object=surface, orientation='horizontal') mlab.view(0, 0) figure.scene.disable_render = False mlab.draw() png_file = os.path.join(destinationFolder, vtkFiles[0]).replace('.vtk', '.png') mlab.savefig(png_file) for f in vtkFiles[1:-1]: vtk_file = os.path.join(sourceFolder, f) vtkSource.initialize(vtk_file) png_file = os.path.join(destinationFolder, f).replace('.vtk', '.png') mlab.savefig(png_file) app = QtCore.QCoreApplication.instance() if app: app.processEvents()
def pattern_tp(array_ip, tht_scan=0, phi_scan=0, tht_min=0, tht_max=np.pi, tht_num=50, phi_min=0, phi_max=2 * np.pi, phi_num=50, scale="dB", dB_limit= -40, factor="GF", plot_type="rect", mayavi_app=False): r""" Function to evaluate 3D AF/GF/NF of a arbitrary 3D array in (tht, phi)-domain. By default, this function calculates the gain-factor (GF). :param array_ip: array excitation data in 'Arraytool' input format (see :func:`ip_format`) :param tht_scan, etc: beam scan position in (tht, phi)-domain :param tht_min, etc: limits of (tht, phi)-domain :param tht_num, etc: number of points between 'tht_min' and 'tht_max' including the boundaries :param scale: specifies the scale choice ... dB/linear :param dB_limit: cutoff limit (see :func:`cutoff`) :param factor: type of pattern you need ... AF/NF/GF :param plot_type: can be rect/polar/contour ... if False, nothing happens :param mayavi_app: if True, the 3D plot will be opened in the MayaVi application :rtype: A list, [tht,phi,F] """ x = array_ip[:, 0] y = array_ip[:, 1] z = array_ip[:, 2] A = array_ip[:, 3] # un-packing "array_ip" finished k = 2 * np.pi # (angular) wave-number, which is 2*pi when lambda = 1 tht_numj = complex(0, tht_num) phi_numj = complex(0, phi_num) [tht, phi] = np.mgrid[tht_min:tht_max:tht_numj, phi_min:phi_max:phi_numj] u = np.sin(tht) * np.cos(phi); v = np.sin(tht) * np.sin(phi); w = np.cos(tht) u1 = np.reshape(u, (u.size, -1)) v1 = np.reshape(v, (v.size, -1)) w1 = np.reshape(w, (w.size, -1)) u_scan = np.sin(tht_scan) * np.cos(phi_scan) v_scan = np.sin(tht_scan) * np.sin(phi_scan) w_scan = np.cos(tht_scan) A = np.reshape(A, (len(A), -1)) U = np.tile(u1 - u_scan, len(x)) V = np.tile(v1 - v_scan, len(x)) W = np.tile(w1 - w_scan, len(x)) X = np.tile(x, (u.size, 1)) Y = np.tile(y, (u.size, 1)) Z = np.tile(z, (u.size, 1)) # Evaluating array-factor of the planar array AF1 = np.dot(np.exp(1j * k * (U * X + V * Y + W * Z)), A) AF = np.reshape(AF1, u.shape) # Evaluation of F = (AF/GF/NF) => depending upon the user's choice if(factor == "AF"): F = AF; n1 = ""; ff = "Array-Factor "; f1 = "AF " elif(factor == "GF"): P_inc = ((abs(A)) ** 2).sum() GF = AF / np.sqrt(P_inc) # Converting the AF to GF F = GF; n1 = ""; ff = "Gain-Factor "; f1 = "GF " elif(factor == "NF"): norm_fact = (abs(A)).sum() F = AF / norm_fact n1 = "Normalized "; ff = "Factor "; f1 = "NF " # converting 'F' from linear to dB scale, if needed if(scale == "linear"): F_plt = abs(F) ss = "in linear scale" elif(scale == "dB"): F = 20 * np.log10(abs(F)) # cutoff the "F" below some limit ... just for the plotting purpose F_plt = cutoff(F, dB_limit) ss = "in dB scale" # plotting the factor (AF/GF/NF) if(plot_type): if (mayavi_app): # opens the 3D plot in MayaVi Application mlab.options.backend = 'envisage' if(plot_type == "rect"): # rectangular plot plt3d = mlab.surf(tht, phi, F_plt, warp_scale='auto') ranges1 = [tht.min(), tht.max(), phi.min(), phi.max(), F_plt.min(), F_plt.max()] mlab.axes(xlabel='Tht', ylabel='Phi', zlabel=f1, ranges=ranges1, nb_labels=5) mlab.title(n1 + ff + ss, size=0.35) mlab.colorbar(orientation="vertical", nb_labels=5) plt3d.scene.isometric_view() mlab.show() if(plot_type == "polar"): # rectangular plot if(scale == "dB"): F_plt = F_plt - dB_limit F_plt_x = F_plt * u; F_plt_y = F_plt * v; F_plt_z = F_plt * w ranges1 = [F_plt_x.min(), F_plt_x.max(), F_plt_y.min(), F_plt_y.max(), F_plt_z.min(), F_plt_z.max()] plt3d = mlab.mesh(F_plt_x, F_plt_y, F_plt_z, scalars=F_plt, extent=ranges1) mlab.axes(xlabel='x', ylabel='y', zlabel='z', ranges=ranges1, nb_labels=5) mlab.title(n1 + ff + ss, size=0.35) mlab.colorbar(orientation="vertical", nb_labels=5) plt3d.scene.isometric_view() mlab.show() if(plot_type == "contour"): # contour plot plt.contourf(tht, phi, F_plt) plt.axis('tight'); plt.grid(True) plt.xlabel(r'$\theta$', fontsize=16) plt.ylabel(r'$\phi$', fontsize=16) plt.colorbar(format='$%.2f$') plt.show() return tht, phi, F
pl.gca().add_patch(rect) pl.gca().set_aspect("equal") pl.show() ####### 误差曲面 ####### scale_k = 1.0 scale_b = 10.0 scale_error = 1000.0 def S(k, b): "计算直线y=k*x+b和原始数据X、Y的误差的平方和" error = np.zeros(k.shape) for x, y in zip(X, Y): error += (y - (k*x + b))**2 return error ks, bs = np.mgrid[k-scale_k:k+scale_k:40j, b-scale_b:b+scale_b:40j] error = S(ks, bs)/scale_error from enthought.mayavi import mlab surf = mlab.surf(ks, bs/scale_b, error) mlab.axes(xlabel="k", ylabel="b", zlabel="error", ranges=[k-scale_k,k+scale_k, b-scale_b,b+scale_b, np.min(error)*scale_error, np.max(error)*scale_error]) mlab.outline(surf) mlab.points3d([k],[b/scale_b],[S(k,b)/scale_error],scale_factor=0.1, color=(1,1,1)) mlab.show()
# Start plotting ... make it an interactive 3D map ! fig1 = mlab.figure(bgcolor=(1.0,1.0,1.0),fgcolor=(0.0,0.0,0.0), size=(1200,900)) surf2 = mlab.contour3d(x,y,z,scidata_cleana,contours=[10],\ opacity=0.5, colormap='RdYlBu', name='[O III]-1') mlab.outline() surf3 = mlab.contour3d(x,y,z,scidata_cleana,contours=[40],\ opacity=1, colormap='Blues', name='[O III]-2') surf5 = mlab.contour3d(x_b,y_b,z_b,scidata_cleanb,contours=[10],\ opacity=0.1,colormap='autumn', name='Hbeta') surf6 = mlab.points3d((stars[:,0]-size_x/2)*0.5*astopc,(stars[:,1]-size_y/2.)*0.5*astopc,stars[:,0]*0.0,stars[:,2]*0.5*astopc*2,color=(0,0,0), scale_factor=1, name = 'Stars') # Now to make it look decent ... ax = mlab.axes(extent=[-10,10,-12,12,-7,7],nb_labels=5) ax.axes.fly_mode = 'outer_edges' ax.title_text_property.font_size = 10 ax.title_text_property.font_family = 'courier' ax.label_text_property.font_family = 'courier' # And a bit of references if anyone is interested ... mlab.text(0.05,0.95,'Oxygen-rich ejecta in SNR N132D. Vogt & Dopita, Ap&SS, 311, 521 (2011); Vogt & Shingles, Ap&SS (2013), submitted.',width=0.75) mlab.text(0.05,0.05,'*****@*****.**',width=0.25) # Label the axes ... ax.axes.x_label = 'X (Dec.) [pc]' ax.axes.y_label = 'Y (R.A.) [pc]' ax.axes.z_label = 'Z [pc]' mlab.show() # Define the view point - useful to make a movie (not build here) ...
def pattern_tp( array_ip, tht_scan=0, phi_scan=0, tht_min=0, tht_max=np.pi, tht_num=50, phi_min=0, phi_max=2 * np.pi, phi_num=50, scale="dB", dB_limit=-40, factor="GF", plot_type="rect", mayavi_app=False, ): r""" Function to evaluate 3D AF/GF/NF of a arbitrary 3D array in (tht, phi)-domain. By default, this function calculates the gain-factor (GF). :param array_ip: array excitation data in 'Arraytool' input format (see :func:`ip_format`) :param tht_scan, etc: beam scan position in (tht, phi)-domain :param tht_min, etc: limits of (tht, phi)-domain :param tht_num, etc: number of points between 'tht_min' and 'tht_max' including the boundaries :param scale: specifies the scale choice ... dB/linear :param dB_limit: cutoff limit (see :func:`cutoff`) :param factor: type of pattern you need ... AF/NF/GF :param plot_type: can be rect/polar/contour ... if False, nothing happens :param mayavi_app: if True, the 3D plot will be opened in the MayaVi application :rtype: A list, [tht,phi,F] """ x = array_ip[:, 0] y = array_ip[:, 1] z = array_ip[:, 2] A = array_ip[:, 3] # un-packing "array_ip" finished k = 2 * np.pi # (angular) wave-number, which is 2*pi when lambda = 1 tht_numj = complex(0, tht_num) phi_numj = complex(0, phi_num) [tht, phi] = np.mgrid[tht_min:tht_max:tht_numj, phi_min:phi_max:phi_numj] u = np.sin(tht) * np.cos(phi) v = np.sin(tht) * np.sin(phi) w = np.cos(tht) u1 = np.reshape(u, (u.size, -1)) v1 = np.reshape(v, (v.size, -1)) w1 = np.reshape(w, (w.size, -1)) u_scan = np.sin(tht_scan) * np.cos(phi_scan) v_scan = np.sin(tht_scan) * np.sin(phi_scan) w_scan = np.cos(tht_scan) A = np.reshape(A, (len(A), -1)) U = np.tile(u1 - u_scan, len(x)) V = np.tile(v1 - v_scan, len(x)) W = np.tile(w1 - w_scan, len(x)) X = np.tile(x, (u.size, 1)) Y = np.tile(y, (u.size, 1)) Z = np.tile(z, (u.size, 1)) # Evaluating array-factor of the planar array AF1 = np.dot(np.exp(1j * k * (U * X + V * Y + W * Z)), A) AF = np.reshape(AF1, u.shape) # Evaluation of F = (AF/GF/NF) => depending upon the user's choice if factor == "AF": F = AF n1 = "" ff = "Array-Factor " f1 = "AF " elif factor == "GF": P_inc = ((abs(A)) ** 2).sum() GF = AF / np.sqrt(P_inc) # Converting the AF to GF F = GF n1 = "" ff = "Gain-Factor " f1 = "GF " elif factor == "NF": norm_fact = (abs(A)).sum() F = AF / norm_fact n1 = "Normalized " ff = "Factor " f1 = "NF " # converting 'F' from linear to dB scale, if needed if scale == "linear": F_plt = abs(F) ss = "in linear scale" elif scale == "dB": F = 20 * np.log10(abs(F)) # cutoff the "F" below some limit ... just for the plotting purpose F_plt = cutoff(F, dB_limit) ss = "in dB scale" # plotting the factor (AF/GF/NF) if plot_type: if mayavi_app: # opens the 3D plot in MayaVi Application mlab.options.backend = "envisage" if plot_type == "rect": # rectangular plot plt3d = mlab.surf(tht, phi, F_plt, warp_scale="auto") ranges1 = [tht.min(), tht.max(), phi.min(), phi.max(), F_plt.min(), F_plt.max()] mlab.axes(xlabel="Tht", ylabel="Phi", zlabel=f1, ranges=ranges1, nb_labels=5) mlab.title(n1 + ff + ss, size=0.35) mlab.colorbar(orientation="vertical", nb_labels=5) plt3d.scene.isometric_view() mlab.show() if plot_type == "polar": # rectangular plot if scale == "dB": F_plt = F_plt - dB_limit F_plt_x = F_plt * u F_plt_y = F_plt * v F_plt_z = F_plt * w ranges1 = [F_plt_x.min(), F_plt_x.max(), F_plt_y.min(), F_plt_y.max(), F_plt_z.min(), F_plt_z.max()] plt3d = mlab.mesh(F_plt_x, F_plt_y, F_plt_z, scalars=F_plt, extent=ranges1) mlab.axes(xlabel="x", ylabel="y", zlabel="z", ranges=ranges1, nb_labels=5) mlab.title(n1 + ff + ss, size=0.35) mlab.colorbar(orientation="vertical", nb_labels=5) plt3d.scene.isometric_view() mlab.show() if plot_type == "contour": # contour plot plt.contourf(tht, phi, F_plt) plt.axis("tight") plt.grid(True) plt.xlabel(r"$\theta$", fontsize=16) plt.ylabel(r"$\phi$", fontsize=16) plt.colorbar(format="$%.2f$") plt.show() return tht, phi, F
def ip_format( a, b, A, gamma=np.pi / 2, plot=False, color="b", linewidth=1, linestyle="-", alpha=1, show=True, stem=False, stemline="g--", stemmarker="ro", mayavi_app=False, ): r""" Function to generate the 'Arraytool' input format. :param a: separation between elements along the x-axis in wavelengths :param b: separation between elements along the y-axis in wavelengths :param A: visual excitation matrix :param gamma: lattice angle in radians :param plot: if True, produces a 2D/3D plot of the array excitation :param stem: if True, the array excitation is plotted as 'stem plot' :param mayavi_app: if True, the 3D plot will be opened in the MayaVi application All other parameters are nothing but the 'Matplotlib' parameters. These should be familiar to 'Matlab' or 'Matplotlib' users. :rtype: array_ip, a Numpy array of size (Number_elements(A)*4) """ M = float(A.shape[1]) # no. of elements along the x-axis N = float(A.shape[0]) # no. of elements along the y-axis if M == 1: # i.e, linear array is along the y-direction a = 0 gamma = np.pi / 2 if N == 1: # i.e, linear array is along the x-direction b = 0 gamma = np.pi / 2 xlim = (M * a) / 2 # array is with in the x-limits [-xlim, +xlim] # Grid generation [x, y] = np.mgrid[0:M, 0:N] x = (x - (M - 1) / 2).T y = np.flipud((y - (N - 1) / 2).T) x = x * a y = y * b # rectangular grid is generated # modifying the rect-grid according to the given lattice angle 'gamma' if gamma != np.pi / 2: x = x + (y / np.tan(gamma)) % a # Adjusting the rows so that the array lies within [-xlim, +xlim] for i1 in range(int(N)): if x[i1, 0] < -xlim: x[i1, :] = x[i1, :] + a # RIGHT shifting the row by 'a' if x[i1, -1] > xlim: x[i1, :] = x[i1, :] - a # LEFT shifting the row by 'a' # Finally, arranging all the data into 'Arraytool' input format x = np.reshape(x, (M * N, -1)) y = np.reshape(y, (M * N, -1)) z = np.zeros_like(x) # because only planar arrays are permitted here A = np.reshape(A, (M * N, -1)) array_ip = np.hstack((x, y, z, A)) # finally, 'Arraytool' input format # plotting the 'absolute' value of the array excitation (2D/3D) if plot: # checking whether 'A' has any imaginary values if (A.imag > 1e-10).sum(): A_plt = abs(A) # if A.imag are significant, then '|A|' will be plotted else: A_plt = A.real # if A.imag are negligible, then 'A' will be plotted if M == 1: # i.e, linear array is along the y-direction plt.plot(y, A_plt, color=color, linewidth=linewidth, linestyle=linestyle, alpha=alpha) if stem: plt.stem(y, A_plt, linefmt=stemline, markerfmt=stemmarker) plt.axis("tight") plt.grid(True) plt.xlabel(r"$y$", fontsize=16) plt.ylabel(r"$\left|A_{n}\right|$", fontsize=16) if show: plt.title(r"$\mathrm{Array}\ \mathrm{Excitation}$", fontsize=18) plt.show() elif N == 1: # i.e, linear array is along the x-direction plt.plot(x, A_plt, color=color, linewidth=linewidth, linestyle=linestyle, alpha=alpha) if stem: plt.stem(x, A_plt, linefmt=stemline, markerfmt=stemmarker) plt.axis("tight") plt.grid(True) plt.xlabel(r"$x$", fontsize=16) plt.ylabel(r"$\left|A_{m}\right|$", fontsize=16) if show: plt.title(r"$\mathrm{Array}\ \mathrm{Excitation}$", fontsize=18) plt.show() else: if mayavi_app: # this option opens the 3D plot in MayaVi Application mlab.options.backend = "envisage" s1 = mlab.quiver3d(x, y, z, z, z, A_plt) # stem3D representation ranges1 = [x.min(), x.max(), y.min(), y.max(), A_plt.min(), A_plt.max()] mlab.axes(xlabel="x", ylabel="y", zlabel="Amn", ranges=ranges1, nb_labels=3) mlab.colorbar(orientation="vertical", nb_labels=5) s1.scene.isometric_view() if show: mlab.show() return array_ip
power=3, threshold=10**(-3), norm=2, neighbor_type='reduced', jacobian_file=None, distance_type='radial') # Unpack the results and calculate the adjusted data estimate, residuals, misfits, goals = results fatiando.mesh.fill(estimate, mesh) adjusted = gplant.adjustment(data, residuals) # PLOT THE INVERSION RESULTS ################################################################################ log.info("Plotting") # Plot the adjusted model plus the skeleton of the synthetic model fig = mlab.figure() fig.scene.background = (1, 1, 1) plot = vis.plot_prism_mesh(seed_mesh, style='surface', label='Density') plot = vis.plot_prism_mesh(mesh, style='surface', label='Density') plot = vis.plot_prism_mesh(mesh, style='surface', label='Density') axes = mlab.axes(plot, nb_labels=5, extent=extent, color=(0, 0, 0)) axes.label_text_property.color = (0, 0, 0) axes.title_text_property.color = (0, 0, 0) axes.axes.label_format = "%-#.0f" mlab.outline(color=(0, 0, 0), extent=extent) Y, X, Z = utils.extract_matrices(data['gzz']) mlab.surf(X, Y, Z) mlab.show()
pylab.plot(p[0], p[1], '*k', markersize=9) labels = pylab.gca().get_xticklabels() for label in labels: label.set_rotation(30) pylab.savefig('seeds.pdf') pylab.xlabel('Northing [m]') pylab.ylabel('Easting [m]') pylab.show() fig = mlab.figure() fig.scene.background = (1, 1, 1) fig.scene.camera.yaw(230) plot = vis.plot_prism_mesh(mesh, opacity=0.4) plot = vis.plot_prism_mesh(seed_mesh) axes = mlab.axes(plot, nb_labels=5, extent=[xmin,xmax,ymin,ymax,-zmax,-zmin]) mlab.show() # Run the inversion results = gplant.grow(data, mesh, seeds, compactness=10**(5), power=5, norm=1, threshold=5*10**(-5), jacobian_file=None, distance_type='radial') estimate, residuals, misfits, goals = results adjusted = gplant.adjustment(data, residuals) fatiando.mesh.fill(estimate, mesh, fillNone=False) log.info("Pickling results")
r_r.append(i) th_r.append(j) ph_r.append(k) s_r.append(v) #elif v >= 0.5: # r_a.append(i) # th_a.append(j) # ph_a.append(k) # s_a.append(v) if False: from enthought.mayavi import mlab fig1 = mlab.figure(bgcolor=(1,1,1),fgcolor=(0,0,0),size=(800,800)) #mlab.points3d(ph_a, th_a, r_a, s_a,opacity=0.1,scale_factor=3)#, color=(0,0,1)) mlab.points3d(ph_r, th_r, r_r, s_r,opacity=0.3,scale_factor=2)#, color=(1,0,0)) mlab.axes(ranges=[0.0, 90.0, 0.0, 90.0, 3.0, 9.0]) #mlab.orientation_axes() mlab.xlabel("phi") mlab.ylabel("theta") mlab.zlabel("centroid\ndistance") #mlab.colorbar(nb_labels=2,nb_colors=2,label_fmt='') mlab.colorbar() #mlab.text(0.1,0.1,"attraction",color=(0,0,1),width=0.1) #mlab.text(0.8,0.1,"repulsion",color=(1,0,0),width=0.1) mlab.text(0.1,0.8,"%s-%s (n=%i; x=%i); (%s)"%(res1,res2,ndata,countNone,pdblistfile),width=0.8) mlab.title("Free Energy (%s,%s)"%(res1,res2),size=0.3,height=0.7,figure=fig1) viewdist = 120 elevation = 60 # angle or 'rotate' azimuth = 180+45 # angle or 'rotate' mlab.view(distance=viewdist,elevation=elevation, azimuth=azimuth)
cat2 = cat(x, y, 2) cat3 = cat(x, y, 3) # The cats lie in a [0, 1] interval, with .5 being the assymptotique # value. We want to reposition this value to 0, so as to put it in the # center of our extents. cat1 -= 0.5 cat2 -= 0.5 cat3 -= 0.5 cat1_extent = (-14,-6, -4,4, 0,5) surf_cat1 = mlab.surf(x-10, y, cat1, colormap='Spectral', warp_scale=5, extent=cat1_extent, vmin=-0.5, vmax=0.5) mlab.outline(surf_cat1, color=(.7, .7, .7)) mlab.axes(surf_cat1, color=(.7, .7, .7), extent=cat1_extent, ranges=(0,1, 0,1, 0,1), xlabel='', ylabel='', zlabel='Probability', x_axis_visibility=False, z_axis_visibility=False) mlab.text(-18, -4, '1 photon', z=-4, width=0.13) cat2_extent = (-4,4, -4,4, 0,5) surf_cat2 = mlab.surf(x, y, cat2, colormap='Spectral', warp_scale=5, extent=cat2_extent, vmin=-0.5, vmax=0.5) mlab.outline(surf_cat2, color=(0.7, .7, .7), extent=cat2_extent) mlab.text(-4, -3, '2 photons', z=-4, width=0.14) cat3_extent = (6,14, -4,4, 0,5) surf_cat3 = mlab.surf(x+10, y, cat3, colormap='Spectral', warp_scale=5, extent=cat3_extent, vmin=-0.5, vmax=0.5) mlab.outline(surf_cat3, color=(.7, .7, .7), extent=cat3_extent)
# -*- coding: utf-8 -*-
import pickle import numpy from enthought.mayavi import mlab from fatiando import vis f = open("mesh.pickle") mesh = pickle.load(f) f.close() f = open("seeds.pickle") seeds = pickle.load(f) f.close() seed_mesh = numpy.array([seed['cell'] for seed in seeds]) fig = mlab.figure() fig.scene.camera.yaw(230) fig.scene.background = (1, 1, 1) vis.plot_prism_mesh(mesh, opacity=0.2) plot = vis.plot_prism_mesh(mesh) vis.plot_prism_mesh(seed_mesh) axes = mlab.axes(plot, nb_labels=5) mlab.show()
import numpy from enthought.mayavi import mlab from fatiando import vis f = open("mesh.pickle") mesh = pickle.load(f) f.close() f = open("seeds.pickle") seeds = pickle.load(f) f.close() f = open("model.pickle") model = pickle.load(f) f.close() seed_mesh = numpy.array([seed['cell'] for seed in seeds]) fig = mlab.figure() fig.scene.camera.yaw(230) fig.scene.background = (1, 1, 1) vis.plot_prism_mesh(model, style='wireframe', xy2ne=True) plot = vis.plot_prism_mesh(mesh, xy2ne=True) vis.plot_prism_mesh(seed_mesh, xy2ne=True) axes = mlab.axes(plot, nb_labels=5, color=(0,0,0)) axes.label_text_property.color = (0,0,0) axes.title_text_property.color = (0,0,0) axes.axes.label_format = "%-#.0f" mlab.outline(color=(0,0,0)) mlab.show()
[phi,theta] = np.meshgrid(phi,theta) # Radius of displayed sphere r = 5 x = r*np.sin(theta)*np.cos(phi) y = r*np.sin(theta)*np.sin(phi) z = r*np.cos(theta) #Plot Sphere mlab.figure("Figure 1") figure1 = mlab.mesh(x,y,z,representation='wireframe') mlab.axes() mlab.title("Figure 1") mlab.outline() #Make the radius a function of theta and phi #antenna pattern response to a +/- polarized wave #See Eq. 7 of Anholm et al. (Phys. Rev. D 79, 084030 (2009)) rp = np.absolute(.5*np.sin(theta)**2 * (np.cos(phi)**2 - np.sin(phi)**2) / (1 + np.cos(theta))) rp_mask = np.ma.masked_invalid(rp) x = rp*np.sin(theta)*np.cos(phi) x[np.isinf(x)] = np.nan y = rp*np.sin(theta)*np.sin(phi)
#a.axes.label_format = "" #a.axes.x_label, a.axes.y_label, a.axes.z_label = "", "", "" #a.property.line_width = 1 mlab.outline(p, extent=extent, color=(0,0,0)) pos = 1000 field = 'gz' scale = 200 Y, X, Z = utils.extract_matrices(data[field]) p = mlab.contour_surf(X, Y, Z, contours=10, colormap='jet') p.contour.filled_contours = True p.actor.actor.position = (0,0,pos) p.actor.actor.scale = (1,1,scale) a = mlab.axes(p, nb_labels=0, extent=[0,3000,0,3000,pos,pos + scale*Z.max()], color=(0,0,0)) a.label_text_property.color = (0,0,0) a.title_text_property.color = (0,0,0) a.axes.label_format = "" a.axes.x_label, a.axes.y_label, a.axes.z_label = "", "", "" a.property.line_width = 1 scene = fig scene.scene.camera.position = [5845.7904104772751, 10826.008452051316, 3697.0607477775502] scene.scene.camera.focal_point = [1317.7924322687745, 1352.1830042500999, -1036.6534494994289] scene.scene.camera.view_angle = 30.0 scene.scene.camera.view_up = [-0.18123807301145317, -0.36888651509323656, 0.91163342406554104] scene.scene.camera.clipping_range = [5326.0395401897185, 18409.2672096317] scene.scene.camera.compute_view_plane_normal() scene.scene.render()
from numpy import array, mgrid, vstack, arange, transpose, zeros from enthought.mayavi.mlab import show, surf, view, roll, axes, xlabel x, y = mgrid[0:3:1,0:3:1] s = surf(x, y, zeros(9).reshape(3,3), warp_scale = 0.0, vmin = 0, vmax = 3) view(0,0,20) for i,j in transpose(vstack((arange(100),arange(100)))): s.mlab_source.x = x*(1+0.01*(i+1)) s.mlab_source.y = y*(1+0.003*(j+1)) s.mlab_source.scalars = (x*(1+0.01*i)-x)+(y*(1+0.01*j)-y) axes() show()
def pattern_uv( array_ip, u_scan=0, v_scan=0, u_min=-1, u_max=1, u_num=50, v_min=-1, v_max=1, v_num=50, scale="dB", dB_limit=-40, factor="GF", plot_type="rect", mayavi_app=False, ): r""" Function to evaluate 3D AF/GF/NF of a planar array in uv-domain. By default, this function calculates the gain-factor (GF). :param array_ip: array excitation data in 'Arraytool' input format (see :func:`ip_format`) :param u_scan, v_scan: beam scan position in uv-domain :param u_min, etc: limits of uv-domain :param u_num, v_num: number of points between 'u_min' and 'u_max' including boundaries :param scale: specifies the scale choice ... dB/linear :param dB_limit: cutoff limit (see :func:`cutoff`) :param factor: type of pattern you need ... AF/NF/GF :param plot_type: can be rect/polar ... if False, nothing happens :param mayavi_app: if True, the 3D plot will be opened in the MayaVi application :rtype: A list, [u,v,F] """ x = array_ip[:, 0] y = array_ip[:, 1] z = array_ip[:, 2] A = array_ip[:, 3] # un-packing "array_ip" finished k = 2 * np.pi # (angular) wave-number, which is 2*pi when lambda = 1 u_numj = complex(0, u_num) v_numj = complex(0, v_num) # Making sure all elements in the z-column of the "array_ip" are zeros z_flag = True if (abs(z) > 0).sum(): print "All elements in the z-column of array input should be zero." z_flag = False # After making sure, proceed to the next level, i.e., evaluate the pattern if z_flag: [u, v] = np.mgrid[u_min:u_max:u_numj, v_min:v_max:v_numj] u1 = np.reshape(u, (u.size, -1)) v1 = np.reshape(v, (v.size, -1)) A = np.reshape(A, (len(A), -1)) U = np.tile(u1 - u_scan, len(x)) V = np.tile(v1 - v_scan, len(x)) X = np.tile(x, (u.size, 1)) Y = np.tile(y, (u.size, 1)) # Evaluating array-factor of the planar array AF1 = np.dot(np.exp(1j * k * (U * X + V * Y)), A) AF = np.reshape(AF1, u.shape) # Evaluation of F = (AF/GF/NF) => depending upon the user's choice if factor == "AF": F = AF n1 = "" ff = "Array-Factor " f1 = "AF " elif factor == "GF": P_inc = ((abs(A)) ** 2).sum() GF = AF / np.sqrt(P_inc) # Converting the AF to GF F = GF n1 = "" ff = "Gain-Factor " f1 = "GF " elif factor == "NF": norm_fact = (abs(A)).sum() F = AF / norm_fact n1 = "Normalized " ff = "Factor " f1 = "NF " # converting 'F' from linear to dB scale, if needed if scale == "linear": F_plt = abs(F) ss = "in linear scale" elif scale == "dB": F = 20 * np.log10(abs(F)) # cutoff the "F" below some limit ... just for the plotting purpose F_plt = cutoff(F, dB_limit) ss = "in dB scale" # plotting the factor (AF/GF/NF) if plot_type: if plot_type == "rect": # rectangular plot if mayavi_app: # opens the 3D plot in MayaVi Application mlab.options.backend = "envisage" plt3d = mlab.surf(u, v, F_plt, warp_scale="auto") ranges1 = [u_min, u_max, v_min, v_max, F_plt.min(), F_plt.max()] mlab.axes(xlabel="u", ylabel="v", zlabel=f1, ranges=ranges1, nb_labels=5) mlab.title(n1 + ff + ss, size=0.35) mlab.colorbar(orientation="vertical", nb_labels=5) plt3d.scene.isometric_view() mlab.show() if plot_type == "contour": # contour plot plt.contourf(u, v, F_plt) vs = plt.Circle((0, 0), radius=1, edgecolor="w", fill=False) ax = plt.gca() ax.add_patch(vs) plt.axis("image") plt.grid(True) plt.xlabel( r"$u,\ \mathrm{where}\ u=\sin \theta \cos \phi\ \mathrm{in}\ \mathrm{the}\ \mathrm{visible-space}$", fontsize=16, ) plt.ylabel( r"$v,\ \mathrm{where}\ v=\sin \theta \sin \phi\ \mathrm{in}\ \mathrm{the}\ \mathrm{visible-space}$", fontsize=16, ) plt.colorbar(format="$%.2f$") plt.show() return u, v, F
# -*- coding: utf-8 -*- import numpy as np from enthought.mayavi import mlab const = 2.19967e34 x, y = np.mgrid[0:700:200j, 300:1500:200j] z = np.exp(-x / y) * np.sqrt(x) / (y**1.5) c = const * z pl = mlab.mesh(x, y, z, scalars=c) mlab.axes(xlabel='Energy(eV)', ylabel='Temprature(k)', zlabel='N/2.19967e34') mlab.outline(pl) mlab.show()
scene = mlab.figure(size=(1200,800)) scene.scene.background = (1, 1, 1) view.bbox(mlab) engine = mlab.get_engine() surfs = [] surfs.append(vis.plot_prism_mesh(res, style='surface', xy2ne=True)) engine.scenes[0].children[-1].children[0].children[0].children[0].scalar_lut_manager.data_range = [0,1000] surfs.append(vis.plot_prism_mesh(mesh, style='surface', xy2ne=True)) engine.scenes[0].children[-1].children[0].children[0].children[0].scalar_lut_manager.lut_mode = "Greys" surfs.append(vis.plot_prism_mesh(seeds, style='surface', xy2ne=True)) engine.scenes[0].children[-1].children[0].children[0].children[0].scalar_lut_manager.lut_mode = "Greys" engine.scenes[0].children[-1].children[0].children[0].children[0].scalar_lut_manager.data_range = [0,1000] o = mlab.outline(color=(0,0,0), extent=extent) o.actor.property.line_width = 1 a = mlab.axes(surfs[0], nb_labels=7, extent=extent, ranges=ranges, color=(0,0,0)) a.label_text_property.color = (0,0,0) a.title_text_property.color = (0,0,0) a.property.line_width = 1 a.axes.label_format = "%-#.1f" a.axes.x_label, a.axes.y_label, a.axes.z_label = "y (km)", "x (km)", "h (km)" mlab.show()
max_mu_q = np.max(np.fabs(s.mu_q_arr)) n_mu_q_arr = s.mu_q_arr / max_mu_q n_std_q_arr = np.sqrt(s.var_q_arr) / max_mu_q import enthought.mayavi.mlab as m f = m.figure(1, size=(1000, 500), fgcolor=(0, 0, 0), bgcolor=(1.0, 1.0, 1.0)) s = m.surf(n_e_arr[1], n_e_arr[2], n_mu_q_arr[0, :, :]) m.axes( s, color=(0.7, 0.7, 0.7), extent=(-1, 1, 0, 1, 0, 1), ranges=(-0.21, 0.21, 0.1, 20, 0, max_mu_q), xlabel="x", ylabel="Lr", zlabel="Force", ) m.view(-60.0, 70.0, focalpoint=[0.0, 0.45, 0.45]) # Store the information view = m.view() roll = m.roll() print "view", view print "roll", roll print n_mu_q_arr.shape[2] ms = s.mlab_source for i in range(1, n_mu_q_arr.shape[0]):
# Draw a box around the cube to aid in the visualization mlab.outline(extent=[ np.min(ras), np.max(ras), np.min(decs), np.max(decs), c_v[slice_min, 1], c_v[slice_max, 1] ], color=(0, 0, 0), line_width=2.0) # Draw a box around it # Now, add some axes ax = mlab.axes(extent=[ np.min(ras), np.max(ras), np.min(decs), np.max(decs), c_v[slice_min, 1], c_v[slice_max, 1] ], nb_labels=3, color=(0, 0, 0)) # Fine tune the look of the axis ax.axes.fly_mode = 'outer_edges' ax.title_text_property.font_size = 10 ax.title_text_property.font_family = 'courier' ax.title_text_property.italic = False ax.label_text_property.font_family = 'courier' ax.label_text_property.italic = False ax.scene.parallel_projection = True ax.scene.background = (1.0, 1.0, 1.0) ax.title_text_property.color = (0, 0, 0) ax.label_text_property.color = (0, 0, 0)
from pylab import * from enthought.mayavi import mlab I = 10 * rand(20, 30) figure(3) hold(False) imshow(I) xlabel(r'first argument of the array, inversed', fontsize=16) ylabel(r'first argument of the array', fontsize=16) hold(True) axis('scaled') title(r'imshow', fontsize=20) draw() # or show() on some machines mlab.figure(1) mlab.surf(I) mlab.axes()
def plot_3d_spectrum_mayavi(fs, fignum=None, vmin=None, vmax=None, pop_ids=None): """ Logarithmic heatmap of single 3d FS. This method relies on MayaVi2's mlab interface. See http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html . To edit plot properties, click leftmost icon in the toolbar. If you get an ImportError upon calling this function, it is likely that you don't have mayavi installed. fs: FS to plot vmin: Values in fs below vmin are masked in plot. vmax: Values in fs above vmax saturate the color spectrum. fignum: Figure number to plot into. If None, a new figure will be created. Note that these are MayaVi figures, which are separate from matplotlib figures. pop_ids: If not None, override pop_ids stored in Spectrum. """ from enthought.mayavi import mlab fig = mlab.figure(fignum, bgcolor=(1,1,1)) mlab.clf(fig) if vmin is None: vmin = fs.min() if vmax is None: vmax = fs.max() # Which entries should I plot? toplot = numpy.logical_not(fs.mask) toplot = numpy.logical_and(toplot, fs.data >= vmin) # For the color mapping normalized = (numpy.log(fs)-numpy.log(vmin))\ /(numpy.log(vmax)-numpy.log(vmin)) normalized = numpy.minimum(normalized, 1) xs,ys,zs = numpy.indices(fs.shape) flat_xs = xs.flatten() flat_ys = ys.flatten() flat_zs = zs.flatten() flat_toplot = toplot.flatten() mlab.barchart(flat_xs[flat_toplot], flat_ys[flat_toplot], flat_zs[flat_toplot], normalized.flatten()[flat_toplot], colormap='hsv', scale_mode='none', lateral_scale=1, figure=fig) if pop_ids is None: if fs.pop_ids is not None: pop_ids = fs.pop_ids else: pop_ids = ['pop0','pop1','pop2'] a = mlab.axes(xlabel=pop_ids[0],ylabel=pop_ids[1],zlabel=pop_ids[2], figure=fig, color=(0,0,0)) a.axes.label_format = "" a.title_text_property.color = (0,0,0) mlab.text3d(fs.sample_sizes[0],fs.sample_sizes[1],fs.sample_sizes[2]+1, '(%i,%i,%i)'%tuple(fs.sample_sizes), scale=0.75, figure=fig, color=(0,0,0)) mlab.view(azimuth=-40, elevation=65, distance='auto', focalpoint='auto') mlab.show()
def pattern_uv(array_ip, u_scan=0, v_scan=0, u_min= -1, u_max=1, u_num=50, v_min= -1, v_max=1, v_num=50, scale="dB", dB_limit= -40, factor="GF", plot_type="rect", mayavi_app=False): r""" Function to evaluate 3D AF/GF/NF of a planar array in uv-domain. By default, this function calculates the gain-factor (GF). :param array_ip: array excitation data in 'Arraytool' input format (see :func:`ip_format`) :param u_scan, v_scan: beam scan position in uv-domain :param u_min, etc: limits of uv-domain :param u_num, v_num: number of points between 'u_min' and 'u_max' including boundaries :param scale: specifies the scale choice ... dB/linear :param dB_limit: cutoff limit (see :func:`cutoff`) :param factor: type of pattern you need ... AF/NF/GF :param plot_type: can be rect/polar ... if False, nothing happens :param mayavi_app: if True, the 3D plot will be opened in the MayaVi application :rtype: A list, [u,v,F] """ x = array_ip[:, 0] y = array_ip[:, 1] z = array_ip[:, 2] A = array_ip[:, 3] # un-packing "array_ip" finished k = 2 * np.pi # (angular) wave-number, which is 2*pi when lambda = 1 u_numj = complex(0, u_num) v_numj = complex(0, v_num) # Making sure all elements in the z-column of the "array_ip" are zeros z_flag = True if ((abs(z) > 0).sum()): print "All elements in the z-column of array input should be zero." z_flag = False # After making sure, proceed to the next level, i.e., evaluate the pattern if(z_flag): [u, v] = np.mgrid[u_min:u_max:u_numj, v_min:v_max:v_numj] u1 = np.reshape(u, (u.size, -1)) v1 = np.reshape(v, (v.size, -1)) A = np.reshape(A, (len(A), -1)) U = np.tile(u1 - u_scan, len(x)) V = np.tile(v1 - v_scan, len(x)) X = np.tile(x, (u.size, 1)) Y = np.tile(y, (u.size, 1)) # Evaluating array-factor of the planar array AF1 = np.dot(np.exp(1j * k * (U * X + V * Y)), A) AF = np.reshape(AF1, u.shape) # Evaluation of F = (AF/GF/NF) => depending upon the user's choice if(factor == "AF"): F = AF; n1 = ""; ff = "Array-Factor "; f1 = "AF " elif(factor == "GF"): P_inc = ((abs(A)) ** 2).sum() GF = AF / np.sqrt(P_inc) # Converting the AF to GF F = GF; n1 = ""; ff = "Gain-Factor "; f1 = "GF " elif(factor == "NF"): norm_fact = (abs(A)).sum() F = AF / norm_fact n1 = "Normalized "; ff = "Factor "; f1 = "NF " # converting 'F' from linear to dB scale, if needed if(scale == "linear"): F_plt = abs(F) ss = "in linear scale" elif(scale == "dB"): F = 20 * np.log10(abs(F)) # cutoff the "F" below some limit ... just for the plotting purpose F_plt = cutoff(F, dB_limit) ss = "in dB scale" # plotting the factor (AF/GF/NF) if(plot_type): if(plot_type == "rect"): # rectangular plot if (mayavi_app): # opens the 3D plot in MayaVi Application mlab.options.backend = 'envisage' plt3d = mlab.surf(u, v, F_plt, warp_scale='auto') ranges1 = [u_min, u_max, v_min, v_max, F_plt.min(), F_plt.max()] mlab.axes(xlabel='u', ylabel='v', zlabel=f1, ranges=ranges1, nb_labels=5) mlab.title(n1 + ff + ss, size=0.35) mlab.colorbar(orientation="vertical", nb_labels=5) plt3d.scene.isometric_view() mlab.show() if(plot_type == "contour"): # contour plot plt.contourf(u, v, F_plt) vs = plt.Circle((0, 0), radius=1, edgecolor='w', fill=False) ax = plt.gca(); ax.add_patch(vs) plt.axis('image'); plt.grid(True) plt.xlabel(r'$u,\ \mathrm{where}\ u=\sin \theta \cos \phi\ \mathrm{in}\ \mathrm{the}\ \mathrm{visible-space}$', fontsize=16) plt.ylabel(r'$v,\ \mathrm{where}\ v=\sin \theta \sin \phi\ \mathrm{in}\ \mathrm{the}\ \mathrm{visible-space}$', fontsize=16) plt.colorbar(format='$%.2f$') plt.show() return u, v, F
#!/usr/bin/env python import numpy as np from enthought.mayavi import mlab x,y=np.ogrid [-2:2:160j,-2:2:160j] z=abs(x)*np.exp(-x**2-(y/.75)**2) pl=mlab.surf(x,y,z,warp_scale=2) mlab.axes(xlabel='x',ylabel='y',zlabel='z') mlab.outline(pl) mlab.show()
if len(iters) > 30000: pointsize = .0003 if len(iters) > 50000: pointsize = .0001 # Again, the axes are adjusting to maximum and minimum values from the array if plotattractor == 1: points3d(np.log10(results[:, 0]), np.log10(results[:, 1]), np.log10(results[:, 2]), iters, color=(0., 0., 0.), scale_factor=pointsize) axes(color=(1., 0., 0.), extent=[ min(np.log10(results[:, 0])), max(np.log10(results[:, 0])), min(np.log10(results[:, 1])), max(np.log10(results[:, 1])), min(np.log10(results[:, 2])), max(np.log10(results[:, 2])) ], ranges=[ min(np.log10(results[:, 0])), max(np.log10(results[:, 0])), min(np.log10(results[:, 1])), max(np.log10(results[:, 1])), min(np.log10(results[:, 2])), max(np.log10(results[:, 2])) ])
scene.scene.background = (1, 1, 1) p = vis.plot_prism_mesh(res, style='surface', xy2ne=True) p.actor.property.line_width = 2 mlab.get_engine().scenes[0].children[-1].children[0].children[0].children[0].scalar_lut_manager.data_range = [0,1200] p = vis.plot_prism_mesh(seeds, style='surface', xy2ne=True) p.actor.property.line_width = 2 mlab.get_engine().scenes[0].children[-1].children[0].children[0].children[0].scalar_lut_manager.data_range = [0,1200] p = vis.plot_prism_mesh(model, style='surface', xy2ne=True) p.actor.property.line_width = 2 p = vis.plot_prism_mesh(mesh.vfilter(model,1100,1201), style='wireframe', xy2ne=True) p.actor.property.color = (0,0,0) p.actor.property.line_width = 3 mlab.outline(color=(0,0,0), extent=extent) a = mlab.axes(p, nb_labels=5, extent=extent, ranges=ranges, color=(0,0,0)) a.label_text_property.color = (0,0,0) a.title_text_property.color = (0,0,0) a.property.line_width = 1 a.axes.label_format = "%-#.1f" a.axes.x_label, a.axes.y_label, a.axes.z_label = "Y (km)", "X (km)", "Z (km)" view.bbox(mlab) view.set(scene) mlab.show()
'value':-1000}) model.append({'x1':4000, 'x2':4500, 'y1':500, 'y2':1500, 'z1':300, 'z2':1000, 'value':-1000}) model.append({'x1':1800, 'x2':3700, 'y1':500, 'y2':1500, 'z1':800, 'z2':1300, 'value':-1000}) model.append({'x1':500, 'x2':4500, 'y1':4000, 'y2':4500, 'z1':500, 'z2':1000, 'value':-1000}) model = numpy.array(model) extent = [0,5000,0,5000,-1500,0] # Show the model before calculating to make sure it's right fig = mlab.figure() fig.scene.background = (1, 1, 1) plot = vis.plot_prism_mesh(model, style='surface', xy2ne=True) axes = mlab.axes(plot, nb_labels=5, extent=extent, color=(0,0,0)) axes.label_text_property.color = (0,0,0) axes.title_text_property.color = (0,0,0) axes.axes.label_format = "%-#.0f" mlab.outline(color=(0,0,0), extent=extent) mlab.show() # Now calculate all the components of the gradient tensor fields = ['gyy', 'gyz', 'gzz'] error = 0.5 data = {} for i, field in enumerate(fields): data[field] = synthetic.from_prisms(model, x1=0, x2=5000, y1=0, y2=5000, nx=25, ny=25, height=150, field=field) data[field]['value'], error = utils.contaminate(data[field]['value'], stddev=error,
import numpy as np from enthought.mayavi import mlab x, y = np.ogrid[-2:2:20j, -2:2:20j] z = x * np.exp(-x**2 - y**2) pl = mlab.surf(x, y, z, warp_scale='auto') mlab.axes(xlabel='x', ylabel='y', zlabel='z') mlab.outline(pl)
prisms.append( geometry.prism(x1=1500, x2=4500, y1=2500, y2=3000, z1=100, z2=500, props={'value': 1500})) prisms = numpy.array(prisms) # Show the model before calculating to make sure it's right fig = mlab.figure() fig.scene.background = (1, 1, 1) dataset = vis.plot_prism_mesh(prisms, style='surface', label='Density kg/cm^3') axes = mlab.axes(dataset, nb_labels=5, extent=[0, 5000, 0, 5000, -1000, 0]) mlab.show() # Pickle the model so that it can be shown next to the inversion result later modelfile = open('model.pickle', 'w') pickle.dump(prisms, modelfile) modelfile.close() # Calculate all the components of the gradient tensor error = 2 pylab.figure(figsize=(16, 8)) pylab.suptitle(r'Synthetic FTG data with %g $E\"otv\"os$ noise' % (error), fontsize=16) pylab.subplots_adjust(wspace=0.4, hspace=0.3)
surf3 = mlab.contour3d(x,y,z,scidata_cleana,contours=[40],\ opacity=1, colormap='Blues', name='[O III]-2') surf5 = mlab.contour3d(x_b,y_b,z_b,scidata_cleanb,contours=[10],\ opacity=0.1,colormap='autumn', name='Hbeta') surf6 = mlab.points3d((stars[:, 0] - size_x / 2) * 0.5 * astopc, (stars[:, 1] - size_y / 2.) * 0.5 * astopc, stars[:, 0] * 0.0, stars[:, 2] * 0.5 * astopc * 2, color=(0, 0, 0), scale_factor=1, name='Stars') # Now to make it look decent ... ax = mlab.axes(extent=[-10, 10, -12, 12, -7, 7], nb_labels=5) ax.axes.fly_mode = 'outer_edges' ax.title_text_property.font_size = 10 ax.title_text_property.font_family = 'courier' ax.label_text_property.font_family = 'courier' # And a bit of references if anyone is interested ... mlab.text( 0.05, 0.95, 'Oxygen-rich ejecta in SNR N132D. Vogt & Dopita, Ap&SS, 311, 521 (2011); Vogt & Shingles, Ap&SS (2013), submitted.', width=0.75) mlab.text(0.05, 0.05, '*****@*****.**', width=0.25) # Label the axes ... ax.axes.x_label = 'X (Dec.) [pc]'
sigma = 10.0 r = 28.0 b = 8.0/3.0 # Initial conditions x = -.5 y = .2 z = 2.17 # Store the trajectory TrajX = [] TrajY = [] TrajZ = [] Time = [] # Integrate the Lorenz ODEs # for t in arange(0.,250.,dt): dxdt = sigma*(y - x) dydt = r * x - y - x * z dzdt = x * y - b * z x = x + dxdt * dt y = y + dydt * dt z = z + dzdt * dt TrajX.append(x) TrajY.append(y) TrajZ.append(z) Time.append(t) plot3d(TrajX,TrajY,TrajZ,Time,colormap='Spectral',tube_radius=0.1) axes(color=(0.,0.,0.),extent=[-15.0,15.0,-15.0,15.0,0.0,50.0],ranges=[-15.0,15.0,-15.0,15.0,0.0,50.0])