def mayavi_flow(): """ 绘制mayavi flow图 :return: """ x, y, z = np.mgrid[-4:4:40j, -4:4:40j, 0:4:20j] r = np.sqrt(x ** 2 + y ** 2 + z ** 2 + 0.1) u = y * np.sin(r) / r v = -x * np.sin(r) / r w = np.ones_like(z) * 0.05 mlab.flow(u, v, w) mlab.show()
def plot_vector_field(): u = np.sin(np.pi*x) * np.cos(np.pi*z) v = -2*np.sin(np.pi*y) * np.cos(2*np.pi*z) w = np.cos(np.pi*x)*np.sin(np.pi*z) + np.cos(np.pi*y)*np.sin(2*np.pi*z) print("showing") src = mlab.pipeline.vector_field(u, v, w) # mlab.pipeline.vectors(src, mask_points=1, scale_factor=3.) # magnitude = mlab.pipeline.extract_vector_norm(src) # mlab.pipeline.iso_surface(magnitude, contours = [1.9, 0.5]) mlab.flow(u,v,w) # mlab.outline() mlab.show()
def startup(self): # super().startup() # print( len( self.data ) ) self.mayavi_plot = mlab.flow(*self.data, figure=self.mayavi_scene, integration_direction='both', seedtype='point', seed_resolution=1, linetype='line') self.set_max_propagation(400) self.set_max_nsteps(4000) mlab.colorbar(self.mayavi_plot, orientation='vertical') # see https://docs.enthought.com/mayavi/mayavi/auto/example_magnetic_field.html # self.mayavi_plot.glyph.trait_set( mask_input_points = True ) # self.mayavi_plot.glyph.mask_points.trait_set( on_ratio = 2, random_mode = False ) # print_info( self.mayavi_plot.glyph.mask_points ) # self.set_mask_points( 5 ) # print_info( self.mayavi_plot ) self.set_orientation_axes(1) # self.set_outline( 1 ) self.needs_startup = 0
def e_field(q, pos, 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 charge, location in zip(q, pos): # draw sphere for point charge sphere(charge, location) # draw electric field lines ball = mplt.flow(X, Y, Z, x_field, y_field, z_field, figure=fig, seedtype='sphere', integration_direction='both') ball.seed.widget.center = location # number of field lines to integrate over ball.seed.widget.theta_resolution = no_lines ball.seed.widget.phi_resolution = no_lines # number of integration steps ball.stream_tracer.maximum_propagation = 200 ball.seed.widget.radius = 1 # dodgy hax... TL;DR widgets are dumb ball.seed.widget.enabled = False ball.seed.widget.enabled = True mplt.axes() # set view to x-axis coming out of screen fig.scene.x_plus_view() mplt.draw(figure=fig) mplt.show()
def test_flow(): x, y, z = np.mgrid[-4:4:40j, -4:4:40j, 0:4:20j] r = np.sqrt(x**2 + y**2 + z**2 + 0.1) u = y * np.sin(r) / r v = -x * np.sin(r) / r w = np.ones_like(z) * 0.05 obj = mlab.flow(u, v, w) return obj
def test18(self): x, y, z = np.mgrid[0:1:20j, 0:1:20j, 0:1:20j] u = np.sin(np.pi * x) * np.cos(np.pi * z) v = -2 * np.sin(np.pi * y) * np.cos(2 * np.pi * z) w = np.cos(np.pi * x) * np.sin(np.pi * z) + np.cos(np.pi * y) * np.sin( 2 * np.pi * z) #以下是四种不同的向量场绘制函数,mlab.pipeline.vector_field是对原向量场的降采样 # #1.绘制等势面,即曲面向量范数相同 # src=mlab.pipeline.vector_field(u,v,w) # magnitude=mlab.pipeline.extract_vector_norm(src) # mlab.pipeline.iso_surface(magnitude,contours=[1.9,1.8]) # #2.绘制整个向量场 # src=mlab.pipeline.vector_field(u,v,w) # mlab.pipeline.vectors(src,mask_points=10,scale_factor=1) # #3.仅绘制一个平面中的向量,且这个平面可以移动 # src=mlab.pipeline.vector_field(u,v,w) # mlab.pipeline.vector_cut_plane(src,mask_points=10,scale_factor=1) # #4.绘制流线图 # src=mlab.pipeline.vector_field(u,v,w) # magnitude=mlab.pipeline.extract_vector_norm(src) # flow = mlab.pipeline.streamline(magnitude, seedtype='point', # seed_visible=False, # seed_scale=0.5, # seed_resolution=5 ) #以下的方法针对所有数据 #显示所有数据 # mlab.quiver3d(u,v,w) #绘制流线图 mlab.flow(u, v, w, seed_scale=1, seed_resolution=3, integration_direction='both', seedtype='sphere') mlab.show()
def plot_property(self, prop=None): ''' This function will plot vector fields for you to enjoy. Right now, if you feed it an electrostatic potential (ESP), it will compute and plot the gradient. If you have a noncollinear solution and run VSPIN with cubegen, it will plot the magnetization (MAG) You need Mayavi to plot in 3D. ''' try: import mayavi.mlab as mlab except ImportError: print("[ImportError] You need Mayavi \n \ (http://docs.enthought.com/mayavi/mayavi/)") if not prop: sys.exit('No property chosen!') if prop == 'ESP': volume = np.gradient(self.volRA, edge_order=2) volumeX = volume[0] volumeY = volume[1] volumeZ = volume[2] import mayavi.mlab as mlab vol = mlab.flow(volumeX,volumeY,volumeZ,\ seed_resolution=25,\ seed_visible=True,\ seedtype='plane',\ seed_scale=2,\ colormap='bone',\ integration_direction='both',\ line_width=1.0) #mlab.quiver3d(volumeX,volumeY,volumeZ) mlab.show() elif (self.vspin) and (prop == 'MAG'): import mayavi.mlab as mlab import matplotlib.pyplot as plt plt.quiver(self.Mx[:, self.ny / 2, :], self.Mz[:, self.ny / 2, :], scale=10.0) plt.show() vol = mlab.flow(self.Mx,self.My,self.Mz,\ seed_resolution=25,\ seed_visible=True,\ seedtype='plane',\ seed_scale=2,\ colormap='bone',\ integration_direction='both',\ line_width=1.0)
def maya_raster_any(result, outfile, **kwds): ''' Plot a "raster" type result as a 3D scalar using MayaVi. ''' from mayavi import mlab arrs = result.array_data_by_type() fx,fy,fz = arrs['gvector'] flow = mlab.flow(u,v,w, seed_scale=1)
def plot_property(self,prop=None): ''' This function will plot vector fields for you to enjoy. Right now, if you feed it an electrostatic potential (ESP), it will compute and plot the gradient. If you have a noncollinear solution and run VSPIN with cubegen, it will plot the magnetization (MAG) You need Mayavi to plot in 3D. ''' try: import mayavi.mlab as mlab except ImportError: print("[ImportError] You need Mayavi \n \ (http://docs.enthought.com/mayavi/mayavi/)") if not prop: sys.exit('No property chosen!') if prop == 'ESP': volume = np.gradient(self.volRA,edge_order=2) volumeX = volume[0] volumeY = volume[1] volumeZ = volume[2] import mayavi.mlab as mlab vol = mlab.flow(volumeX,volumeY,volumeZ,\ seed_resolution=25,\ seed_visible=True,\ seedtype='plane',\ seed_scale=2,\ colormap='bone',\ integration_direction='both',\ line_width=1.0) #mlab.quiver3d(volumeX,volumeY,volumeZ) mlab.show() elif (self.vspin) and (prop == 'MAG'): import mayavi.mlab as mlab import matplotlib.pyplot as plt plt.quiver(self.Mx[:,self.ny/2,:],self.Mz[:,self.ny/2,:],scale=10.0) plt.show() vol = mlab.flow(self.Mx,self.My,self.Mz,\ seed_resolution=25,\ seed_visible=True,\ seedtype='plane',\ seed_scale=2,\ colormap='bone',\ integration_direction='both',\ line_width=1.0)
def do(self): ############################################################ # Imports. from mayavi import mlab ############################################################ # Create a new scene and set up the visualization. s = self.new_scene() ############################################################ # run all the "test_foobar" functions in the mlab module. for name, func in getmembers(mlab): if not callable(func) or not name[:4] in ('test', 'Test'): continue mlab.clf() func() # Mayavi has become too fast: the operator cannot see if the # Test function was succesful. sleep(0.1) ############################################################ # Test some specific corner-cases import numpy x, y, z = numpy.mgrid[1:10, 1:10, 1:10] u, v, w = numpy.mgrid[1:10, 1:10, 1:10] s = numpy.sqrt(u**2 + v**2) mlab.clf() # Test the extra argument "scalars" mlab.quiver3d(x, y, z, u, v, w, scalars=s) # Test surf with strange-shaped inputs X, Y = numpy.ogrid[-10:10, -10:10] Z = X**2 + Y**2 mlab.surf(X, Y, Z) mlab.surf(X.ravel(), Y.ravel(), Z) x, y, z = numpy.mgrid[-10:10, -10:10, -3:2] mlab.flow(x, y, z) # Test glyphs with number-only coordinnates mlab.points3d(0, 0, 0, resolution=50)
def do(self): ############################################################ # Imports. from mayavi import mlab ############################################################ # Create a new scene and set up the visualization. s = self.new_scene() s.scene.isometric_view() ############################################################ # run all the "test_foobar" functions in the mlab module. run_mlab_examples() ############################################################ # Test some specific corner-cases import numpy x, y, z = numpy.mgrid[1:10, 1:10, 1:10] u, v, w = numpy.mgrid[1:10, 1:10, 1:10] s = numpy.sqrt(u**2 + v**2) mlab.clf() # Test the extra argument "scalars" mlab.quiver3d(x, y, z, u, v, w, scalars=s) # Test surf with strange-shaped inputs X, Y = numpy.ogrid[-10:10, -10:10] Z = X**2 + Y**2 mlab.surf(X, Y, Z) mlab.surf(X.ravel(), Y.ravel(), Z) x, y, z = numpy.mgrid[-10:10, -10:10, -3:2] mlab.flow(x, y, z) # Test glyphs with number-only coordinnates mlab.points3d(0, 0, 0, resolution=50)
def test_probe_data(self): """ Test probe_data """ x, y, z = np.mgrid[0:1:10j, 0:1:10j, 0:1:10j] r = np.sqrt(x**2 + y**2 + z**2) iso = mlab.contour3d(x, y, z, r) x_, y_, z_ = np.random.random((3, 10, 4, 2)) r_ = mlab.pipeline.probe_data(iso, x_, y_, z_) np.testing.assert_array_almost_equal(r_, np.sqrt(x_**2 + y_**2 + z_**2), decimal=1) flow = mlab.flow(x, y, z, x, y, z) u_, v_, w_ = mlab.pipeline.probe_data(flow, x_, y_, z_, type='vectors') np.testing.assert_array_almost_equal(u_, x_, decimal=2) np.testing.assert_array_almost_equal(v_, y_, decimal=2) np.testing.assert_array_almost_equal(w_, z_, decimal=3)
def test_probe_data(self): """ Test probe_data """ x, y, z = np.mgrid[0:1:10j, 0:1:10j, 0:1:10j] r = np.sqrt(x**2 + y**2 + z**2) iso = mlab.contour3d(x, y, z, r) x_, y_, z_ = np.random.random((3, 10, 4, 2)) r_ = mlab.pipeline.probe_data(iso, x_, y_, z_) np.testing.assert_array_almost_equal( r_, np.sqrt(x_**2 + y_**2 + z_**2), decimal=1 ) flow = mlab.flow(x, y, z, x, y, z) u_, v_, w_ = mlab.pipeline.probe_data(flow, x_, y_, z_, type='vectors') np.testing.assert_array_almost_equal(u_, x_, decimal=2) np.testing.assert_array_almost_equal(v_, y_, decimal=2) np.testing.assert_array_almost_equal(w_, z_, decimal=3)
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()
# obj = quiver3d(X, Y, Z, Bx, By ,Bz) src = mlab.pipeline.vector_field(reshapeBX, reshapeBY, reshapeBZ) mlab.pipeline.vector_cut_plane(src, mask_points=2, scale_factor=3) if (plotType == 3): src = mlab.pipeline.vector_field(reshapeBX, reshapeBY, reshapeBZ) magnitude = mlab.pipeline.extract_vector_norm(src) mlab.pipeline.iso_surface(magnitude, contours=[1.9, 0.3]) if (plotType == 4): flow = mlab.flow(reshapeBX, reshapeBY, reshapeBZ, seedtype = 'plane', seed_scale=1.0, seed_resolution=20, seed_visible = False, integration_direction='both') if (plotType == 5): src = mlab.pipeline.vector_field(reshapeBX, reshapeBY, reshapeBZ) magnitude = mlab.pipeline.extract_vector_norm(src) iso = mlab.pipeline.iso_surface(magnitude, contours=[1.9, 0.3], opacity=0.3) vec = mlab.pipeline.vectors(magnitude, mask_points=60, line_width=1, color=(.8, .8, .8), scale_factor=3.) """
src = mlab.pipeline.vector_field(u, v, w) if _MODE_ == 'mask': mlab.pipeline.vectors(src, mask_points=10, scale_factor=2.0) elif _MODE_ == 'cut': mlab.pipeline.vector_cut_plane(src, mask_points=10, scale_factor=2.0) elif _MODE_ == 'iso': magnitude = mlab.pipeline.extract_vector_norm(src) mlab.pipeline.iso_surface(magnitude, contours=[2.0, 0.5]) mlab.outline() elif _MODE_ == 'flow': mlab.flow(u, v, w, seed_scale=1, seed_resolution=5, integration_direction='both') mlab.outline() elif _MODE_ == 'comp': pass else: mlab.quiver3d(u, v, w) mlab.outline() mlab.show()
unn = np.divide(u, un) vnn = np.divide(v, vn) wnn = np.divide(w, wn) nanpos = np.isnan(unn) unn[nanpos] = 0.0 nanpos = np.isnan(vnn) vnn[nanpos] = 0.0 nanpos = np.isnan(wnn) wnn[nanpos] = 0.0 ##### simple show of vectors #quiver3d( x, y, z, unn, vnn, wnn)# colormap='copper', opacity=0.3, mode='2darrow', scale_factor=1) #quiver3d( gx, gy, gz, ux, vy, wz, colormap='copper', opacity=0.3, mode='2darrow', scale_factor=1) ##### trial to show flow ff = flow(x, y, z, unn, vnn, wnn)#, color=(0, 1, 1), opacity=0.7 ) #quiver3d(px, py, pz, vx, vy, vz, color=(0, 1, 1), opacity=0.3, mode='2darrow', scale_factor=1) #quiver3d( gx, gy, gz, ux, vy, wz, colormap='copper', opacity=0.3, mode='2darrow', scale_factor=1) ##### Color coded tracks. #for row in range(len(frame)): #quiver3d( gx[row], gy[row], gz[row], ux[row], vy[row], wz[row], color=colorlist[row], opacity=1, mode='2darrow', scale_factor=1, line_width=4 ) ######vector field example maya.outline() #src = maya.pipeline.vector_field(x, y, z, unn, vnn, wnn) #maya.pipeline.vectors(src, scale_factor=3.0) ######################
def lorenz(x, y, z, s=10., r=28., b=8. / 3.): """The Lorenz system.""" u = s * (y - x) v = r * x - y - x * z w = x * y - b * z return u, v, w # Sample the space in an interesting region. x, y, z = numpy.mgrid[-50:50:100j, -50:50:100j, -10:60:70j] u, v, w = lorenz(x, y, z) fig = mlab.figure(size=(400, 300), bgcolor=(0, 0, 0)) # Plot the flow of trajectories with suitable parameters. f = mlab.flow(x, y, z, u, v, w, line_width=3, colormap='Paired') f.module_manager.scalar_lut_manager.reverse_lut = True f.stream_tracer.integration_direction = 'both' f.stream_tracer.maximum_propagation = 200 # Uncomment the following line if you want to hide the seed: #f.seed.widget.enabled = False # Extract the z-velocity from the vectors and plot the 0 level set # hence producing the z-nullcline. src = f.mlab_source.m_data e = mlab.pipeline.extract_vector_components(src) e.component = 'z-component' zc = mlab.pipeline.iso_surface(e, opacity=0.5, contours=[0, ], color=(0.6, 1, 0.2)) # When using transparency, hiding 'backface' triangles often gives better # results
mlab.imshow(vals) x,y,z = np.mgrid[-5:5:64j,-5:5:64j,-5:5:64j] mlab.contour3d(0.5*x**2 + y**2 + 2*z**2) mlab.volume_slice(x,y,z,0.5*x*x + y*y + 2*z*z) mlab.test_quiver3d() x,y,z = np.mgrid[-2:3:50j,-2:3:50j,-2:3:50j] r = np.sqrt(x**2 + y**2 + z**2) u = y*np.sin(r)/(r+0.001) v = -x*np.sin(r)/(r+0.001) w = np.ones_like(z)*0.1 mlab.flow(x,y,z,u,v,w,seedtype='plane') def lorenz(x,y,z,s=10,r=28,b=8/3): u = s*(y-x) v = r*x-y-x*z w = x*y-b*z return u,v,w x,y,z = np.mgrid[-50:50:20j,-50:50:20j,-10:60:20j] u,v,w = lorenz(x,y,z) mlab.quiver3d(x,y,z,u,v,w,scale_factor=0.01,mask_points=5) mlab.flow(x,y,z,u,v,w) from scipy.integrate import odeint def lorenz_ode(state,t): return np.array(lorenz(*state))
import scipy import matplotlib.pyplot as plt import numpy from os.path import join from mayavi import mlab from scipy.io import loadmat datadir = "core1 2 3-20190201T183913Z-001" subdir = "core1 2 3" rho1 = loadmat(join(join(datadir, subdir), 'rho1.mat')) bi = loadmat(join(join(datadir, subdir), 'bi1.mat')) bj = loadmat(join(join(datadir, subdir), 'bj1.mat')) bk = loadmat(join(join(datadir, subdir), 'bk1.mat')) mlab.contour3d(rho1['cl']) mlab.flow(bk['bk'], bj['bj'], bi['bi'])
data = [analyzer.data[key][timestep] for key in keys] if plot_type == 'vcp': mask_points = int(np.prod(data[0].shape) / 20**3) print('mask_points = %d' % mask_points) plotting.vector_cut_plane_wrap(data, mask_points=mask_points, scale_factor=5) if plot_type == 'flow': plot = mlab.flow( *data, seed_resolution=1, # seedtype = 'point', seedtype='point', integration_direction='both', linetype='line') plot.stream_tracer.maximum_number_of_steps = 40000 plot.stream_tracer.maximum_propagation = 4000 mlab.colorbar(orientation='vertical') mlab.outline() mlab.axes() mlab.orientation_axes() mlab.axes(nb_labels=4, line_width=4)
#rho0=1e-2 #img= np.array(frb['density'])[::-1]/rho0 #Bhoriz,Bvert= np.array(frb['KaysBx'])[::-1], np.array(frb['KaysBy'])[::-1] ##im= ax[i].imshow(np.log10(img),cmap=cmaps[args.cmap],\ ## vmin=np.log10(args.clim[0]),vmax=np.log10(args.clim[1])) ##ax[i].autoscale(False) ##quiver plot #X, Y = np.meshgrid(np.arange(0,Npx), np.arange(0,Npx)) #fout=open(os.path.join(os.path.dirname(args.data_hdf5),'xyBxBy.pickle'),'w') #pickle.dump((X,Y,Bhoriz,Bvert),fout) #fout.close() #sys.exit() fin=open(args.bpickle,'r') (x,y,Bx,By)= pickle.load(fin) fin.close() fig = mlab.figure(size=(500, 500), bgcolor=(0, 0, 0)) # # Plot the flow of trajectories with suitable parameters. Bz=np.zeros(Bx.shape)+1 f = mlab.flow(x,y,y,Bx,By,Bz, line_width=3, colormap='Paired') f.module_manager.scalar_lut_manager.reverse_lut = True f.stream_tracer.integration_direction = 'both' f.stream_tracer.maximum_propagation = 200 # Uncomment the following line if you want to hide the seed: #f.seed.widget.enabled = False # # A nice view of the plot. #mlab.view(140, 120, 113, [0.65, 1.5, 27]) mlab.show()
def lorenz(x, y, z, s=10., r=28., b=8. / 3.): """The Lorenz system.""" u = s * (y - x) v = r * x - y - x * z w = x * y - b * z return u, v, w # Sample the space in an interesting region. x, y, z = numpy.mgrid[-50:50:100j, -50:50:100j, -10:60:70j] u, v, w = lorenz(x, y, z) fig = mlab.figure(size=(400, 300), bgcolor=(0, 0, 0)) # Plot the flow of trajectories with suitable parameters. f = mlab.flow(x, y, z, u, v, w, line_width=3, colormap='Paired') f.module_manager.scalar_lut_manager.reverse_lut = True f.stream_tracer.integration_direction = 'both' f.stream_tracer.maximum_propagation = 200 # Uncomment the following line if you want to hide the seed: #f.seed.widget.enabled = False # Extract the z-velocity from the vectors and plot the 0 level set # hence producing the z-nullcline. src = f.mlab_source.m_data e = mlab.pipeline.extract_vector_components(src) e.component = 'z-component' zc = mlab.pipeline.iso_surface(e, opacity=0.5, contours=[ 0,
idx = 30 tristan_data.load_indices([idx]) print(tristan_data.data.bx[30].shape) sys.exit(0) # x, y, z = np.ogrid[-5:5:64j, -5:5:64j, -5:5:64j] # print( x ) # print( x.shape ) # print # scalars = x * x * 0.5 + y * y + z * z * 2.0 obj = mlab.volume_slice(tristan_data.data.bz[idx], plane_orientation='x_axes') mlab.show() bx, by, bz = [tristan_data.data[key][idx] for key in ['bx', 'by', 'bz']] mlab.quiver3d(bx, by, bz) mlab.show() mlab.flow(bx, by, bz) mlab.show()
def equations(x, y, z): xpoint = 10 * (y - x) ypoint = 28 * x - y - x * z zpoint = x * y - 2.667 * z return xpoint, ypoint, zpoint x, y, z = numpy.mgrid[-50:50:100j, -50:50:100j, -10:60:70j] xpoint, ypoint, zpoint = equations(x, y, z) fig = mlab.figure(size=(500, 500), bgcolor=(0, 0, 0)) fill = mlab.flow(x, y, z, xpoint, ypoint, zpoint, line_width=3, colormap='Paired') fill.module_manager.scalar_lut_manager.reverse_lut = True fill.stream_tracer.integration_direction = 'both' fill.stream_tracer.maximum_propagation = 200 src = fill.mlab_source.m_data ext = mlab.pipeline.extract_vector_components(src) ext.component = 'z-component' zc = mlab.pipeline.iso_surface(ext, opacity=0.5, contours=[ 0, ], color=(0.6, 1, 0.4))
fix_mayavi_bugs() p, r, b = (10.0, 28.0, 3.0) x, y, z = np.mgrid[-17:20:20j, -21:28:20j, 0:48:20j] u, v, w = p*(y-x), x*(r-z)-y, x*y-b*z mlab.figure(size=(600, 600)) mlab.quiver3d(x, y, z, u, v, w) mlab.figure(size=(600, 600)) vectors = mlab.quiver3d(x, y, z, u, v, w) vectors.glyph.mask_input_points = True vectors.glyph.mask_points.on_ratio = 20 vectors.glyph.glyph.scale_factor = 5.0 mlab.figure(size=(600, 600)) src = mlab.pipeline.vector_field(x, y, z, u, v, w) mlab.pipeline.vector_cut_plane(src, mask_points=2, scale_factor=5) magnitude = mlab.pipeline.extract_vector_norm(src) surface = mlab.pipeline.iso_surface(magnitude) surface.actor.property.opacity = 0.3 mlab.gcf().scene.background = (0.8, 0.8, 0.8) mlab.figure(size=(600, 600)) mlab.flow(x, y, z, u, v, w) mlab.show()
def func1(iter): c = Collection(gen_magnets(mag_pos)) if axis == 0: rot = [iter - 90, 0, 0] if axis == 1: rot = [0, iter - 90, 0] if axis == 2: rot = [0, 0, iter - 90] c.rotate(rot[0], (1, 0, 0), anchor=(0, 0, 0)) c.rotate(rot[1], (0, 1, 0), anchor=(0, 0, 0)) c.rotate(rot[2], (0, 0, 1), anchor=(0, 0, 0)) x_lower, x_upper = -30, 30 y_lower, y_upper = -30, 30 z_lower, z_upper = -30, 30 grid_spacing_value = 2 #0.25 xd = int((x_upper - x_lower) / grid_spacing_value) yd = int((y_upper - y_lower) / grid_spacing_value) zd = int((z_upper - z_lower) / grid_spacing_value) x, y, z = np.mgrid[x_lower:x_upper:xd * 1j, y_lower:y_upper:yd * 1j, z_lower:z_upper:zd * 1j] xs = np.linspace(x_lower, x_upper, xd) ys = np.linspace(y_lower, y_upper, yd) zs = np.linspace(z_lower, z_upper, zd) U = np.zeros((xd, yd, zd)) V = np.zeros((xd, yd, zd)) W = np.zeros((xd, yd, zd)) i = 0 if printouts: print("simulating magnetic data") for zi in zs: POS = np.array([(x, y, zi) for x in xs for y in ys]) Bs = c.getB(POS).reshape(len(xs), len(ys), 3) U[:, :, i] = Bs[:, :, 0] V[:, :, i] = Bs[:, :, 1] W[:, :, i] = Bs[:, :, 2] i = i + 1 if printouts: print("(%d/%d)" % (i, zd)) i = 0 if printouts: print("generating flow whole cube") fig = mlab.figure(bgcolor=(1, 1, 1), size=(1500, 1500), fgcolor=(0, 0, 0)) fig.scene.disable_render = True for xi in xs: st = mlab.flow(x, y, z, U, V, W, line_width=0.1, seedtype='plane', integration_direction='both', figure=fig, opacity=0.05) st.streamline_type = 'tube' st.seed.visible = False st.tube_filter.radius = 0.1 st.seed.widget.origin = np.array([xi, y_lower, z_upper]) st.seed.widget.point1 = np.array([xi, y_upper, z_upper]) st.seed.widget.point2 = np.array([xi, y_lower, z_lower]) st.seed.widget.resolution = 10 #int(xs.shape[0]) st.seed.widget.enabled = True st.seed.widget.handle_property.opacity = 0 st.seed.widget.plane_property.opacity = 0 if printouts: print("(%d/%d)" % (i, xd)) i = i + 1 fig.scene.disable_render = False mayavi.mlab.view(azimuth=-50, elevation=70) mlab.axes(extent=[x_lower, x_upper, y_lower, y_upper, z_lower, z_upper], figure=fig) if axis == 0: mlab.savefig(movie_path + '/x-axis/movie001/' + 'anim%05d.png' % (iter)) if axis == 1: mlab.savefig(movie_path + '/y-axis/movie001/' + 'anim%05d.png' % (iter)) if axis == 2: mlab.savefig(movie_path + '/z-axis/movie001/' + 'anim%05d.png' % (iter)) mlab.clf(fig) fig = mlab.figure(bgcolor=(1, 1, 1), size=(1500, 1500), fgcolor=(0, 0, 0)) fig.scene.disable_render = True if printouts: print("generating flow sensor plane") for zi in np.linspace(-1, 1, 10): st = mlab.flow(x, y, z, U, V, W, line_width=0.1, seedtype='plane', integration_direction='both', figure=fig, opacity=0.05) st.streamline_type = 'tube' st.seed.visible = False st.tube_filter.radius = 0.1 st.seed.widget.origin = np.array([x_lower, y_upper, zi]) st.seed.widget.point1 = np.array([x_upper, y_upper, zi]) st.seed.widget.point2 = np.array([x_lower, y_lower, zi]) st.seed.widget.resolution = 10 #int(xs.shape[0]) st.seed.widget.enabled = True st.seed.widget.handle_property.opacity = 0 st.seed.widget.plane_property.opacity = 0 if printouts: print("(%d/%d)" % (i, xd)) i = i + 1 fig.scene.disable_render = False mayavi.mlab.view(azimuth=-50, elevation=70) mlab.axes(extent=[x_lower, x_upper, y_lower, y_upper, z_lower, z_upper], figure=fig) if axis == 0: mlab.savefig(movie_path + '/x-axis/movie002/' + 'anim%05d.png' % (iter)) if axis == 1: mlab.savefig(movie_path + '/y-axis/movie002/' + 'anim%05d.png' % (iter)) if axis == 2: mlab.savefig(movie_path + '/z-axis/movie002/' + 'anim%05d.png' % (iter)) mlab.clf(fig)
def calculate_field_lines(sdfFile, n_lines, direction, integration_variable, starting_z=0): """Uses Mayavi to calculate streamlines. Returns Mayavi flow structure.""" bx = sdfFile.Magnetic_Field_bx_centred.data by = sdfFile.Magnetic_Field_by_centred.data bz = sdfFile.Magnetic_Field_bz_centred.data dx = (sdfFile.Grid_Grid.extents[3] - sdfFile.Grid_Grid.extents[0] ) / sdfFile.Magnetic_Field_bx_centred.dims[0] dy = (sdfFile.Grid_Grid.extents[4] - sdfFile.Grid_Grid.extents[1] ) / sdfFile.Magnetic_Field_bx_centred.dims[1] dz = (sdfFile.Grid_Grid.extents[5] - sdfFile.Grid_Grid.extents[2] ) / sdfFile.Magnetic_Field_bx_centred.dims[2] print("Plotting " + integration_variable) if integration_variable == "twist": integrand = field_twist(bx, by, bz, dx, dy, dz) elif integration_variable == "parallel_electric_field": integrand = parallel_electric_field(bx, by, bz, dx, dy, dz) elif integration_variable == "connectivity": integrand = None else: integrand = None print(integration_variable, "not found! Purely calculating field lines.") # field = mlab.pipeline.vector_field(bx, by, bz) # magnitude = mlab.pipeline.extract_vector_norm(field) if integrand is not None: flow = mlab.flow(bx, by, bz, scalars=integrand, seedtype='plane', seed_resolution=n_lines) else: flow = mlab.flow(bx, by, bz, seedtype='plane', seed_resolution=n_lines) flow.update_mode = 'non-interactive' flow.seed.update_mode = 'non-interactive' nx = sdfFile.Magnetic_Field_bx_centred.dims[0] nz = sdfFile.Magnetic_Field_bz_centred.dims[2] z_plane = float(starting_z) * nz # print("Resizing grid to ", nx) flow.seed.widget.normal = np.array([0.0, 0.0, 1.0]) flow.seed.widget.origin = np.array([0.0, 0.0, float(z_plane) + 2.0]) flow.seed.widget.point1 = np.array([float(nx), 0.0, float(z_plane) + 2.0]) flow.seed.widget.point2 = np.array([0.0, float(nx), float(z_plane) + 2.0]) flow.seed.widget.update_placement() flow.stream_tracer.maximum_propagation = 1000 flow.stream_tracer.integration_direction = direction flow.update_streamlines = 0 del bx, by, bz, integrand print("Calculated field lines") return flow
from FieldGeneration import calc_vec_field_fast from mayavi import mlab from pylab import array # We first define the main 3D points of the route # For closed loop trajectories: loop=True Pos0 = array([4, 8, 3]) Pos1 = array([14, 12, 17]) Pos2 = array([14, 4, 17]) Loop = True Pos = array([Pos0, Pos1, Pos2]) # We obtain a path from a set of discrete points using # Cubic splines X, Y, Z, Tt = path_3d(Pos, Loop) # Now we calculate the vector field using the provided functions vector_field_3D, Xc, Yc, Zc = calc_vec_field_fast(X, Y, Z, 20, 1) # We plot mlab.figure(size=(800, 600)) mlab.flow(Xc, Yc, Zc, vector_field_3D[0], vector_field_3D[1], vector_field_3D[2], linetype='tube', seedtype='plane') mlab.pipeline.vector_field(Xc, Yc, Zc, vector_field_3D[0], vector_field_3D[1], vector_field_3D[2], name='vector field') mlab.points3d(X, Y, Z, Tt) mlab.quiver3d(Xc, Yc, Zc, vector_field_3D[0], vector_field_3D[1], vector_field_3D[2]) mlab.show()
from pylab import * from mayavi import mlab if __name__ == '__main__': fig = mlab.figure(size = (3000, 3000), bgcolor = (1, 1, 1)) x, y, z = np.mgrid[0:5, 0:5, 0:5] r = np.sqrt(x ** 2 + y ** 2 + z ** 4) u = y * np.sin(r) / r v = -x * np.sin(r) / r w = np.zeros_like(z) mlab.flow(u, v, w, line_width = 3) mlab.savefig(sys.argv[1], size = (3000, 3000))
unn = np.divide(u, un) vnn = np.divide(v, vn) wnn = np.divide(w, wn) nanpos = np.isnan(unn) unn[nanpos] = 0.0 nanpos = np.isnan(vnn) vnn[nanpos] = 0.0 nanpos = np.isnan(wnn) wnn[nanpos] = 0.0 ##### simple show of vectors #quiver3d( x, y, z, unn, vnn, wnn)# colormap='copper', opacity=0.3, mode='2darrow', scale_factor=1) #quiver3d( gx, gy, gz, ux, vy, wz, colormap='copper', opacity=0.3, mode='2darrow', scale_factor=1) ##### trial to show flow ff = flow(x, y, z, unn, vnn, wnn) #, color=(0, 1, 1), opacity=0.7 ) #quiver3d(px, py, pz, vx, vy, vz, color=(0, 1, 1), opacity=0.3, mode='2darrow', scale_factor=1) #quiver3d( gx, gy, gz, ux, vy, wz, colormap='copper', opacity=0.3, mode='2darrow', scale_factor=1) ##### Color coded tracks. #for row in range(len(frame)): #quiver3d( gx[row], gy[row], gz[row], ux[row], vy[row], wz[row], color=colorlist[row], opacity=1, mode='2darrow', scale_factor=1, line_width=4 ) ######vector field example maya.outline() #src = maya.pipeline.vector_field(x, y, z, unn, vnn, wnn) #maya.pipeline.vectors(src, scale_factor=3.0) ######################
# obj = quiver3d(X, Y, Z, Bx, By ,Bz) src = mlab.pipeline.vector_field(reshapeBX, reshapeBY, reshapeBZ) mlab.pipeline.vector_cut_plane(src, mask_points=2, scale_factor=3) if (plotType == 3): src = mlab.pipeline.vector_field(reshapeBX, reshapeBY, reshapeBZ) magnitude = mlab.pipeline.extract_vector_norm(src) mlab.pipeline.iso_surface(magnitude, contours=[1.9, 0.3]) if (plotType == 4): flow = mlab.flow(reshapeBX, reshapeBY, reshapeBZ, seedtype='plane', seed_scale=1.0, seed_resolution=20, seed_visible=False, integration_direction='both') if (plotType == 5): src = mlab.pipeline.vector_field(reshapeBX, reshapeBY, reshapeBZ) magnitude = mlab.pipeline.extract_vector_norm(src) iso = mlab.pipeline.iso_surface(magnitude, contours=[1.9, 0.3], opacity=0.3) vec = mlab.pipeline.vectors(magnitude, mask_points=60,
W[:, :, i] = Bs[:, :, 2] i = i + 1 print("(%d/%d)" % (i, zd)) # print(Bs) i = 0 print("generating flow") fig.scene.disable_render = True for xi in xs: st = mlab.flow(x, y, z, U, V, W, line_width=0.1, seedtype='plane', integration_direction='both', figure=fig, opacity=0.05) st.streamline_type = 'tube' st.seed.visible = False st.tube_filter.radius = 0.1 st.seed.widget.origin = np.array([xi, y_lower, z_upper]) st.seed.widget.point1 = np.array([xi, y_upper, z_upper]) st.seed.widget.point2 = np.array([xi, y_lower, z_lower]) st.seed.widget.resolution = 10 #int(xs.shape[0]) st.seed.widget.enabled = True st.seed.widget.handle_property.opacity = 0 st.seed.widget.plane_property.opacity = 0
def field_in_lens(lens, vis_type=None): """ Main problem here: for an angle of a column ( say, 30 deg form X-axis), I cannot make the empty grid X, Y, Z rotate accordingly. It just doesnt do it properly. Need to work on this one. Main problem #2: it seems that the y and z axes are not symmetrical when visualizing. One is accurate, the other is off. """ if lens.R is None: return None # create grid of points begin = get_mag(lens.beginning) end = get_mag(lens.ending) if lens.lens_type == 'space': X, Y, Z = np.mgrid[begin:end:16j, -lens.R:lens.R:16j, -lens.R:lens.R:16j] else: X, Y, Z = np.mgrid[begin:end:4j, -lens.R:lens.R:4j, -lens.R:lens.R:4j] precision = 1e2 X = np.round(X * precision) / precision Y = np.round(Y * precision) / precision Z = np.round(Z * precision) / precision # X, Y, Z = rotate_mgrid(lens.n, X, Y, Z) # r = np.c_[X.ravel()*np.cos(np.pi/6.) - Y.ravel()*np.sin(np.pi/6.), # X.ravel()*np.sin(np.pi/6.) + Y.ravel()*np.cos(np.pi/6.), Z.ravel()] r = np.c_[X.ravel(), Y.ravel(), Z.ravel()] # for i in range(0, 4095): # r[i, :] = get_rotational_matrix(lens.n).dot(r[i, :]) X = r[:, 0].reshape(X.shape) Y = r[:, 1].reshape(Y.shape) B = lens.getB(r) Bx = B[:, 0] By = B[:, 1] Bz = B[:, 2] Bx.shape = X.shape By.shape = Y.shape Bz.shape = Z.shape B_norm = np.sqrt(Bx * Bx + By * By + Bz * Bz) # Visualization # We threshold the data ourselves, as the threshold filter produce a # data structure inefficient with IsoSurface # if scale is None: # B_max = 10 # else: # B_max = scale B_max = 4 * np.mean(B_norm) Bx[B_norm > B_max] = 0 By[B_norm > B_max] = 0 Bz[B_norm > B_max] = 0 B_norm[B_norm > B_max] = B_max if vis_type == None: vis_type = 0 if vis_type == 1: field = mlab.flow(X, Y, Z, Bx, By, Bz, scalars=B_norm, name='B field') if vis_type == 0: field = mlab.pipeline.vector_field(X, Y, Z, Bx, By, Bz, scalars=B_norm, name='B field') vectors = mlab.pipeline.vectors( field, scale_factor=(X[1, 0, 0] - X[0, 0, 0]), ) # Mask random points, to have a lighter visualization. if lens.lens_type == 'space': vectors.glyph.mask_input_points = True vectors.glyph.mask_points.on_ratio = 6 vcp = mlab.pipeline.vector_cut_plane( field, plane_orientation="x_axes", view_controls=True) vcp.glyph.glyph.scale_factor = 5 * (X[1, 0, 0] - X[0, 0, 0])
""" @Time : 2020/2/15 09:47 @Author : fate @Site : @File : Flow可视化.py @Software: PyCharm """ import numpy as np from mayavi import mlab x, y, z = np.mgrid[0:1:20j, 0:1:20j, 0:1:20j] u = np.sin(np.pi * x) * np.cos(np.pi * z) v = -2 * np.sin(np.pi * y) * np.cos(2 * np.pi * z) w = np.cos(np.pi * x) * np.sin(np.pi * z) + np.cos(np.pi * y) * np.sin( 2 * np.pi * z) flow = mlab.flow( u, v, w, seed_scale=1, seed_resolution=5, integration_direction='both' # 'forword' 'backword' 'both' ) mlab.outline() mlab.show()
if __name__ == "__main__": a = Matter((-8, 0, 0), +5, 0) b = Matter((8, 0, 0), +5, 0) field = Field(precision=1) field.add(a) field.update_potential() field.add(b) field.update_potential() x, y, z = field.space u, v, w = field.grad() # mlab.quiver3d(x, y, z, u, v, w, mode='2dhooked_arrow', scale_factor=1) # u, v, w = field.phi # mlab.flow(x, y, z, u, v, w, seedtype='plane', seed_resolution=8, seed_visible=False) mlab.flow(x, y, z, u, v, w, seedtype='sphere', seed_resolution=8, seed_visible=True) mlab.points3d(-8, 0, 0, scale_factor=1) mlab.points3d(8, 0, 0, scale_factor=1) mlab.outline() mlab.show()
fix_mayavi_bugs() p, r, b = (10.0, 28.0, 3.0) x, y, z = np.mgrid[-17:20:20j, -21:28:20j, 0:48:20j] u, v, w = p * (y - x), x * (r - z) - y, x * y - b * z mlab.figure(size=(600, 600)) mlab.quiver3d(x, y, z, u, v, w) mlab.figure(size=(600, 600)) vectors = mlab.quiver3d(x, y, z, u, v, w) vectors.glyph.mask_input_points = True vectors.glyph.mask_points.on_ratio = 20 vectors.glyph.glyph.scale_factor = 5.0 mlab.figure(size=(600, 600)) src = mlab.pipeline.vector_field(x, y, z, u, v, w) mlab.pipeline.vector_cut_plane(src, mask_points=2, scale_factor=5) magnitude = mlab.pipeline.extract_vector_norm(src) surface = mlab.pipeline.iso_surface(magnitude) surface.actor.property.opacity = 0.3 mlab.gcf().scene.background = (0.8, 0.8, 0.8) mlab.figure(size=(600, 600)) mlab.flow(x, y, z, u, v, w) mlab.show()