def Surf(self, z, scene='updated', type='terrain'): # Depending on input selects which scene to plot in. if scene == 'updated': figureToPlotIn = self.updatedScene.mayavi_scene else: figureToPlotIn = self.originalScene.mayavi_scene # Depending on input specifies settings like colour and opacity for the surface. if type == 'terrain': surfaceColour = (0.5, 0.45, 0.4) surfaceOpacity = 1 else: if type == 'water': surfaceColour = (0.1, 0.3, 0.5) surfaceOpacity = 0.5 else: if type == 'sediment': surfaceColour = (0.25, 0.15, 0.15) surfaceOpacity = 1 # Adds the surface to the selected scene. #if type == 'sediment': # #z[z==np.min(z)]+=50 # #z += 50 # self.a = mlab.surf(z, figure=figureToPlotIn, opacity=surfaceOpacity) #else: mlab.surf(z, figure=figureToPlotIn, color=surfaceColour, opacity=surfaceOpacity)
def plotSurf(self,det,axisX,axisY,start=None,stop=None): bin = self.detector[det] try: bin.data except AttributeError: self.arrayRead(det) sumaxis = [2,1,0] sumaxis.remove(axisX) sumaxis.remove(axisY) low,high = self.__ranges(det,start,stop) subdata = (slice(low[0],high[0]),slice(low[1],high[1]),slice(low[2],high[2])) plotdata = bin.data[subdata] plotdata = sum(plotdata,sumaxis[0]) #Renormalize data if (bin.type in [1,7,11,17]): #Cylinder bins plotdata = plotdata/((pi*high[0]**2*high[2]*high[1]/(2*pi))-(pi*low[0]**2*low[2]*low[1]/(2*pi))) elif (bin.type in [0,3,4,5,10,13,14,15,16]): #Cartesian bins plotdata = plotdata/((high[0]-low[0])*(high[1]-low[1])*(high[1]-low[1])) x = linspace(bin.start[axisX]+bin.delta[axisX]/2,bin.stop[axisX]+bin.delta[axisX]/2, num=bin.num[axisX], endpoint=False)[slice(low[axisX],high[axisX])] y = linspace(bin.start[axisY]+bin.delta[axisY]/2,bin.stop[axisY]+bin.delta[axisY]/2, num=bin.num[axisY], endpoint=False)[slice(low[axisY],high[axisY])] mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) z =plotdata # Visualize the points mlab.surf(x,y,z) mlab.show()
def main(): parser = argparse.ArgumentParser() parser.add_argument("point_x", help="x coordinate of point.", type=int) parser.add_argument("point_y", help="y coordinate of point.", type=int) parser.add_argument("file", help="The bathymetry file.") parser.add_argument("--halo", help="Size of halo.", type=int, default=50) args = parser.parse_args() f = nc.Dataset(args.file) topo = f.variables['depth'][:] # Calculate the extents of the topo array to show. We don't just add halo to (point_x, point_y) # because it may run off the edge of the map. north_ext = min(args.point_y + args.halo, topo.shape[0]) south_ext = max(args.point_y - args.halo, 0) east_ext = min(args.point_x + args.halo, topo.shape[1]) west_ext = max(args.point_x - args.halo, 0) width = east_ext - west_ext height = north_ext - south_ext # The origin of the figure in global coordinates. origin_x = west_ext + width / 2 origin_y = south_ext + height / 2 point_y = args.point_y - origin_y point_x = args.point_x - origin_x mlab.surf(topo[south_ext:north_ext, west_ext:east_ext], warp_scale=0.005) mlab.points3d([point_y], [point_x], [0], color=(1, 0, 0), scale_factor=1.0) mlab.show()
def k_COV_plots(k_arr, COV_arr): sig_max_arr = np.zeros((len(k_arr), len(COV_arr))) wmax_arr = np.zeros((len(k_arr), len(COV_arr))) mu_r, mu_tau = 0.01, 0.1 for i, k in enumerate(k_arr): for j, cov in enumerate(COV_arr): Vf = Vf_k(k) loc_r = mu_r * (1 - cov * np.sqrt(3.0)) scale_r = cov * 2 * np.sqrt(3.0) * mu_r loc_tau = mu_tau * (1 - cov * np.sqrt(3.0)) scale_tau = cov * 2 * np.sqrt(3.0) * mu_tau reinf = ContinuousFibers(r=RV('uniform', loc=loc_r, scale=scale_r), tau=RV('uniform', loc=loc_tau, scale=scale_tau), xi=WeibullFibers(shape=7.0, sV0=0.003), V_f=Vf, E_f=200e3, n_int=100) ccb_view.model.reinforcement_lst = [reinf] sig_max, wmax = ccb_view.sigma_c_max sig_max_arr[i, j] = sig_max/Vf wmax_arr[i, j] = wmax ctrl_vars = orthogonalize([np.arange(len(k_arr)), np.arange(len(COV_arr))]) print sig_max_arr print wmax_arr mlab.surf(ctrl_vars[0], ctrl_vars[1], sig_max_arr / np.max(sig_max_arr)) mlab.surf(ctrl_vars[0], ctrl_vars[1], wmax_arr / np.max(wmax_arr)) mlab.show()
def plot_solution(self): xn, yn, pn = self.get_plot_data() u, v, p = pn[..., 0], pn[..., 1], pn[..., 2] for arr in (xn, yn, u, v, p): arr.shape = arr.shape + (1, ) vmag = np.sqrt(u*u + v*v) pde = self.pde if self.plt1 is None: mlab.figure( size=(700, 700), fgcolor=(0, 0, 0), bgcolor=(1, 1, 1) ) if self.show_exact and pde.has_exact(): un = pde.exact(xn, yn) mlab.surf(xn, yn, un, colormap='viridis', representation='wireframe') src = mlab.pipeline.vector_field( xn, yn, np.zeros_like(xn), u, v, np.zeros_like(u), scalars=vmag, name='vectors' ) self.plt1 = mlab.pipeline.vectors( src, scale_factor=0.2, mask_points=3, colormap='viridis' ) self.plt1.scene.z_plus_view() cgp = mlab.pipeline.contour_grid_plane( src, opacity=0.8, colormap='viridis', ) cgp.enable_contours = False mlab.colorbar(self.plt1) else: self.plt1.mlab_source.trait_set(u=u, v=v, scalars=vmag) return self.get_error(xn, yn, pn)
def render_cylinder(self, cylinder: _geometry.Cylinder, *args, **kwargs): # get transformation to apply transform = kwargs.get('transformation', _HomogenousTransformation()) # quicker access to width, depth, and height of cuboid radii = cylinder.radius height = cylinder.height theta = _np.linspace(0, 2 * _np.pi, num=36, endpoint=True) z = _np.linspace(-height / 2, height / 2, num=2, endpoint=True) theta, z = _np.meshgrid(theta, z) x = radii[0] * _np.cos(theta) y = radii[1] * _np.sin(theta) vertices = _np.stack((x, y, z), axis=1).T # apply transformation to the vertices try: vertices = transform.apply(vertices) except ValueError: vertices = _np.asarray( [transform.apply(page) for page in vertices.T]).T vertices = _np.stack( [transform.apply(page) for page in vertices.T], axis=0) # outside surface _mlab.surf( *self._prepare_plot_coordinates( self._extract_coordinates(_np.swapaxes(vertices, 0, 1))), ) # # top and bottom caps for ring in vertices: _mlab.surf( *self._prepare_plot_coordinates( self._extract_coordinates(ring)), )
def plot_2d_gm(): """ This function plot two 2D Gaussian distribution density side by side centralized at (-500, 0) and (500, 0) for comparison. In this example, the Gaussian density has a covariance matrix of .. math:: cov = \left[ \begin{matrix} 10000, 0 0, 10000 \end{matrix} \right] The peak of the density distribution is .. math:: max(\mathcal{N}) = \frac{1}{\sqrt{2\pi 10000}} = 1.59\times 10^{-5} You can verify the value according to the plotted graph. """ figure = mlab.figure('GMGaussian') X, Y = np.mgrid[-1000:1000:10, -500:500:10] Z_GM = np.zeros(X.shape, dtype=np.float) Z_PDF = np.zeros(X.shape, dtype=np.float) GM_mean = np.array([[-500], [0.]]) PDF_mean = np.array([[500], [0.]]) # Covariance matrix - with std to be 100 on both dimensions cov = np.eye(2) * 10000 gm = GaussianComponent(n=2, weight=1., mean=GM_mean, cov=cov) mvnormal = scipy.stats.multivariate_normal(mean=PDF_mean.flatten(), cov=cov) for i in range(X.shape[0]): for j in range(X.shape[1]): eval_x = np.array([[X[i, j]], [Y[i, j]]]) Z_GM[i, j] = gm.dmvnormcomp(eval_x) Z_PDF[i, j] = mvnormal.pdf(eval_x.flatten()) print(Z_GM - Z_PDF) scale_factor = max(np.max(Z_GM), np.max(Z_PDF)) # mlab.surf(X, Y, f, opacity=.3, color=(1., 0, 0)) mlab.surf(X, Y, Z_GM * (2000 / scale_factor), opacity=.3, color=(1., 0, 0)) mlab.surf(X, Y, Z_PDF * (2000 / scale_factor), opacity=.3, color=(0., 1., 0)) mlab.outline(None, color=(.7, .7, .7), extent=[-1000, 1000, -500, 500, 0, 2000]) mlab.axes(None, color=(.7, .7, .7), extent=[-1000, 1000, -500, 500, 0, 2000], ranges=[-1000, 1000, -500, 500, 0, scale_factor], nb_labels=6) mlab.show()
def plot_mayavi(self): """Use mayavi to plot a phenotype phase plane in 3D. The resulting figure will be quick to interact with in real time, but might be difficult to save as a vector figure. returns: mlab figure object""" from mayavi import mlab figure = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) figure.name = "Phenotype Phase Plane" max = 10.0 xmax = self.reaction1_fluxes.max() ymax = self.reaction2_fluxes.max() zmax = self.growth_rates.max() xgrid, ygrid = meshgrid(self.reaction1_fluxes, self.reaction2_fluxes) xgrid = xgrid.transpose() ygrid = ygrid.transpose() xscale = max / xmax yscale = max / ymax zscale = max / zmax mlab.surf(xgrid * xscale, ygrid * yscale, self.growth_rates * zscale, representation="wireframe", color=(0, 0, 0), figure=figure) mlab.mesh(xgrid * xscale, ygrid * yscale, self.growth_rates * zscale, scalars=self.shadow_prices1 + self.shadow_prices2, resolution=1, representation="surface", opacity=0.75, figure=figure) # draw axes mlab.outline(extent=(0, max, 0, max, 0, max)) mlab.axes(opacity=0, ranges=[0, xmax, 0, ymax, 0, zmax]) mlab.xlabel(self.reaction1_name) mlab.ylabel(self.reaction2_name) mlab.zlabel("Growth rates") return figure
def make_frame(t): i = int(np.ceil(t * speed_factor / dt)) source2 = runname + '_{0:04}'.format(i) + '.asc' # Load the dem into a numpy array arr = np.loadtxt(source2, skiprows=6) for i in range(0, ny): H_cent[i, 0:nx] = arr[i, 0:nx] W_cent = B_cent + H_cent idx = np.ma.masked_where(H_cent == -9999, W_cent) W_cent[np.where(np.ma.getmask(idx) == True)] = np.nan mlab.clf() # clear the figure (to reset the colors) topo = mlab.surf(xs, ys, B_cent, color=(0.5, 0.6, 0.7)) mlab.outline(topo, color=(.7, .7, .7)) surf = mlab.surf(xs, ys, W_cent + 1.e-1, color=(0.4, 0.4, 0.4)) surf.actor.property.interpolation = 'phong' surf.actor.property.specular = 1.0 surf.actor.property.specular_power = 50 mlab.text(-10, 0, 't=' + str(t * speed_factor) + 's', z=10, width=0.15, color=(0, 0, 0)) return mlab.screenshot(antialiased=True)
def plot3d(gc): #aGc_cE=np.linspace(0.2,0.3,21) aNoise = [ 0.00001, 0.00002, 0.00005, 0.0001, 0.0002, 0.0005, 0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5 ] for noise in aNoise: data = np.loadtxt( u'F:\\postprocess\\AC\\Sigmoidal\\Square\\Connor0HH0ML1_16384ML2_0Inh_(0,0)\\gc_exc=%.5f_gc_inh=%.5f_noise=%.5f_AC_square_average_sum.dat' % (gc, gc, noise)) fig.clear() X = np.linspace( 0, 128 ) #(min(data[:,1]),max(data[:,0]),(max(data[:,0])-min(data[:,1]))/0.1+2) Y = np.linspace( 0, 128 ) #(min(data[:,1]),max(data[:,1]),(max(data[:,1])-min(data[:,1]))/0.1+2) x, y = np.meshgrid(X, Y) mlab.surf(x, y, data, warp_scale="auto") plt.xlabel(u'{\Symbol a}') plt.ylabel(u'{\Symbol b}') plt.xlim([1, 128]) plt.ylim([1, 128]) #plt.title(u'') #plt.show() outfilename=u'F:\\Graduation Thesis\\spiral wave animation\\Sigmoidal\\Square\\Connor0HH0ML1_16384ML2_0Inh_(0,0)\\gc_exc=%.5f_gc_inh=%.5f_noise=%.5f_AC_square_average_sum.tiff'\ %(gc,gc,noise) plt.savefig(outfilename)
def showPath(self): px, py, pz, dirx,diry,dirz = [],[],[],[],[],[] print self.path print len(self.z) for node in self.path: px.append(node[0]) py.append(node[1]) pz.append(self.z[node[0]][node[1]]) dirx.append(cos(radians(node[2]))) diry.append(sin(radians(node[2]))) dirz.append(0) px = np.array(px) py = np.array(py) pz = np.array(pz) dirx = np.array(dirx) diry = np.array(diry) dirz = np.array(dirz) mlab.quiver3d(self.x,self.y,self.z,self.gx,self.gy,self.Gt,color=(1,0,0),scale_factor=1) mlab.quiver3d(px,py,pz,dirx,diry,dirz,color=(0,0,0),scale_factor=1) mlab.surf(self.x, self.y, self.z, representation='wireframe') mlab.show()
def k_COV_plots(k_arr, COV_arr): sig_max_arr = np.zeros((len(k_arr), len(COV_arr))) wmax_arr = np.zeros((len(k_arr), len(COV_arr))) mu_r, mu_tau = 0.01, 0.1 for i, k in enumerate(k_arr): for j, cov in enumerate(COV_arr): Vf = Vf_k(k) loc_r = mu_r * (1 - cov * np.sqrt(3.0)) scale_r = cov * 2 * np.sqrt(3.0) * mu_r loc_tau = mu_tau * (1 - cov * np.sqrt(3.0)) scale_tau = cov * 2 * np.sqrt(3.0) * mu_tau reinf = ContinuousFibers(r=RV('uniform', loc=loc_r, scale=scale_r), tau=RV('uniform', loc=loc_tau, scale=scale_tau), xi=WeibullFibers(shape=7.0, sV0=0.003), V_f=Vf, E_f=200e3, n_int=100) ccb_view.model.reinforcement_lst = [reinf] sig_max, wmax = ccb_view.sigma_c_max sig_max_arr[i, j] = sig_max / Vf wmax_arr[i, j] = wmax ctrl_vars = orthogonalize([np.arange(len(k_arr)), np.arange(len(COV_arr))]) print sig_max_arr print wmax_arr mlab.surf(ctrl_vars[0], ctrl_vars[1], sig_max_arr / np.max(sig_max_arr)) mlab.surf(ctrl_vars[0], ctrl_vars[1], wmax_arr / np.max(wmax_arr)) mlab.show()
def run(self, ips, imgs, para=None): from mayavi import mlab img = ips.get_img() scale, sigma = para['scale'], para['sigma'] imgblur = gaussian_filter(img[::scale, ::scale], sigma) mlab.surf(imgblur, warp_scale=para['h']) IPy.callafter(mlab.show)
def draw_working_area(self, width, height): color = (0.9, 0.9, 0.7) x, y = np.mgrid[0:height+1:10, 0:width+1:10] z = np.zeros(x.shape) mlab.surf(x, y, z, color=color, line_width=1.0, representation='wireframe', warp_scale=self.scale) mlab.axes()
def ripple(): """Plot z = sin(10(x^2 + y^2))/10 on [-1,1]x[-1,1] using Mayavi.""" x, y = np.mgrid[-1:1:0.025, -1:1:0.025] z = np.sin(10 * (x**2 + y**2)) / 10 mlab.surf(x, y, z) mlab.show()
def render(self, colour=(1, 0, 0), line_width=2, step=None, marker_style='2darrow', marker_resolution=8, marker_size=0.05, alpha=1.0): from mayavi import mlab warp_scale = kwargs.get('warp_scale', 'auto') mlab.surf(self.values, warp_scale=warp_scale) return self
def main(): # Load grid = Grid.load(os.path.join(data_folder, "grid.pickle")) volcano_coords = grid.cells data_coords = np.load(os.path.join(data_folder,"surface_data_coords.npy")) ground_truth = np.load("./ground_truth.npy") data_values = np.load(os.path.join(data_folder, "post_data_sample.npy")) surface_coords = grid.surface # Interpolate surface on regular grid. X_surface_mesh, Y_surface_mesh, Z_surface_mesh = point_cloud_to_2D_regular_grid( surface_coords, n_grid=300) density_structured_grid = underground_point_cloud_to_structured_grid( volcano_coords, ground_truth, surface_coords, n_grid=50, fill_offset=1, fill_value=-1e6) # Threshold to only plot one region. vals[vals > 500] = 0 vals[vals < 0] = 0 mlab.surf(X_surface_mesh, Y_surface_mesh, Z_surface_mesh, opacity=0.35) d = mlab.pipeline.add_dataset(density_structured_grid) iso = mlab.pipeline.iso_surface(d) mlab.show()
def anim_pics_mandel(self, go_up=True, puiss=2): """Shows the Mandlebrot set in 3D. It saves the video in .avi. :param go_up: type of display, using in mandle_loop function :type go_up: boolean :param puiss: the exponent in the Mandlebrot equation, using in the mandle_loop function :type puiss: integer """ mlab.figure(size=(800, 800)) mandel = self.mandel_loop(go_up=go_up, puiss=puiss) mlab.surf(mandel, colormap='hot', warp_scale='auto', vmax=1.5) script_dir = os.path.dirname(__file__) results_dir = os.path.join(script_dir, 'Animations') if not os.path.isdir(results_dir): os.makedirs(results_dir) for t in range(0, 170, 1): mlab.view(elevation=180-t) imgname = os.path.join(results_dir, 'rotation' + str(t) + ".png") mlab.savefig(imgname) for t in range(0, 30, 1): mlab.view(distance=1000-5*t, elevation=180) imgname = os.path.join(results_dir, 'rotation' + str(170+t) + ".png") mlab.savefig(imgname) mlab.close() os.system("ffmpeg -r 20 -i " + os.path.join(results_dir, "rotation") + "%1d.png -vcodec mpeg4 -q:v 3 -ab 192k -y " + os.path.join(results_dir, "movie.avi"))
def ripple(): """Plot z = sin(10(x^2 + y^2))/10 on [-1,1]x[-1,1] using Mayavi.""" X, Y = np.mgrid[-1:1:.01, -1:1:0.01] Z = np.sin(10 * (X**2 + Y**2)) / 10 mlab.surf(X, Y, Z, colormap='RdYlGn') mlab.show() pass
def test_3_1(plot_u=1, version='scalar'): """ """ _c_ = 0.25 def u_e(x, y, t): return x*0 + _c_ def f(x, y, t): return 0.0 def I(x, y): return x*0 + _c_ def V(x, y): return 0.0 def q(x, y): return x*0 + 1 # np.sin(x)*np.cos(y) bc = {'N': None, 'W': None, 'E': None, 'S': None} b = 1.0 Nx = 8 Ny = 15 T = 15 Lx = 50 Ly = 50 # initialize plot # https://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#surf test_extent = (0, Lx, 0, Ly, 0, 1) x = np.linspace(0, Lx, Nx+1) # mesh points in x dir y = np.linspace(0, Ly, Ny+1) # mesh points in y dir X, Y = np.meshgrid(x, y) Z = I(X, Y) mlab.figure(1, size=(1920, 1080), fgcolor=(1, 1, 1), bgcolor=(0.5, 0.5, 0.5)) ms1 = mlab.surf(X.T, Y.T, Z.T, colormap='Spectral') ms2 = mlab.surf(X.T, Y.T, Z.T, color=(0.0, .0, .0), representation="wireframe") mlab.outline(ms1, color=(0.7, .7, .7), extent=test_extent) ax = mlab.axes(ms1, color=(.7, .7, .7), extent=test_extent, ranges=test_extent, xlabel='X', ylabel='Y', zlabel='u(t)') ax.axes.label_format = '%.0f' mlab.view(142, -72, 32) def action(u, x, y, t, n): print(n) print(u) # print('action, t=', t, 'u=', u, 'x=', x, 'y=', y) u_exakt = u_e(X.T, Y.T, t[n]) ms1.mlab_source.set(z=u_exakt, scalars=u_exakt) ms2.mlab_source.set(z=u, scalars=u) mlab.title('Test, t = {:.2f}'.format(t[n])) return solver(I, f, q, bc, Lx, Ly, Nx, Ny, 0, T, b, V, user_action=action, version='vectorized', ue_const=_c_) mlab.show()
def surfLike(x=None, y=None, z=None, X=None, f=None): """ plot z(x,y) with the same scaling as X[2](X[0], X[1]) """ try: switch = (X.ndim == 2) except AttributeError: switch = False if switch: if x == None: x = arange(X.shape[0]) if y == None: y = arange(X.shape[1]) ml.surf(scLike(x, x), scLike(y, y), scLike(z, X), extent=scaleExtent(rgs(x, y, z), rgs(x, y, X)), figure=f) else: print "switch is false" if x == None: x = X[0] if y == None: y = X[1] if z == None: z = arange(x.shape[0] * y.shape[0]) ml.surf(scLike(x, X[0]), scLike(y, X[1]), scLike(z, X[2]), extent=scaleExtent(rgs(x, y, z), rgs(X[0], X[1], X[2])), figure=f) return f
def surf3(x=None, y=None, z=None, f=None, axeLab=['', '', ''], clf=True): """ 3 argument surface plot """ if x == None: x = arange(z.shape[0]) if y == None: y = arange(z.shape[1]) if z == None: z = arange(x.shape[0] * y.shape[0]) if clf: ml.clf(f) if z.ndim == 3: for i in range(z.shape[-1]): ml.surf(sc(x), sc(y), scLike(z[..., i], z[..., 0]), extent=ex, figure=f) axe(axeLab, rgs(x, y, z[..., 0]), f) else: ml.surf(sc(x), sc(y), sc(z), extent=ex, figure=f) axe(axeLab, rgs(x, y, z), f) out() return f
def ripple(): """Plot z = sin(10(x^2 + y^2))/10 on [-1,1]x[-1,1] using Mayavi.""" X, Y = np.mgrid[-1:1:.01, -1:1:0.01] Z = np.sin(10*(X**2+Y**2))/10 mlab.surf(X,Y,Z, colormap='RdYlGn') mlab.show() pass
def plot_3D( self ): x = self.compute3D_plot[0] y = self.compute3D_plot[1] z = self.compute3D_plot[2] # print x_axis, y_axis, z_axis if self.autowarp_bool: x = x / x[-1] y = y / y[-1] z = z / z[-1] * self.z_scale mlab.surf( x, y , z, representation = 'wireframe' ) engine = Engine() engine.start() if len( engine.scenes ) == 75.5: engine.new_scene() surface = engine.scenes[0].children[0].children[0].children[0].children[0].children[0] surface.actor.mapper.scalar_range = np.array( [ 6.97602671, 8.8533387 ] ) surface.actor.mapper.scalar_visibility = False scene = engine.scenes[0] scene.scene.background = ( 1.0, 1.0, 1.0 ) surface.actor.property.specular_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.diffuse_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.ambient_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.color = ( 0.0, 0.0, 0.0 ) surface.actor.property.line_width = 1. scene.scene.isometric_view() mlab.xlabel( self.x_name3D ) mlab.ylabel( self.y_name3D ) mlab.outline() mlab.show()
def lDOS(centers, heights, c=0.3, norm=True, show=False, fortran=True): """ This function returns a XYZ grid with a gaussian with a given height in each center """ def calc_lDOS(x, y, centers, heights, c=0.3): def gaussian3d(x, y, r0, a=1, c=0.3): r = np.sqrt((x - r0[0])**2 + (y - r0[1])**2) return a * np.exp(-(r * r / (2 * c * c))) Z = 0.0 * x #for i in tqdm(range(len(centers))): for i in range(len(centers)): cent, high = centers[i], heights[i] Z += gaussian3d(x, y, cent, high) return Z X = centers[:, 0] Y = centers[:, 1] lx = 15 mx, Mx = -lx, lx #np.min(X),np.max(X) ly = 30 my, My = -ly, ly #np.min(Y),np.max(Y) mz, Mz = np.min(Z), np.max(Z) d = 3 * c #xv, yv = np.mgrid[np.min(X)-d:np.max(X)+d:0.1, np.min(Y)-d:np.max(Y)+d:0.1] x = np.linspace(mx - d, Mx + d, n0) y = np.linspace(my - d, My + d, int(n0 * (ly / lx))) yv, xv = np.meshgrid(x, y) if fortran: zv = num.ldos(xv, yv, centers, heights, 0.3) else: zv = calc_lDOS(xv, yv, centers, heights) if norm: zv = zv / np.max(zv) if show: mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) #, size=(1600,1080)) mlab.clf() f = 10 #np.mean( [np.max(xv)-np.min(xv), np.max(yv)-np.min(yv)] )/10 mlab.surf(xv, yv, f * zv) #mlab.axes(z_axis_visibility=False) # ========== # Ejes # ========== def ejes(n=3): mlab.plot3d([0, n], [0, 0], [0, 0]) mlab.plot3d([0, 0], [0, n], [0, 0]) mlab.plot3d([0, 0], [0, 0], [0, n]) mlab.text3d(n, -0.3, 0, 'X', scale=0.2) mlab.text3d(0, n, 0, 'Y', scale=0.2) mlab.text3d(0, 0, n - 0.15, 'Z', scale=0.2) ejes() mlab.show() return xv, yv, zv
def plot_3D_spectrum(self, xmin=None, xmax=None, xN=None, ymin=None, ymax=None, yN=None, trajectory=False, tube_radius=1e-2, part='imag'): """Plot the Riemann sheet structure around the EP. Parameters: ----------- xmin, xmax: float Dimensions in x-direction. ymin, ymax: float Dimensions in y-direction. xN, yN: int Number of sampling points in x and y direction. trajectory: bool Whether to include a projected trajectory of the eigenbasis coefficients. part: str Which function to apply to the eigenvalues before plotting. tube_radius: float Trajectory tube thickness. """ from mayavi import mlab X, Y, Z = self.sample_H(xmin, xmax, xN, ymin, ymax, yN) Z0, Z1 = [Z[..., n] for n in (0, 1)] def get_min_and_max(*args): data = np.concatenate(*args) return data.min(), data.max() surf_kwargs = dict(colormap='Spectral', mask=np.diff(Z0.real) > 0.015) mlab.figure(0) Z_min, Z_max = get_min_and_max([Z0.real, Z1.real]) mlab.surf(X.real, Y.real, Z0.real, vmin=Z_min, vmax=Z_max, **surf_kwargs) mlab.surf(X.real, Y.real, Z1.real, vmin=Z_min, vmax=Z_max, **surf_kwargs) mlab.axes(zlabel="Re(E)") mlab.figure(1) Z_min, Z_max = get_min_and_max([Z0.imag, Z1.imag]) mlab.mesh(X.real, Y.real, Z0.imag, vmin=Z_min, vmax=Z_max, **surf_kwargs) mlab.mesh(X.real, Y.real, Z1.imag, vmin=Z_min, vmax=Z_max, **surf_kwargs) mlab.axes(zlabel="Im(E)") if trajectory: x, y = self.get_cycle_parameters(self.t) _, c1, c2 = self.solve_ODE() for i, part in enumerate([np.real, np.imag]): e1, e2 = [part(self.eVals[:, n]) for n in (0, 1)] z = map_trajectory(c1, c2, e1, e2) mlab.figure(i) mlab.plot3d(x, y, z, tube_radius=tube_radius) mlab.points3d(x[0], y[0], z[0], # color=line_color, scale_factor=1e-1, mode='sphere') 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 plot_3d(pdf_A, pdf_B, filename, scale=2e2): mlab.clf() mlab.surf(pdf_A, colormap='Reds', warp_scale=scale) mlab.surf(pdf_B, colormap='Blues', warp_scale=scale) mlab.view(distance=500, focalpoint=(3, 2, 0)) # the figure is saved and displayed as an image # because the interactive version is not convertible to pdf mlab.savefig(filename=filename, size=(2000, 2000))
def plot_3d_mayavi(X, Y, Z): f = figure(bgcolor=(1, 1, 1)) surf(X.T, Y.T, Z, figure=f, warp_scale='auto') axes(xlabel='N Samples', ylabel='Sample', zlabel='Gradient', z_axis_visibility=False, nb_labels=10, line_width=1) show()
def zoom3D(npkd, zoom, fontsize=0.7, font='times', colormap='blue-red', showaxes=True): """ use the zoom region and display it in interactive 3D zoom : f1lo, f1up, f2lo, f2up - expressed in current unit remark, use a small zoom region ! x = axis 2 y = axis 1 z = intensity """ # z1lo = int(npkd.axis1.ctoi(zoom[0])) # z1up = int(npkd.axis1.ctoi(zoom[1])) # z2lo = int(npkd.axis2.ctoi(zoom[2])) # z2up = int(npkd.axis2.ctoi(zoom[3])) z1lo, z1up, z2lo, z2up = npk.parsezoom(npkd, zoom) #print (z1lo, z1up, z2lo, z2up) # d2 = npkd.extract(*zoom) # extract modifies the data - # d3 = d2.get_buffer() # d4 = np.array(d3) # d5 = d4.transpose() # get_buffer() loads everything in memory - so we'll do it line by line d5 = np.zeros((z2up - z2lo + 1, z1up - z1lo + 1)) # tranposed matrix compared to npkd for i in range(z2lo, z2up + 1): cc = npkd.col(i) # going column wise is probably faster ... d5[i - z2lo, :] = cc[ z1lo:z1up + 1] # taking a slice out of a npkdata returns a np.array zmax = np.amax(d5) zmin = np.amin(d5) # 0 - some data-set are negative xmin = zoom[2] xmax = zoom[3] ymin = zoom[0] ymax = zoom[1] mlab.figure(bgcolor=(1., 1., 1.), fgcolor=(0., 0., 0.)) mlab.surf(d5, extent=[0, 1000, 0, 1000, 0, 1000], warp_scale='auto', colormap=colormap) ax = mlab.axes(x_axis_visibility=showaxes, y_axis_visibility=showaxes, z_axis_visibility=showaxes, xlabel="F2 " + npkd.axis2.currentunit, ylabel="F1 " + npkd.axis1.currentunit, zlabel='Intensity', ranges=[xmin, xmax, ymin, ymax, zmin, zmax], nb_labels=5) ax.label_text_property.font_family = font ax.title_text_property.font_family = font ax.axes.font_factor = fontsize
def surface_plot(): N = 100 e = 0.01 x, y = np.mgrid[e:1 - e:N * 1j, e:1 - e:N * 1j] f = lambda x, y: g(x, y, z(x, y), 0.01) mlab.surf(x, y, f, warp_scale="auto") mlab.points3d(0, 0, 0) mlab.show()
def vis(g, f, f0, s, sv): from mayavi import mlab x, y = s.T z = sv mlab.points3d(x, y, z, scale_factor=0.2, scale_mode='none') x, y = (g[..., i] for i in range(2)) mlab.surf(x, y, f) print(f0, sv) mlab.show()
def UpdatedSceneSettings(self): self.updatedScene.interactor.interactor_style = \ tvtk.InteractorStyleTerrain() # The distance value is set in such a way that the entire surface should be visible without need to zoom out. self.updatedScene.scene.mlab.view(30, 60, distance=2.5 * 512) mlab.surf(np.zeros([2, 2]), figure=self.updatedScene.mayavi_scene, opacity=0) # Dummy surface mlab.text(0.6, 0.9, 'Eroded', width=0.4)
def display(self): if self.detector_position is not None: det_position = self.beginning + self.detector_position * self.width const = -det_position.dot(self.n) y = y = np.linspace(-self.R/2, self.R/2, 10) y, z = np.meshgrid(y, y) x = (-self.n[1]*y - self.n[2]*z - const) * (1./self.n[0]) mlab.surf(x, y, z, transparent=True, opacity=.2)
def __init__(self, wp_list, np_file='/tmp/magnetic_ground_truth.np', width=800, height=600): self.debug = True self.width = width self.height = height self.wp_list = wp_list self.f = mlab.figure(size=(self.width, self.height)) visual.set_viewer(self.f) v = mlab.view(135, 180) self.balls = [] self.trajectories = [] colors = list(RoiSimulator.color_codes) color_black = colors.pop(0) color_red = colors.pop(0) wp_curve = visual.curve(color=color_red, radius=RoiSimulator.curve_radius) hist_pos = [] for i in xrange(len(self.wp_list)): ball = visual.sphere(color=color_black, radius=RoiSimulator.ball_radius) wp = self.wp_list[i] ball.x = wp[1] ball.y = wp[0] ball.z = wp[2] self.balls.append(ball) arr = visual.vector(float(wp[1]), float(wp[0]), float(wp[2])) hist_pos.append(arr) wp_curve.extend(hist_pos) x = np.linspace(0, self.width, 1) y = np.linspace(0, self.height, 1) z = np.loadtxt(np_file) z *= 255.0 / z.max() # HARDCODED # Todo: REMOVE THIS CODE ON THE FINAL RELEASE for xx in xrange(0, 200): for yy in xrange(400, 600): z[yy][xx] = 0 mlab.surf(x, y, z)
def problem8(): opener = urllib.URLopener() opener.retrieve('https://s3.amazonaws.com/storage.enthought.com/www/sample_data/N36W113.hgt.zip', 'N36W113.hgt.zip') data = np.fromstring(zipfile.ZipFile('N36W113.hgt.zip').read('N36W113.hgt'), '>i2').reshape((3601, 3601)).astype('float32') data = data[:1000, 900:1900] data[data == -32768] = data[data>0].min() mlab.figure(size=(400, 320), bgcolor = (.16, .28, .46)) mlab.surf(data, colormap="gist_earth", warp_scale=.2, vmin=1200, vmax=1610) mlab.view(-5.9, 83, 570, [5.3, 20, 238]) return mlab.gcf()
def viewer_original_vs_ransac_pointcloud_vs_plane(ransac_pcl, original_pcl, plane_model): sensor_range = 120.0 mlab.figure(bgcolor=(1, 1, 1)) x, y = np.ogrid[-sensor_range+50:sensor_range+50:1, -sensor_range:sensor_range:1] mlab.points3d(original_pcl[:, 0], original_pcl[:, 1], original_pcl[:, 2], color=(0, 0, 0), mode='point') mlab.points3d(ransac_pcl[:, 0], ransac_pcl[:, 1], ransac_pcl[:, 2], color=(1, 0, 0), mode='point') mlab.surf(x, y, (-plane_model[3] - (plane_model[0]*x) - (plane_model[1]*y)) / plane_model[2], color=(0.8, 0.8, 1), opacity=0.3) mlab.show() return
def mayavi_surf(): """ 绘制mayavi surf图 :return: """ pk_x, pk_y = np.mgrid[-5:5:70j, -5:5:70j] pk_z = peaks(pk_x, pk_y) mlab.surf(pk_z, warp_scale='auto', colormap='jet') mlab.colorbar() mlab.show()
def __init__(self, hex_list, np_file='/tmp/magnetic_ground_truth.np', robot_height=40, width=800, height=600, start_point=(0, 0, 0)): self.debug = False self.animator = None self.movement_mode = 0 self.start_point = start_point self.robot_height = robot_height self.width = width self.height = height self.f = mlab.figure(size=(self.width, self.height)) visual.set_viewer(self.f) v = mlab.view(270, 180) #print v engine = mlab.get_engine() s = engine.current_scene s.scene.interactor.add_observer('KeyPressEvent', self.keypress_callback) self.robots = [] colors = list(PathRobustSimulator.color_codes) for key, local_hex_list in sorted(hex_list['internal_routes'].items()): color = colors.pop(0) ball = visual.sphere(color=color, radius=PathRobustSimulator.ball_radius) ball.x = self.start_point[0] ball.y = self.start_point[1] ball.z = self.start_point[2] curve = visual.curve(color=color, radius=PathRobustSimulator.curve_radius) r_ball = RobotBall(key, local_hex_list, hex_list['external_routes'][key], ball, curve) self.robots.append(r_ball) x = np.linspace(0, self.width, 1) y = np.linspace(0, self.height, 1) z = np.loadtxt(np_file) z *= 255.0 / z.max() mlab.surf(x, y, z) self.master_cmd = MasterCommand(self.robots)
def __init__(self, hex_list, np_file='/tmp/magnetic_ground_truth.np', robot_height=40, width=800, height=600, start_point=(0, 0, 0), message='experiment default message...'): self.debug = False self.animator = None self.movement_mode = 0 self.start_point = start_point self.robot_height = robot_height self.message = message self.start_time = int(time.time() * 1000) self.width = width self.height = height self.f = mlab.figure(size=(self.width, self.height)) visual.set_viewer(self.f) v = mlab.view(270, 180) #print v engine = mlab.get_engine() self.s = engine.current_scene self.s.scene.interactor.add_observer('KeyPressEvent', self.keypress_callback) self.robots = [] colors = list(PathBatterySimulator.color_codes) for key, local_hex_list in sorted(hex_list['internal_routes'].items()): color = colors.pop(0) ball = visual.sphere(color=color, radius=PathBatterySimulator.ball_radius) ball.x = self.start_point[0] ball.y = self.start_point[1] ball.z = self.start_point[2] r, g, b = color rt = r + (0.25 * (1 - r)) gt = g + (0.25 * (1 - g)) bt = b + (0.25 * (1 - b)) curve_color = (rt, gt, bt) curve = visual.curve(color=curve_color, radius=PathBatterySimulator.curve_radius) r_ball = RobotBall(key, local_hex_list, hex_list['external_routes'][key], ball, curve) self.robots.append(r_ball) x = np.linspace(0, self.width, 1) y = np.linspace(0, self.height, 1) z = np.loadtxt(np_file) z *= 255.0/z.max() mlab.surf(x, y, z) self.master_cmd = MasterCommand(self.robots)
def draw_working_area(self, width, height): color = (0.9, 0.9, 0.7) x, y = np.mgrid[0:height + 1:10, 0:width + 1:10] z = np.zeros(x.shape) mlab.surf(x, y, z, color=color, line_width=1.0, representation='wireframe', warp_scale=self.scale)
def __init__(self, **traits): # Has to be done since it's a Traits class super(MayaviTraitsApp, self).__init__(**traits) x, y = mgrid[-5:5:100j, -5:5:100j] r = sqrt(x**2 + y**2) z = 5*sin(r)/r # Build the visualization of the data: specifying which Mayavi scene to # use is necessary mlab.surf(x, y, z, figure=self.scene.mayavi_scene)
def test_Gaussian(plot_u=1, version='scalar'): """ Initial Gaussian bell in the middle of the domain. plot: not plot: 0; mesh: 1, surf: 2. """ # Clean up plot files for name in glob('tmp_*.png'): os.remove(name) def V(x, y): return 0.0 def I(x, y): return exp(-(x-Lx/2.0)**2/2.0 - (y-Ly/2.0)**2/2.0) def f(x, y, t): return 0.0 Nx = 40 Ny = 40 T = 15 Lx = 10 Ly = 10 q = 1.0 b = 1.0 # initialize plot # https://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#surf gauss_extent = (0, Lx, 0, Ly, 0, 1) x = np.linspace(0, Lx, Nx+1) # mesh points in x dir y = np.linspace(0, Ly, Ny+1) # mesh points in y dir X, Y = np.meshgrid(x, y) Z = I(X, Y) mlab.figure(1, size=(1920, 1080), fgcolor=(1, 1, 1), bgcolor=(0.5, 0.5, 0.5)) ms1 = mlab.surf(X.T, Y.T, Z.T, colormap='Spectral') ms2 = mlab.surf(X.T, Y.T, Z.T, color=(0.0, .0, .0), representation="wireframe") mlab.outline(ms1, color=(0.7, .7, .7), extent=gauss_extent) ax = mlab.axes(ms1, color=(.7, .7, .7), extent=gauss_extent, ranges=gauss_extent, xlabel='X', ylabel='Y', zlabel='u(t)') ax.axes.label_format = '%.0f' mlab.view(142, -72, 32) bc = {'N': None, 'W': None, 'E': None, 'S': None} def action(u, x, y, t, n): ms1.mlab_source.set(z=u, scalars=u) ms2.mlab_source.set(z=u, scalars=u) mlab.title('Gaussian bell, t = {:.2f}'.format(t[n])) solver(I, f, q, bc, Lx, Ly, Nx, Ny, 0, T, b, V, user_action=action, version='vectorized') # vectorized or scalar mlab.show()
def create_surf_map(self, zip_path, hgt_path, map_offset_x = 0.0, map_offset_y = 0.0, map_offset_z = 0.0): self.parse_srtm_data(zip_path, hgt_path) mlab.surf(self._data, name=hgt_path, colormap='gist_earth', warp_scale=0.2, vmin=self.vmin, vmax=self.vmax) self.adjust_offsets(map_offset_x, map_offset_y, map_offset_z) del self._data
def plotData2D(a): """ Reduce one dimension of the 3D array """ n = np.empty((a.shape[0], a.shape[1]), dtype=a.dtype) for i in range(a.shape[0]): for j in range(a.shape[1]): s = np.sum(a[i, j, :]) n[i, j] = np.round(s/20) mlab.surf(n) mlab.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 load_3D_plot( self ): config = 0 os.chdir( 'DATA' ) # os.chdir( self.load_folder3D ) os.chdir( self.dropdownls3D ) x = np.load( 'x.npy' ) y = np.load( 'y.npy' ) z = np.load( 'z.npy' ) print 'min_x', np.min( x ) print 'max_x', np.max( x ) print 'min_y', np.min( y ) print 'max_y', np.max( y ) print 'min_z', np.min( z ) print 'max_z', np.max( z ) # print x_axis, y_axis, z_axis engine = Engine() engine.start() if len( engine.scenes ) == 0: engine.new_scene # print os.curdir # os.chdir( '.' )() if self.autowarp_bool: x = x / x[-1] y = y / y[0][-1] z = z / z[-1] * self.z_scale # print x, y, z mlab.surf( x, y , z, representation = 'wireframe', line_width = 10 ) # ,warp_scale = "auto" if 'config.py' in os.listdir( os.curdir ): execfile( 'config.py' ) os.chdir( os.pardir ) os.chdir( os.pardir ) else: os.chdir( os.pardir ) os.chdir( os.pardir ) surface = engine.scenes[0].children[0].children[0].children[0].children[0].children[0] surface.actor.mapper.scalar_range = np.array( [ 6.97602671, 8.8533387 ] ) surface.actor.mapper.scalar_visibility = False scene = engine.scenes[0] scene.scene.background = ( 1.0, 1.0, 1.0 ) surface.actor.property.specular_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.diffuse_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.ambient_color = ( 0.0, 0.0, 0.0 ) surface.actor.property.color = ( 0.0, 0.0, 0.0 ) surface.actor.property.line_width = 1. scene.scene.isometric_view() mlab.outline() outline = engine.scenes[0].children[0].children[0].children[0].children[0].children[1] outline.actor.property.specular_color = ( 0.0, 0.0, 0.0 ) outline.actor.property.diffuse_color = ( 0.0, 0.0, 0.0 ) outline.actor.property.ambient_color = ( 0.0, 0.0, 0.0 ) outline.actor.property.color = ( 0.0, 0.0, 0.0 ) mlab.show()
def surf3d(df, **surfargs): """ Mayavi mlab surf plot from a dataframe. For now, just posting here because it works, not sure how necessary it will be.""" from mayavi import mlab warp_scale=surfargs.pop('warp_scale', 'auto') ### So this is how I need to overcome glitches to pass x,y in if they are needed. If no axis needed, ### see below. #mlab.surf(np.asarray(list(df.columns)), np.asarray(list(df.index)) , np.asarray(df), warp_scale='auto') mlab.surf(np.asarray(df), warp_scale=warp_scale, **surfargs) mlab.show()
def show_scalar_in_mayavi(self, fld, max_val=None, **kwargs): if max_val is not None: fld[fld > max_val] = max_val fld[fld < -max_val] = -max_val if len(fld.shape) == 1: fld = fld.reshape(self.nd_points.shape[1:]) nd_points = self.nd_points.squeeze()[self._get_nontrivial_dims()] squeezed_fld = fld.squeeze() from mayavi import mlab mlab.surf(nd_points[0], nd_points[1], squeezed_fld, **kwargs)
def plot_data(cls, geomdim, p, data, style="-", opacity=1.0): if geomdim == 1: # 2d plot plt.plot(p[0], data, style) # plt.ylim([-1, 1]) plt.show() else: # 3d plot assert geomdim == 2 if style == "-": mlab.surf(p[0], p[1], data, opacity=opacity) else: mlab.points3d(p[0], p[1], data)
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_potential(grid, potential, along_axes=False, interactive=False, view=None, size=(800,700)): # The Grid u, v = grid.get_nodes(split=True, flat=False) u = real(u) v = real(v) # Create potential and evaluate eigenvalues potew = potential.evaluate_eigenvalues_at(grid) potew = [ level.reshape(grid.get_number_nodes(overall=False)) for level in potew ] # Plot the energy surfaces of the potential fig = mlab.figure(size=size) for level in potew: if view is not None: mlab.surf(u, v, real(level), extent=view) else: mlab.surf(u, v, real(level)) fig.scene.parallel_projection = True fig.scene.isometric_view() fig.scene.show_axes = True mlab.savefig("potential_3D_view.png") # Parallele views if along_axes is True: fig.scene.x_minus_view() mlab.savefig("potential_xm_view.png") fig.scene.x_plus_view() mlab.savefig("potential_xp_view.png") fig.scene.y_minus_view() mlab.savefig("potential_ym_view.png") fig.scene.y_plus_view() mlab.savefig("potential_yp_view.png") fig.scene.z_minus_view() mlab.savefig("potential_zm_view.png") fig.scene.z_plus_view() mlab.savefig("potential_zp_view.png") if interactive is True: # Enable interactive plot mlab.show() else: mlab.close(fig)
def animateGIF(filename, prices): '''Creates a mayavi visualization of a pd DataFrame containing stock prices Then uses MoviePy to animate and save as a gif Inputs: prices => a pd DataFrame, w/ index: dates; columns: company names ''' #Because of mayavi requirements, replace dates and company names with integers #until workaround is figured out x_length, y_length = prices.shape xTime = np.array([list(xrange(x_length)),] * y_length).transpose() yCompanies = np.array([list(xrange(y_length)),] * x_length) #Sort indexed prices by total return on last date lastDatePrices = prices.iloc[-1] lastDatePrices.sort_values(inplace=True) sortOrder = lastDatePrices.index zPrices = prices[sortOrder] #Create mayavi2 object dims = xTime.shape fig = mlab.figure(bgcolor=(.4,.4,.4)) vis = mlab.surf(xTime, yCompanies, zPrices) mlab.outline(vis) mlab.orientation_axes(vis) mlab.axes(vis, nb_labels=0, xlabel = 'Time', ylabel = 'Company', zlabel = 'Price') # duration = 2 #Duration of the animation in seconds (will loop) animation = mpy.VideoClip(make_frame, duration = 4).resize(1.0) # animation.write_videofile('prototype_animation.mp4', fps=20) animation.write_gif(filename, fps=20)
def visualizePrices(prices): '''Creates a mayavi visualization of a pd DataFrame containing stock prices Inputs: prices => a pd DataFrame, w/ index: dates; columns: company names ''' #Because of mayavi requirements, replace dates and company names with integers #until workaround is figured out x_length, y_length = prices.shape xTime = np.array([list(xrange(x_length)),] * y_length).transpose() yCompanies = np.array([list(xrange(y_length)),] * x_length) #Sort indexed prices by total return on last date lastDatePrices = prices.iloc[-1] lastDatePrices.sort_values(inplace=True) sortOrder = lastDatePrices.index zPrices = prices[sortOrder] #Create mayavi2 object dims = xTime.shape fig = mlab.figure(bgcolor=(.4,.4,.4)) vis = mlab.surf(xTime, yCompanies, zPrices) mlab.outline(vis) mlab.orientation_axes(vis) #mlab.title('S&P 500 Market Data Visualization', size = .25) mlab.axes(vis, nb_labels=0, xlabel = 'Time', ylabel = 'Company', zlabel = 'Price') #Functionality to be added: # cursor3d = mlab.points3d(0., 0., 0., mode='axes', # color=(0, 0, 0), # scale_factor=20) #picker = fig.on_mouse_pick(picker_callback) mlab.show()
def etsIntro(): 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)
def animateGIF(filename, prices): '''Creates a mayavi visualization of a pd DataFrame containing stock prices Then uses MoviePy to animate and save as a gif Inputs: prices => a pd DataFrame, w/ index: dates; columns: company names ''' #Imports mlab here to delay starting of mayavi engine until necessary from mayavi import mlab #Because of current mayavi requirements, replaces dates and company names with integers x_length, y_length = prices.shape xTime = np.array([list(xrange(x_length)),] * y_length).transpose() yCompanies = np.array([list(xrange(y_length)),] * x_length) #Sort indexed prices by total return on last date lastDatePrices = prices.iloc[-1] lastDatePrices.sort_values(inplace=True) sortOrder = lastDatePrices.index zPrices = prices[sortOrder] #Create mayavi2 object fig = mlab.figure(bgcolor=(.4,.4,.4)) vis = mlab.surf(xTime, yCompanies, zPrices) mlab.outline(vis) mlab.orientation_axes(vis) mlab.axes(vis, nb_labels=0, xlabel = 'Time', ylabel = 'Company', zlabel = 'Price') animation = mpy.VideoClip(make_frame, duration = 4).resize(1.0) animation.write_gif(filename, fps=20)
def visualizePrices(prices): '''Creates a mayavi visualization of a pd DataFrame containing stock prices Inputs: prices => a pd DataFrame, w/ index: dates; columns: company names ''' #Imports mlab here to delay starting of mayavi engine until necessary from mayavi import mlab #Because of current mayavi requirements, replaces dates and company names with integers x_length, y_length = prices.shape xTime = np.array([list(xrange(x_length)),] * y_length).transpose() yCompanies = np.array([list(xrange(y_length)),] * x_length) #Sort indexed prices by total return on last date lastDatePrices = prices.iloc[-1] lastDatePrices.sort_values(inplace=True) sortOrder = lastDatePrices.index zPrices = prices[sortOrder] #Create mayavi2 object fig = mlab.figure(bgcolor=(.4,.4,.4)) vis = mlab.surf(xTime, yCompanies, zPrices) mlab.outline(vis) mlab.orientation_axes(vis) #mlab.title('S&P 500 Market Data Visualization', size = .25) mlab.axes(vis, nb_labels=0, xlabel = 'Time', ylabel = 'Company', zlabel = 'Price') mlab.show()
def test_mayaxes(): from mayaxes import mayaxes from scipy import sqrt,sin,meshgrid,linspace,pi import mayavi.mlab as mlab resolution = 200 lambda_var = 3 theta = linspace(-lambda_var*2*pi,lambda_var*2*pi,resolution) x, y = meshgrid(theta, theta) r = sqrt(x**2 + y**2) z = sin(r)/r fig = mlab.figure(size=(1024,768)) surf = mlab.surf(theta,theta,z,colormap='jet',opacity=1.0,warp_scale='auto') mayaxes(title_string='Figure 1: Diminishing polar cosine series', \ xlabel='X data',ylabel='Y data',zlabel='Z data',handle=surf) fig.scene.camera.position = [435.4093863309094, 434.1268937227623, 315.90311468125287] fig.scene.camera.focal_point = [94.434632665253829, 93.152140057106593, -25.071638984402856] fig.scene.camera.view_angle = 30.0 fig.scene.camera.view_up = [0.0, 0.0, 1.0] fig.scene.camera.clipping_range = [287.45231734040635, 973.59247058049255] fig.scene.camera.compute_view_plane_normal() fig.scene.render() mlab.show()
def plot_mcontour(self, ndim0, ndim1, z, show_mode): "use mayavi.mlab to plot contour." if not mayavi_installed: self.__logger.info("Mayavi is not installed on your device.") return #do 2d interpolation #get slice object s = np.s_[0:ndim0:1, 0:ndim1:1] x, y = np.ogrid[s] mx, my = np.mgrid[s] #use cubic 2d interpolation interpfunc = interp2d(x, y, z, kind='cubic') newx = np.linspace(0, ndim0, 600) newy = np.linspace(0, ndim1, 600) newz = interpfunc(newx, newy) #mlab face = mlab.surf(newx, newy, newz, warp_scale=2) mlab.axes(xlabel='x', ylabel='y', zlabel='z') mlab.outline(face) #save or show if show_mode == 'show': mlab.show() elif show_mode == 'save': mlab.savefig('mlab_contour3d.png') else: raise ValueError('Unrecognized show mode parameter : ' + show_mode) return