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 plotsln(mesh, z=None, sln=None, colorbar=False, view=(0,0), filename="a.png"): """ Plot a solution for the mesh editor in the online lab. """ x = [n[0] for n in mesh.nodes] y = [n[1] for n in mesh.nodes] if z == None: try: z = [n[2] for n in mesh.nodes] except IndexError: z = [0]*len(y) from enthought.mayavi import mlab mlab.options.offscreen = True mlab.clf() #mlab.options.show_scalar_bar = False mlab.triangular_mesh(x, y, z, mesh.elems, scalars=sln) engine = mlab.get_engine() image = engine.current_scene image.scene.background = (1.0, 1.0, 1.0) image.scene.foreground = (0.0, 0.0, 0.0) if colorbar: mlab.colorbar(orientation="vertical") if view: mlab.view(view[0], view[1]) mlab.savefig(filename)
def plot_sln_mayavi(x, y, mesh, sln_values, colorbar=False): """ Plot a solution using mayavi. Example: >>> from numpy import array >>> from femhub.plot import plot_sln_mayavi >>> f = plot_sln_mayavi([0, 1, 1], [0, 0, 1], [1, 2, 3]) >>> f.savefig("a.png") """ from enthought.mayavi import mlab #mlab.options.offscreen = True mlab.clf() #mlab.options.show_scalar_bar = False z = [0] * len(x) mlab.triangular_mesh(x, y, z, mesh, scalars=sln_values) engine = mlab.get_engine() image = engine.current_scene image.scene.background = (1.0, 1.0, 1.0) image.scene.foreground = (0.0, 0.0, 0.0) if colorbar: mlab.colorbar(orientation="vertical") mlab.view(0, 0) return mlab
def plot_normals(pts, normals, curvature=None): x = pts[0, :].A1 y = pts[1, :].A1 z = pts[2, :].A1 u = normals[0, :].A1 v = normals[1, :].A1 w = normals[2, :].A1 if curvature != None: #mlab.points3d(x,y,z,curvature,mode='point',scale_factor=1.0) mlab.points3d(x, y, z, curvature, mode='sphere', scale_factor=0.1, mask_points=1) mlab.colorbar() else: mlab.points3d(x, y, z, mode='point') mlab.quiver3d(x, y, z, u, v, w, mask_points=16, scale_factor=0.1) # mlab.axes() 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 ChargeDensityFog3D(directory, save_file=None , DrawAtoms=True, DrawCell=True, opacity_range=[0,1]): # Get data from calculation files with jasp(directory) as calc: atoms = calc.get_atoms() x, y, z, cd = calc.get_charge_density() mlab.figure(bgcolor=(0,0,0), size=(640,480)) # Draw atoms if DrawAtoms == True: for atom in atoms: mlab.points3d(atom.x, atom.y, atom.z, scale_factor=vdw_radii[atom.number]/10., resolution=16, color=tuple(cpk_colors[atom.number]), scale_mode='none') # Draw unit cell if DrawCell == True: a1, a2, a3 = atoms.get_cell() origin = [0,0,0] cell_matrix = [[origin, a1], [origin, a2], [origin, a3], [a1, a1+a2], [a1, a1+a3], [a2, a2+a1], [a2, a2+a3], [a3, a1+a3], [a3, a2+a3], [a1+a2, a1+a2+a3], [a2+a3, a1+a2+a3], [a1+a3, a1+a3+a2]] # contains all points on the box for p1, p2 in cell_matrix: mlab.plot3d([p1[0], p2[0]], # x-coords of box [p1[1], p2[1]], # y-coords [p1[2], p2[2]]) # z-coords # Plot the charge density src = mlab.pipeline.scalar_field(x, y, z, cd) #Source data vmin = cd.min() #find minimum and maximum value of CD data vmax = cd.max() vol = mlab.pipeline.volume(src) # Make a volumetric representation of the data # Set opacity transfer function from tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() otf.add_point(vmin, opacity_range[0]) #Transparency at zero electron density otf.add_point(vmax*1, opacity_range[1]) #Transparency at max electron density vol._otf=otf vol._volume_property.set_scalar_opacity(otf) #Show a legend mlab.colorbar(title="e- density\n(e/Ang^3)", orientation="vertical", nb_labels=5, label_fmt='%.2f') mlab.view(azimuth=-90, elevation=90, distance='auto') # Set viewing angle mlab.show() if save_file != None: mlab.savefig(save_file)
def plot(pts,color=(1.,1.,1.), scalar_list=None): if scalar_list != None: mlab.plot3d(pts[0,:].A1,pts[1,:].A1,pts[2,:].A1,scalar_list, representation = 'wireframe', tube_radius = None) mlab.colorbar() else: mlab.plot3d(pts[0,:].A1,pts[1,:].A1,pts[2,:].A1,color=color, representation = 'wireframe', tube_radius = None)
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 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 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 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 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 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 save(self,it): msh = self.__msh w = (self.__eqn).get(self.__var)() mlab.clf() mlab.points3d(msh.x[:,0], msh.x[:,1], zeros(w.shape), w, scale_factor=self.__scale, scale_mode=self.__mode) mlab.outline(extent=[msh.BB[0,0],msh.BB[1,0],msh.BB[0,1],msh.BB[1,1], 0,0]) mlab.view(0,0,self.__zoom,self.__xView) mlab.colorbar() fSol = ''.join([self.__figDir,'/',self.__name,'%04d.png'% it]) #print fSol mlab.savefig(fSol)
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 show_variable_timecourse(self, var, time_point, start_value, end_value): """Show an animation of all the section that have the recorded variable among time""" # Getting the new scalar new_scalar = self.get_var_data(var, time_point) d = self.dataset.point_data.get_array('diameter') if len(d) != len(new_scalar): message = "ERROR! MISMATCH on the Vector Length. \ If you assign the new vectors it will not work \ Diameter length: %s New Scalar length: %s var: %s" % ( len(d), len(new_scalar), var) logger.error(message) # ReEnable the rendering self.mayavi.visualization.scene.disable_render = True self.redraw_color(new_scalar, var) if not self.colorbar: self.colorbar = mlab.colorbar(orientation='vertical') self.timelabel = mlab.text(0.05, 0.05, str(time_point), width=0.05) self.colorbar.data_range = [start_value, end_value] time = self.manager.groups['t'][time_point] self.timelabel.text = str(round(time, 3)) self.mayavi.visualization.scene.disable_render = False
def show( self, x, y, z_middle, displayed_value ): """Test contour_surf on regularly spaced co-ordinates like MayaVi. """ print '*** plotting data***' s = points3d( X, Y, z_middle, displayed_value, colormap = "gist_rainbow", mode = "cube", scale_factor = 0.3 ) sb = colorbar( s ) # Recorded script from Mayavi2 #try: # engine = mayavi.engine #except NameError: # from enthought.mayavi.api import Engine # engine = Engine() # engine.start() #if len(engine.scenes) == 0: # engine.new_scene() # ------------------------------------------- glyph = s#.pipeline.scenes[0].children[0].children[0].children[0] glyph.glyph.glyph_source.glyph_source.center = array( [ 0., 0., 0.] ) glyph.glyph.glyph_source.glyph_source.progress = 1.0 glyph.glyph.glyph_source.glyph_source.x_length = 0.6 glyph.glyph.glyph_source.glyph_source.y_length = 0.6 sb.scalar_bar.title = 'thickness [m]' #print s.pipeline #s.scene.background = (1.0, 1.0, 1.0) return s
def plot(pts, color=(1., 1., 1.), scalar_list=None): if scalar_list != None: mlab.plot3d(pts[0, :].A1, pts[1, :].A1, pts[2, :].A1, scalar_list, representation='wireframe', tube_radius=None) mlab.colorbar() else: mlab.plot3d(pts[0, :].A1, pts[1, :].A1, pts[2, :].A1, color=color, representation='wireframe', tube_radius=None)
def show(self, sln, show=True, lib="mpl", notebook=False, filename="a.png", **options): """ Shows the solution. show ... should it actually plot the window? Set to False in tests. lib .... which library to use for the plotting? either "mpl" or "mayavi" notebook ... are we running inside Sage notebook? If True, just save the image to a.png filename ... the name of the filename if we are saving the image (e.g. notebook == False) Example: >>> 1 + 1 2 >>> 1 + 2 3 """ self._lib = lib self._notebook = notebook if lib == "mpl": plot_sln_mpl(sln, **options) import pylab if show: if notebook: pylab.savefig(filename) else: pylab.ion() pylab.draw() pylab.ioff() elif lib == "mayavi": plot_sln_mayavi(sln, notebook=notebook) from enthought.mayavi import mlab if show: engine = mlab.get_engine() image = engine.current_scene image.scene.background = (1.0, 1.0, 1.0) image.scene.foreground = (0.0, 0.0, 0.0) mlab.colorbar(orientation="vertical") if notebook: mlab.savefig(filename) else: mlab.show() else: raise NotImplementedError("Unknown library '%s'" % lib)
def show_blobs(blobs, v, faces,fa_slice=None,colormap='jet'): """Mayavi gets really slow when triangular_mesh is called too many times so this function stacks blobs and calls triangular_mesh once """ print blobs.shape xcen = blobs.shape[0]/2. ycen = blobs.shape[1]/2. zcen = blobs.shape[2]/2. faces = np.asarray(faces, 'int') xx = [] yy = [] zz = [] count = 0 ff = [] mm = [] for ii in xrange(blobs.shape[0]): for jj in xrange(blobs.shape[1]): for kk in xrange(blobs.shape[2]): m = blobs[ii,jj,kk] #m /= (2.2*m.max()) #m /= (2.2*abs(m).max()) #m /= (2.2*1.) #m[m<.4*abs(m).max()]=0 x, y, z = v.T*m/2.2 x += ii - xcen y += jj - ycen z += kk - zcen ff.append(count+faces) count += len(x) xx.append(x) yy.append(y) zz.append(z) mm.append(m) ff = np.concatenate(ff) xx = np.concatenate(xx) yy = np.concatenate(yy) zz = np.concatenate(zz) mm = np.concatenate(mm) mlab.triangular_mesh(xx, yy, zz, ff, scalars=mm, colormap=colormap) if fa_slice!=None: mlab.imshow(fa_slice, colormap='gray', interpolate=False) mlab.colorbar() 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 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 plot_normals(pts, normals, curvature=None): x = pts[0, :].A1 y = pts[1, :].A1 z = pts[2, :].A1 u = normals[0, :].A1 v = normals[1, :].A1 w = normals[2, :].A1 if curvature != None: # mlab.points3d(x,y,z,curvature,mode='point',scale_factor=1.0) mlab.points3d(x, y, z, curvature, mode="sphere", scale_factor=0.1, mask_points=1) mlab.colorbar() else: mlab.points3d(x, y, z, mode="point") mlab.quiver3d(x, y, z, u, v, w, mask_points=16, scale_factor=0.1) # mlab.axes() 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 plot_points(pts, color=(1., 1., 1.), scale_factor=0.02, mode='point', scalar_list=None): if scalar_list != None: mlab.points3d(pts[0, :].A1, pts[1, :].A1, pts[2, :].A1, scalar_list, mode=mode, scale_factor=scale_factor) mlab.colorbar() else: mlab.points3d(pts[0, :].A1, pts[1, :].A1, pts[2, :].A1, mode=mode, color=color, scale_factor=scale_factor)
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 plot_normals(pts, normals, curvature=None, mask_points=1, color=(0.,1.,0.), scale_factor = 0.1): x = pts[0,:].A1 y = pts[1,:].A1 z = pts[2,:].A1 u = normals[0,:].A1 v = normals[1,:].A1 w = normals[2,:].A1 if curvature != None: curvature = np.array(curvature) #idxs = np.where(curvature>0.03) #mlab.points3d(x[idxs],y[idxs],z[idxs],curvature[idxs],mode='sphere',scale_factor=0.1,mask_points=1) mlab.points3d(x,y,z,curvature,mode='sphere',scale_factor=0.1,mask_points=1, color=color) # mlab.points3d(x,y,z,mode='point') mlab.colorbar() else: mlab.points3d(x,y,z,mode='point') mlab.quiver3d(x, y, z, u, v, w, mask_points=mask_points, scale_factor=scale_factor, color=color)
def plot_normals(pts, normals, curvature=None, mask_points=1, color=(0., 1., 0.), scale_factor=0.1): x = pts[0, :].A1 y = pts[1, :].A1 z = pts[2, :].A1 u = normals[0, :].A1 v = normals[1, :].A1 w = normals[2, :].A1 if curvature != None: curvature = np.array(curvature) #idxs = np.where(curvature>0.03) #mlab.points3d(x[idxs],y[idxs],z[idxs],curvature[idxs],mode='sphere',scale_factor=0.1,mask_points=1) mlab.points3d(x, y, z, curvature, mode='sphere', scale_factor=0.1, mask_points=1, color=color) # mlab.points3d(x,y,z,mode='point') mlab.colorbar() else: mlab.points3d(x, y, z, mode='point') mlab.quiver3d(x, y, z, u, v, w, mask_points=mask_points, scale_factor=scale_factor, color=color)
def plot_sln_mayavi(sln, offscreen=False, show_scale=True): """ Plots the Solution() instance sln using Linearizer() and matplotlib. It takes the vertices from linearizer and interpolates them. """ lin = Linearizer() lin.process_solution(sln) vert = lin.get_vertices() triangles = lin.get_triangles() from numpy import zeros from enthought.mayavi import mlab x = vert[:, 0] y = vert[:, 1] z = zeros(len(y)) t = vert[:, 2] if offscreen: # the off screen rendering properly works only with VTK-5.2 or above: mlab.options.offscreen = True mlab.clf() mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) s = mlab.triangular_mesh(x, y, z, triangles, scalars=t) mlab.view(0, 0) mlab.view(distance=4) mlab.view(focalpoint=(.35, 0, 0)) mlab.colorbar(title="Solution", orientation="vertical") #mlab.move(right=-1.0, up=-10.0) # Below is a code that does exactly what the "View along the +Z axis" # button does: #scene = mlab.get_engine().current_scene.scene #scene.camera.focal_point = [0, 0, 0] #scene.camera.position = [0, 0, 1] #scene.camera.view_up = [0, 1, 0] #scene.renderer.reset_camera() #scene.render() # the above looks ok, but there is still quite a large margin, so we prefer # to just call .view(0, 0), which seems to be working fine. return mlab
def plot_sln_mayavi(sln, offscreen=False, show_scale=True): """ Plots the Solution() instance sln using Linearizer() and matplotlib. It takes the vertices from linearizer and interpolates them. """ lin = Linearizer() lin.process_solution(sln) vert = lin.get_vertices() triangles = lin.get_triangles() from numpy import zeros from enthought.mayavi import mlab x = vert[:, 0] y = vert[:, 1] z = zeros(len(y)) t = vert[:, 2] if offscreen: # the off screen rendering properly works only with VTK-5.2 or above: mlab.options.offscreen = True mlab.clf() mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) s = mlab.triangular_mesh(x, y, z, triangles, scalars=t) mlab.view(0, 0) mlab.view(distance=4) mlab.view(focalpoint=(.35,0,0)) mlab.colorbar(title="Solution", orientation="vertical") #mlab.move(right=-1.0, up=-10.0) # Below is a code that does exactly what the "View along the +Z axis" # button does: #scene = mlab.get_engine().current_scene.scene #scene.camera.focal_point = [0, 0, 0] #scene.camera.position = [0, 0, 1] #scene.camera.view_up = [0, 1, 0] #scene.renderer.reset_camera() #scene.render() # the above looks ok, but there is still quite a large margin, so we prefer # to just call .view(0, 0), which seems to be working fine. return mlab
def add_balls(at, colours=None, colorbar=False, atom_scale_factor=1.0, vmin=None, vmax=None): r = np.array([quippy.ElementCovRad[z] for z in at.z]) if colours is None: scalars = at.z vmin = 0 vmax = 110 else: scalars = colours pts = mlab.quiver3d(at.pos[1, :], at.pos[2, :], at.pos[3, :], r, [0] * len(r), [0] * len(r), scale_factor=atom_scale_factor, scale_mode='vector', scalars=scalars, mode='sphere', name='balls', vmin=vmin, vmax=vmax) pts.glyph.color_mode = 'color_by_scalar' #pts.glyph.glyph.scale_mode = 'scale_by_vector' pts.glyph.glyph_source.glyph_source.center = [0, 0, 0] if colours is None: pts.module_manager.scalar_lut_manager.lut.table = atom_colours_lut if colorbar: mlab.colorbar() return pts
def play(self, fileroot='cell', show_colorbar=True, show_title=False): ''' Step through cell response over time ''' dt = self.play_dt tstop = self.play_tstop nrn.init() nrn.cvode_active(0) img_counter=0 f = mlab.gcf() if show_colorbar: mlab.colorbar(self.mlab_cell) nrn.initPlot() nrn.init() nrn.initPlot() nrn.init() for x in xrange(0, int(tstop/dt)): timestamp = "TIME: %.1f" % (x*dt) print timestamp if show_title: try: ftitle.text = timestamp except: ftitle = mlab.title(timestamp) nrn.continuerun(x*dt) dataset = self.mlab_cell.mlab_source.dataset v = array(self.calculate_voltage()) dataset.point_data.remove_array('data') array_id = dataset.point_data.add_array(v.T.ravel()) dataset.point_data.get_array(array_id).name = 'data' dataset.point_data.update() self.mlab_cell.update_data() self.mlab_cell.update_pipeline() if self.save_img: f.scene.save_png('img/%s_%03d.png' % (fileroot, img_counter)) img_counter += 1
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 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
mlab.figure(1, fgcolor=(1, 1, 1), bgcolor=(0, 0, 0)) # We create a scalar field with the module of Phi as the scalar src = mlab.pipeline.scalar_field(np.abs(Phi)) # And we add the phase of Phi as an additional array # This is a tricky part: the layout of the new array needs to be the same # as the existing dataset, and no checks are performed. The shape needs # to be the same, and so should the data. Failure to do so can result in # segfaults. src.image_data.point_data.add_array(np.angle(Phi).T.ravel()) # We need to give a name to our new dataset. src.image_data.point_data.get_array(1).name = 'angle' # Make sure that the dataset is up to date with the different arrays: src.image_data.point_data.update() # We select the 'scalar' attribute, ie the norm of Phi src2 = mlab.pipeline.set_active_attribute(src, point_scalars='scalar') # Cut isosurfaces of the norm contour = mlab.pipeline.contour(src2) # Now we select the 'angle' attribute, ie the phase of Phi contour2 = mlab.pipeline.set_active_attribute(contour, point_scalars='angle') # And we display the surface. The colormap is the current attribute: the phase. mlab.pipeline.surface(contour2, colormap='hsv') mlab.colorbar(title='Phase', orientation='vertical', nb_labels=3) mlab.show()
temperature[i,j,k] = (f[:,i,j,k]* v[2:-2]**2).sum() / f.sum(axis=0)[i,j,k] return temperature for frame in range(len(fileh.root.Time[:])): # 3D Movie frame = 4*frame mlab.clf(figure=fig3d) scene = mlab.contour3d(Temperature(fileh.root.Phasespace[:,:,:,:,frame], fileh.root.Phasespace.attrs.v), contours=50) # Density profile #scene = mlab.contour3d(fileh.root.Phasespace[:,:,:,:,frame].sum(axis=0), contours=50) #source = mlab.pipeline.scalar_field(Temperature(fileh.root.Phasespace[:,:,:,:,frame], fileh.root.Phasespace.attrs.v)) #vol = mlab.pipeline.volume(source) angle = 50. mlab.view(azimuth=angle%360, distance=72.0) #mlab.axes(color=(0.0,0.0,0.),extent=ext,xlabel='X',ylabel='Y',zlabel='Z') #a = array(gradient(fileh.root.Phi[:,:,:,frame]))**2 #mlab.quiver3d(a[0],a[1],a[2]) mlab.colorbar(orientation='vertical')#, label_fmt="%.2f", nb_labels=3) mlab.outline() mlab.savefig("Rho_" + string.zfill(frame, 4) + ".jpg")#, size=(600,600)) print "[", string.zfill(frame, 4),"/", len(fileh.root.Time[:]), "]" #mencoder "mf://*.jpg" -mf fps=10 -ovc lavc -o mymovie.av
def show_odfs(odfs, vertices_faces, image=None, colormap='jet', scale=2.2, norm=True, radial_scale=True): """ Display a grid of ODFs. Parameters ---------- odfs : (X, Y, Z, M) ndarray A 3-D arrangement of orientation distribution functions (ODFs). At each ``(x, y, z)`` position, it contains the the values of the corresponding ODF evaluated on the M vertices. vertices_faces : str or tuple of (vertices, faces) A named sphere from `dipy.data.get_sphere`, or a combination of `(vertices, faces)`. image : (X, Y) ndarray Background image (e.g., fractional anisotropy) do display behind the ODFs. colormap : str Color mapping. scale : float Increasing the scale spaces ODFs further apart. norm : bool Whether or not to normalize each individual ODF (divide by its maximum absolute value). radial_scale : bool Whether or not to change the radial shape of the ODF according to its scalar value. If set to False, the ODF is displayed as a sphere. Notes ----- Mayavi gets really slow when `triangular_mesh` is called too many times, so this function stacks ODF data and calls `triangular_mesh` once. Examples -------- >>> from dipy.data import get_sphere >>> verts, faces = get_sphere('symmetric724') >>> angle = np.linspace(0, 2*np.pi, len(verts)) >>> odf1 = np.sin(angle) >>> odf2 = np.cos(angle) >>> odf3 = odf1**2 * odf2 >>> odf4 = odf1 + odf2**2 >>> odfs = [[[odf1, odf2], ... [odf3, odf4]]] >>> show_odfs(odfs, (verts, faces), scale=5) """ vertices, faces = sphere_vf_from(vertices_faces) odfs = np.asarray(odfs) if odfs.ndim != 4: raise ValueError("ODFs must by an (X,Y,Z,M) array. " + "Has shape " + str(odfs.shape)) grid_shape = np.array(odfs.shape[:3]) faces = np.asarray(faces, dtype=int) xx, yy, zz, ff, mm = [], [], [], [], [] count = 0 for ijk in np.ndindex(*grid_shape): m = odfs[ijk] if norm: m /= abs(m).max() if radial_scale: xyz = vertices.T * m else: xyz = vertices.T.copy() xyz += scale * (ijk - grid_shape / 2.)[:, None] x, y, z = xyz ff.append(count + faces) xx.append(x) yy.append(y) zz.append(z) mm.append(m) count += len(x) ff, xx, yy, zz, mm = (np.concatenate(arrs) for arrs in (ff, xx, yy, zz, mm)) mlab.triangular_mesh(xx, yy, zz, ff, scalars=mm, colormap=colormap) if image is not None: mlab.imshow(image, colormap='gray', interpolate=False) mlab.colorbar() mlab.show()
points[:, 2], faces, color=(1, 1, 0), opacity=0.3) # show one cortical surface mlab.triangular_mesh(lh_points[:, 0], lh_points[:, 1], lh_points[:, 2], lh_faces, color=(0.7, ) * 3) # show dipole as small cones dipoles = mlab.quiver3d(pos[:, 0], pos[:, 1], pos[:, 2], ori[:, 0], ori[:, 1], ori[:, 2], opacity=1., scale_factor=4e-4, scalars=time, mode='cone', colormap='RdBu') # revert colormap dipoles.module_manager.scalar_lut_manager.reverse_lut = True mlab.colorbar(dipoles, title='Dipole fit time (ms)') # proper 3D orientation mlab.get_engine().scenes[0].scene.x_plus_view()
def 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
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
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
scale_mode='none') """ # create a scalar field with the rho as the scalar src = mlab.pipeline.scalar_field(rho) # add the `esp` as an additional array src.image_data.point_data.add_array(esp.ravel())#(esp_ravel) #(esp.T.ravel()) # give a name to our new dataset. src.image_data.point_data.get_array(1).name = 'esp' # The dataset should be up to date with the different arrays: src.image_data.point_data.update() # select the 'scalar' attribute src2 = mlab.pipeline.set_active_attribute(src, point_scalars='scalar') # Cut isosurfaces of the scalar contour = mlab.pipeline.contour(src2) # select the 'esp' attribute, contour2 = mlab.pipeline.set_active_attribute(contour, point_scalars='esp') # display the surface. The colormap is the current attribute: the phase. mlab.pipeline.surface(contour2, transparent=True) #, colormap='hsv') mlab.colorbar(title='ESP', orientation='vertical', nb_labels=5) mlab.savefig('images/H2O-esp.png') mlab.show()
r_c, phi_c, theta_c = vectors.cart2spher_coord( *center.T) colors_ = r_c mlab.clf() mlab.points3d(center.T[0], center.T[1], center.T[2], colors_, scale_factor=0.05, scale_mode='none', colormap='RdBu', vmin=colors_.min(), vmax=colors_.max()) #mlab.quiver3d(center.T[0],center.T[1],center.T[2],normal.T[0],normal.T[1],normal.T[2],colormap='spectral',scale_mode='none') mlab.colorbar() if i >= 1: vx,vy,vz = center.T[0]-old_center.T[0],\ center.T[1]-old_center.T[1],\ center.T[2]-old_center.T[2] v = np.sqrt(vx**2 + vy**2 + vz**2) mlab.quiver3d(center.T[0],center.T[1],center.T[2],\ vx,vy,vz,scalars=v,colormap='spectral',scale_mode='scalar') #mlab.show() old_center = center.copy() mlab.view(distance=5, azimuth=-90, elevation=90) mlab.savefig('pulsation_lm%d%d_k%03d_%03d.png' % (l, m, k, i)) mlab.close() multimedia.make_movie(
try: from enthought.mayavi import mlab except: from mayavi import mlab lh_points = src[0]['rr'] lh_faces = src[0]['use_tris'] mlab.figure(size=(600, 600), bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) # show brain surface after proper coordinate system transformation points = brain_surface['rr'] faces = brain_surface['tris'] coord_trans = fwd['mri_head_t']['trans'] points = np.dot(coord_trans[:3,:3], points.T).T + coord_trans[:3,-1] mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2], faces, color=(1, 1, 0), opacity=0.3) # show one cortical surface mlab.triangular_mesh(lh_points[:, 0], lh_points[:, 1], lh_points[:, 2], lh_faces, color=(0.7, ) * 3) # show dipole as small cones dipoles = mlab.quiver3d(pos[:,0], pos[:,1], pos[:,2], ori[:,0], ori[:,1], ori[:,2], opacity=1., scale_factor=4e-4, scalars=time, mode='cone') mlab.colorbar(dipoles, title='Dipole fit time (ms)') # proper 3D orientation mlab.get_engine().scenes[0].scene.x_plus_view()
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') # # s=contour3d(x,y,z,data[10,:,:,:], contours=4, transparent=True) # mlab.view(0.,0.) colorbar() # axes() # outline() # Run the animation. anim(s, data[:, :, :, 10] + 0.1, s1, save=True)
def viz_Potential(r_data, V_data, X, Y, Z, j_data, file_name=None, size=(600, 600)): u"""Visualizes the electrostatic potential difference of the molecule. ** Parameters ** r_data, V_data : numpy.ndarray Voxels of the electron density and the potential difference of the molecule, respectively. X, Y, Z : numpy.ndarray Meshgrids as generated by numpy.mgrid, for positioning the voxels. j_data : dict Data on the molecule, as deserialized from the scanlog format. file_name : str, optional Base name of the file in which to save the image. size : tuple(int, int), optional The size of the image to save. ** Returns ** figure : mayavi.core.scene.Scene The MayaVi scene containing the visualization. """ figure = _init_scene(j_data)[0] src = mlab.pipeline.scalar_field(X, Y, Z, r_data, figure=figure) ## Add potential as additional array src.image_data.point_data.add_array(V_data.T.ravel() / V_to_Kcal_mol) ## Name it src.image_data.point_data.get_array(1).name = "potential" ## Update object src.update() ## Select scalar attribute srcp = mlab.pipeline.set_active_attribute(src, figure=figure, point_scalars="scalar") ## Plot it cont = mlab.pipeline.contour(srcp, figure=figure) cont.filter.contours = [0.001] ## Select potential cont_V = mlab.pipeline.set_active_attribute(cont, figure=figure, point_scalars="potential") #contp = mlab.pipeline.threshold(cont_V, figure=figure, up=) #contn = mlab.pipeline.threshold(cont_V, figure=figure, low=V_data.min()*0.95) ## And finally plot that mlab.pipeline.surface(cont_V, figure=figure, opacity=0.7) ## Continue with this until problems with potential calculation are fixed #V_data[np.isinf(V_data)] = np.nan #src = mlab.pipeline.scalar_field(X, Y, Z, V_data, figure=figure) #srcp = mlab.pipeline.iso_surface(src, figure=figure, contours=[ 0.4], color=(0.0, 0.5, 0.5)) #srcn = mlab.pipeline.iso_surface(src, figure=figure, contours=[-0.05], color=(0.95, 0.95, 0.95)) mlab.colorbar(title='Kcal/mol', orientation='vertical', nb_labels=3) #mlab.show() if file_name is not None: mlab.savefig("{}-Potential.png".format(file_name), figure=figure, size=size) return figure
f = mlab.figure(size=(800,600)) # Tell visual to use this as the viewer. visual.set_viewer(f) ######################################################## # Do the appropriate graph #s = mlab.contour_surf(r,z,fun, contours=30, line_width=.5, transparent=True) #s=mlab.surf(r,z,fun, colormap='Spectral') s = mlab.mesh(r,z,fm[0,:,:], scalars=fm[0,:,:], colormap='PuOr')#, wrap_scale='true')#, representation='wireframe') s.enable_contours=True s.contour.filled_contours=True # Define perspective and optional attributes. You can also implement from the window afterwards mlab.view(0,0) #mlab.view(-94.159958841373324, # 53.777002382688906, # 8.2311808018087582) mlab.draw(f) mlab.colorbar(orientation="vertical") #mlab.axes() #mlab.outline() ######################################################## # mlab animation anim(s,fm, save=True)
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
# 3D Movie mlab.clf(figure=fig3d) #Simple contour scene = mlab.contour3d((fileh.root.Phi[2:-2,2:-2,2:-2,frame]**2), contours=50, extent=ext, vmax=fmax, vmin=fmin)#, colormap='ylgn') # Cutplane #E = gradient(fileh.root.Phi[:,:,:,frame]) #mlab.quiver3d(E[0], E[1], E[2]) #src = mlab.pipeline.vector_field(E[2], E[1], E[0]) #mlab.pipeline.vectors(src, mask_points=20, scale_factor=3.) #mlab.pipeline.vector_cut_plane(src, mask_points=1, scale_factor=5) #src = mlab.pipeline.vector_field(E[0], E[1], E[2]) #magnitude = mlab.pipeline.extract_vector_norm(src) #flow = mlab.pipeline.streamline(magnitude, seedtype='plane', seed_visible=False, seed_scale=1.0, seed_resolution=100, linetype='line',integration_direction='both') #$mlab.axes(color=(0.0,0.0,0.),extent=ext,xlabel='X',ylabel='Y',zlabel='Z') #source = mlab.pipeline.scalar_field(fileh.root.Phi[:,:,:,frame]**2) #vol = mlab.pipeline.volume(source) #a = array(gradient(fileh.root.Phi[:,:,:,frame]))**2 #mlab.quiver3d(a[0],a[1],a[2]) # mlab.view(azimuth=angle%360, distance=128.0) mlab.view(azimuth=angle%360, distance=10.0) angle += 1.0 mlab.colorbar(orientation='vertical', label_fmt="%.2e", nb_labels=5) mlab.outline() mlab.savefig("Phi3D_" + filename + "_" + string.zfill(frame, 4) + ".jpg")#, size=(600,600)) print "[", string.zfill(frame, 4),"/", len(fileh.root.Time[:]), "]" #mencoder "mf://*.jpg" -mf fps=10 -ovc lavc -o mymovie.av
scene = mlab.contour3d((fileh.root.Phi[2:-2, 2:-2, 2:-2, frame]**2), contours=50, extent=ext, vmax=fmax, vmin=fmin) #, colormap='ylgn') # Cutplane #E = gradient(fileh.root.Phi[:,:,:,frame]) #mlab.quiver3d(E[0], E[1], E[2]) #src = mlab.pipeline.vector_field(E[2], E[1], E[0]) #mlab.pipeline.vectors(src, mask_points=20, scale_factor=3.) #mlab.pipeline.vector_cut_plane(src, mask_points=1, scale_factor=5) #src = mlab.pipeline.vector_field(E[0], E[1], E[2]) #magnitude = mlab.pipeline.extract_vector_norm(src) #flow = mlab.pipeline.streamline(magnitude, seedtype='plane', seed_visible=False, seed_scale=1.0, seed_resolution=100, linetype='line',integration_direction='both') #$mlab.axes(color=(0.0,0.0,0.),extent=ext,xlabel='X',ylabel='Y',zlabel='Z') #source = mlab.pipeline.scalar_field(fileh.root.Phi[:,:,:,frame]**2) #vol = mlab.pipeline.volume(source) #a = array(gradient(fileh.root.Phi[:,:,:,frame]))**2 #mlab.quiver3d(a[0],a[1],a[2]) # mlab.view(azimuth=angle%360, distance=128.0) mlab.view(azimuth=angle % 360, distance=10.0) angle += 1.0 mlab.colorbar(orientation='vertical', label_fmt="%.2e", nb_labels=5) mlab.outline() mlab.savefig("Phi3D_" + filename + "_" + string.zfill(frame, 4) + ".jpg") #, size=(600,600)) print "[", string.zfill(frame, 4), "/", len(fileh.root.Time[:]), "]" #mencoder "mf://*.jpg" -mf fps=10 -ovc lavc -o mymovie.av
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