def main(argv=None): """docstring for main""" from enthought.mayavi import mlab if argv is None: argv = sys.argv x1 = x2 = y1 = y2 = 0 fname = '' try: fname = argv[1] x1, x2, y1, y2 = [int(i) for i in argv[2:]] except: print('Usage: {0} fname x1 x2 y1 y2'.format(argv[0])) print(x1, x2, y1, y2) ds = gdal.Open(fname) band = ds.GetRasterBand(1) STORED_VALUE = band.ReadAsArray(x1, y1, x2 - x1, y2 - y1) ds = 0 # PDS label infos: SCALING_FACTOR = 0.25 OFFSET = -8000 topo = (STORED_VALUE * SCALING_FACTOR) + OFFSET mlab.surf(topo, warp_scale=1 / 115., vmin=1700) mlab.colorbar(orientation='vertical', title='Height [m]', label_fmt='%4.0f') mlab.show()
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 main(argv=None): """docstring for main""" from enthought.mayavi import mlab if argv is None: argv = sys.argv x1 = x2 = y1 = y2 = 0 fname = "" try: fname = argv[1] x1, x2, y1, y2 = [int(i) for i in argv[2:]] except: print("Usage: {0} fname x1 x2 y1 y2".format(argv[0])) print(x1, x2, y1, y2) ds = gdal.Open(fname) band = ds.GetRasterBand(1) STORED_VALUE = band.ReadAsArray(x1, y1, x2 - x1, y2 - y1) ds = 0 # PDS label infos: SCALING_FACTOR = 0.25 OFFSET = -8000 topo = (STORED_VALUE * SCALING_FACTOR) + OFFSET mlab.surf(topo, warp_scale=1 / 115.0, vmin=1700) mlab.colorbar(orientation="vertical", title="Height [m]", label_fmt="%4.0f") mlab.show()
def mlab3Dview(): e_arr = orthogonalize([x, w]) n_e_arr = [ e / np.max(np.fabs(e)) for e in e_arr ] n_mu_q_arr = mu_q_arr / np.max(np.fabs(mu_q_arr)) m.surf(n_e_arr[0], n_e_arr[1], n_mu_q_arr) m.show()
def add_map(colormap='Accent', opacity=1): "Adds the land/water mask to the 3d mask as a basemap." # The maximum x and y values are equal to the number of rows and columns, # respectively, in the mask raster. This is done to make the map line up with # the scalar density field. mlab.surf(d.root.unmasked[:].astype('float'), extent=[0,d.root.unmasked.shape[0],0,d.root.unmasked.shape[1],0,1], colormap=colormap, opacity=opacity)
def add_mean(color=(.9,0,.3), opacity=.3): "Adds the mean to the map as a 3d surface." mlab.surf(d.root.mean[:], # The maximum x and y values are equal to the number of rows and columns, # respectively, in the mask raster. The maximum z value is equal to the # number of bins in the density field. This is done to make the surface line # up with the scalar density field. extent=[0,d.root.unmasked.shape[0],0,d.root.unmasked.shape[1],0,d.root.density_field.shape[-1]*d.root.mean[:].max()], color=color, # colormap='Accent', opacity=opacity)
def test_colorbar(self): """ Test that when an object with scalars hidden is created, it does not get a colorbar, unless no other is avalaible. """ a = np.random.random((5, 5)) s1 = mlab.surf(a, colormap='gist_earth') s2 = mlab.surf(a, color=(0, 0, 0)) mlab.colorbar() self.assertEqual(s2.module_manager.scalar_lut_manager.show_scalar_bar, False) self.assertEqual(s1.module_manager.scalar_lut_manager.show_scalar_bar, True)
def test_colorbar(self): """ Test that when an object with scalars hidden is created, it does not get a colorbar, unless no other is avalaible. """ a = np.random.random((5, 5)) s1 = mlab.surf(a, colormap='gist_earth') s2 = mlab.surf(a, color=(0, 0, 0)) mlab.colorbar() self.assertEqual( s2.module_manager.scalar_lut_manager.show_scalar_bar, False) self.assertEqual( s1.module_manager.scalar_lut_manager.show_scalar_bar, True)
def plotsquare3d(us): from enthought.mayavi.mlab import surf, show, colorbar, xlabel, ylabel, figure for u in us: figure() Np = 60 points = uniformsquarepoints(Np) x = points[:,0].reshape(Np,Np) y = points[:,1].reshape(Np,Np) up = np.real(u(points)) surf(x,y, up.reshape(Np,Np)) colorbar() xlabel('x') ylabel('y') show()
def surface(fcm, idx0, idx1): """Plots a surface plot for 2D data.""" x = fcm[:, idx0] y = fcm[:, idx1] bins = int(numpy.sqrt(len(x))) z, xedge, yedge = numpy.histogram2d(y, x, bins=[bins, bins], range=[(numpy.min(y), numpy.max(y)), (numpy.min(x), numpy.max(x))] ) mlab.figure() mlab.surf(xedge, yedge, z, warp_scale='auto') mlab.xlabel(fcm.channels[idx0]) mlab.ylabel(fcm.channels[idx1]) mlab.zlabel('Density')
def plotframe(frameno,level=1, water_opacity=1.): plotdata = ClawPlotData() plotdata.outdir = outdir print "Plotting solution from ",plotdata.outdir plotdata = setplot(plotdata) try: frame = plotdata.getframe(frameno) except: print "Unable to get frame" return mlab.figure(1,bgcolor=(1,1,1),size=(700,600)) mlab.clf() for grid in frame.grids: if grid.level == level: y = grid.c_center[1] x = grid.c_center[0] q = grid.q eta = q[:,:,3] h = q[:,:,0] topo = eta - h cutoff = 0.5 #cutoff2 = -500. shift = 0. scale = 1. topo1 = scale*where(topo<cutoff, topo-shift, cutoff-shift) #topo1 = scale*where(topo>cutoff2, topo1, nan) eta1 = scale*where(eta<cutoff, eta-shift, cutoff-shift) water1 = where(h>=1.e-3, eta1, nan) scale = 12. #mlab.mesh(x,y,topo1,colormap='Greens',vmin=-1.0, vmax=0.8) #mlab.mesh(x,y,water1,colormap='Blues',vmin=-0.8, vmax=0.8) mlab.surf(x,y,topo1,colormap='YlGn',warp_scale=scale,\ vmin=-0.3,vmax=0.3) mlab.surf(x,y,water1,colormap='Blues',warp_scale=scale,\ vmin=-0.2,vmax=0.3, opacity=water_opacity) # set the view: (Do V = view() to figure out the current view) V = (29.157490879985176,\ 67.560491214404507,\ 79.798910042690324,\ array([ 0. , 1. , -0.07500005])) mlab.view(*V) t = frame.t mlab.title('Time = %5.2f' % t,color=(0,0,0),height=0.1,size=0.5)
def surface(fcm, idx0, idx1): """Plots a surface plot for 2D data.""" x = fcm[:, idx0] y = fcm[:, idx1] bins = int(numpy.sqrt(len(x))) z, xedge, yedge = numpy.histogram2d(y, x, bins=[bins, bins], range=[(numpy.min(y), numpy.max(y)), (numpy.min(x), numpy.max(x))]) mlab.figure() mlab.surf(xedge, yedge, z, warp_scale='auto') mlab.xlabel(fcm.channels[idx0]) mlab.ylabel(fcm.channels[idx1]) mlab.zlabel('Density')
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 testVerticalSurface(): import pylab, numpy pylab.clf() no_of_phenotypes = 5 x, y = numpy.mgrid[ 0:2 * no_of_phenotypes:1, 0:10: 1] #added a gap of 1 column between two phenotypes. one phenotype occupies two rows & two columns. #remove the gap in x & y needed_index_ls = [0, 5] #for i in [0, 5]: # for j in range(no_of_phenotypes): # needed_index_ls.append(no_of_phenotypes*i+j) #for i in range(0, no_of_phenotypes): # needed_index_ls.append(2*i) #needed_index_ls.append(3*i+1) #y[3*i+1][1]=2 x = x[:, needed_index_ls] y = y[:, needed_index_ls] enrichment_matrix = numpy.ones(x.shape, numpy.float) enrichment_matrix[:, :] = 10 enrichment_matrix[0, 0] = 3 from enthought.mayavi import mlab mlab.clf() #from palos.yh_mayavi import customBarchart bar = customBarchart(x, y, enrichment_matrix, x_scale=0.9, y_scale=4.5, opacity=1, mode='cube', color=(0, 1, 0), scale_factor=1.0) """ #mlab.ylabel("KW") #mlab.xlabel("Emma") #mlab.zlabel("Enrichment Ratio") from palos.DrawMatrix import get_font font = get_font() for i in range(len(xlabel_ls)): label = xlabel_ls[i] char_width, char_height = font.getsize(label) #W is the the biggest(widest) mlab.text(2*i, 0, label, z=0, width=char_width/1500.) #min(0.0075*len(label), 0.04)) """ s = numpy.zeros(x.shape, numpy.int) #s[0,1]=0.5 surf = mlab.surf(x, y, s, opacity=0.6, extent=[-1, 2 * no_of_phenotypes, -1, 10, 0.0, 0.0]) mlab.show()
def gsurf(): """Test contour_surf on regularly spaced co-ordinates like MayaVi.""" def f(x, y): return x**2+y**2 - 25. x, y = numpy.mgrid[-10.:10.:0.25, -10.:10.0:0.25] s = surf(x, y, f, warp_scale = 0.) colorbar(s,orientation='horizontal') return s
def plotframe(frameno,level=1, water_opacity=1.): plotdata = ClawPlotData() plotdata.outdir = outdir print "Plotting solution from ",plotdata.outdir plotdata = setplot(plotdata) try: frame = plotdata.getframe(frameno) except: print "Unable to get frame" return mlab.figure(1,bgcolor=(1,1,1),size=(700,600)) mlab.clf() for grid in frame.grids: if grid.level == level: y = grid.c_center[1] x = grid.c_center[0] q = grid.q eta = q[:,:,3] h = q[:,:,0] topo = eta - h cutoff = 100. #cutoff2 = -500. shift = 0. scale = 1. topo1 = scale*where(topo<cutoff, topo-shift, cutoff-shift) #topo1 = scale*where(topo>cutoff2, topo1, nan) eta1 = scale*where(eta<cutoff, eta-shift, cutoff-shift) water1 = where(h>=1.e-3, eta1, nan) scale = 10. #mlab.mesh(x,y,topo1,colormap='Greens',vmin=-1.0, vmax=0.8) #mlab.mesh(x,y,water1,colormap='Blues',vmin=-0.8, vmax=0.8) if 0: mlab.surf(x,y,topo1,colormap='YlGn',warp_scale=scale,\ vmin=-0.3,vmax=0.3) mlab.surf(x,y,water1,colormap='Blues',warp_scale=scale,\ vmin=-0.2,vmax=0.3, opacity=water_opacity) # set the view: (Do V = view() to figure out the current view) #mlab.view(*V) t = frame.t
def do(self): ############################################################ # Imports. from enthought.mayavi import mlab ############################################################ # Create a new scene and set up the visualization. s = self.new_scene() ############################################################ # run all the "test_foobar" functions in the mlab module. for name, func in getmembers(mlab): if not callable(func) or not name[:4] in ('test', 'Test'): continue mlab.clf() func() # Mayavi has become too fast: the operator cannot see if the # Test function was succesful. sleep(0.1) ############################################################ # Test some specific corner-cases import numpy x, y, z = numpy.mgrid[1:10, 1:10, 1:10] u, v, w = numpy.mgrid[1:10, 1:10, 1:10] s = numpy.sqrt(u**2 + v**2) mlab.clf() # Test the extra argument "scalars" mlab.quiver3d(x, y, z, u, v, w, scalars=s) # Test surf with strange-shaped inputs X, Y = numpy.ogrid[-10:10, -10:10] Z = X**2 + Y**2 mlab.surf(X, Y, Z) mlab.surf(X.ravel(), Y.ravel(), Z) x, y, z = numpy.mgrid[-10:10, -10:10, -3:2] mlab.flow(x, y, z) # Test glyphs with number-only coordinnates mlab.points3d(0, 0, 0, resolution=50)
def add_quantiles(quantiles=[.25, .5, .75], colors=None, opacities = None): """ Adds the given quantiles to the map as 3d surfaces. Colors and opacities can be set individually. """ # Default color and opacity values. if colors is None: colors = [(.9,0,.3)]*len(quantiles) if opacities is None: opacities = [.3]*len(quantiles) # Get the empirical CDF of each pixel. cu_data = np.cumsum(d.root.density_field[:], axis=-1) cu_data /= cu_data.max() for quantile,color,opacity in zip(quantiles,colors,opacities): # Compute the actual quantile surface. # FIXME: Use histogram_finalize for speed s = np.zeros(d.root.unmasked.shape) for i in xrange(cu_data.shape[0]): for j in xrange(cu_data.shape[1]): for k in xrange(cu_data.shape[2]): if cu_data[i,j,k]>quantile: s[i,j] = k break # Normalize s /= cu_data.shape[2] mlab.surf(s, # The maximum x and y values are equal to the number of rows and columns, # respectively, in the mask raster. The maximum z value is equal to the # number of bins in the density field. This is done to make the surface line # up with the scalar density field. extent=[0,d.root.unmasked.shape[0],0,d.root.unmasked.shape[1],0,d.root.density_field.shape[-1]*s.max()], color=color, # colormap='Accent', opacity=opacity)
def plot_wireframe(self, lib): """ plot the fin wireframe """ #lib = 'mayavi' #Filter to lower resolution xfilter = arange(0,len(self.x_axis),len(self.x_axis)/1) yfilter = arange(0,len(self.y_axis),len(self.y_axis)/1) x = self.x_axis[xfilter] y = self.y_axis[yfilter] z = self.surf[xfilter,:] z = z[:,yfilter] if lib == 'gnuplot': import Gnuplot z[isnan(z)] = 5 g = Gnuplot.Gnuplot() g.splot(Gnuplot.GridData(z, x, y, binary=0)) raw_input('Please press return to continue...\n') elif lib == 'matplotlib': import mpl_toolkits.mplot3d.axes3d as p3 fig=plt.figure(3) ax = p3.Axes3D(fig) x2 = zeros((100,100)) x2[:,:]=x[:] y2 = zeros((100,100)) y2[:,:]=y[:] ax.plot_wireframe(x2, y2.transpose(), z.transpose()) elif lib == 'mayavi': from enthought.mayavi.mlab import surf z[isnan(z)] = 0 surf(x, y, z)
def test_surf(): """Test surf on regularly spaced co-ordinates like MayaVi.""" def f(x, y): omega = numpy.sqrt(10.) sinh, cosh = numpy.sinh, numpy.cosh resp = numpy.zeros_like(x) resp[x<1.55] = cosh(omega*x[x<1.55])/cosh(omega*1.55) resp[x>=1.55] = cosh(-omega*(x[x>=1.55]-3.1))/cosh(omega*1.55) return resp x, y = numpy.mgrid[0.:3.1:100j, 0.:2.1:2j] s = surf(x, y, f) #, warp_scale = 0.05) #cs = contour_surf(x, y, f, contour_z=0) return s
def main(): planner = Planner() rospy.init_node('harlie_obstacle_planner') rospy.Subscriber("/odom", Odometry, setRobotPose,planner) rospy.Subscriber("/move_base/global_costmap/inflated_obstacles", GridCells, setObstacles,planner) rate = rospy.client.Rate(.1) while not rospy.is_shutdown(): print time.time() goal = planner.runUpdatePlanner() if goal: sendGoal(goal) #Show some data FUL=120 data=split(planner.FullCost,planner.robot.x-FUL,planner.robot.y-FUL,planner.robot.x+FUL,planner.robot.y+FUL) l = mlab.surf(data) #mlab.show() rate.sleep()
def testVerticalSurface(): import pylab, numpy pylab.clf() no_of_phenotypes = 5 x, y = numpy.mgrid[0:2*no_of_phenotypes:1, 0:10:1] #added a gap of 1 column between two phenotypes. one phenotype occupies two rows & two columns. #remove the gap in x & y needed_index_ls = [0,5] #for i in [0, 5]: # for j in xrange(no_of_phenotypes): # needed_index_ls.append(no_of_phenotypes*i+j) #for i in range(0, no_of_phenotypes): # needed_index_ls.append(2*i) #needed_index_ls.append(3*i+1) #y[3*i+1][1]=2 x = x[:, needed_index_ls] y = y[:, needed_index_ls] enrichment_matrix = numpy.ones(x.shape, numpy.float) enrichment_matrix[:,:] =10 enrichment_matrix[0,0]=3 from enthought.mayavi import mlab mlab.clf() from pymodule.yh_mayavi import customBarchart bar = customBarchart(x, y , enrichment_matrix, y_scale=4.5, opacity=1, mode='cube', color=(0,1,0), scale_factor=1.0, x_scale=0.9) """ #mlab.ylabel("KW") #mlab.xlabel("Emma") #mlab.zlabel("Enrichment Ratio") from pymodule.DrawMatrix import get_font font = get_font() for i in range(len(xlabel_ls)): label = xlabel_ls[i] char_width, char_height = font.getsize(label) #W is the the biggest(widest) mlab.text(2*i, 0, label, z=0, width=char_width/1500.) #min(0.0075*len(label), 0.04)) """ s = numpy.zeros(x.shape, numpy.int) #s[0,1]=0.5 surf = mlab.surf(x, y, s, opacity=0.6, extent=[-1, 2*no_of_phenotypes, -1, 10, 0.0,0.0]) mlab.show()
def plot3dtraj (self, behavior = 'landing', fig = 1, stim = 1): # initialize 3d plot: #f = mlab.figure(fig) # plot the stimulus if stim: radius = self.stimulus.radius post_height = self.stimulus.center[2] post_bottom = -.1 step = 0.0005 x, y = np.mgrid[-1*radius-step:radius+step:step, -1*radius-step:radius+step:step] z = x*0 for i in range(x.shape[0]): for j in range(y.shape[1]): if (x[i,j]**2 + y[i,j]**2) < radius**2: z[i,j] = post_height else: z[i,j] = post_bottom s = mlab.surf(x, y, z, color=(0.01,0.01,0.01) ) if 1: # find max speed for normalizing colors max_speed = 0 for k,v in self.trajecs.items(): if self.trajecs[k].behavior is behavior: max_speed_tmp = self.trajecs[k].speed.max() if max_speed_tmp > max_speed: max_speed = max_speed_tmp # plot trajectories of chosen behavior for k,v in self.trajecs.items(): if self.trajecs[k].behavior is behavior: colors = self.trajecs[k].speed / max_speed x = self.trajecs[k].positions[:,0] y = self.trajecs[k].positions[:,1] z = self.trajecs[k].positions[:,2] mlab.points3d(x, y, z, colors, colormap="jet", scale_mode='none') print "REMEMBER TO RUN IPYTHON USING --WTHREAD"
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 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(): planner = Planner() rospy.init_node('harlie_obstacle_planner') rospy.Subscriber("/odom", Odometry, setRobotPose, planner) rospy.Subscriber("/move_base/global_costmap/inflated_obstacles", GridCells, setObstacles, planner) rate = rospy.client.Rate(.1) while not rospy.is_shutdown(): print time.time() goal = planner.runUpdatePlanner() if goal: sendGoal(goal) #Show some data FUL = 120 data = split(planner.FullCost, planner.robot.x - FUL, planner.robot.y - FUL, planner.robot.x + FUL, planner.robot.y + FUL) l = mlab.surf(data) #mlab.show() rate.sleep()
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 show(self): """show Vm in a graph. Works for 1D projects only""" if self.Vm.ndim == 2: pylab.imshow(self.Vm,aspect='auto',cmap=cm.jet) pylab.show() elif self.Vm.ndim == 3: s = mlab.surf(self.Vm[...,0]) raw_input("Press Enter to lauch the simulation...") for i in range(self.Vm.shape[-1]): s.mlab_source.scalars = self.Vm[...,i] elif self.Vm.ndim == 4: p = mlab.pipeline.scalar_field(self.Vm[...,0]) s = mlab.pipeline.image_plane_widget( p, plane_orientation='x_axes', slice_index=self.mdl.stimCoord[0], vmin = self.Vm.min(), vmax = self.Vm.max() ) s2 = mlab.pipeline.image_plane_widget(p, plane_orientation='y_axes', slice_index=self.mdl.stimCoord[2], vmin = self.Vm.min(), vmax = self.Vm.max() ) s3 = mlab.pipeline.image_plane_widget( p, plane_orientation='z_axes', slice_index=self.mdl.stimCoord[4], vmin = self.Vm.min(), vmax = self.Vm.max() ) mlab.scalarbar(s,orientation='vertical',nb_labels=4,label_fmt='%.3f') mlab.outline(color=(1,1,1)) raw_input("Press Enter to lauch the simulation...") for i in range(self.Vm.shape[-1]): p.mlab_source.scalars = self.Vm[...,i]
# -*- coding: utf-8 -*- from enthought.mayavi import mlab import numpy as np x, y = np.ogrid[-10:10:100j, -1:1:100j] z = np.sin(5 * ((x / 10)**2 + y**2)) mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) mlab.surf(x, y, z) mlab.axes() mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) mlab.surf(x, y, z, extent=(-1, 1, -1, 1, -0.5, 0.5)) mlab.axes(nb_labels=5) mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) mlab.surf(x, y, z, extent=(-1, 1, -1, 1, -0.5, 0.5)) mlab.axes(ranges=(x.min(), x.max(), y.min(), y.max(), z.min(), z.max()), nb_labels=5) mlab.show()
def show(self): """Test contour_surf on regularly spaced co-ordinates like MayaVi.""" x, y = self.out_grid s = surf(x, y, self.scalars, warp_scale = 0.5) colorbar(s) return s
#!//usr/bin/env python import math from enthought.mayavi import mlab Zs, Xs, Ys = [], [], [] for p in range(360): for t in range(180): phi = p * math.pi / 180. theta = t * math.pi / 180. Xs.append(math.sin(phi) * math.cos(theta)) Ys.append(math.cos(phi)) Zs.append(math.sin(phi) * math.sin(theta)) s = mlab.surf(Xs, Ys, Zs) mlab.show() raw_input()
colormap, but we modify add to add a transparency effect. Notice in the resulting image how the surface becomes more transparent for its lower points. """ # Create some data import numpy as np x, y = np.mgrid[-10:10:200j, -10:10:200j] z = 100 * np.sin(x * y) / (x * y) # Visualize it with mlab.surf from enthought.mayavi import mlab mlab.figure(bgcolor=(1, 1, 1)) surf = mlab.surf(z, colormap='cool') # Retrieve the LUT of the surf object. lut = surf.module_manager.scalar_lut_manager.lut.table.to_array() # The lut is a 255x4 array, with the columns representing RGBA # (red, green, blue, alpha) coded with integers going from 0 to 255. # We modify the alpha channel to add a transparency gradient lut[:, -1] = np.linspace(0, 255, 256) # and finally we put this LUT back in the surface object. We could have # added any 255*4 array rather than modifying an existing LUT. surf.module_manager.scalar_lut_manager.lut.table = lut # We need to force update of the figure now that we have changed the LUT. mlab.draw()
# 菱形平均分两步,分别计算水平和垂直方向上的点 t = a[::s2, s::s2] t[...] = buf[:, :-1] + buf[:, 1:] t[:-1] += tmp t[1:] += tmp t[[0, -1], :] /= 3 # 边上是3个值的平均 t[1:-1, :] /= 4 # 中间的是4个值的平均 t[...] += np.random.normal(0, scale, t.shape) t = a[s::s2, ::s2] t[...] = buf[:-1, :] + buf[1:, :] t[:, :-1] += tmp t[:, 1:] += tmp t[:, [0, -1]] /= 3 t[:, 1:-1] /= 4 t[...] += np.random.normal(0, scale, t.shape) scale *= d return a if __name__ == "__main__": from enthought.mayavi import mlab from scipy.ndimage.filters import convolve a = hill2d_ds(8, 0.5) a /= np.ptp(a) / (0.5 * 2**8) a = convolve(a, np.ones((3, 3)) / 9.0) mlab.surf(a) mlab.show()
# -*- coding: utf-8 -*- """ Created on Wed Jul 20 22:27:33 2016 @author: liuxiangyu """ 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) mlab.show()
#!/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()
# -*- coding: utf-8 -*- """ Created on Sun Oct 17 22:10:35 2010 @author: - """ import numpy from enthought.mayavi import mlab x, y = numpy.mgrid[0:3:1, 0:3:1] s = mlab.surf(x, y, numpy.asarray(x * 0.1, 'd')) # for i in range(10): s.mlab_source.scalars = numpy.asarray(x * 0.1 * (i + 1), 'd') # # Produce some nice data. n_mer, n_long = 6, 11 pi = numpy.pi dphi = pi / 1000.0 phi = numpy.arange(0.0, 2 * pi + 0.5 * dphi, dphi, 'd') mu = phi * n_mer x = numpy.cos(mu) * (1 + numpy.cos(n_long * mu / n_mer) * 0.5) y = numpy.sin(mu) * (1 + numpy.cos(n_long * mu / n_mer) * 0.5) z = numpy.sin(n_long * mu / n_mer) * 0.5 # View it. l = mlab.plot3d(x, y, z, numpy.sin(mu), tube_radius=0.025, colormap='Spectral') # Now animate the data. ms = l.mlab_source for i in range(10):
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)
import sys from enthought.mayavi import mlab import numpy as np for i in sys.argv: print i if (len(sys.argv)>3): # read xsm data filename=sys.argv[3] f=open(filename) header = f.readline() nx,ny = header.split()[2].split('x') nx = int(nx) ny = int(ny) print "nx : "+str(nx) print "ny : "+str(ny) read_data = np.fromfile(file=f, dtype=np.float32).reshape((nx,ny)) f.close() # 3D visualization of data: #[x,y]=np.mgrid[0:1.0:1.0/nx,0:1.0:1.0/ny] mlab.figure(size=(400, 300)) mlab.surf(read_data, warp_scale='auto') mlab.show() else: print "You must provide data filename" print "usage: mayavi2 -x heat.py filename"
bgcolor=(0.5, 0.5, 0.5)) mlab.clf() cat1 = cat(x, y, 1) 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)
import pylab as py def func(x, y): return (x + y) * np.exp(-5.0 * (x**2 + y**2)) x, y = np.mgrid[-1:1:15j, -1:1:15j] fvals = func(x, y) newfunc = interpolate.interp2d(x, y, fvals, kind='cubic') # Notice that we evaluate on new 1-d arrays xnew = np.linspace(-1, 1, 100) ynew = xnew # Return the cross product fnew = newfunc(xnew, ynew) py.figure(1) py.clf() py.imshow(fnew, extent=[-1, 1, -1, 1], cmap=py.cm.jet) from enthought.mayavi import mlab # Need fully-fleshed out grid for surf x2, y2 = np.mgrid[-1:1:100j, -1:1:100j] mlab.clf() mlab.surf(x2, y2, fnew * 2)
opener = urllib.urlopen( 'http://staging.enthought.com/projects/mayavi/N36W113.hgt.zip' #'ftp://e0srp01u.ecs.nasa.gov/srtm/version2/SRTM1/Region_04/N36W113.hgt.zip' ) open('N36W113.hgt.zip', 'w').write(opener.read()) # Load the data (signed 2 byte integers, big endian) ########################### import zipfile import numpy as np data = np.fromstring( zipfile.ZipFile('N36W113.hgt.zip').read('N36W113.hgt'), '>i2') data.shape = (3601, 3601) data = data.astype(np.float32) # Plot an interesting section ################################################## from enthought.mayavi import mlab data = data[:1000, 900:1900] # Convert missing values into something more sensible. data[data == -32768] = data[data > 0].min() mlab.figure(size=(400, 320), bgcolor=(0.16, 0.28, 0.46)) mlab.surf(data, colormap='gist_earth', warp_scale=0.2, vmin=1200, vmax=1610) # The data takes a lot of memory, and the surf command has created a # copy. We free the inital memory. del data # A view of the canyon mlab.view(-5.9, 83, 570, [5.3, 20, 238]) mlab.show()
import numpy as np x, y = np.mgrid[-10:10:100j, -10:10:100j] r = np.sqrt(x**2 + y**2) z = np.sin(r) / r from enthought.mayavi import mlab mlab.surf(z, warp_scale='auto') mlab.outline() mlab.axes()
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
ns = data.shape[1] ne = data.shape[2] nz = data.shape[3] f = mlab.figure(size=(600, 600)) # Tell visual to use this as the viewer. visual.set_viewer(f) # First way s1 = contour_surf(data[0, :, :, 10] + 0.1, contours=30, line_width=0.5, transparent=True) s = surf(data[0, :, :, 10] + 0.1, colormap="Spectral" ) # , warp_scale='.1')#, representation='wireframe') # second way # x, y= mgrid[0:ns:1, 0:ne:1] # s = mesh(x,y,data[0,:,:,10], colormap='Spectral')#, warp_scale='auto') # #, representation='wireframe') s.enable_contours = True s.contour.filled_contours = True # # x, y, z= mgrid[0:ns:1, 0:ne:1, 0:nz:1] # # p=plot3d(x,y,z,data[10,:,:,:], tube_radius=0.025, colormap='Spectral') # p=points3d(x,y,z,data[10,:,:,:], colormap='Spectral') #
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()
def test_solve_minimal_surface_optimization_problem_with_projected_gradients(): """ This is a minimal surface problem, discretized on a regular mesh with box constraints using projected gradients. The necessary gradient is computed with adolc. """ def projected_gradients(x0, ffcn,dffcn, box_constraints, beta = 0.5, delta = 10**-3, epsilon = 10**-2, max_iter = 1000, line_search_max_iter = 100): """ INPUT: box_constraints [L,U], where L (resp. U) vector or matrix with the lower (resp. upper) bounds """ x = x0.copy() L = numpy.array(box_constraints[0]) U = numpy.array(box_constraints[1]) def pgn(s): a = 1.* (x>L) b = 1.*(abs(x-L) <0.00001) c = 1.*(s>0) d = numpy.where( a + (b*c)) return numpy.sum(s[d]) def P(x, s, alpha): x_alpha = x + alpha * s a = x_alpha-L b = U - x_alpha return x_alpha - 1.*(a<0) * a + b * 1. * (b<0) s = - dffcn(x) k = 0 while pgn(s)>epsilon and k<= max_iter: k +=1 s = - dffcn(x) for m in range(line_search_max_iter): #print 'm=',m alpha = beta**m x_alpha = P(x,s,alpha) if ffcn( x_alpha ) - ffcn(x) <= - delta * numpy.sum(s* (x_alpha - x)): break x_old = x.copy() x = x_alpha return x_old,s def O_tilde(u): """ this is the objective function""" M = numpy.shape(u)[0] h = 1./(M-1) return M**2*h**2 + numpy.sum(0.25*( (u[1:,1:] - u[0:-1,0:-1])**2 + (u[1:,0:-1] - u[0:-1, 1:])**2)) # INITIAL VALUES M = 20 h = 1./M u = numpy.zeros((M,M),dtype=float) u[0,:]= [numpy.sin(numpy.pi*j*h/2.) for j in range(M)] u[-1,:] = [ numpy.exp(numpy.pi/2) * numpy.sin(numpy.pi * j * h / 2.) for j in range(M)] u[:,0]= 0 u[:,-1]= [ numpy.exp(i*h*numpy.pi/2.) for i in range(M)] # tape the function evaluation trace_on(1) au = adouble(u) independent(au) ay = O_tilde(au) dependent(ay) trace_off() def dO_tilde(u): ru = numpy.ravel(u) rg = gradient(1,ru) g = numpy.reshape(rg, numpy.shape(u)) # on the edge the analytical solution is fixed to zero g[:,0] = 0 g[0,:] = 0 g[:,-1] = 0 g[-1,:] = 0 return g # X AND Y PARTITION x_grid = numpy.linspace(0,1,M) y_grid = numpy.linspace(0,1,M) # BOX CONSTRAINTS lo = 2.5 L = numpy.zeros((M,M),dtype=float) for n in range(M): for m in range(M): L[n,m] = 2.5 * ( (x_grid[n]-0.5)**2 + (y_grid[m]-0.5)**2 <= 1./16) U = 100*numpy.ones((M,M),dtype=float) Z,s = projected_gradients(u,O_tilde,dO_tilde,[L,U]) # THIS CODE BELOW ONLY WORKS FOR MATPLOTLIB 0.91X try: import pylab import matplotlib.axes3d as p3 x = y = range(numpy.shape(Z)[0]) X,Y = numpy.meshgrid(x_grid,y_grid) fig=pylab.figure() ax = p3.Axes3D(fig) ax.plot_wireframe(X,Y,Z) xs = Z + s for n in range(M): for m in range(M): ax.plot3d([x_grid[m],x_grid[m]], [ y_grid[n], y_grid[n]], [Z[n,m], xs[n,m]], 'r') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') pylab.title('Minimal Surface') pylab.savefig('./3D_plot.png') #pylab.show() except: pass # Plot with MAYAVI try: import enthought.mayavi.mlab as mlab mlab.figure() mlab.view(azimuth=130) s = mlab.surf(x, y, Z, representation='wireframe', warp_scale='auto', line_width=1.) mlab.savefig('./mayavi_3D_plot.png') #mlab.show() except: pass
# Reshape long 1D results to 2D grid: uu=np.zeros((n+1,n+1)) uu[1:n,1:n] = u.reshape(n-1,n-1).transpose() xx,yy = np.meshgrid(x,y) value = uu[n/2,n/2] # Interpolate to finer grid and plot uu = uu.flatten(1) uuu = interp2d(x,y,uu,kind='cubic') a = np.linspace(-1.,1.,100) b = np.linspace(-1.,1.,100) xxx,yyy = np.meshgrid(a,b) newfunc = uuu(a,b) # Plot results # wireframe: fig=p.figure() ax = p3.Axes3D(fig) ax.plot_wireframe(xxx,yyy,newfunc) ax.text(-0.8,0.5,.022,'u(0,0) = %13.11f' % value) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') p.show() # mlab plotting from enthought.mayavi import mlab mlab.surf(a,b,newfunc) 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
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()
lo = 2.5 L = numpy.zeros((M, M), dtype=float) for n in range(M): for m in range(M): L[n, m] = 2.5 * ((x_grid[n] - 0.5)**2 + (y_grid[m] - 0.5)**2 <= 1. / 16) U = 100 * numpy.ones((M, M), dtype=float) Z, s = projected_gradients(u, O_tilde, dO_tilde, [L, U]) # # Plot with MAYAVI x = y = list(range(numpy.shape(Z)[0])) try: import enthought.mayavi.mlab as mlab except: import mayavi.mlab as mlab mlab.figure() mlab.view(azimuth=130) s = mlab.surf(x, y, Z, representation='wireframe', warp_scale='auto', line_width=1.) mlab.savefig('./mayavi_3D_plot.png') # mlab.show()
#!/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()
""" import numpy as np from scipy import interpolate import pylab as py def func(x, y): return (x + y) * np.exp(-5.0 * (x**2 + y**2)) x = np.random.uniform(-1.0, 1.0, size=50) y = np.random.uniform(-1.0, 1.0, size=50) fvals = func(x, y) newfunc = interpolate.Rbf(x, y, fvals, function='multiquadric') xnew, ynew = np.mgrid[-1:1:100j, -1:1:100j] fnew = newfunc(xnew, ynew) tru = func(xnew, ynew) # Create image plot py.figure(1) py.clf() py.imshow(fnew, extent=[-1, 1, -1, 1], cmap=py.cm.jet) py.scatter(x, y, 30, fvals, cmap=py.cm.jet) # Create surface plot from enthought.mayavi import mlab mlab.clf() mlab.surf(xnew, ynew, fnew * 2)
from stats.spirrid import orthogonalize from time import sleep e_arr = orthogonalize(s.evar_list) n_e_arr = [e / np.max(np.fabs(e)) for e in e_arr] 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()
#array([[ 0. , 0.5, 1. ]]) #ogrid为什么不是函数 #根据Python的语法,只有在中括号中才能使用用冒号隔开的切片语法,如果ogrid #是函数的话,那么这些切片必须使用slice函数创建,这显然会增加代码的长度。 #利用ogrid的返回值,我能很容易计算x, y网格面上各点的值,或者x, y, z #网格体上各点的值。下面是绘制三维曲面 x * exp(x**2 - y**2) 的程序: 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) #2.2.2 ufunc的方法 #ufunc函数本身还有些方法,这些方法只对两个输入一个输出的ufunc函数有效, #其它的ufunc对象调用这些方法时会抛出ValueError异常。 #reduce 方法和Python的reduce函数类似,它沿着axis轴对array进行操作, #相当于将<op>运算符插入到沿axis轴的所有子数组或者元素当中。 #<op>.reduce (array=, axis=0, dtype=None) #例如:
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()
import numpy as np import enthought.mayavi.mlab as mlab def f(x, y): return x + y*y x, y = np.mgrid[1:3:0.1, -2.:2.:0.01] s = mlab.surf(x, y, f)
x = np.linspace(0, 20, 20000) #print x[35] x -= x[70] #print x #crack_x = x - #x = np.linspace( -10 , 10 , 100 ) # eps = sb.get_eps_x_reinf( x ) # # plt.plot( x, eps, lw = 2, color = 'black' ) # plt.show() import enthought.mayavi.mlab as m from stats.spirrid import orthogonalize resolution = 200 profiles_list = [] forces_arr = np.linspace(0, 6200, resolution) for i, p in enumerate(forces_arr): sb.P = p profiles_list.append(sb.get_eps_x_reinf(x)) profiles_arr = np.array(profiles_list) param_arr = orthogonalize([x, forces_arr]) norm_param_arr = [ e / np.max(np.fabs(e)) for e in param_arr ] norm_profiles_arr = profiles_arr / np.max(np.fabs(profiles_arr)) m.surf(norm_param_arr[0], norm_param_arr[1], norm_profiles_arr) m.show()
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()