def generate_plots_3d(self): self.ax = mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(800, 600)) self.clf = mlab.clf() minS, maxS = maxint, 0 contour_plots = [] for cond in self.conductors.itervalues(): minS, maxS, face_data = self.generate_plot_data_for_faces_3d(cond, minS, maxS) for (x, y, z, s) in face_data: if isinstance(cond, conductor_type_3d['Unstructured']): pts = mlab.points3d(x, y, z, s, scale_mode='none', scale_factor=0.002) mesh = mlab.pipeline.delaunay3d(pts) contour_plots.append(mlab.pipeline.surface(mesh, colormap='viridis')) else: if np.min(s) < 0.0: contour_plots.append(mlab.mesh(x, y, z, color=(0, 0, 0), colormap='viridis')) else: contour_plots.append(mlab.mesh(x, y, z, scalars=s, colormap='viridis')) for cp in contour_plots: cp.module_manager.scalar_lut_manager.trait_set(default_data_range=[minS * 0.95, maxS * 1.05]) mlab.draw() mlab.colorbar(object=contour_plots[0], orientation='vertical') mlab.show()
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 draw_encoders(encoders, angle=None, colors=None): """Add encoders to the scene. Can either supply a collection of encoders, or an integer giving the number of encoders to randomly generate. encoders: int or collection angle: angle giving size of the cap drawn to represent an encoder colors: collection of normalized rgb colors to paint the encoders """ if isinstance(encoders, int): encoders = dists.UniformHypersphere(3, surface=True).sample(encoders) if colors is None: colors = [black for e in encoders] if not angle: angle = 0.01 * np.pi for enc, color in zip(encoders, colors): front = color back = black cap = threed.make_cap(r=1.01*radius, cap_angle=angle, direction=enc) mlab.mesh(*cap, color=front, opacity=1.0) cap = threed.make_cap(r=1.007*radius, cap_angle=angle, direction=enc) mlab.mesh(*cap, color=back, opacity=1.0)
def plot(self, Ps): from mayavi import mlab mlab.figure(mlab.figure(), bgcolor=(1, 1, 1)) for s in range(len(Ps)): mlab.mesh(Ps[s][:, :, 0], Ps[s][:, :, 1], Ps[s][:, :, 2], color=(65 / 256, 105 / 256, 225 / 256)) mlab.show()
def plotvfonsph3D(theta_rad, phi_rad, E_th, E_ph, freq=0.0, vcoord='sph', projection='equirectangular'): PLOT3DTYPE = "quiver" (x, y, z) = sph2crtISO(theta_rad, phi_rad) from mayavi import mlab mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300)) mlab.clf() if PLOT3DTYPE == "MESH_RADIAL" : r_Et = numpy.abs(E_th) r_Etmx = numpy.amax(r_Et) mlab.mesh(r_Et*(x)-1*r_Etmx, r_Et*y, r_Et*z, scalars=r_Et) r_Ep = numpy.abs(E_ph) r_Epmx = numpy.amax(r_Ep) mlab.mesh(r_Ep*(x)+1*r_Epmx , r_Ep*y, r_Ep*z, scalars=r_Ep) elif PLOT3DTYPE == "quiver": ##Implement quiver plot s2cmat = getSph2CartTransfMatT(numpy.array([x,y,z])) E_r = numpy.zeros(E_th.shape) E_fldsph = numpy.rollaxis(numpy.array([E_r, E_ph, E_th]), 0, 3)[...,numpy.newaxis] E_fldcrt = numpy.rollaxis(numpy.matmul(s2cmat, E_fldsph).squeeze(), 2, 0) #print E_fldcrt.shape mlab.quiver3d(x+1.5, y, z, numpy.real(E_fldcrt[0]), numpy.real(E_fldcrt[1]), numpy.real(E_fldcrt[2])) mlab.quiver3d(x-1.5, y, z, numpy.imag(E_fldcrt[0]), numpy.imag(E_fldcrt[1]), numpy.imag(E_fldcrt[2])) mlab.show()
def draw_ballast(self, fig, centerline, freeboard, h_section, r_nodes, h_perm, h_water): from mayavi import mlab npts = 40 th = np.linspace(0, 2*np.pi, npts) z_nodes = np.flipud( freeboard - np.r_[0.0, np.cumsum(np.flipud(h_section))] ) # Permanent ballast z_perm = z_nodes[0] + np.linspace(0, h_perm, npts) r_perm = np.interp(z_perm, z_nodes, r_nodes) R, TH = np.meshgrid(r_perm, th) Z, _ = np.meshgrid(z_perm, th) X = R*np.cos(TH) + centerline[0] Y = R*np.sin(TH) + centerline[1] ck = np.array([122, 85, 33]) / 255.0 ck = tuple(ck.tolist()) mlab.mesh(X, Y, Z, color=ck, figure=fig) # Water ballast z_water = z_perm[-1] + np.linspace(0, h_water, npts) r_water = np.interp(z_water, z_nodes, r_nodes) R, TH = np.meshgrid(r_water, th) Z, _ = np.meshgrid(z_water, th) X = R*np.cos(TH) + centerline[0] Y = R*np.sin(TH) + centerline[1] ck = (0.0, 0.1, 0.8) # Dark blue mlab.mesh(X, Y, Z, color=ck, figure=fig)
def draw_column(self, fig, centerline, freeboard, h_section, r_nodes, spacingVec=None, ckIn=None): from mayavi import mlab npts = 20 nsection = h_section.size z_nodes = np.flipud( freeboard - np.r_[0.0, np.cumsum(np.flipud(h_section))] ) th = np.linspace(0, 2*np.pi, npts) for k in xrange(nsection): rk = np.linspace(r_nodes[k], r_nodes[k+1], npts) z = np.linspace(z_nodes[k], z_nodes[k+1], npts) R, TH = np.meshgrid(rk, th) Z, _ = np.meshgrid(z, th) X = R*np.cos(TH) + centerline[0] Y = R*np.sin(TH) + centerline[1] # Draw parameters if ckIn is None: ck = (0.6,)*3 if np.mod(k,2) == 0 else (0.4,)*3 else: ck = ckIn #ax.plot_surface(X, Y, Z, alpha=0.5, color=ck) mlab.mesh(X, Y, Z, opacity=0.7, color=ck, figure=fig) if spacingVec is None: continue z = z_nodes[k] + spacingVec[k] while z < z_nodes[k+1]: rk = np.interp(z, z_nodes[k:], r_nodes[k:]) #ax.plot(rk*np.cos(th), rk*np.sin(th), z*np.ones(th.shape), 'r', lw=0.25) mlab.plot3d(rk*np.cos(th) + centerline[0], rk*np.sin(th) + centerline[1], z*np.ones(th.shape), color=(0.5,0,0), figure=fig) z += spacingVec[k] '''
def zoncaview(m): """ m is a healpix sky map, such as provided by WMAP or Planck. """ nside = hp.npix2nside(len(m)) vmin = -1e3; vmax = 1e3 # Set up some grids: xsize = ysize = 1000 theta = np.linspace(np.pi, 0, ysize) phi = np.linspace(-np.pi, np.pi, xsize) longitude = np.radians(np.linspace(-180, 180, xsize)) latitude = np.radians(np.linspace(-90, 90, ysize)) # Project the map to a rectangular matrix xsize x ysize: PHI, THETA = np.meshgrid(phi, theta) grid_pix = hp.ang2pix(nside, THETA, PHI) grid_map = m[grid_pix] # Create a sphere: r = 0.3 x = r*np.sin(THETA)*np.cos(PHI) y = r*np.sin(THETA)*np.sin(PHI) z = r*np.cos(THETA) # The figure: mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300)) mlab.clf() mlab.mesh(x, y, z, scalars=grid_map, colormap="jet", vmin=vmin, vmax=vmax) mlab.draw() return
def plot_both_mayavi(f, xbounds=(-1, 1), ybounds=(-1, 1), res=401): """ Plot the real and imaginary parts of the function 'f', given the bounds and resolution. """ X, Y, vals = get_vals(f, xbounds, ybounds, res) ml.mesh(X, Y, vals.real) ml.mesh(X, Y, vals.imag) ml.show()
def plotOrs(*ptss): mlab.figure(34); mlab.clf() r = 1 phi, theta = mgrid[0:pi:101j, 0:2*pi:101j] x = r*sin(phi)*cos(theta) y = r*sin(phi)*sin(theta) z = r*cos(phi) mlab.mesh(x,y,z, colormap='gray',opacity=.2) colors = [(1,0,0),(0,1,0),(0,0,1)] print len(colors) print len(ptss) for (pts,col) in izip(ptss,colors): print col ors = normr(pts) # Create a sphere x,y,z = ors.T mlab.points3d(x,y,z,color=col) mlab.plot3d(x,y,z,color=col,tube_radius=.025)
def addDepthMap(figure, input_atoms, vmin, vmax, scale_factors=None, colormap='hot', resolution=32, ): from mayavi import mlab if scale_factors is None: scale_factors=np.ones(len(input_atoms)) numbers = input_atoms.get_atomic_numbers() collections = set(zip(numbers, scale_factors)) for number, scale_factor in collections: take1 = numbers == number take2 = scale_factors == scale_factor take = np.logical_and(take1, take2) atoms = input_atoms[take] points = atoms.positions radius = my_radii[number]/2.0 radius *= scale_factor points = points[points[:, 2] > vmin - radius] for point in points: x, y, z = sphere(point, radius, resolution=resolution) mlab.mesh(x,y,z, scalars=z, vmin=vmin, vmax=vmax, colormap=colormap, figure=figure, )
def plot_sphere_func(f, grid='Clenshaw-Curtis', theta=None, phi=None, colormap='jet', fignum=0): # Note: all grids except Clenshaw-Curtis have holes at the poles import matplotlib matplotlib.use('WxAgg') matplotlib.interactive(True) from mayavi import mlab if grid == 'Driscoll-Healy': b = f.shape[0] / 2 elif grid == 'Clenshaw-Curtis': b = (f.shape[0] - 2) / 2 elif grid == 'SOFT': b = f.shape[0] / 2 elif grid == 'Gauss-Legendre': b = (f.shape[0] - 2) / 2 if theta is None or phi is None: theta, phi = meshgrid(b=b, convention=grid) phi = np.r_[phi, phi[0, :][None, :]] theta = np.r_[theta, theta[0, :][None, :]] f = np.r_[f, f[0, :][None, :]] x = np.sin(theta) * np.cos(phi) y = np.sin(theta) * np.sin(phi) z = np.cos(theta) mlab.figure(fignum, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(600, 400)) mlab.clf() mlab.mesh(x, y, z, scalars=f, colormap=colormap) # mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25)) mlab.show()
def plotView(rays,pts=None, **kwargs): if not pts is None: x = scipy.zeros((len(rays)+1,pts)) y = scipy.zeros(x.shape) z = scipy.zeros(x.shape) for i in rays: i.norm.s = scipy.linspace(i.norm.s[0],i.norm.s[-1],pts) else: x = scipy.zeros((len(rays)+1,len(rays[0].norm.s))) y = scipy.zeros(x.shape) z = scipy.zeros(x.shape) for i in xrange(len(rays)): if rays[i]._origin.flag: rays[i] = rays[i].c() x[i] = rays[i].x()[0] y[i] = rays[i].x()[1] z[i] = rays[i].x()[2] x[-1] = rays[0].x()[0] y[-1] = rays[0].x()[1] z[-1] = rays[0].x()[2] mlab.mesh(x,y,z,**kwargs)
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 drawstick(p1, p2, radius=1, clr = (1,0,0), alpha = 1, samplenum = 6, ): if isinstance(radius,tuple): clr = radius[1] alpha = radius[2] samplenum = radius[3] radius = radius[0] pi = np.pi cos = np.cos sin = np.sin theta = np.linspace(0,2*pi,samplenum) normv = (p1-p2) / np.linalg.norm(p1-p2) u = np.empty((3,1)) if normv[0]!= 0: u[1] = u[2] = 1 u[0] = -(normv[1]+normv[2])/normv[0] elif normv[1]!= 0: u[0] = u[2] = 1 u[1] = -(normv[0]+normv[2])/normv[1] else:# normv[2]!= 0 u[0] = u[1] = 1 u[2] = -(normv[1]+normv[0])/normv[2] u = u / np.linalg.norm(u) circle = radius * np.multiply(cos(theta),u) + radius * np.multiply( sin(theta), np.cross(normv.T, u.T).T ) p1arr = np.tile(p1,circle.shape[1]) p2arr = np.tile(p2,circle.shape[1]) c1 = circle + p1arr c2 = circle + p2arr x = np.vstack((p1arr[0],c1[0],c2[0],p2arr[0])) y = np.vstack((p1arr[1],c1[1],c2[1],p2arr[1])) z = np.vstack((p1arr[2],c1[2],c2[2],p2arr[2])) mlab.mesh(x,y,z, color=clr, opacity=alpha)
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 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 plane(self,n,p,c=None): d = -np.sum(p*n) x = np.linspace(-2,2) y = np.linspace(-2,2) [xx,yy]=np.meshgrid(x,y); zz = (-n[0]*xx - n[1]*yy - d)/n[2] mlab.mesh(xx,yy,zz,opacity=0.15,figure=self.fig)
def makefinegrid(): coor=make_coor(20j) mlab.figure() mlab.mesh(coor.x, coor.y, coor.z) mlab.points3d(coor.x, coor.y, coor.z, scale_factor=0.1) savefig('finegrid.png')
def plotElements(): for i in range(25-1): for j in range(25-1): xtmp = x[j:j+2,i:i+2] ytmp = y[j:j+2,i:i+2] ztmp = z[j:j+2,i:i+2] ctmp = c[j:j+2,i:i+2] mlab.mesh(xtmp,ytmp,ztmp,scalars=ctmp,vmin=vmin,vmax=vmax) mlab.mesh(xtmp,ytmp,ztmp,representation='wireframe',color = (0,0,0))
def plot_alpha_sphere(): x,y,z = make_sphere(50, 1.0) mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300)) mlab.clf() s = np.zeros(x.shape) mlab.mesh(x, y, z, scalars=s, colormap='jet', opacity=0.1) mlab.show(stop=True)
def show(self, using='maya', fit_ellipse=False, show_hull=False): """ A simple scatter-plot to represent the aggregate - either using mpl or mayavi """ if fit_ellipse: (center, radii, rotation) = self.fit_ellipse() u = np.linspace(0.0, 2.0 * np.pi, 100) v = np.linspace(0.0, np.pi, 100) # cartesian coordinates that correspond to the spherical angles: x = radii[0] * np.outer(np.cos(u), np.sin(v)) y = radii[1] * np.outer(np.sin(u), np.sin(v)) z = radii[2] * np.outer(np.ones_like(u), np.cos(v)) # rotate accordingly for i in range(len(x)): for j in range(len(x)): [x[i,j],y[i,j],z[i,j]] = np.dot([x[i,j],y[i,j],z[i,j]], rotation) + center if show_hull: hull = self.chull() hull_x = hull.points[:,0] hull_y = hull.points[:,1] hull_z = hull.points[:,2] if using=='mpl': from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() # ax = fig.add_subplot(111, projection='3d' ax = Axes3D(fig) # ax.set_aspect('equal') h = ax.scatter(self.pos[:,0], self.pos[:,1], self.pos[:,2], s=100.) if fit_ellipse: ax.plot_wireframe(x, y, z, rstride=4, cstride=4, color='k', alpha=0.2) plt.show() elif using=='maya': import mayavi.mlab as mlab fig = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) h = mlab.points3d(self.pos[:,0], self.pos[:,1], self.pos[:,2], self.radius, scale_factor=2, resolution=16) if fit_ellipse: mlab.mesh(x,y,z, opacity=0.25, color=(1,1,1)) if show_hull: mlab.triangular_mesh(hull_x, hull_y, hull_z, hull.simplices, representation='wireframe', color=(1,1,1)) else: print('ERROR: using= must ne either mpl or maya') return h
def plotvMF(mu,tau,pi,figm,color=(1.,0.0,0.0)): X,Y,Z = S2.mesh(1.) q = np.c_[X.ravel(),Y.ravel(),Z.ravel()].T pdf = pi*np.exp(mu.T.dot(q)*tau)*tau/(4*np.pi*np.sinh(tau)) +1. X*=np.reshape(pdf,X.shape) Y*=np.reshape(pdf,X.shape) Z*=np.reshape(pdf,X.shape) mlab.mesh(X,Y,Z,color=color,opacity=0.3,figure=figm,mode='2dtriangle') mlab.plot3d([0,mu[0]],[0,mu[1]],[0,mu[2]],color=color,opacity=0.9,figure=figm)
def make_exact(self): if(self.exact!=None): sol = self.exact(self.X,self.Y,0) for k in xrange(self.Nt): mlab.mesh(self.X,self.Y,sol, color=(0.0, 0.3, 0.6)) sol = self.exact(self.X, self.Y, self.t[k]) mlab.savefig("wtmp%04d.png" %k) mlab.clf() filename = "exact_dt%2.1f.gif" %self.dt sci.movie("wtmp*.png",encoder='convert', fps=5, output_file=filename)
def display_depth(z): """ Display the computed depth function as a surface using mayavi mlab. """ m, n = z.shape x, y = np.mgrid[0:m, 0:n] mlab.mesh(x, y, z, colormap="gray") mlab.view(azimuth=0, elevation=90) mlab.show()
def estimate_lebesgue_constant(n, nodes, visualize=False): """Estimate the `Lebesgue constant <https://en.wikipedia.org/wiki/Lebesgue_constant_(interpolation)>`_ of the *nodes* at polynomial order *n*. :arg nodes: an array of shape *(dims, nnodes)* as returned by :func:`modepy.warp_and_blend_nodes`. :arg visualize: visualize the function that gives rise to the returned Lebesgue constant. (2D only for now) :return: the Lebesgue constant, a scalar .. versionadded:: 2013.2 """ from modepy.matrices import vandermonde from modepy.modes import simplex_onb dims = len(nodes) basis = simplex_onb(dims, n) vdm = vandermonde(basis, nodes) from pytools import generate_nonnegative_integer_tuples_summing_to_at_most \ as gnitstam huge_n = 30*n equi_node_tuples = list(gnitstam(huge_n, dims)) tons_of_equi_nodes = ( np.array(equi_node_tuples, dtype=np.float64) / huge_n * 2 - 1).T eq_vdm = vandermonde(basis, tons_of_equi_nodes) eq_to_out = la.solve(vdm.T, eq_vdm.T).T lebesgue_worst = np.sum(np.abs(eq_to_out), axis=1) lebesgue_constant = np.max(lebesgue_worst) if visualize: print("Lebesgue constant: %g" % lebesgue_constant) from modepy.tools import submesh import mayavi.mlab as mlab mlab.figure(bgcolor=(1, 1, 1)) mlab.triangular_mesh( tons_of_equi_nodes[0], tons_of_equi_nodes[1], lebesgue_worst / lebesgue_constant, submesh(equi_node_tuples)) x, y = np.mgrid[-1:1:20j, -1:1:20j] mlab.mesh(x, y, 0*x, representation="wireframe", color=(0.4, 0.4, 0.4), line_width=0.6) mlab.show() return lebesgue_constant
def plot_data(x, y, z): if PLOT_BY == 'matplotlib': fig = pylab.figure() axes = Axes3D(fig) #axes.plot_surface(y, x, z) axes.plot_surface(x, y, z, rstride=4, cstride=4, cmap = cm.jet ) pylab.show() elif PLOT_BY == 'mayavi': mlab.mesh(x, y, z, colormap='YlGnBu', ) mlab.view(.0, -5.0, 4) mlab.show()
def harmonic2(name): x = np.linspace(0, np.pi) y = np.linspace(0, np.pi) x, y = np.meshgrid(x, y, copy=False) z = np.sin(2 * x) * np.sin(2 * y) mlab.mesh(x, y, z) # Zoom in a bit. mlab.gcf().scene.camera.position = mlab.gcf().scene.camera.position / 1.3 # Save the plot. mlab.savefig(name) mlab.clf()
def plot3d(self,type='surface',**kargs): nmax=kargs.get('nmax',200) # max wireframe lines if type=='surface': # mayavi and pylab version<3 needs the environment variable # QT_API=pyqt, otherwise there will be the error "ValueError: API # 'QString' has already been set to version 1 # This is because ipython uses pyqt4 using the version 1 of the api # see: http://mail.scipy.org/pipermail/ipython-user/2012-February/009478.html import sys pver=eval(sys.version[:3]) qtapi=os.environ.get('QT_API','') if pver<3 and qtapi!='pyqt': print 'warning: environmen variable QT_API may need to be set as pyqt '\ 'in python <3 so that mayavi can be used after pylab' \ a=raw_input('Wanna continue ([n],y) ?') if a!='y': return from mayavi import mlab z=-self.h.copy() z[self.mask==0]=np.nan rx=self.lon.max()-self.lon.min() ry=self.lat.max()-self.lat.min() r=2*(self.h.max()-self.h.min())/(0.5*(rx+ry)) mlab.mesh(self.lon,self.lat,z/r) else: # wireframe from mpl_toolkits.mplot3d import axes3d import pylab as pl fig=pl.figure() ax=fig.add_subplot(111, projection='3d') ny,nx=self.h.shape dx=int(np.round(nx/float(nmax))) dy=int(np.round(ny/float(nmax))) x=self.lon[::dy,::dx] y=self.lat[::dy,::dx] h=-self.h[::dy,::dx] h[self.mask[::dy,::dx]==0]=np.nan ax.plot_wireframe(x,y,h,lw=0.5,alpha=.5) ax.contour3D(self.lon,self.lat,self.mask,[.5])
def draw_plane(self, plane, points3d, color=(1, 0.1, 0)): # a plane is a*x+b*y+c*z+d=0 # [a,b,c] is the normal. Thus, we have to calculate d and we're set a, b, c, d = plane #xmin, xmax = int(np.min(points3d[:,0])), int(np.max(points3d[:,0])) #ymin, ymax = int(np.min(points3d[:,1])), int(np.max(points3d[:,1])) ymin, ymax = -0.1, 0.1 zmin, zmax = 0, 1.5 * np.max(points3d[:, 2]) #x, z = np.mgrid[xmin:xmax:10, 0:500:10] #y = (a * x + c * z + d) / -b y, z = np.mgrid[ymin:ymax:0.09, zmin:zmax:0.09] x = (b * y + c * z + d) / -a print x, y, z mlab.mesh(x, y, z, color=color, opacity=0.5, transparent=True)
x = r * sin(phi) * cos(theta) y = r * sin(phi) * sin(theta) z = r * cos(phi) mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300)) mlab.clf() # Represent spherical harmonics on the surface of the sphere for n in range(0, 4): s_tot = np.zeros((201, 201)) for m in range(-n, 1): s = np.abs(sph_harm(m, n, theta, phi).real) s_tot = s_tot + s s = s_tot # mlab.mesh(x - m, y - n, z, scalars=s, colormap='jet') mlab.mesh(x - m, y - n, z, scalars=s, colormap='Spectral') s[s < 0] *= 0.97 s /= s.max() mlab.mesh(s * x - m, s * y - n, s * z + 1.3, scalars=s, colormap='Spectral') # scalars=s, colormap='jet') mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25)) mlab.show()
for i in range(d.shape[0]): if d[i] < r: y[i] = (r - abs(x[i]-u))/r return y x = np.linspace(-0.5, 0.5, num=1000) y = gaussian(x, 0.0, 0.03) #y = uni(x, 0.0, 0.05) plt.plot(x,y) plt.show() ''' dphi, dtheta = pi / 250.0, pi / 250.0 [phi, theta] = mgrid[0:pi + dphi * 1.5:dphi, 0:2 * pi + dtheta * 1.5:dtheta] m0 = 4 m1 = 3 m2 = 2 m3 = 3 m4 = 6 m5 = 2 m6 = 6 m7 = 4 r = sin(m0 * phi)**m1 + cos(m2 * phi)**m3 + sin(m4 * theta)**m5 + cos( m6 * theta)**m7 x = r * sin(phi) * cos(theta) y = r * cos(phi) z = r * sin(phi) * sin(theta) s = mlab.mesh(x, y, z) mlab.show()
plt.xlabel("Phi [degrees]") plt.ylabel("Theta [degrees]") plt.colorbar(label="Realized Gain [dBi]") # plt.show() ## Plot in 3D (project onto surface of sphere) ## x2d = np.sin(np.deg2rad(theta2d)) * np.cos(np.deg2rad(phi2d)) y2d = np.sin(np.deg2rad(theta2d)) * np.sin(np.deg2rad(phi2d)) z2d = np.cos(np.deg2rad(theta2d)) mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0., 0., 0.)) mlab.mesh(x2d, y2d, z2d, scalars=pattern_db[:, :, fidx], colormap='jet', vmax=pltmax, vmin=pltmin) mlab.colorbar(orientation='vertical') mlab.orientation_axes() # mlab.show() ## Plot in 3D ## r = pattern_db[:, :, fidx] - pltmin r[r < 0.0] = 0.0 x2d = r * np.sin(np.deg2rad(theta2d)) * np.cos(np.deg2rad(phi2d)) y2d = r * np.sin(np.deg2rad(theta2d)) * np.sin(np.deg2rad(phi2d)) z2d = r * np.cos(np.deg2rad(theta2d))
idx = np.sqrt(x**2 + y**2) if x > 0 and y > 0: V11 = A * (1 - np.exp(-B * idx)) elif x < 0 and y < 0: V11 = -A * (1 - np.exp(B * idx)) else: V11 = 0 V22 = -V11 V12 = C * np.exp(-D * (idx**2)) return np.matrix([[V11, V12], [V12, V22]]) allH = np.zeros((x.shape[0], x.shape[1], 2, 2)) allE = np.zeros((x.shape[0], x.shape[1], 2)) allU = np.zeros_like(allH) for ix in range(x.shape[0]): for iy in range(x.shape[1]): H = create_H1(x[ix, iy], y[ix, iy]) E, U = np.linalg.eigh(H) allH[ix, iy] = H allE[ix, iy] = E allU[ix, iy] = U mlab.mesh(x, y, allE[:, :, 0] * 100, color=(1, 0, 0)) #mlab.points3d(x, y, allE[:, :, 1], color=(0, 0, 1)) mlab.show()
boundary_l.remove() # Make a fading colormap by changing opacity at ends lut = np.reshape(np.array([150, 150, 150, 255] * 256), (256, 4)) fade_value = 125 lut[:fade_value, -1] = np.linspace(0, 255, fade_value) lut[-fade_value:, -1] = np.linspace(255, 0, fade_value) # Set up boundary visualisation boundary_r = mlab.mesh(xix_boundary_r_vals_t, zgrid_zy, ygrid_zy, extent=[ ext_min_r, ext_max_r, 1, nz, 0, (ny - 1) * y_spacing ], opacity=1., representation='wireframe', line_width=12., scalars=zgrid_zy) boundary_l = mlab.mesh(xix_boundary_l_vals_t, zgrid_zy, ygrid_zy, extent=[ ext_min_l, ext_max_l, 1, nz, 0, (ny - 1) * y_spacing ], opacity=1., representation='wireframe', line_width=12.,
# Create a sphere r = 0.3 pi = np.pi cos = np.cos sin = np.sin phi, theta = np.mgrid[0:pi:501j, 0:2 * pi:501j] x = r * sin(phi) * cos(theta) y = r * sin(phi) * sin(theta) z = r * cos(phi) mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300)) mlab.clf() # Represent spherical harmonics on the surface of the sphere mlab.mesh(x, y, z, color=(0.5, 0.5, 0.5), opacity=1) # phi, theta = np.mgrid[-.2:.2:10j, 0:2*pi:10j] phi = 0.1 * np.random.randn(100) theta = np.random.randn(100) * 2.0 * pi; theta = theta + pi / 6.0 x = r * sin(phi) * cos(theta) y = r * sin(phi) * sin(theta) z = r * cos(phi) R = rotation_matrix([2, 3, 1], pi / 4) v = np.dot(R, np.array([x, y, z])) mlab.points3d(v[0,], v[1,], v[2,], scale_factor=0.01, color=(1, 0, 0)) phi = 0.1 * np.random.randn(100) theta = np.random.randn(100) * 2.0 * pi;
grid_theta=np.linspace(min_new_theta,max_new_theta,num=500) grid_phi=np.linspace(min_new_phi,max_new_phi,num=400) grid_theta,grid_phi=np.meshgrid(grid_theta,grid_phi) grid_theta2=np.linspace(110/180.0*np.pi,145/180.0*np.pi,num=500) grid_phi2=np.linspace(-40/180.0*np.pi,60/180.0*np.pi,num=400) grid_theta2,grid_phi2=np.meshgrid(grid_theta2,grid_phi2) v_grid=griddata((new_theta,new_phi), new_v, (grid_theta2,grid_phi2), method='linear') B_grid=griddata((new_theta,new_phi), new_B, (grid_theta,grid_phi), method='linear') vA_grid=griddata((new_theta,new_phi), new_vA, (grid_theta,grid_phi), method='linear') X_grid=target_R*np.sin(grid_theta)*np.cos(grid_phi) Y_grid=target_R*np.sin(grid_theta)*np.sin(grid_phi) Z_grid=target_R*np.cos(grid_theta) mlab.figure("|B| field") sphere_mesh=mlab.mesh(X_grid[::-1,:],Y_grid[::-1,:],Z_grid,scalars=np.log(B_grid[:,:]),colormap='bone') sphere_mesh.actor.property.backface_culling = True sphere_mesh.module_manager.scalar_lut_manager.reverse_lut = True if plot_field_lines: for idx in range(min(len(R_start),len(theta_start),len(phi_start))): field_line_start=np.array([R_start[idx],theta_start[idx],phi_start[idx]]) field_line_sph=field_line_flicks(field_line_start,coord_logR,coord_theta,coord_phi,B_flicks,1.0,2.9,nlblks,n1pm1,n2pm1,n3pm1,step_size=1E-2) field_line_X=field_line_sph[:,0]*np.sin(field_line_sph[:,1])*np.cos(field_line_sph[:,2]) field_line_Y=-field_line_sph[:,0]*np.sin(field_line_sph[:,1])*np.sin(field_line_sph[:,2]) field_line_Z=field_line_sph[:,0]*np.cos(field_line_sph[:,1]) mlab.plot3d(field_line_X,field_line_Y,field_line_Z,line_width=0.01,color=(0,0,0),tube_radius=0.004) plt.plot(field_line_sph[:,2],field_line_sph[:,1],color="black") mlab.view(azimuth=0, elevation=110, roll=90, distance=4.0)#, focalpoint=None, roll=None, reset_roll=True, figure=None) mlab.show()
def _plot_radiation_pattern_mayavi(ned_mt): """ Plot the radiation pattern using MayaVi. This private function uses the mayavi (vtk) library to plot the radiation pattern to screen. Note that you might have to set the QT_API environmental variable to e.g. export QT_API=pyqt that mayavi works properly. :param ned_mt: moment tensor in NED convention """ # use mayavi if possible. try: from mayavi import mlab except Exception as err: print(err) msg = ("ObsPy failed to import MayaVi. " "You need to install the mayavi module " "(e.g. 'conda install mayavi', 'pip install mayavi'). " "If it is installed and still doesn't work, " "try setting the environmental variable QT_API to " "pyqt (e.g. export QT_API=pyqt) before running the " "code. Another option is to avoid mayavi and " "directly use kind='vtk' for vtk file output of the " "radiation pattern that can be used by external " "software like ParaView") raise ImportError(msg) # get mopad moment tensor mopad_mt = MomentTensor(ned_mt, system='NED') bb = BeachBall(mopad_mt, npoints=200) bb._setup_BB(unit_circle=False) # extract the coordinates of the nodal lines neg_nodalline = bb._nodalline_negative pos_nodalline = bb._nodalline_positive # add the first point to the end to close the nodal line neg_nodalline = np.hstack((neg_nodalline, neg_nodalline[:, 0][:, None])) pos_nodalline = np.hstack((pos_nodalline, pos_nodalline[:, 0][:, None])) # plot radiation pattern and nodal lines points = _equalarea_spherical_grid(nlat=20) dispp = farfield(ned_mt, points, type="P") disps = farfield(ned_mt, points, type="S") # get vector lengths normp = np.sum(dispp * points, axis=0) normp /= np.max(np.abs(normp)) norms = np.sqrt(np.sum(disps * disps, axis=0)) norms /= np.max(np.abs(norms)) # make sphere to block view to the other side of the beachball rad = 0.8 pi = np.pi cos = np.cos sin = np.sin phi, theta = np.mgrid[0:pi:101j, 0:2 * pi:101j] x = rad * sin(phi) * cos(theta) y = rad * sin(phi) * sin(theta) z = rad * cos(phi) # p wave radiation pattern mlab.figure(size=(800, 800), bgcolor=(0, 0, 0)) pts1 = mlab.quiver3d(points[0], points[1], points[2], dispp[0], dispp[1], dispp[2], scalars=normp, vmin=-1., vmax=1.) pts1.glyph.color_mode = 'color_by_scalar' mlab.plot3d(*neg_nodalline, color=(0, 0.5, 0), tube_radius=0.01) mlab.plot3d(*pos_nodalline, color=(0, 0.5, 0), tube_radius=0.01) mlab.mesh(x, y, z, color=(0, 0, 0)) # s wave radiation pattern mlab.figure(size=(800, 800), bgcolor=(0, 0, 0)) pts2 = mlab.quiver3d(points[0], points[1], points[2], disps[0], disps[1], disps[2], scalars=norms, vmin=-0., vmax=1.) pts2.glyph.color_mode = 'color_by_scalar' mlab.plot3d(*neg_nodalline, color=(0, 0.5, 0), tube_radius=0.01) mlab.plot3d(*pos_nodalline, color=(0, 0.5, 0), tube_radius=0.01) mlab.mesh(x, y, z, color=(0, 0, 0)) mlab.show()
import numpy as np from scipy.special import sph_harm # Create a sphere r = 0.3 pi = np.pi cos = np.cos sin = np.sin phi, theta = np.mgrid[0:pi:101j, 0:2 * pi:101j] x = r * sin(phi) * cos(theta) y = r * sin(phi) * sin(theta) z = r * cos(phi) mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300)) mlab.clf() # Represent spherical harmonics on the surface of the sphere for n in range(3, 4): for m in range(n): s = sph_harm(m, n, theta, phi).real mlab.mesh(x - m, y - n, z, scalars=s, colormap='jet') s[s < 0] *= 0.97 s /= s.max() #mlab.mesh(s*x-m, s*y-n, s*z+1.3, scalars=s, colormap='Spectral') mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25)) mlab.show()
g2r = 'rect(eta+tau[i,j], te)[0]' g1i = 'rect(eta, te)[1]' g2i = 'rect(eta+tau[i,j], te)[1]' mu = 1 g1r = 'LFM(eta, mu, te)[0]' g2r = 'LFM(eta+tau[i,j], mu, te)[0]' g1i = 'LFM(eta, mu, te)[1]' g2i = 'LFM(eta+tau[i,j], mu, te)[1]' ambig = np.zeros(wd.shape, dtype='complex') for i in range(wd.shape[0]): for j in range(wd.shape[1]): gg_real = lambda eta: (eval(g1r) * eval(g2r) + eval(g1i) * eval( g2i)) * np.cos(wd[i, j] * eta) - (eval(g1r) * eval(g2i) - eval( g1i) * eval(g2r)) * np.sin(wd[i, j] * eta) tmp_real = integrate.quad(gg_real, -np.inf, np.inf)[0] gg_imag = lambda eta: (eval(g1r) * eval(g2r) + eval(g1i) * eval( g2i)) * np.sin(wd[i, j] * eta) + (eval(g1r) * eval(g2i) - eval( g1i) * eval(g2r)) * np.cos(wd[i, j] * eta) tmp_imag = integrate.quad(gg_imag, -np.inf, np.inf)[0] ambig[i, j] = tmp_real + 1j * tmp_imag mlab.mesh(tau, wd, abs(ambig)) mlab.show()
else: f = open("V.txt", "w+") for i in range(numbers): for j in range(numbers): f.write("%9.6f %9.6f %9.6f %9.3f\n" % (xyz[0, i, j], xyz[1, i, j], xyz[2, i, j], V[i, j])) f.close() #plot mlab.options.backend = 'envisage' if caltype == "E": s = mlab.mesh(xyz[0], xyz[1], xyz[2], representation="wireframe", line_width=3.0, scalars=E) mlab.title("Young's modulus") elif caltype == "B": s = mlab.mesh(xyz[0], xyz[1], xyz[2], representation="wireframe", line_width=3.0, scalars=B) mlab.title("linear compressibility") elif caltype == "G": s = mlab.mesh(xyz[0], xyz[1], xyz[2],
def generate_cartesian_volume(fig, length=250, spacing=10): ''' Generates a meshed cartesian volume that encapsulates the ROI. INPUTS: - fig : Scene/figure to populate. - length : Length of axes ( generates a KxKxK sized cube ). - spacing: Spacing between consecutive lines. OUTPUT: - No return; generates a mesh on the render window. ''' print("Constructing cartesian volume ..."), K = length + 1 # Number of lines to plot N = spacing # Subdivisions (aka K/N lines are drawn) # Draw horizontal lines on the xy-, yz-, and xz-planes lvlC_H = np.arange(0, K, N) # Horizontal level curve lvlC_V = np.zeros_like(lvlC_H) # Vertical level curve H, V = np.meshgrid(lvlC_H, lvlC_V) # Mesh both arrays to a matrix (a grid) lvlC_0 = np.zeros_like( H) # Force everything into a 2D plane by setting the 3rd plane to 0 for i in range(0, K, N): mlab.mesh(H, V + i, lvlC_0, figure=fig, representation='mesh', tube_radius=0.25, color=(1., 1., 1.)) mlab.mesh(lvlC_0, H, V + i, figure=fig, representation='mesh', tube_radius=0.25, color=(1., 1., 1.)) mlab.mesh(H, lvlC_0, V + i, figure=fig, representation='mesh', tube_radius=0.25, color=(1., 1., 1.)) # Draw vertical lines on the xy-, yz-, and xz-planes lvlC_V = np.arange(0, K, N) # Vertical level curve lvlC_H = np.zeros_like(lvlC_V) # Horizontal level curve H, V = np.meshgrid(lvlC_H, lvlC_V) # Mesh both arrays to form a matrix (a grid) lvlC_0 = np.zeros_like( H) # Force everything into a 2D plane by setting the 3rd plane to 0 for i in range(0, K, N): mlab.mesh(H + i, V, lvlC_0, figure=fig, representation='mesh', tube_radius=0.25, color=(1., 1., 1.)) mlab.mesh(lvlC_0, H + i, V, figure=fig, representation='mesh', tube_radius=0.25, color=(1., 1., 1.)) mlab.mesh(H + i, lvlC_0, V, figure=fig, representation='mesh', tube_radius=0.25, color=(1., 1., 1.)) # Generate outline and label axes mlab.outline(extent=[0, K - 1, 0, K - 1, 0, K - 1], figure=fig) mlab.axes(extent=[0, K - 1, 0, K - 1, 0, K - 1], figure=fig, line_width=1.0, x_axis_visibility=True, y_axis_visibility=True, z_axis_visibility=True) print("SUCCESS!")
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import mayavi.mlab as mlab mlab.figure(fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) #更改背景色 s = np.random.normal(size=(21, 21)) #mlab.barchart(s) #x,y为矩阵p的坐标,可以省略 #mlab.imshow(s) # the colormap x, y = np.mgrid[-10:10:21j, -10:10:21j] mlab.mesh(x, y, s) mlab.vectorbar() #颜色bar mlab.show()
# -*- coding: utf-8 *-* # Author: Gael Varoquaux <*****@*****.**> # Copyright (c) 2007, Enthought, Inc. # License: BSD Style. from numpy import sin, cos, mgrid, pi, sqrt from mayavi import mlab import os os.environ['QT_API'] = 'pyside' mlab.figure(fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) u, v = mgrid[-0.035:pi:0.01, -0.035:pi:0.01] X = 2 / 3. * (cos(u) * cos(2 * v) + sqrt(2) * sin(u) * cos(v)) * cos(u) / ( sqrt(2) - sin(2 * u) * sin(3 * v)) Y = 2 / 3. * (cos(u) * sin(2 * v) - sqrt(2) * sin(u) * sin(v)) * cos(u) / ( sqrt(2) - sin(2 * u) * sin(3 * v)) Z = -sqrt(2) * cos(u) * cos(u) / (sqrt(2) - sin(2 * u) * sin(3 * v)) S = sin(u) mlab.mesh( X, Y, Z, scalars=S, colormap='YlGnBu', ) # Nice view from the front mlab.view(.0, -5.0, 4) mlab.show()
import numpy as np from mayavi import mlab from scipy.special import sph_harm # Mit diesem Werten kann gespielt werden: l = 3 m = 0 # -------------------------------------- theta_ld = np.linspace(0, np.pi, 91) phi_ld = np.linspace(0, 2 * np.pi, 181) theta_2d, phi_2d = np.meshgrid(theta_ld, phi_ld) xyz_2d = np.array([ np.sin(theta_2d) * np.sin(phi_2d), np.sin(theta_2d) * np.cos(phi_2d), np.cos(theta_2d) ]) Y_lm = sph_harm(m, l, phi_2d, theta_2d) r = abs(Y_lm.real) * xyz_2d mlab.figure(size=(700, 830)) mlab.mesh(r[0], r[1], r[2], scalars=Y_lm.real, colormap="cool") mlab.view(azimuth=0, elevation=75, distance=2.4, roll=-50) mlab.savefig("images/Y_%i_%i.jpg" % (l, m)) mlab.show() print("I did it, Babe!")
""" From "COMPUTATIONAL PHYSICS" & "COMPUTER PROBLEMS in PHYSICS" by RH Landau, MJ Paez, and CC Bordeianu (deceased) Copyright R Landau, Oregon State Unv, MJ Paez, Univ Antioquia, C Bordeianu, Univ Bucharest, 2017. Please respect copyright & acknowledge our work.""" # YlmMayavi: Surface plot of spherical harmonic from numpy import pi, sin, cos, mgrid dphi, dtheta = pi / 250.0, pi / 250.0 [phi, theta] = mgrid[0:pi + dphi * 1.5:dphi, 0:2 * pi + dtheta * 1.5:dtheta] # Create data m0 = 4 m1 = 3 m2 = 2 m3 = 3 m4 = 6 m5 = 2 m6 = 6 m7 = 4 r = sin(m0 * phi)**m1 + cos(m2 * phi)**m3 + sin(m4 * theta)**m5 + cos( m6 * theta)**m7 x = r * sin(phi) * cos(theta) y = r * cos(phi) z = r * sin(phi) * sin(theta) from mayavi import mlab s = mlab.mesh(x, y, z) # View data mlab.show()
def plot_surface(r): x = r[:, :, 0] y = r[:, :, 1] z = r[:, :, 2] p = mlab.mesh(x, y, z, color=(0.8, 0.0, 0.0)) return p
# (use 'extent' for auto-scaling) plt.plot3d(curve_x, curve_y, curve_z, tube_radius=0.2, extent=(0, 1, 0, 1, 0, 1)) plt.figure(3, fgcolor=(.0, .0, .0), bgcolor=(1.0, 1.0, 1.0)) # Use 'warp_scale' for vertical scaling plt.surf(xv, yv, hv, warp_scale=0.01, color=(.5, .5, .5)) plt.plot3d(curve_x, curve_y, 0.01 * curve_z, tube_radius=0.2) # endsimpleplots # Create one figure with three subplots plt.figure(4, fgcolor=(.0, .0, .0), bgcolor=(1.0, 1.0, 1.0)) plt.mesh(xv, yv, hv, extent=(0, 0.25, 0, 0.25, 0, 0.25), colormap='cool') plt.outline( plt.mesh(xv, yv, hv, extent=(0.375, 0.625, 0, 0.25, 0, 0.25), colormap='Accent')) plt.outline(plt.mesh(xv, yv, hv, extent=(0.75, 1, 0, 0.25, 0, 0.25), colormap='prism'), color=(.5, .5, .5)) # endsubplot hv = h0 / (1 + (xv**2 + yv**2) / (R**2))
#field_line_Z=field_line_sph[:,0]*np.cos(field_line_sph[:,1]) #plt.figure() #print(np.shape(Q_grid1),np.shape(phi_grid1),np.shape(theta_grid1)) #plt.plot(phi_grid1[:,0]) #plt.plot(theta_grid1[0,:]) fig=plt.figure("",figsize=(10,7)) color_plot=plt.pcolormesh(phi_grid1,theta_grid1,Q_grid1,cmap='RdBu_r',vmin=-10,vmax=10) #mlab.figure(bgcolor=(1,0.8,0.55)) mlab.figure(bgcolor=(1,1,1)) sphere_mesh=mlab.mesh(X_grid1[::-1,:],Y_grid1[::-1,:],Z_grid1[:,:],scalars=Q_grid1[:,:],colormap='RdBu',vmin=-10,vmax=10) sphere_mesh.actor.property.backface_culling = True sphere_mesh.module_manager.scalar_lut_manager.reverse_lut = True #mlab.colorbar(orientation="vertical") if plot_R3: sphere_mesh3=mlab.mesh(X_grid3[::-1,:],Y_grid3[::-1,:],Z_grid3[:,:],scalars=Q_grid3[:,:],colormap='RdBu',vmin=-10,vmax=10,opacity=0.4) sphere_mesh3.actor.property.backface_culling = True sphere_mesh3.module_manager.scalar_lut_manager.reverse_lut = True for idx in range(min(len(R_start),len(theta_start),len(phi_start))): field_line_start=np.array([R_start[idx],theta_start[idx],phi_start[idx]]) field_line_sph=field_line_spherical(field_line_start,R,theta,phi,B,1.0,2.9,step_size=1E-2) field_line_X=field_line_sph[:,0]*np.sin(field_line_sph[:,1])*np.cos(field_line_sph[:,2]) field_line_Y=-field_line_sph[:,0]*np.sin(field_line_sph[:,1])*np.sin(field_line_sph[:,2])
# * $y=x^2+\delta$ # * $z=x^2-\delta$ # * $y=z^2+\delta$ # In[ ]: delta = 0.5 # In[ ]: res = 200j x, z = np.mgrid[-3:3:res, -3:3:res] y = x**2 + delta mlab.mesh(x, y, z) if 1: y, x = np.mgrid[-3:3:res, -3:3:res] z = x**2 - delta mlab.mesh(x, y, z) if 1: x, z = np.mgrid[-3:3:res, -3:3:res] y = z**2 + delta mlab.mesh(x, y, z) # In[ ]:
x_size = 318 y_size = 159 theta = np.linspace(np.pi, 0, y_size) phi = np.linspace(-np.pi, np.pi, x_size) longitude = np.radians(np.linspace(-180, 180, x_size)) latitude = np.radians(np.linspace(-90, 90, y_size)) # project the map to a rectangular matrix xsize x ysize PHI, THETA = np.meshgrid(phi, theta) # Create a sphere r = 0.3 x = r*np.sin(THETA)*np.cos(PHI) y = r*np.sin(THETA)*np.sin(PHI) z = r*np.cos(THETA) # Plot it! mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300)) mlab.clf() mlab.mesh(x, y, z, scalars=img, colormap="jet", vmin=vmin, vmax=vmax) cv2.imshow('Image', img) mlab.show() while True: if cv2.waitKey(1) & 0xFF == ord('q'): break
# Create forcing function ix = grid[:, 2] >= surf_plane chi[ix] = image[xi[ix], yi[ix]] # Make sure forcing is a cp extension chi = E * chi # Re-threshold chi = (chi > 0.9).astype(np.int) xp, yp, zp = s.parametric_grid(256) Eplot = build_interp_matrix( int_grid, np.column_stack((xp.ravel(), yp.ravel(), zp.ravel())), dx, p, ll, virtual_grid_shape) # Plot forcing function mlab.figure(1, fgcolor=(1.0, 1.0, 1.0)) mlab.mesh(xp, yp, zp, scalars=(Eplot * (1 - chi)).reshape(xp.shape)) mlab.view(azimuth=158, elevation=25, distance=7) mlab.title('forcing function') # Parameters and functions for Gray--Scott F = 0.054 kk = 0.063 nuu = 1 / (3 / dx.min())**2 nuv = nuu / 2. f = lambda u, v: -u * v**2 + F * (1 - u) g = lambda u, v: u * v**2 - (F + kk) * v # Initial conditions - small perturbation from steady state pert = 0.5 * np.exp(-(10 * (grid[:, 2] - 1))**2) + 0.5 * np.random.randn( grid.shape[0]) u0 = 1 - pert
def plot_potential(self, fig=None, r=None, theta=None, phi=None, lowering=True): if not self.USE_MAYAVI: return None if fig is None: fig = mlab.figure('Potential')#, bgcolor=(0, 0, 0)) else: mlab.figure(fig, bgcolor=fig.scene.background) if r is None: r = np.linspace(1e-9, 20e-9, num=50, endpoint=True) if theta is None: theta = np.linspace(0, np.pi, num=50, endpoint=True) if phi is None: phi = np.linspace(0, 2 * np.pi, num=50, endpoint=True) r_grid, theta_grid, phi_grid = np.meshgrid(r, theta, phi) volumetric_data = self.potential(r, theta, phi) energy_scale = np.max(np.abs(r)) / np.max(np.abs(volumetric_data[:, :, 0])) dim_idx = 2 for i, dim in enumerate(r_grid.shape): if dim == 1: dim_idx = i break if dim_idx == 2: print 'here' surf = mlab.mesh(r_grid[:, :, 0] * np.cos(theta_grid[:, :, 0]), r_grid[:, :, 0] * np.sin(theta_grid[:, :, 0]), volumetric_data[:, :, 0] * energy_scale, #extent=(0, 1, 0, 1, 0, 1), representation='wireframe', colormap='RdBu') elif dim_idx == 1: surf = mlab.mesh(r_grid[:, 0, :] * np.sin(theta_grid[0, 0, 0]) * np.cos(phi_grid[:, 0, :]), r_grid[:, 0, :] * np.sin(theta_grid[0, 0, 0]) * np.sin(phi_grid[:, 0, :]), volumetric_data[:, 0, :], extent=(0, 1, 0, 1, 0, 1), representation='wireframe', colormap='RdBu') elif dim_idx == 0: surf = mlab.mesh(theta_grid[0, :, :], phi_grid[0, :, :], volumetric_data[0, :, :], extent=(0, 1, 0, 1, 0, 1), representation='wireframe', colormap='RdBu') mlab.outline() if lowering: theta2 = np.linspace(0, 2*np.pi, num=50) barrier_lowering = np.array([self.barrier_lowering(theta_i) for theta_i in theta2]) idx = np.where(barrier_lowering[:, 1] > 0) print barrier_lowering[idx] mlab.plot3d(barrier_lowering[idx][:, 1] * np.cos(theta2[idx]), barrier_lowering[idx][:, 1] * np.sin(theta2[idx]), barrier_lowering[idx][:, 0] * energy_scale, tube_radius=energy_scale * 5e-3, color=(1, 0, 0)) #mlab.outline() ''' mlab.points3d(barrier_lowering[idx][:, 1] * np.cos(theta2[idx]), barrier_lowering[idx][:, 1] * np.sin(theta2[idx]), barrier_lowering[idx][:, 0] * energy_scale) mlab.outline() ''' return fig
#============================================================================== # Plotting current vectors #============================================================================== #mlab.options.backend = 'envisage' # one way to save visualization #f = mlab.figure() c1 = mlab.points3d(0, 0, 0) mlab.quiver3d(x, y, z2, J_x, J_y, J_z, colormap="jet", scale_factor=1) #============================================================================== # Plotting actual ***boids #============================================================================== if (eps1 == 1): s2 = mlab.mesh(x, y, z2, colormap="gray", transparent=True) # mlab.quiver3d(x, y, z2, u2, v2, w2, scale_factor=1) else: # sr = mlab.mesh(x_r, y_r, z_r, colormap="gray", transparent=True) s2 = mlab.mesh(x, y, z2, colormap="gray", transparent=True) # mlab.quiver3d(x, y, z2, u2, v2, w2,colormap="gray",transparent=True, scale_factor=1) # s1 = mlab.mesh(x, y, z1,colormap="gray", transparent=True) # mlab.quiver3d(x, y, z1, u1, v1, w1,colormap="gray",transparent=True, scale_factor=1) #============================================================================== # Show the scene #==============================================================================
def show_sph_harm(l, m, real=True, N=50, use_sphere=True, plot='mpl'): ''' Show the spherical harmonics on a unit sphere ''' assert plot.lower() in ['mpl', 'mayavi', 'plotly'] theta = np.linspace(0, np.pi, N) phi = np.linspace(0, 2 * np.pi, N) theta, phi = np.meshgrid(theta, phi) # The Cartesian coordinates of the unit sphere x = np.sin(theta) * np.cos(phi) y = np.sin(theta) * np.sin(phi) z = np.cos(theta) xyz = np.c_[x.ravel(), y.ravel(), z.ravel()] # from time import time # t0 = time() if real: ylm = sph_r(xyz, l, m).reshape(N, N) else: ylm = sph_c(xyz, l, m).reshape(N, N).real # t1 = time() # print(t1 - t0) # Calculate the spherical harmonic Y(l,m) and normalize to [0,1] fcolors = ylm fmax, fmin = fcolors.max(), fcolors.min() fcolors = (fcolors - fmin) / (fmax - fmin) if not use_sphere: r0 = np.abs(ylm) if plot.lower() == 'mpl': import matplotlib.pyplot as plt from matplotlib import cm, colors from mpl_toolkits.mplot3d import Axes3D # Set the aspect ratio to 1 so our sphere looks spherical fig = plt.figure(figsize=plt.figaspect(1.)) ax = fig.add_subplot(111, projection='3d') if use_sphere: ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=cm.seismic(fcolors)) xmax = ymax = zmax = np.max([x, y, z]) xmin = ymin = zmin = np.min([x, y, z]) else: ax.plot_surface(x * r0, y * r0, z * r0, rstride=1, cstride=1, facecolors=cm.seismic(fcolors)) xmax = ymax = zmax = np.max([r0 * x, r0 * y, r0 * z]) xmin = ymin = zmin = np.min([r0 * x, r0 * y, r0 * z]) # Turn off the axis planes # ax.set_axis_off() ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) ax.set_zlim(zmin, zmax) ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') plt.show() elif plot == 'mayavi': from mayavi import mlab fig = mlab.figure(size=(800, 800), bgcolor=(1, 1, 1)) if use_sphere: mlab.mesh(x, y, z, colormap='seismic', scalars=fcolors) else: mlab.mesh(x * r0, y * r0, z * r0, colormap='seismic', scalars=fcolors) mlab.orientation_axes() mlab.show() else: import plotly.graph_objects as go if use_sphere: fig = go.Figure(data=[ go.Surface(z=z, x=x, y=y, surfacecolor=fcolors, colorscale='balance', showscale=False, opacity=1.0, hoverinfo='none') ], ) else: fig = go.Figure(data=[ go.Surface(z=r0 * z, x=r0 * x, y=r0 * y, surfacecolor=fcolors, colorscale='balance', showscale=False, opacity=1.0, hoverinfo='none') ], ) fig.update_layout( width=800, height=800, ) fig.show()
gnitstam(p, dims), simplex_onb(dims, p), ): all_nodes.append(plot_nodes + [stretch_factor * i, stretch_factor * j]) all_triangles.append(tri_subtriangles + node_count) all_values.append(basis_func(eval_nodes)) node_count += len(plot_nodes) all_nodes = np.vstack(all_nodes) all_triangles = np.vstack(all_triangles) all_values = np.hstack(all_values) # plot import mayavi.mlab as mlab fig = mlab.figure(bgcolor=(1, 1, 1)) mlab.triangular_mesh(all_nodes[:, 0], all_nodes[:, 1], 0.2 * all_values, all_triangles) x, y = np.mgrid[-1:p * stretch_factor + 1:20j, -1:p * stretch_factor + 1:20j] mlab.mesh(x, y, 0 * x, representation="wireframe", color=(0.4, 0.4, 0.4), line_width=0.6) mlab.view(-153, 58, 10, np.array([1.61, 2.49, -0.59])) mlab.show()
def explore(prefix, faults): """ CFMX: Community Fault Model Explorer A simple tool for exploring the CFM Keyboard Controls: Fault selection [ ] Fault selection and view { } Clear fault selection \\ Rotate the view Arrows Pan the view Shift-Arrows Zoom the view - = Reset view 0 Toggle stereo view 3 Save a screen-shot S Help h ? """ doc = explore.__doc__ # must use hardcode function name to inspect doc if not faults: print('No faults found') return import pyproj from mayavi import mlab fault_names = json.load(open(home + 'data/CFM-Fault-Names.json')) # parameters extent = (-122.0, -114.0), (31.5, 37.5) resolution = 'high' view_azimuth = -90 view_elevation = 45 view_angle = 15 color_bg = 1.0, 1.0, 0.0 color_hl = 1.0, 0.0, 0.0 single_fault = isinstance(faults, str) # projection proj = pyproj.Proj(**projection) # setup figure s = 'SCEC Community Fault Model' if prefix: s = [s] + [fault_names[i][k] for i, k in enumerate(prefix[:3])] if single_fault: s += [prefix[3].replace('_', ' ')] s = ', '.join(s) print('\n%s\n' % s) fig = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(1280, 720)) fig.name = s fig.scene.disable_render = True # DEM f = os.path.join(repository, 'CFM', 'dem.npy') if os.path.exists(f): x, y, z = numpy.load(f) else: x, y, z = data.dem(extent, mesh=True) extent = (x.min(), x.max()), (y.min(), y.max()) x, y = proj(x, y) numpy.save(f, [x, y, z]) mlab.mesh(x, y, z, color=(1, 1, 1), opacity=0.3) # base map f = os.path.join(repository, 'CFM', 'mapdata.npy') if os.path.exists(f): x, y, z = numpy.load(f) else: ddeg = 0.5 / 60.0 # FIXME x, y = numpy.c_[ data.gshhg('coastlines', resolution, extent, 10.0, delta=ddeg), [float('nan'), float('nan')], data.gshhg('borders', resolution, extent, delta=ddeg), ] x -= 360.0 z = interp.interp2(extent, z, (x, y)) x, y = proj(x, y) i = numpy.isnan(z) x[i] = float('nan') y[i] = float('nan') numpy.save(f, [x, y, z]) mlab.plot3d(x, y, z, color=(0, 0, 0), line_width=1, tube_radius=None) mlab.view(view_azimuth, view_elevation) fig.scene.camera.view_angle = view_angle fig.scene.disable_render = False fig.scene.disable_render = True # read fault surfaces tsurfs = [] if single_fault: f, s = (faults + ':').split(':')[:2] x, t = read(f)[:2] if s: for i in s.split(','): tsurfs.append(('%s:%s' % (f, i), x.T, t[int(i)].T)) else: for i, j in enumerate(t): tsurfs.append(('%s:%s' % (f, i), x.T, j.T)) else: for f in faults: if isinstance(f, str): x, t = tsurf_merge(read(f)) else: f, s = f x, t = tsurf_merge(read(i) for i in s) tsurfs.append((f, x, t)) # plot fault surfaces surfs = [] for isurf, f in enumerate(tsurfs): name, vtx, tri = f print(name) m = geometry(vtx, tri) x, y, z = vtx s = [ 'Mean Strike: %10.5f deg' % m['strike'], 'Mean Dip: %10.5f deg' % m['dip'], 'Centroid Lon: %10.5f deg' % m['centroid_lon'], 'Centroid Lat: %10.5f deg' % m['centroid_lat'], 'Centroid Elev: %10d m' % m['centroid_z'], 'Min Elevation: %10d m' % z.min(), 'Max Elevation: %10d m' % z.max(), 'Surface Area: %10d km^2' % (m['area'] * 0.000001), ] k = name.split('-', 3) s += [fault_names[i][a] for i, a in enumerate(k[:3])] if k[3:]: s += [k[3].replace('_', ' ')] s += [name] p = mlab.triangular_mesh( x, y, z, tri, representation='surface', color=color_bg, ).actor.actor.property u = m['centroid_x'], m['centroid_y'], m['centroid_z'] if single_fault: surfs.append((isurf, u, s, p)) else: i = m['centroid_lon'] surfs.append((i, u, s, p)) surfs = [i[1:] for i in sorted(surfs)] # handle key press def on_key_press(obj, event, save=[0]): k = obj.GetKeyCode() isurf = save[0] fig.scene.disable_render = True if k in '[]{}': c, s, p = surfs[isurf] if p.color == color_bg: p.color = color_hl else: p.color = color_bg d = {'[': -1, ']': 1, '{': -1, '}': 1}[k] isurf = (isurf + d) % len(surfs) c, s, p = surfs[isurf] p.color = color_hl print('\n' + '\n'.join(s)) if k in '{}': mlab.view(focalpoint=c) elif k == '\\': surfs[isurf][-1].color = color_bg elif k == '0': mlab.view(view_azimuth, view_elevation) fig.scene.camera.view_angle = view_angle elif k in '/?h': print(doc) fig.scene.disable_render = False save[0] = isurf return # finish up fig.scene.interactor.add_observer('KeyPressEvent', on_key_press) mlab.view(view_azimuth, view_elevation) fig.scene.camera.view_angle = view_angle fig.scene.disable_render = False print('\nPress H in the figure window for help.') mlab.show() return
from mayavi import mlab import numpy as np r = 0.5 R = 1.0 u, v = np.mgrid[0:2 * np.pi:25j, 0:2 * np.pi:50j] x = (R + r * np.cos(v)) * np.cos(u) y = (R + r * np.cos(v)) * np.sin(u) z = r * np.sin(v) mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(800, 800)) mlab.clf() # https://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#mesh mlab.mesh(x, y, z, opacity=0.8) # , color=(0.1, 0.1, 0.6) mlab.mesh(x, y, z, opacity=0.8, color=(0, 0, 0), representation='wireframe') mlab.points3d(1.5, 0, 0, color=(1.0, 0.0, 0.0), scale_factor=0.1) mlab.orientation_axes() mlab.show()
def main(thetamax=None, link_in_ra=True, dec_refine_factor=1, ra_refine_factor=1): from math import radians if not thetamax: thetamax = 30 ra_limits = [0.0, 360.0] dec_limits = [-90.0, 90.0] sphere, num_ra = gridlink_sphere(thetamax, link_in_ra=link_in_ra, dec_refine_factor=dec_refine_factor, ra_refine_factor=ra_refine_factor, ra_limits=ra_limits, dec_limits=dec_limits, return_num_ra_cells=True) ra_limits = [radians(a) for a in ra_limits] dec_limits = [radians(a) for a in dec_limits] ndec = num_ra.size ncells = sphere.size dec, ra, dec_bands, scalars = spherical_meshgrid(sphere, num_ra) x = cos(dec) * cos(ra) y = cos(dec) * sin(ra) z = sin(dec) volume = mlab.mesh(x, y, z, scalars=scalars, colormap='viridis', opacity=0.95) volume.actor.property.specular = 0.45 volume.actor.property.specular_power = 5 # Backface culling is necessary for more a beautiful transparent # rendering. volume.actor.property.backface_culling = True # Mark the declination bands phi = np.linspace(ra_limits[0], ra_limits[1], 100) for angle in dec_bands: # Lower limits of the dec-bands, except for the two poles if angle == -0.5 * np.pi or angle == 0.5 * np.pi: continue # Draw the declination band xx = np.cos(phi) * np.cos(angle) yy = np.sin(phi) * np.cos(angle) zz = np.ones_like(phi) * np.sin(angle) mlab.plot3d(xx, yy, zz, color=(1, 1, 1), opacity=0.5, tube_radius=None) # Now draw the ra cells. from itertools import izip, count off = 0 for idec, dec_low, dec_hi in izip(count(), dec_bands[0:-1], dec_bands[1:]): dodgerblue = (0.1167315175, 0.5625, 1.0) white = (1.0, 1.0, 1.0) gray = (0.5, 0.5, 0.5) for ira in xrange(num_ra[idec]): phi = sphere['ra_limit'][off] color, tube_radius = (dodgerblue, 0.01) if ira == 0 else (white, None) theta = np.linspace(dec_low, dec_hi, 100) xx = np.cos(theta) * np.cos(phi[0]) yy = np.cos(theta) * np.sin(phi[0]) zz = np.sin(theta) mlab.plot3d(xx, yy, zz, color=color, opacity=0.5, tube_radius=tube_radius) off += 1 theta = np.linspace(dec_low, dec_hi, 100) xx = np.cos(theta) * np.cos(phi[1]) yy = np.cos(theta) * np.sin(phi[1]) zz = np.sin(theta) mlab.plot3d(xx, yy, zz, color=dodgerblue, opacity=0.5, tube_radius=0.01) mlab.show()
from numpy import pi, sin, cos, mgrid from mayavi import mlab #建立数据 dphi, dtheta = pi / 250.0, pi / 250.0 [phi, theta] = mgrid[0:pi + dphi * 1.5:dphi, 0:2 * pi + dtheta * 1.5:dtheta] m0 = 4 m1 = 3 m2 = 2 m3 = 3 m4 = 6 m5 = 2 m6 = 6 m7 = 4 r = sin(m0 * phi)**m1 + cos(m2 * phi)**m3 + sin(m4 * theta)**m5 + cos( m6 * theta)**m7 x = r * sin(phi) * cos(theta) y = r * cos(phi) z = r * sin(phi) * sin(theta) #对该数据进行三维可视化 s = mlab.mesh(x, y, z, representation='wireframe', line_width=3.0) mlab.show()