def display(self,bgcolor=None,showAxes=False): mlab.figure(bgcolor=bgcolor) for x,y,z,op,col in zip(self.xMesh,self.yMesh,self.zMesh,self.meshOpacity,self.meshColor): mlab.mesh(x,y,z,opacity=op,color=col) if showAxes: mlab.axes() 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 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 labels(self): ''' Add 3d text to show the axes. ''' fontsize = max(self.xrang, self.yrang)/40. tcolor = (1,1,1) mlab.text3d(self.xrang/2,-40,self.zrang+40,'R.A.',scale=fontsize,orient_to_camera=True,color=tcolor) mlab.text3d(-40,self.yrang/2,self.zrang+40,'Decl.',scale=fontsize,orient_to_camera=True,color=tcolor) mlab.text3d(-40,-40,self.zrang/2-10,'V (km/s)',scale=fontsize,orient_to_camera=True,color=tcolor) # Label the coordinates of the corners # Lower left corner ra0 = self.extent[0]; dec0 = self.extent[2] c = coord.ICRS(ra=ra0, dec=dec0, unit=(u.degree, u.degree)) RA_ll = str(int(c.ra.hms.h))+'h'+str(int(c.ra.hms.m))+'m'+str(round(c.ra.hms.s,1))+'s' mlab.text3d(0,-20,self.zrang+20,RA_ll,scale=fontsize,orient_to_camera=True,color=tcolor) DEC_ll = str(int(c.dec.dms.d))+'d'+str(int(abs(c.dec.dms.m)))+'m'+str(round(abs(c.dec.dms.s),1))+'s' mlab.text3d(-80,0,self.zrang+20,DEC_ll,scale=fontsize,orient_to_camera=True,color=tcolor) # Upper right corner ra0 = self.extent[1]; dec0 = self.extent[3] c = coord.ICRS(ra=ra0, dec=dec0, unit=(u.degree, u.degree)) RA_ll = str(int(c.ra.hms.h))+'h'+str(int(c.ra.hms.m))+'m'+str(round(c.ra.hms.s,1))+'s' mlab.text3d(self.xrang,-20,self.zrang+20,RA_ll,scale=fontsize,orient_to_camera=True,color=tcolor) DEC_ll = str(int(c.dec.dms.d))+'d'+str(int(abs(c.dec.dms.m)))+'m'+str(round(abs(c.dec.dms.s),1))+'s' mlab.text3d(-80,self.yrang,self.zrang+20,DEC_ll,scale=fontsize,orient_to_camera=True,color=tcolor) # V axis if self.extent[5] > self.extent[4]: v0 = self.extent[4]; v1 = self.extent[5] else: v0 = self.extent[5]; v1 = self.extent[4] mlab.text3d(-20,-20,self.zrang,str(round(v0,1)),scale=fontsize,orient_to_camera=True,color=tcolor) mlab.text3d(-20,-20,0,str(round(v1,1)),scale=fontsize,orient_to_camera=True,color=tcolor) mlab.axes(self.field, ranges=self.extent, x_axis_visibility=False, y_axis_visibility=False, z_axis_visibility=False) mlab.outline()
def plotDensity(mToB,coeffs,n=100,plotVals="real",plotBnd=True): """Plot boundary density with Mayavi INPUT: mToB - Mesh-to-Basis map coeffs - Coefficients of boundary density n - Discretisation points per element (default 100) plotVals - "real", "imag" or "abs" for real/imaginary part or absolute values (default "real") plotBnd - Also plot boundary of shape (default True) """ from mayavi import mlab transforms={"real":numpy.real,"imag":numpy.imag,"abs":numpy.abs} x,f=evalDensity(mToB,coeffs,n) f=transforms[plotVals](f) xmin=min(x[0]) xmax=max(x[0]) ymin=min(x[1]) ymax=max(x[1]) zmin=max([-1,min(f)]) zmax=min([1,max(f)]) extent=[xmin,xmax,ymin,ymax,zmin,zmax] ranges=[xmin,xmax,ymin,ymax,min(f),max(f)] fig=mlab.figure(bgcolor=(1,1,1)) mlab.plot3d(x[0],x[1],f,extent=extent,color=(0,0,0),tube_radius=None,figure=fig) if plotBnd: mlab.plot3d(x[0],x[1],numpy.zeros(x[0].shape),extent=[xmin,xmax,ymin,ymax,0,0],tube_radius=None,figure=fig) mlab.axes(extent=extent,ranges=ranges,line_width=3.0,figure=fig) mlab.show()
def action(u, x, xv, y, yv, t, n): #print 'action, t=',t,'\nu=',u, '\Nx=',x, '\Ny=', y if plot == 1: mesh(xv, yv, u, title='t=%g' %t[n]) time.sleep(0.2) # pause between frames elif plot == 2: # mayavi plotting mlab.clf() extent1 = (0, 20, 0, 20,-2, 2) s = mlab.surf(x , y, u, colormap='Blues', warp_scale=5,extent=extent1) mlab.axes(s, color=(.7, .7, .7), extent=extent1, ranges=(0, 10, 0, 10, -1, 1), xlabel='', ylabel='', zlabel='', x_axis_visibility=False, z_axis_visibility=False) mlab.outline(s, color=(0.7, .7, .7), extent=extent1) mlab.text(2, -2.5, '', z=-4, width=0.1) mlab.colorbar(object=None, title=None, orientation='horizontal', nb_labels=None, nb_colors=None, label_fmt=None) mlab.title('test 1D t=%g' % t[n]) mlab.view(142, -72, 50) f = mlab.gcf() camera = f.scene.camera camera.yaw(0) if plot > 0: path = 'Figures_wave2D' time.sleep(0) # pause between frames if save_plot and plot != 2: filename = '%s/%08d.png' % (path, n) savefig(filename) # time consuming! elif save_plot and plot == 2: filename = '%s/%08d.png' % (path,n) mlab.savefig(filename) # time consuming!
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 show_sensors(pth, red=None, green=None): """ show sensors stored in a h5. :param red: a list of labels to be shown in red """ if red is None: red = [] if green is None: green = [] mlab.figure() sensors = h5py.File(pth) d = numpy.array(sensors['locations']) labels = list(sensors['labels']) highlight = numpy.ones(d.shape[0]) for i, l in enumerate(labels): if l in red: highlight[i] = 5.0 elif l in green: highlight[i] = 7.0 else: highlight[i] = 2.0 mlab.points3d(d[:,0], d[:,1], d[:,2], highlight, scale_mode='none') mlab.axes()
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 plot3D(name, X, Y, Z, zlabel): """ Plots a 3d surface plot of Z using the mayavi mlab.mesh function. Parameters ---------- name: string The name of the figure. X: 2d ndarray The x-axis data. Y: 2d ndarray The y-axis data. Z: 2d nd array The z-axis data. zlabel: The title that appears on the z-axis. """ mlab.figure(name) mlab.clf() plotData = mlab.mesh(X/(np.max(X) - np.min(X)), Y/(np.max(Y) - np.min(Y)), Z/(np.max(Z) - np.min(Z))) mlab.outline(plotData) mlab.axes(plotData, ranges=[np.min(X), np.max(X), np.min(Y), np.max(Y), np.min(Z), np.max(Z)]) mlab.xlabel('Space ($x$)') mlab.ylabel('Time ($t$)') mlab.zlabel(zlabel)
def 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
def plot(self): """Plots the geometry using the package Mayavi.""" print('\nPlot the three-dimensional geometry ...') from mayavi import mlab x_init = self.gather_coordinate('x', position='initial') y_init = self.gather_coordinate('y', position='initial') z_init = self.gather_coordinate('z', position='initial') x = self.gather_coordinate('x') y = self.gather_coordinate('y') z = self.gather_coordinate('z') figure = mlab.figure('body', size=(600, 600)) figure.scene.disable_render = False same = (numpy.allclose(x, x_init, rtol=1.0E-06) and numpy.allclose(y, y_init, rtol=1.0E-06) and numpy.allclose(z, z_init, rtol=1.0E-06)) if not same: mlab.points3d(x_init, y_init, z_init, name='initial', scale_factor=0.01, color=(0, 0, 1)) mlab.points3d(x, y, z, name='current', scale_factor=0.01, color=(1, 0, 0)) mlab.axes() mlab.orientation_axes() mlab.outline() figure.scene.disable_render = True mlab.show()
def AortaSinusoidModelingVisualization(filename): path = 'C:\\Users\\shijingliu\\Dropbox\\Reggie\\Results\\Sinusoid Modeling Result (2 seconds window size)\\Aorta Modeling Results\\' file = filename finalname = path+file+'.csv' 'declare the x, y, z, s array for point visualization' index = 0 x_array = [] y_array = [] z_array = [] s_array = [] with open(finalname, 'rb') as csvfile: rowreader = csv.reader(csvfile) for row in rowreader: if index <1: index = index + 1 else: s = int(row[0]) x_data = float(row[1]) y_data = float(row[2]) z_data = float(row[3]) if (np.abs(x_data)<=20.0) and (np.abs(y_data)<=20.0) and (np.abs(z_data)<=200.0): s_array.append(s) x_array.append(x_data) y_array.append(y_data) z_array.append(z_data) mlab.axes(mlab.outline(mlab.points3d(x_array, y_array, z_array, s_array, colormap="Reds", scale_mode='none')))
def PlotHorizon3d(tss): """ Plot a list of horizons. Parameters ---------- tss : list of trappedsurface All the trapped surfaces to visualize. """ from mayavi import mlab cmaps = ['bone', 'jet', 'hot', 'cool', 'spring', 'summer', 'winter'] assert len(cmaps) > len(tss) extents = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] for ts, cm in zip(tss, cmaps): mlab.mesh(ts.X, ts.Y, ts.Z, colormap=cm, opacity=0.4) extents[0] = min(extents[0], np.min(ts.X)) extents[1] = max(extents[1], np.max(ts.X)) extents[2] = min(extents[2], np.min(ts.Y)) extents[3] = max(extents[3], np.max(ts.Y)) extents[4] = min(extents[4], np.min(ts.Z)) extents[5] = max(extents[5], np.max(ts.Z)) mlab.axes(extent=extents) mlab.outline(extent=extents) mlab.show()
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 ''' #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 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 draw_cloud(self, points3d, scale=1): scale = self.scale * scale mlab.points3d(points3d[:, 0], points3d[:, 1], points3d[:, 2], points3d[:, 2], colormap='jet', opacity=0.75, scale_factor=scale) mlab.outline() mlab.colorbar(title='Planar disparity (mm)') mlab.axes()
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 plot_u(u, x, xv, y, yv, t, n): """User action function for plotting.""" if t[n] == 0: time.sleep(2) if plot_method == 1: # Works well with Gnuplot backend, not with Matplotlib st.mesh(x, y, u, title='t=%g' % t[n], zlim=[-1,1], caxis=[-1,1]) elif plot_method == 2: # Works well with Gnuplot backend, not with Matplotlib st.surfc(xv, yv, u, title='t=%g' % t[n], zlim=[-1, 1], colorbar=True, colormap=st.hot(), caxis=[-1,1], shading='flat') elif plot_method == 3: print 'Experimental 3D matplotlib...under development...' # Probably too slow #plt.clf() ax = fig.add_subplot(111, projection='3d') u_surf = ax.plot_surface(xv, yv, u, alpha=0.3) #ax.contourf(xv, yv, u, zdir='z', offset=-100, cmap=cm.coolwarm) #ax.set_zlim(-1, 1) # Remove old surface before drawing if u_surf is not None: ax.collections.remove(u_surf) plt.draw() time.sleep(1) elif plot_method == 4: # Mayavi visualization mlab.clf() extent1 = (0, 20, 0, 20,-2, 2) s = mlab.surf(x , y, u, colormap='Blues', warp_scale=5,extent=extent1) mlab.axes(s, color=(.7, .7, .7), extent=extent1, ranges=(0, 10, 0, 10, -1, 1), xlabel='', ylabel='', zlabel='', x_axis_visibility=False, z_axis_visibility=False) mlab.outline(s, color=(0.7, .7, .7), extent=extent1) mlab.text(6, -2.5, '', z=-4, width=0.14) mlab.colorbar(object=None, title=None, orientation='horizontal', nb_labels=None, nb_colors=None, label_fmt=None) mlab.title('Gaussian t=%g' % t[n]) mlab.view(142, -72, 50) f = mlab.gcf() camera = f.scene.camera camera.yaw(0) if plot_method > 0: time.sleep(0) # pause between frames if save_plot: filename = 'tmp_%04d.png' % n if plot_method == 4: mlab.savefig(filename) # time consuming! elif plot_method in (1,2): st.savefig(filename) # time consuming!
def plotFancy(a): src = mlab.pipeline.scalar_field(a) mlab.pipeline.iso_surface(src, contours=[a.min() + 0.1 * a.ptp(), ], opacity=0.1) mlab.pipeline.iso_surface(src, contours=[a.max() - 0.1 * a.ptp(), ],) mlab.pipeline.image_plane_widget(src, plane_orientation='z_axes', slice_index=len(a[0,0,:])/2, ) mlab.axes(xlabel="x", ylabel="y", zlabel="z")
def plot(view="iso"): redis = Redis() px, py, pz = (redis.get('x'), redis.get('y'), redis.get('z')) if None in (px, py, pz): raise UntrainedException("You must train first!") x, y, z = (pickle.loads(px), pickle.loads(py), pickle.loads(pz)) fig = mlab.figure(size=(800, 600)) # these options could help on certain platforms # mlab.options.offscreen = True # fig.scene.off_screen_rendering = True # Define the points in 3D space # including color code based on Z coordinate. mlab.points3d(x, y, z, y) xlabel = "day of week" ylabel = "# logins" zlabel = "hour" mlab.axes(xlabel=xlabel, ylabel=ylabel, zlabel=zlabel, ranges=[0, 6, min(y), max(y), 0, 23]) mlab.scalarbar(title=ylabel, nb_labels=10, orientation='vertical') mlab.orientation_axes(xlabel=xlabel, ylabel=ylabel, zlabel=zlabel) views = {"xp": fig.scene.x_plus_view, "xm": fig.scene.x_minus_view, "yp": fig.scene.y_plus_view, "ym": fig.scene.y_minus_view, "zp": fig.scene.z_plus_view, "zm": fig.scene.z_minus_view, "iso": fig.scene.isometric_view } try: views[view]() except KeyError as e: raise PlotException("Invalid view option: %s" % view) # can't save directly to stringIO, so have to go through a file fig.scene.save_png('fig.png') # mayavi doesn't seem to play well with celery on some platforms and # doesn't shut down properly - probably because it's in a background thread # on centos, celery just throws a WorkerLostError after a couple of requests. # fig.remove() # fig.parent.close_scene(fig) # this doesn't work on centos: # mlab.close() with open('fig.png', 'rb') as f: buf = f.read() return buf
def show(self): '''Show the 3D diagram in the screen.''' from mayavi import mlab self.triangleMesh= mlab.triangular_mesh(self.x, self.y, self.z, self.triangles, scalars= self.scalars) mlab.colorbar(self.triangleMesh, orientation='vertical') mlab.outline(self.triangleMesh) mlab.axes(self.triangleMesh, xlabel= self.axialForceLabel, ylabel= self.bendingMomentYLabel, zlabel= self.bendingMomentZLabel) #mlab.title(self.title) mlab.show()
def draw_mesh(self, mesh, color=WHITE, opacity=0.7): x, y, z, triangles = self._get_triangular_mesh(mesh) mlab.triangular_mesh(x, y, z, triangles, color=color, opacity=opacity, representation='surface') #mlab.triangular_mesh(x, y, z, triangles, colormap='bone', # opacity=0.8, representation='surface') mlab.triangular_mesh(x, y, z, triangles, color=(0, 0, 0), line_width=1.0, representation='wireframe') mlab.outline() mlab.axes()
def _add_points(self, scene, name=None, new=None): scene.disable_render = True mlab.clf(figure=scene) x,y,z = np.random.rand(3,50) mlab.points3d(x,y,z, figure=scene.mayavi_scene ) mlab.axes() scene.disable_render = False
def labels(self): ''' Add 3d text to show the axes. ''' fontsize = max(self.xrang, self.yrang)/40. tcolor = (1,1,1) mlab.text3d(self.xrang/2,-10,self.zrang+10,'R.A.',scale=fontsize,orient_to_camera=True,color=tcolor) mlab.text3d(-10,self.yrang/2,self.zrang+10,'Decl.',scale=fontsize,orient_to_camera=True,color=tcolor) mlab.text3d(-10,-10,self.zrang/2-10,'V (km/s)',scale=fontsize,orient_to_camera=True,color=tcolor) # Add scale bars if self.leng != 0.0: distance = self.dist * 1e3 length = self.leng leng_pix = np.round(length/distance/np.pi*180./np.abs(self.hdr['cdelt1'])) bar_x = [self.xrang-20-leng_pix, self.xrang-20] bar_y = [self.yrang-10, self.yrang-10] bar_z = [0, 0] mlab.plot3d(bar_x, bar_y, bar_z, color=tcolor, tube_radius=1.) mlab.text3d(self.xrang-30-leng_pix,self.yrang-25,0,'{:.2f} pc'.format(length),scale=fontsize,orient_to_camera=False,color=tcolor) if self.vsp != 0.0: vspan = self.vsp vspan_pix = np.round(vspan/np.abs(self.hdr['cdelt3']/1e3)) bar_x = [self.xrang, self.xrang] bar_y = [self.yrang-10, self.yrang-10] bar_z = np.array([5, 5+vspan_pix])*self.zscale mlab.plot3d(bar_x, bar_y, bar_z, color=tcolor, tube_radius=1.) mlab.text3d(self.xrang,self.yrang-25,10,'{:.1f} km/s'.format(vspan),scale=fontsize,orient_to_camera=False,color=tcolor,orientation=(0,90,0)) # Label the coordinates of the corners # Lower left corner ra0 = self.extent[0]; dec0 = self.extent[2] c = SkyCoord(ra=ra0*u.degree, dec=dec0*u.degree, frame='icrs') RA_ll = str(int(c.ra.hms.h))+'h'+str(int(c.ra.hms.m))+'m'+str(round(c.ra.hms.s,1))+'s' mlab.text3d(0,-10,self.zrang+5,RA_ll,scale=fontsize,orient_to_camera=True,color=tcolor) DEC_ll = str(int(c.dec.dms.d))+'d'+str(int(abs(c.dec.dms.m)))+'m'+str(round(abs(c.dec.dms.s),1))+'s' mlab.text3d(-40,0,self.zrang+5,DEC_ll,scale=fontsize,orient_to_camera=True,color=tcolor) # Upper right corner ra0 = self.extent[1]; dec0 = self.extent[3] c = SkyCoord(ra=ra0*u.degree, dec=dec0*u.degree, frame='icrs') RA_ll = str(int(c.ra.hms.h))+'h'+str(int(c.ra.hms.m))+'m'+str(round(c.ra.hms.s,1))+'s' mlab.text3d(self.xrang,-10,self.zrang+5,RA_ll,scale=fontsize,orient_to_camera=True,color=tcolor) DEC_ll = str(int(c.dec.dms.d))+'d'+str(int(abs(c.dec.dms.m)))+'m'+str(round(abs(c.dec.dms.s),1))+'s' mlab.text3d(-40,self.yrang,self.zrang+5,DEC_ll,scale=fontsize,orient_to_camera=True,color=tcolor) # V axis if self.extent[5] > self.extent[4]: v0 = self.extent[4]; v1 = self.extent[5] else: v0 = self.extent[5]; v1 = self.extent[4] mlab.text3d(-10,-10,self.zrang,str(round(v0,1)),scale=fontsize,orient_to_camera=True,color=tcolor) mlab.text3d(-10,-10,0,str(round(v1,1)),scale=fontsize,orient_to_camera=True,color=tcolor) mlab.axes(self.field, ranges=self.extent, x_axis_visibility=False, y_axis_visibility=False, z_axis_visibility=False) mlab.outline()
def show_surface(pth): """ show surface from a h5 """ mlab.figure() cap = h5py.File(pth) v = numpy.array(cap['vertices']) t = numpy.array(cap['triangles']) mlab.triangular_mesh(v[:,0], v[:,1], v[:,2], t) mlab.axes()
def scatter3d(results, outcomes, policy=None): ''' Function for making a 3d scatter plots. This function will plot the 3 supplied outcomes against each other over time. If the data is a time series, end states will be used. :param results: The return from :meth:`perform_experiments`. :param outcomes: The names of the 3 outcomes of interest that are to be plotted. :param policy: Optional argument, if provided, only for that particular policy the scatter plot is generated. It is *recommended* that this argument is provided if there are indeed multiple policies. ''' if len(outcomes)!=3: raise EMAError("you provided %s outcomes, while you should supply 3" % (len(outcomes))) #prepare the data experiments, results = results #get the results for the specific outcome of interest results1 = results.get(outcomes[0]) results2 = results.get(outcomes[1]) results3 = results.get(outcomes[2]) results = [results1, results2, results3] #restrict to policy if provided if policy: logical = experiments['policy'] == policy results = [entry[logical] for entry in results] #convert time series temp = [] for entry in results: if len(entry.shape) > 1: if (entry.shape[1]>1): entry = entry[:,-1] temp.append(entry) results = temp #visualize results mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) extent = [0,1,0,1,0,1] s = mlab.points3d(results[0],results[1], results[2], extent=extent, mode='point') mlab.axes(xlabel=outcomes[0], ylabel=outcomes[1], zlabel = outcomes[2], ) mlab.show()
def plot_kern_3d(kern): """ Plot a ndarray -> do not use with big arrays !! it costs a lot :param kern: :return: plot the graph """ # noinspection PyUnusedLocal figure = mlab.figure('DensityPlot') mlab.points3d(kern) mlab.axes() mlab.show()
def axe(labs, rgs, f): """ add an axes object to the plot labs - list of axis labels rgs - array of axis ranges, may be produced by rgs f - figure to which to add the axes """ try: ml.axes(xlabel=labs[0], ylabel=labs[1], zlabel=labs[2], ranges=rgs, extent=ex, nb_labels=5, figure=f) except: ml.axes(xlabel=labs[0], ylabel=labs[1], zlabel=labs[2], ranges=rgs, extent=ex, figure=f)
def visualize(self, max_dist=0.1): try: from mayavi import mlab except: print("mayavi is not installed!") figure = mlab.figure('Signed Density Field') SCALE = 100 # The dimensions will be expressed in cm for better visualization. data = np.copy(self.data) data = np.minimum(max_dist, data) xmin, ymin, zmin = SCALE * self.origin xmax, ymax, zmax = SCALE * self.max_coords delta = SCALE * self.delta xi, yi, zi = np.mgrid[xmin:xmax:delta, ymin:ymax:delta, zmin:zmax:delta] data[data <= 0] -= 0.2 data = -data grid = mlab.pipeline.scalar_field(xi, yi, zi, data) vmin = np.min(data) vmax = np.max(data) mlab.pipeline.volume(grid, vmin=vmin, vmax=(vmax + vmin) / 2) mlab.axes() mlab.show()
def plot_cone_surface(X, Y, Z): # Some parameters (note size only really changes scale on axis) #sizeX,sizeY = 1,2 #amplitude = 1 #nPoints = 500 # Calculate wavenumbers #kx = nX*pi/sizeX #ky = nY*pi/sizeY x = np.array(X) y = np.array(Y) z = np.array(Z) #amplitude*np.sin(kx*X)*np.sin(ky*Y) xyz = np.vstack([x, y, z]) kde = stats.gaussian_kde(xyz) density = kde(xyz) # Plot scatter with mayavi figure = mlab.figure('DensityPlot') pts = mlab.points3d(x, y, z, density, scale_mode='none', scale_factor=0.07) mlab.axes() mlab.show() '''fig = plt.figure()
def make_frame(t): mlab.clf() src = mlab.pipeline.scalar_field(b) m = mlab.pipeline.iso_surface(src, contours=[0.8, 0.9, 1], opacity=0.3, colormap='Blues', figure=fig_myv) mlab.axes(ranges=[-650, 650, -650, 650, -350, 350], color=(0, 0, 0), nb_labels=5, xlabel='X(pc)', ylabel='Y(pc)', zlabel='Z(pc)', figure=fig_myv) mlab.view(azimuth=0, elevation=0, distance=500, figure=fig_myv) #m.scene.camera.elevation(-95) m.scene.camera.elevation(-10 * t) m.scene.camera.orthogonalize_view_up() #m.scene.camera.compute_view_plane_normal() return mlab.screenshot(antialiased=True)
def plot(self,lim=None): from mayavi import mlab if lim is None: # Calculate limits mus = np.concatenate(tuple([[N.mean] for N in filter(lambda N: N is not None, self.numN+self.denN)]), axis=0) maxs = np.amax(mus,axis=0) + 1 mins = np.amin(mus,axis=0) - 1 s = np.amax(maxs-mins) / 2 mid = (maxs + mins) / 2 lim = [[mid[i]-1.2*s, mid[i]+1.2*s] for i in range(maxs.shape[0])] if len(lim) == 3: # Evaluate xi,yi,zi = np.mgrid[lim[0][0]:lim[0][1]:50j, lim[1][0]:lim[1][1]:50j, lim[2][0]:lim[2][1]:50j] coords = np.vstack([item.ravel() for item in [xi, yi, zi]]) density = self.evaluate(coords.T).reshape(xi.shape) # Plot scatter with mayavi figure = mlab.figure('DensityPlot') grid = mlab.pipeline.scalar_field(xi, yi, zi, density) minval = 0 maxval = density.max() mlab.pipeline.volume(grid, vmin=minval, vmax=minval + .5*(maxval-minval)) mlab.axes() mlab.show()
def surface_3d(): """ 使用Mayavi将二维数组绘制成3D曲面 x * exp(x**2 - y**2) :return: """ import numpy as np # create data x, y = np.ogrid[-2:2:20j, -2:2:20j] z = x * np.exp(-x**2 - y**2) # view it from mayavi import mlab # 绘制一个三维空间中的曲面 pl = mlab.surf(x, y, z, warp_scale="auto") # 在三维空间中添加坐标轴 mlab.axes(xlabel='x', ylabel='y', zlabel='z') # 在三维空间中添加曲面区域的外框 mlab.outline(pl) mlab.show()
def test_baxter_gripper(): mesh_filename = '/home/jmahler/jeff_working/GPIS/data/grippers/baxter/gripper.obj' of = objf.ObjFile(mesh_filename) gripper_mesh = of.read() gripper_mesh.center_vertices_bb() #gripper_mesh.rescale(0.9) # to make fingertips at the wide 0.67 distance oof = objf.ObjFile(mesh_filename) oof.write(gripper_mesh) T_mesh_world = stf.SimilarityTransform3D(pose=tfx.pose(np.eye(4)), from_frame='world', to_frame='mesh') R_grasp_gripper = np.array([[0, 0, -1], [0, 1, 0], [1, 0, 0]]) R_mesh_gripper = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) t_mesh_gripper = np.array([0.005, 0.0, 0.055]) T_mesh_gripper = stf.SimilarityTransform3D(pose=tfx.pose(R_mesh_gripper, t_mesh_gripper), from_frame='gripper', to_frame='mesh') T_gripper_world = T_mesh_gripper.inverse().dot(T_mesh_world) T_grasp_gripper = stf.SimilarityTransform3D(pose=tfx.pose(R_grasp_gripper), from_frame='gripper', to_frame='grasp') T_mesh_gripper.save('/home/jmahler/jeff_working/GPIS/data/grippers/baxter/T_mesh_gripper.stf') T_grasp_gripper.save('/home/jmahler/jeff_working/GPIS/data/grippers/baxter/T_grasp_gripper.stf') gripper_params = {} gripper_params['min_width'] = 0.026 gripper_params['max_width'] = 0.060 f = open('/home/jmahler/jeff_working/GPIS/data/grippers/baxter/params.json', 'w') json.dump(gripper_params, f) MayaviVisualizer.plot_pose(T_mesh_world, alpha=0.05, tube_radius=0.0025, center_scale=0.005) MayaviVisualizer.plot_pose(T_gripper_world, alpha=0.05, tube_radius=0.0025, center_scale=0.005) MayaviVisualizer.plot_mesh(gripper_mesh, T_mesh_world, style='surface', color=(1,1,1)) mv.axes()
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 visualize_data(ast, Ug_array, grid): nx = grid['nx'] ny = grid['ny'] nz = grid['nz'] xg = grid['xg'] yg = grid['yg'] zg = grid['zg'] # plot some contour plots in mayavi # engine = mayavi.api.Engine() # engine.start() # scene = engine.scenes[0] potential_fig = mlab.figure(figure=None) mesh = wavefront.draw_polyhedron_mayavi(ast.V, ast.F, potential_fig) # contour plot # contour3d = mlab.contour3d(xg, yg, zg, Ug_array, figure=potential_fig) # volume rendering # volume = mlab.pipeline.volume(mlab.pipeline.scalar_field(Ug_array)) f = mlab.pipeline.scalar_field(xg, yg, zg, Ug_array) v = mlab.pipeline.volume(f, vmin=0, vmax=0.2) # cut planes mlab.pipeline.image_plane_widget(f, plane_orientation='x_axes', slice_index=nx / 2) mlab.pipeline.image_plane_widget(f, plane_orientation='y_axes', slice_index=ny / 2) mlab.pipeline.image_plane_widget(f, plane_orientation='z_axes', slice_index=nz / 2) mlab.outline() mlab.axes() mlab.colorbar(object=mesh, title='mm/sec^2')
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 visualize(tetrahedrons, save=False, file_name='tetrahedron_mesh.vtu', just_surface=True, octmps_output_file='ClassI_ScattFilt.out'): if just_surface: data = get_surface_structure(tetrahedrons) else: data = get_complete_structure(tetrahedrons) # Saving as VTU file if save: write_data(data, file_name=file_name) mlab.figure(figure='OCTMPS', fgcolor=(1, 1, 1), bgcolor=(0.5, 0.5, 0.5)) src = VTKDataSource(data=data) surf = mlab.pipeline.surface(src, opacity=0.01) mlab.axes() mlab.pipeline.surface(mlab.pipeline.extract_edges(surf), color=(1, 1, 1), line_width=0.0) if octmps_output_file: # Make the data and add it to the pipeline. data, x_positions, z_positions = make_data( octmps_output_file=octmps_output_file) data = np.array([data]).swapaxes(1, 0) src = ArraySource(transpose_input_array=True) src.scalar_data = data src.spacing = (x_positions[1] - x_positions[0], 0., z_positions[1] - z_positions[0]) src.origin = (x_positions[0], 0.0, z_positions[0]) mlab.pipeline.surface(src, colormap='jet') mlab.colorbar(orientation='vertical', title='Reflectance') mlab.show()
def m_field_wire(ori, pos, grid, x_grid, y_grid, z_grid, x_field, y_field, z_field, no_lines): fig = mplt.figure() X, Y, Z = np.meshgrid(x_grid, y_grid, z_grid, indexing='ij') for orientation, location in zip(ori, pos): # draw sphere for point charge wire(orientation, location, grid) # draw electric field lines line = mplt.flow(X, Y, Z, x_field, y_field, z_field, figure=fig, seedtype='line', integration_direction='both') # number of integration steps line.stream_tracer.maximum_propagation = 200 mplt.axes() # set view to x-axis coming out of screen fig.scene.x_plus_view() mplt.draw(figure=fig) mplt.show()
def main(): mu = np.array([1, 10, 20]) sigma = np.matrix([[20, 10, 10], [10, 25, 1], [10, 1, 50]]) np.random.seed(100) data = np.random.multivariate_normal(mu, sigma, 1000) values = data.T kde = stats.gaussian_kde(values) # Create a regular 3D grid with 50 points in each dimension xmin, ymin, zmin = data.min(axis=0) xmax, ymax, zmax = data.max(axis=0) xi, yi, zi = np.mgrid[xmin:xmax:50j, ymin:ymax:50j, zmin:zmax:50j] # Evaluate the KDE on a regular grid... coords = np.vstack([item.ravel() for item in [xi, yi, zi]]) density = kde(coords).reshape(xi.shape) # Visualize the density estimate as isosurfaces mlab.contour3d(xi, yi, zi, density, opacity=0.5) mlab.axes() mlab.show()
def axes(plot, nlabels=5, extent=None, ranges=None, color=(0, 0, 0), width=2, fmt="%-#.2f"): """ Add an Axes module to a Mayavi2 plot or dataset. Parameters: * plot Either the plot (as returned by one of the plotting functions of this module) or a TVTK dataset. * nlabels : int Number of labels on the axes * extent : list = [xmin, xmax, ymin, ymax, zmin, zmax] Default if the objects extent. * ranges : list = [xmin, xmax, ymin, ymax, zmin, zmax] What will be display in the axes labels. Default is *extent* * color : tuple = (r, g, b) RGB of the color of the axes and text * width : float Line width * fmt : str Label number format Returns: * axes : Mayavi axes instace The axes object in the pipeline """ _lazy_import_mlab() a = mlab.axes(plot, nb_labels=nlabels, color=color) a.label_text_property.color = color a.title_text_property.color = color if extent is not None: a.axes.bounds = extent if ranges is not None: a.axes.ranges = ranges a.axes.use_ranges = True a.property.line_width = width a.axes.label_format = fmt a.axes.x_label, a.axes.y_label, a.axes.z_label = "N", "E", "Z" return a
def scene_style(objs: dict, **kwargs) -> None: sc = mlab.scalarbar( objs["streamlines"], title="Field\nStrength [T]", orientation="vertical", nb_labels=4, ) # horizontal and vertical position from left->right, bottom->top sc.scalar_bar_representation.position = np.array([0.85, 0.1]) # width and height of colourbar sc.scalar_bar_representation.position2 = np.array([0.1, 0.8]) # The title of colourbar does not scale so we need to manually set it sc.scalar_bar.unconstrained_font_size = True sc.title_text_property.font_size = 20 sc.label_text_property.font_size = 20 ax = mlab.axes() mlab.view(azimuth=42, elevation=73)
def axes(scene, show_axis_labels, view): axes = mlab.axes(scene, nb_labels=1, line_width=3) axes.axes.label_format = '' if show_axis_labels == True: axes.axes.x_label = 'x' if view == 'front-parallel': axes.axes.y_label = 'z' axes.axes.z_label = '' elif view == 'top-parallel': axes.axes.y_label = '' axes.axes.z_label = 'y' else: axes.axes.y_label = 'z' axes.axes.z_label = 'y' else: axes.axes.x_label = '' axes.axes.y_label = '' axes.axes.z_label = ''
def animate_3d_mrt_observations(dataset, embedding, observations): """Animate Observation with sensor vector embedding in 3D space using mayavi Args: dataset (:obj:`CASASDataset`): CASAS dataset class containing sensor information. embedding (:obj:`numpy.ndarray`): A 2D array of size (#sensors, #vec_ndim) containing vector embedding of each sensor. observations (:obj:`list`): List of observations. Each observation is a :obj:`list` of index or target name of sensors that are ON, PRESENT or OPEN (depends on what type of sensor it is) at each time step. """ figure = mlab.figure(dataset.data_dict['name']) figure.scene.disable_render = True points = mlab.points3d(embedding[:, 0], embedding[:, 1], embedding[:, 2], scale_factor=0.03) for i, x in enumerate(embedding): mlab.text3d(x[0], x[1], x[2], dataset.sensor_list[i]['name'], scale=(0.02, 0.02, 0.02)) points.glyph.scale_mode = 'scale_by_vector' points.mlab_source.dataset.point_data.vectors = np.tile( np.ones(embedding.shape[0]), (3, 1)) color_vector = np.zeros(embedding.shape[0]) points.mlab_source.dataset.point_data.scalars = color_vector mlab.outline(None, color=(.7, .7, .7), extent=[-1, 1, -1, 1, -1, 1]) ax = mlab.axes(None, color=(.7, .7, .7), extent=[-1, 1, -1, 1, -1, 1], ranges=[-1, 1, -1, 1, -1, 1], nb_labels=6) ax.label_text_property.font_size = 3 ax.axes.font_factor = 0.4 figure.scene.disable_render = False @mlab.animate(delay=250) def anim(): f = mlab.gcf() while True: for observation in observations: color_vector[:] = 0 color_vector[observation] = 1 points.mlab_source.dataset.point_data.scalars = color_vector yield anim() mlab.show()
def plot_3d(img, slice=False, axis='z', color=None, size=(1000, 800)): """Visualize 3D segmentation results via mayavi""" res = None try: img = img.astype(np.uint16) assert img.ndim == 3, "Invalid dimension of 3D image: {}".format( img.ndim) bg_color = colors.to_rgb("black") depth, height, width = img.shape mlab.figure(bgcolor=bg_color, size=size) axes_extent = [0, height, 0, width, 0, depth] xlabel, ylabel, zlabel = 'X', 'Y', 'Z' if slice: if axis == 'z': res = mlab.volume_slice(img, colormap='Vega20') axes_extent = [0, depth, 0, height, 0, width] xlabel, zlabel = 'Z', 'X' else: res = mlab.volume_slice(img.transpose((1, 2, 0)), colormap='Vega20') else: if color is not None: res = mlab.contour3d(img.transpose((1, 2, 0)), color=color) else: res = mlab.contour3d(img.transpose((1, 2, 0)), contours=10, transparent=True) # axes feature configuration ax = mlab.axes(line_width=0.5, extent=axes_extent, xlabel=xlabel, ylabel=ylabel, zlabel=zlabel) ax.axes.font_factor = 0.75 mlab.outline() except FileNotFoundError: print("3D segmentation array loading unsuccessful") return res
def plot_3d_sensor_vector(dataset, embedding): """Plot sensor embedding in 3D space using mayavi Args: """ figure = mlab.figure('Sensor Embedding (3D)') figure.scene.disable_render = True points = mlab.points3d(embedding[:, 0], embedding[:, 1], embedding[:, 2], scale_factor=0.03) for i, x in enumerate(embedding): mlab.text3d(x[0], x[1], x[2], dataset.sensor_list[i]['name'], scale=(0.02, 0.02, 0.02)) mlab.outline(None, color=(.7, .7, .7), extent=[-1, 1, -1, 1, -1, 1]) ax = mlab.axes(None, color=(.7, .7, .7), extent=[-1, 1, -1, 1, -1, 1], ranges=[-1, 1, -1, 1, -1, 1], nb_labels=6) ax.label_text_property.font_size = 3 ax.axes.font_factor = 0.4 figure.scene.disable_render = False mlab.show()
def disp_3d_contour(self, size=(1000, 800)): depth, height, width = self.masks.shape bg_color = colors.to_rgb("black") axes_extent = [0, height, 0, width, 0, depth] xlabel, ylabel, zlabel = 'X', 'Y', 'Z' mlab.figure(bgcolor=bg_color, size=size) res = mlab.contour3d(self.masks.transpose((1, 2, 0)), contours=10, transparent=True) ax = mlab.axes(line_width=0.5, extent=axes_extent, xlabel=xlabel, ylabel=ylabel, zlabel=zlabel) ax.axes.font_factor = 0.75 mlab.outline() return res
def redraw_scene(self, scene, cur_scatter_data): # Notice how each mlab call points explicitely to the figure it # applies to. mlab.clf(figure=scene.mayavi_scene) x = cur_scatter_data[0] y = cur_scatter_data[1] z = cur_scatter_data[2] xlabel_text = cur_scatter_data[3][0] ylabel_text = cur_scatter_data[3][1] zlabel_text = cur_scatter_data[3][2] cur_colors = cur_scatter_data[4] cur_scales = [np.array(x) for x in cur_scatter_data[5]] label_unique = cur_scatter_data[6] points_dict.clear() for ii in range(len(label_unique)): points_dict[label_unique[ii]] = mlab.points3d( x[ii], y[ii], z[ii], cur_scales[ii] * self.cur_scale, color=cur_colors[ii][0], scale_factor=0.01, opacity=self.cur_opacity / 100) for ii in range(len(outputs_unique)): mlab.text(0.02, 1 - 0.035 * (ii + 1), '-' + str(outputs_unique[ii]), width=0.06, color=all_colors[ii]) cur_axex = mlab.axes(xlabel=xlabel_text, ylabel=ylabel_text, zlabel=zlabel_text, extent=[ min(sum(x, [])), max(sum(x, [])), min(sum(y, [])), max(sum(y, [])), min(sum(z, [])), max(sum(z, [])) ]) cur_axex.axes.font_factor = 0.8
def plot3d_embeddings(dataset, embeddings, figure=None): """Plot sensor embedding in 3D space using mayavi. Given the dataset and a sensor embedding matrix, each sensor is shown as a sphere in the 3D space. Note that the shape of embedding matrix is (num_sensors, 3) where num_sensors corresponds to the length of ``dataset.sensor_list``. All embedding vectors range between 0 and 1. Args: dataset (:obj:`~pymrt.casas.CASASDataset`): CASAS smart home dataset. embeddings (:obj:`numpy.ndarray`): 3D sensor vector embedding. """ show_figure = False if figure is None: show_figure = True figure = mlab.figure('Sensor Embedding (3D)') # Plot sensors, texts and outlines figure.scene.disable_render = True points = mlab.points3d(embeddings[:, 0], embeddings[:, 1], embeddings[:, 2], scale_factor=0.015) for i, x in enumerate(embeddings): mlab.text3d(x[0], x[1], x[2], dataset.sensor_list[i]['name'], scale=(0.01, 0.01, 0.01)) mlab.outline(None, color=(.7, .7, .7), extent=[0, 1, 0, 1, 0, 1]) ax = mlab.axes(None, color=(.7, .7, .7), extent=[0, 1, 0, 1, 0, 1], ranges=[0, 1, 0, 1, 0, 1], nb_labels=6) ax.label_text_property.font_size = 3 ax.axes.font_factor = 0.3 figure.scene.disable_render = False if show_figure: mlab.show() return figure, points
def show_mayavi(x, y, z, res): fig = mlab.figure(bgcolor=(1, 1, 1), size=(640, 480)) mlab.outline(color=(0, 0, 0)) res = np.asarray(res) xx, yy = np.mgrid[-10:10:0.5, -10:10:0.5] zz = res[0] * xx + res[1] * yy + res[2] # z /= 4 # mlab.surf(xx, yy, zz, color=(0, 0, 1), warp_scale=.25, representation='wireframe', line_width=0.5) # mlab.points3d(x, y, z, color=(1, 0, 0), scale_factor=.3, figure=fig) mlab.points3d(x, y, z, color=(1, 0, 0), mode='point', figure=fig) axes = mlab.axes(color=(0, 0, 0), nb_labels=5) axes.title_text_property.color = (0.0, 0.0, 0.0) axes.title_text_property.font_family = 'times' axes.label_text_property.color = (0.0, 0.0, 0.0) axes.label_text_property.font_family = 'times' mlab.gcf().scene.parallel_projection = True mlab.orientation_axes() mlab.show()
def disp_3d_slice(self, axis='z'): """Display 3D segmentation results interactively along z-axis or y-axis""" depth, height, width = self.masks.shape bg_color = colors.to_rgb("black") axes_extent = [0, depth, 0, height, 0, width] xlabel, ylabel, zlabel = 'X', 'Y', 'Z' if axis == 'z': res = mlab.volume_slice(self.masks, colormap='Vega20') axes_extent = [0, depth, 0, height, 0, width] xlabel, zlabel = 'Z', 'X' else: res = mlab.volume_slice(self.masks.transpose((1, 2, 0)), colormap='Vega20') ax = mlab.axes(line_width=0.5, extent=axes_extent, xlabel=xlabel, ylabel=ylabel, zlabel=zlabel) ax.axes.font_factor = 0.75 mlab.outline() return res
def draw_ply(array_in, array_out): mlab.figure(bgcolor=(1, 1, 1), size=(640, 480)) mlab.outline(color=(0, 0, 0)) mlab.points3d(array_in[:, 0], array_in[:, 1], array_in[:, 2], color=(1, 0, 0), mode='point') mlab.points3d(array_out[:, 0], array_out[:, 1], array_out[:, 2], color=(0, 0, 1), mode='point') axes = mlab.axes(color=(0, 0, 0), nb_labels=5) axes.title_text_property.color = (0.0, 0.0, 0.0) axes.title_text_property.font_family = 'times' axes.label_text_property.color = (0.0, 0.0, 0.0) axes.label_text_property.font_family = 'times' mlab.gcf().scene.parallel_projection = True mlab.orientation_axes() mlab.show()
def vis_multiple(multi_points, save_folder, save_name, normalize=True, save_gif=True, delete=False, show=False): # points = np.loadtxt(full_path, delimiter=',') # points = points[:50, :] fig = mlab.figure(size=(1024, 1024)) for idx, points in enumerate(multi_points): if normalize: points[:, :3] = pc_normalize(points[:, :3]) x, y, z = np.split(points[:, :3], 3, axis=-1) # vx, vy, vz = np.split(points[:, 3:], 3, axis=-1) if save_gif: fig.scene.movie_maker.record = True fig.scene.movie_maker.directory = './' selected_color = colors[idx] s = points3d(x, y, z, color=selected_color, scale_factor=0.01, opacity=0.5) # mlab.quiver3d(x, y, z, vx, vy, vz, mode='arrow', scale_factor=0.03) # ms = s.mlab_source # animate(ms, points, transformer) axes = mlab.axes() axes.axes.fly_mode = 'none' axes.axes.bounds = np.array([0, 0.4, 0.4, 0., 0., 0.4]) mlab.title(save_name, size=0.1) if show: mlab.show() if save_gif: save(save_name=save_name, images_folder=save_folder, delete=delete)
#dataExport(4) # In[2]: n = 4 for i in range(n): #l=0,1,2,3 for j in range(-i, i + 1): xdata = "xdata{}{}{}.dat".format(n, i, j) ydata = "ydata{}{}{}.dat".format(n, i, j) zdata = "zdata{}{}{}.dat".format(n, i, j) magdata = "density{}{}{}.dat".format(n, i, j) x = load(xdata) y = load(ydata) z = load(zdata) density = load(magdata) figure = mlab.figure('DensityPlot{}{}{}'.format(n, i, j)) mag = density / amax(density) #pts = mlab.points3d(mag ,opacity =0.5, transparent=True) pts = mlab.contour3d(mag, opacity=0.5) mlab.colorbar(orientation='vertical') mlab.axes() mlab.savefig("{}{}{}_contour.png".format(n, i, j)) print "{}{}{}.png saved".format(n, i, j) print "Completed" # In[ ]:
#random_indices = random.sample(range(len(x)),5000) #x = np.array([x[i] for i in sorted(random_indices)]) #y = np.array([y[i] for i in sorted(random_indices)]) #z = np.array([z[i] for i in sorted(random_indices)]) #vx = np.array([vx[i] for i in sorted(random_indices)]) #vy = np.array([vy[i] for i in sorted(random_indices)]) #vz = np.array([vz[i] for i in sorted(random_indices)]) xyz = np.vstack([x,y,z]) kde = stats.gaussian_kde(xyz, bw_method=0.1) X, Y, Z = np.mgrid[x.min():x.max():100j, y.min():y.max():100j, z.min():z.max():100j] positions = np.vstack([X.ravel(), Y.ravel(), Z.ravel()]) density = kde(positions).reshape(X.shape) #Visualize the density estimate as isosurfaces figure = mlab.figure('myfig') figure.scene.disable_render = True # Super duper trick mlab.contour3d(X, Y, Z, density, opacity=0.3, colormap = 'Blues', figure = figure) #mlab.quiver3d(x, y, z, vx, vy, vz) mlab.axes(extent = [-650, 650, -650, 650, -650, 650], ranges = [-650, 650, -650, 650, -650, 650], nb_labels = 7, figure = figure) mlab.points3d(x_OB, y_OB, z_OB, np.full(len(x_OB),10), scale_factor=1, figure = figure) OB_Names = ['gammavelorum', 'NGC2547', 'trumpler10', 'NGC2516', 'velaOB2', 'OriOB1', 'HIP22931', 'HIP27345', 'HIP33175', 'NGC2232', 'Bellatrix', 'Rigel', 'Alnilam', 'USco', 'UCL', 'LLC', 'IC2602', 'aCar', 'IC2391', 'HIP45189', 'NGC2451A', 'Col135', 'HIP28944'] for i in range(len(x_OB)): mlab.text3d(x_OB[i], y_OB[i], z_OB[i], OB_Names[i], scale=5, figure = figure) figure.scene.disable_render = False # Super duper trick mlab.show()
delta = 0.025 a = 4.0 b = 10.0 sigma = 10.0 t, X = ms.int_translated_system(a=2.0, b=100, T=200000, x0=[0.8, 0.9, 0.5]) # t, X = ms.int_system( a = 4.0, b = 10.0, T = 400000, x0 = [0.9, 0.2, 0.5]) ux, vx, rhox = np.mgrid[0:1:50j, 0:1:50j, -0.5:0.5:50j] # ux, vx, rhox = np.mgrid[0:1:50j, 0:1:50j, -1.0:1.0:50j] # values = F(rhox + 0.5, ux, vx) # mlab.contour3d(ux, vx, rhox, values, contours=[0], opacity = 0.3) mlab.figure(size=(800, 600), bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) mlab.clf() values = ms.G_t(rhox, ux, vx) mlab.contour3d(ux, vx, rhox, values, contours=[0], opacity=0.5) values = ms.fold_t(rhox, ux, vx) mlab.contour3d(ux, vx, rhox, values, contours=[0], opacity=0.5) mlab.plot3d(X[0, :], X[1, :], X[2, :], color=(0, 0, 0), line_width=2.0, tube_radius=None) mlab.points3d(X[0, 0], X[1, 0], X[2, 0], scale_factor=0.03, line_width=0.1) mlab.axes(extent=[0, 1, 0, 1, -0.5, 0.5], xlabel='u', ylabel='v', zlabel='rho') # mlab.axes(extent = [0, 1, 0, 1, -1.0, 1.0], xlabel = 'u', ylabel = 'v', zlabel = 'rho') # mlab.outline(color = (0, 0, 0)) mlab.show()
def plot(self, x, y, z, mx, my, mz, scalars, fname, savefig=True): ''' x,y,z,mx,my,mz为xyzdxdydz方式的数据 scalars:标量数据,可能用于标记颜色 fname:str,文件的名字 ''' figure = mlab.figure(bgcolor=self.bgcolor, size=self.size) #图片的 mlab.quiver3d(x, y, z, mx, my, mz, scalars=scalars, colormap=self.colormap, scale_mode=self.scale_mode, scale_factor=self.scale_factor) if self.show_colorbar: mlab.colorbar( title='Mz', #color 的名字 orientation='vertical', #垂直方向 nb_labels=5, #显示五个标签 label_fmt='%.1f') #保留一位小数 #坐标轴: if self.show_axes: #线宽,显示五个标签 mlab.axes(xlabel='x', ylabel='y', zlabel='z', line_width=3.0, nb_labels=5) if self.show_outline: #线宽2.0 ,有一点透明 mlab.outline(line_width=2.0, opacity=0.5) for view in self.view: mlab.view(view[0], view[1]) #观察角度 if isinstance(fname, str) and isinstance(self.save_path, str) and savefig: print('savefig in ', self.save_path) if self.gpu: mlab.savefig(os.path.join( self.save_path, '%s-z%d-x%d.%s' % (fname, view[0], view[1], self.fig_format)), magnification=3) else: mlab.savefig( os.path.join( self.save_path, '%s-z%d-x%d.%s' % (fname, view[0], view[1], self.fig_format))) if self.show_fig: print( "Need to manually turn off the picture, will continue drawing!" ) mlab.show() #显示图片 if not self.show_fig: mlab.close(all=True) #关闭画布