def J_video(J, n, saveFile = None): """Given current density J, plot quiver animation""" Jn = J[n] def update_quiver(num,Q): real_Jn = (Jn*np.e**(-1*1j*num/10.0)).real Q.set_UVC(real_Jn[:,:,0], real_Jn[:,:,1]) return Q, # py.quiver(Jn[:,:,0], Jn[:,:,1]) fig,ax = py.subplots(1,1) im2 = draw_circle() Q = ax.quiver(Jn[:,:,0], Jn[:,:,1],color='blue',scale=30000) anim = animation.FuncAnimation(fig, update_quiver, fargs=(Q,), interval=10, blit = False) if saveFile: ani.save(saveFile) py.title("Current Density") py.figure(2) x,y = np.meshgrid(np.arange(120), np.arange(120)) U = Jn[:,:,0].real V = Jn[:,:,1].real py.streamplot(x,y,U,V) draw_circle() py.show()
def main(): # For timing purposes start = time.time() pr = cProfile.Profile() pr.enable() # Ex 5.21 q1 = [0.05, 0.0] q2 = [-0.05, 0.0] a = -0.5 b = 0.5 num_squares = 100 x = np.linspace(a, b, num_squares) xcoor, ycoor = np.meshgrid(x, x) phi = np.zeros((num_squares, num_squares)) E = np.zeros((num_squares, num_squares)) for i in range(num_squares): for j in range(num_squares): r1 = np.sqrt((xcoor[i][j] - q1[0])**2 + (ycoor[i][j] - q1[1])**2) r2 = np.sqrt((xcoor[i][j] - q2[0])**2 + (ycoor[i][j] - q2[1])**2) phi[i][j] = (1 / 4 * np.pi * cons.epsilon_0) * (1 / r1 - 1 / r2) plt.imshow(phi) plt.title("electric potential of two particles") plt.colorbar() plt.show() Ex, Ey = np.gradient(phi) # Distance formula def R(x, y): return np.sqrt(x**2 + y**2) # Potential for every point q1x, q1y = xcoor - q1[0], ycoor - q1[1] q2x, q2y = xcoor - q2[0], ycoor - q2[1] # Electric field via partial derivative h = 1e-5 def V(q, x, y): return q * (1 / 4 * np.pi * cons.epsilon_0) * (1 / R(x, y)) vx1 = (V(1, (q1x + h / 2), q1y) - V(1, (q1x - h / 2), q1y)) / h vy1 = (V(1, q1x, (q1y + h / 2)) - V(1, q1x, (q1y - h / 2))) / h vx2 = (V(-1, (q2x + h / 2), q2y) - V(-1, (q2x - h / 2), q2y)) / h vy2 = (V(-1, q2x, (q2y + h / 2)) - V(-1, q2x, (q2y - h / 2))) / h Vx = vx1 + vx2 Vy = vy1 + vy2 streamplot(xcoor, ycoor, Vx, Vy, density=2.5, linewidth=0.5, arrowsize=0.8) plt.title("Electric Field of a Dipole") plt.show() pr.disable() # pr.print_stats(sort='time') end = time.time() print(f"Program took :{end - start} seconds to run")
def Bsf(self): if not hasattr(self, 'Br'): self.Bfeild() pl.streamplot(self.r, self.z, self.Br.T, self.Bz.T, color=self.Br.T, cmap=pl.cm.RdBu) pl.clim([-1.5, 1.5])
def plot_streamlines(xin,yin): x = np.linspace(xin[0], xin[-1], 64) y = np.linspace(yin[0], yin[-1], 64) X,Y = np.meshgrid(x,y) relX = (X - xin[0]) / (xin[-1] - xin[0]) relY = (Y - xin[0]) / (yin[-1] - yin[0]) A = 2*pi B = pi U = 1 - 4 * np.cos(B*relY) * np.sin(A*relX)**2 * np.sin(B*relY) V = 4 * np.cos(A*relX) * np.sin(B*relY)**2 * np.sin(A*relX) S = np.sqrt(U*U + V*V) pl.streamplot(X, Y, U, V, linewidth=np.sqrt(S), color="lightsteelblue", density=1.1, minlength=0.9, arrowstyle='-')
def plot_B_streamlines(mi, mq, mu, imax, imin): ''' Plotting B-field lines on top of Stokes I map ''' import pylab as plt import os if np.shape(np.shape(mi))[0] == 1: return print('********** NO PLOT: Maps must be 2D arrays ************' ), os.system('afplay /System/Library/Sounds/Sosumi.aiff') nx = np.shape(mi)[0] ny = np.shape(mi)[1] x = np.linspace(0, nx - 1, nx) y = np.linspace(0, ny - 1, ny) xp = x yp = y y2, x2 = np.meshgrid(xp, yp, indexing='ij') psi = -0.5 * np.arctan2(mu, mq) x3 = np.cos(psi) y3 = np.sin(psi) plt.figure(10) plt.contourf(mi, levels=np.arange(imin, imax, (imax - imin) / 500.), extent=[0, nx, 0, ny]) plt.colorbar() plt.streamplot(x2, y2, x3, y3, density=[3, 3], color='w', arrowstyle='-', linewidth=0.5) plt.show() return
import pylab, numpy as np import math xvalues, yvalues = pylab.meshgrid(np.arange(-4,4, 0.1), np.arange(-4,4,0.1)) vx = yvalues*np.cos(xvalues*yvalues) vy = xvalues*np.cos(xvalues*yvalues) pylab.streamplot(xvalues, yvalues, vx, vy) pylab.show()
np.set_printoptions(threshold='nan') magU = np.sqrt(U*U+V*V) cmap = py.cm.get_cmap('coolwarm') lmax = 3.2 # (int(magU.max()*10) + 1.)/10 lev = np.linspace(0, lmax, 11) CF = py.contourf(x, y, magU, cmap=cmap, levels=lev) # streamplot version (need matplotlib 1.2.1, use only evenly grid) from matplotlib.mlab import griddata interp = 'linear' # 'nn' N = 50 xi = np.linspace(0, 1, 2*N) yi = np.linspace(0, .5, 4*N) U = griddata(X0, Y0, U0, xi, yi, interp=interp) V = griddata(X0, Y0, V0, xi, yi, interp=interp) py.streamplot(xi, yi, U, V, color='k', density=0.89, minlength=.2, arrowstyle='->') py.text(-.07, .4, r'$u_{i1}$', fontsize=10) py.xlabel(r'$x$', labelpad=-3) py.ylabel(r'$z$', labelpad=-3, rotation=0) py.xlim(0,1) py.ylim(0,0.5) ax = py.axes() ax.set_aspect('equal') ax.set_yticks([0,0.5]) ax.set_xticks([0,1]) from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(py.axes()) cax = divider.append_axes("right", "5%", pad="5%") py.colorbar(CF, cax=cax)
density.T, 100, norm=colors.SymLogNorm(linthresh=density.max() / 20, vmin=density_min, vmax=density_max), cmap='bwr') # pl.colorbar() pl.title(r'Time = ' + "%.2f" % (time_array[start_index + file_number]) + " ps") pl.streamplot(x[:, 0], y[0, :], j_x_m, j_y_m, density=2, color='k', linewidth=2.5, arrowsize=3, transform=rot + base) pl.xlim([0, 5]) pl.ylim([-1.25, 0]) # print (j_x) #radius = 0.1666 #theta = np.arange(0., 2*np.pi, 0.01) #pl.plot(radius*np.cos(theta), radius*np.sin(theta), color = 'k', alpha = 0.3) #pl.xlim([q1[0], q1[-1]]) #pl.ylim([q2[0], q2[-1]])
def View2D(g, option=0): # plot and check the field fig = figure(num=2, figsize=(16, 6)) # fig.suptitle('Efit Analysis', fontsize=20) ax = subplot2grid((3, 3), (0, 0), colspan=1, rowspan=3) nlev = 100 minf = np.min(g.psi) maxf = np.max(g.psi) levels = np.arange( np.float(nlev)) * (maxf - minf) / np.float(nlev - 1) + minf ax.contour(g.r, g.z, g.psi, levels=levels) # ax.set_xlim([0,6]) ax.set_xlabel('R') ax.set_ylabel('Z') ax.yaxis.label.set_rotation('horizontal') ax.set_aspect('equal') # fig.suptitle('Efit Analysis', fontsize=20) # title('Efit Analysis', fontsize=20) text(0.5, 1.08, 'Efit Analysis', horizontalalignment='center', fontsize=20, transform=ax.transAxes) draw() if option == 0: show(block=False) plot(g.xlim, g.ylim, 'g-') draw() csb = contour(g.r, g.z, g.psi, levels=[g.sibdry]) clabel( csb, [g.sibdry], # label the level inline=1, fmt='%9.6f', fontsize=14) csb.collections[0].set_label('boundary') # pl1=plot(g.rbdry,g.zbdry,'b-',marker='x', label='$\psi=$'+ np.str(g.sibdry)) # legend(bbox_to_anchor=(0., 1.05, 1., .105), loc='upper left') draw() # fig.set_tight_layout(True) # show(block=False) # Function fpol and qpsi are given between simagx (psi on the axis) and sibdry ( # psi on limiter or separatrix). So the toroidal field (fpol/R) and the q profile are within these boundaries npsigrid = old_div( np.arange(np.size(g.pres)).astype(float), (np.size(g.pres) - 1)) fpsi = np.zeros((2, np.size(g.fpol)), np.float64) fpsi[0, :] = (g.simagx + npsigrid * (g.sibdry - g.simagx)) fpsi[1, :] = g.fpol boundary = np.array([g.xlim, g.ylim]) rz_grid = Bunch( nr=g.nx, nz=g.ny, # Number of grid points r=g.r[:, 0], z=g.z[0, :], # R and Z as 1D arrays simagx=g.simagx, sibdry=g.sibdry, # Range of psi psi=g.psi, # Poloidal flux in Weber/rad on grid points npsigrid=npsigrid, # Normalised psi grid for fpol, pres and qpsi fpol=g.fpol, # Poloidal current function on uniform flux grid pres=g.pres, # Plasma pressure in nt/m^2 on uniform flux grid qpsi=g.qpsi, # q values on uniform flux grid nlim=g.nlim, rlim=g.xlim, zlim=g.ylim) # Wall boundary critical = analyse_equil(g.psi, g.r[:, 0], g.z[0, :]) n_opoint = critical.n_opoint n_xpoint = critical.n_xpoint primary_opt = critical.primary_opt inner_sep = critical.inner_sep opt_ri = critical.opt_ri opt_zi = critical.opt_zi opt_f = critical.opt_f xpt_ri = critical.xpt_ri xpt_zi = critical.xpt_zi xpt_f = critical.xpt_f psi_inner = 0.6 psi_outer = 0.8, nrad = 68 npol = 64 rad_peaking = [0.0] pol_peaking = [0.0] parweight = 0.0 boundary = np.array([rz_grid.rlim, rz_grid.zlim]) # Psi normalisation factors faxis = critical.opt_f[critical.primary_opt] fnorm = critical.xpt_f[critical.inner_sep] - critical.opt_f[ critical.primary_opt] # From normalised psi, get range of f f_inner = faxis + np.min(psi_inner) * fnorm f_outer = faxis + np.max(psi_outer) * fnorm fvals = radial_grid(nrad, f_inner, f_outer, 1, 1, [xpt_f[inner_sep]], rad_peaking) ## Create a starting surface #sind = np.int(nrad / 2) #start_f = 0. #fvals[sind] # Find where we have rational surfaces # define an interpolation of psi(q) psiq = np.arange(np.float(g.qpsi.size)) * ( g.sibdry - g.simagx) / np.float(g.qpsi.size - 1) + g.simagx fpsiq = interpolate.interp1d(g.qpsi, psiq) # Find how many rational surfaces we have within the boundary and locate x,y position of curves nmax = g.qpsi.max().astype(int) nmin = g.qpsi.min().astype(int) nr = np.arange(nmin + 1, nmax + 1) psi = fpsiq(nr) cs = contour(g.r, g.z, g.psi, levels=psi) labels = ['$q=' + np.str(x) + '$\n' for x in range(nr[0], nr[-1] + 1)] for i in range(len(labels)): cs.collections[i].set_label(labels[i]) style = ['--', ':', '--', ':', '-.'] # gca().set_color_cycle(col) # proxy = [Rectangle((0,0),1,1, fc=col[:i+1]) # for pc in cs.collections] # # l2=legend(proxy, textstr[:i) # # gca().add_artist(l1) x = [] y = [] for i in range(psi.size): xx, yy = surface(cs, i, psi[i], opt_ri[primary_opt], opt_zi[primary_opt], style, option) x.append(xx) y.append(yy) #props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) #textstr = ['$q='+np.str(x)+'$\n' for x in range(psi.size)] # #ax.text(0.85, 1.15, ''.join(textstr), transform=ax.transAxes, fontsize=14, #verticalalignment='top', bbox=props) legend(bbox_to_anchor=(-.8, 1), loc='upper left', borderaxespad=0.) draw() #compute B - field Bp = np.gradient(g.psi) dr = old_div((np.max(g.r[:, 0]) - np.min(g.r[:, 0])), np.size(g.r[:, 0])) dz = old_div((np.max(g.z[0, :]) - np.min(g.z[0, :])), np.size(g.z[0, :])) dpsidr = Bp[0] dpsidz = Bp[1] Br = -dpsidz / dz / g.r Bz = dpsidr / dr / g.r Bprz = np.sqrt(Br * Br + Bz * Bz) # plot Bp field if option == 0: sm = query_yes_no("Overplot vector field") if sm == 1: lw = 50 * Bprz / Bprz.max() streamplot( g.r.T, g.z.T, Br.T, Bz.T, color=Bprz, linewidth=2, cmap=cm.bone) #density =[.5, 1], color='k')#, linewidth=lw) draw() # plot toroidal field ax = subplot2grid((3, 3), (0, 1), colspan=2, rowspan=1) ax.plot(psiq, fpsi[1, :]) #ax.set_xlim([0,6]) #ax.set_xlabel('$\psi$') ax.set_ylabel('$fpol$') ax.yaxis.label.set_size(20) #ax.xaxis.label.set_size(20) ax.set_xticks([]) ax.yaxis.label.set_rotation('horizontal') #ax.xaxis.labelpad = 10 ax.yaxis.labelpad = 20 #props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) #ax.text(0.85, 0.95, '$B_t$', transform=ax.transAxes, fontsize=14, # verticalalignment='top', bbox=props) # draw() # plot pressure ax = subplot2grid((3, 3), (1, 1), colspan=2, rowspan=1) ax.plot(psiq, g.pres) #ax.set_xlim([0,6]) #ax.set_xlabel('$\psi$') ax.set_ylabel('$P$') ax.yaxis.label.set_size(20) #ax.xaxis.label.set_size(20) ax.set_xticks([]) ax.yaxis.label.set_rotation('horizontal') #ax.xaxis.labelpad = 10 ax.yaxis.labelpad = 20 #props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) #ax.text(0.85, 0.95, '$B_t$', transform=ax.transAxes, fontsize=14, # verticalalignment='top', bbox=props) # draw() # plot qpsi ax = subplot2grid((3, 3), (2, 1), colspan=2, rowspan=1) ax.plot(psiq, g.qpsi) ax.set_xlabel('$\psi$') ax.set_ylabel('$q$') ax.yaxis.label.set_rotation('horizontal') ax.yaxis.label.set_size(20) ax.xaxis.label.set_size(20) ax.xaxis.labelpad = 10 ax.yaxis.labelpad = 20 tick_params(\ axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='on', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='on') draw() # Compute and draw Jpar # # MU = 4.e-7*np.pi # # jpar0 = - Bxy * fprime / MU - Rxy*Btxy * dpdpsi / Bxy # # fig.set_tight_layout(True) fig.subplots_adjust(left=0.2, top=0.9, hspace=0.1, wspace=0.5) draw() if option == 0: show(block=False) if option != 0: return Br, Bz, x, y, psi
print("spsolve() time = %1.6s" % (time.time() - start_time)) #============================================================================== #============================================================================== # Calculating the gradient of the solution vx = -(Dx_2d * u.ravel()).reshape(Ny, Nx) vy = -(Dy_2d * u.ravel()).reshape(Ny, Nx) v = np.sqrt(vx**2 + vy**2) #============================================================================== #////////////////////////////////////////////////////////////////////////////// #////////////////////////////////////////////////////////////////////////////// #////////////////////////////////////////////////////////////////////////////// #============================================================================== # Plot solution py.figure(figsize=(12, 7)) my_contourf(x, y, u, r'$u\,(x,y)$') # Plotting the gradient py.figure(figsize=(12, 7)) my_contourf(x, y, v, r'$|-\nabla u\,(x,y)|$', 'afmhot') py.streamplot(x, y, vx, vy, color='w', density=1.2, linewidth=0.4) # thin_factor = 10 # skip = (slice(None, None, thin_factor), slice(None, None, thin_factor)) # py.quiver(X[skip],Y[skip],vx[skip]/v[skip],vy[skip]/v[skip],color = 'w') #==============================================================================
delta_n = density - np.mean(density) pl.contourf(q1, q2, delta_n, 200, norm=colors.SymLogNorm(linthresh=delta_n.max() / 20), cmap='bwr', transform=rot + base) pl.streamplot(q1, q2, vel_drift_x, vel_drift_y, density=1.4 * l, color='black', linewidth=1, arrowsize=1.5, transform=rot + base) pl.yticks([0, 5.]) pl.xticks([]) pl.xlim([q1[0], q1[-1]]) pl.ylim([q2[0], q2[-1]]) pl.gca().set_aspect('equal') #pl.contourf(q1_meshgrid, q2_meshgrid, density.T, 100, cmap='bwr') #pl.title(r'Time = ' + "%.2f"%(time_array[file_number]) + " ps")
pl.contourf(x, y, density.T, 100, norm=MidpointNormalize(midpoint=0, vmin=density_min, vmax=density_max), cmap='bwr') pl.colorbar() pl.title(r'Time = ' + "%.2f" % (time_array[start_index + file_number]) + " ps") pl.streamplot(x[:, 0], y[0, :], j_x, j_y, density=2, color='k', linewidth=0.7, arrowsize=1) # print (j_x) pl.xlim([q1[0], q1[-1]]) pl.ylim([q2[0], q2[-1]]) pl.gca().set_aspect('equal') pl.xlabel(r'$x\;(\mu \mathrm{m})$') pl.ylabel(r'$y\;(\mu \mathrm{m})$') #pl.suptitle('$\\tau_\mathrm{mc} = \infty$, $\\tau_\mathrm{mr} = \infty$') pl.savefig('images/dump_' + '%06d' % (start_index + file_number) + '.png') pl.clf()
def velocity_image(sim, width="10 kpc", vector_color='black', edgecolor='black', vector_resolution=40, scale=None, mode='quiver', key_x=0.3, key_y=0.9, key_color='white', key_length="100 km s**-1", density=1.0, **kwargs): """ Make an SPH image of the given simulation with velocity vectors overlaid on top. For a description of additional keyword arguments see :func:`~pynbody.plot.sph.image`, or see the `tutorial <http://pynbody.github.io/pynbody/tutorials/pictures.html#velocity-vectors>`_. **Keyword arguments:** *vector_color* (black): The color for the velocity vectors *edgecolor* (black): edge color used for the lines - using a color other than black for the *vector_color* and a black *edgecolor* can result in poor readability in pdfs *vector_resolution* (40): How many vectors in each dimension (default is 40x40) *scale* (None): The length of a vector that would result in a displayed length of the figure width/height. *mode* ('quiver'): make a 'quiver' or 'stream' plot *key_x* (0.3): Display x (width) position for the vector key (quiver mode only) *key_y* (0.9): Display y (height) position for the vector key (quiver mode only) *key_color* (white): Color for the vector key (quiver mode only) *key_length* (100 km/s): Velocity to use for the vector key (quiver mode only) *density* (1.0): Density of stream lines (stream mode only) """ subplot = kwargs.get('subplot', False) if subplot: p = subplot else: import matplotlib.pylab as p vx = image(sim, qty='vx', width=width, log=False, resolution=vector_resolution, noplot=True) vy = image(sim, qty='vy', width=width, log=False, resolution=vector_resolution, noplot=True) key_unit = _units.Unit(key_length) if isinstance(width, str) or issubclass(width.__class__, _units.UnitBase): if isinstance(width, str): width = _units.Unit(width) width = width.in_units(sim['pos'].units, **sim.conversion_context()) width = float(width) X, Y = np.meshgrid( np.arange(-width / 2, width / 2, width / vector_resolution), np.arange(-width / 2, width / 2, width / vector_resolution)) im = image(sim, width=width, **kwargs) if mode == 'quiver': if scale is None: Q = p.quiver(X, Y, vx, vy, color=vector_color, edgecolor=edgecolor) else: Q = p.quiver(X, Y, vx, vy, scale=_units.Unit(scale).in_units(sim['vel'].units), color=vector_color, edgecolor=edgecolor) p.quiverkey(Q, key_x, key_y, key_unit.in_units(sim['vel'].units, **sim.conversion_context()), r"$\mathbf{" + key_unit.latex() + "}$", labelcolor=key_color, color=key_color, fontproperties={'size': 16}) elif mode == 'stream': Q = p.streamplot(X, Y, vx, vy, color=vector_color, density=density) return im
import pylab as p # Make an x,z grid grid = np.linspace(-6,6,200) x, z = np.meshgrid(grid,grid) mu=4*np.pi # dipole strength (in z-direction) # and the 2D cross section of the potential (scalar field) phi = mu * z / (4 * np.pi * (x**2+z**2)**(3/2)) # End initialization # Start contour plot from matplotlib import colors p.figure(figsize=(6,6)) heights = np.linspace(-0.6,0.6,7) CS = p.contour(x,z,phi,heights,colors='k') p.clabel(CS, inline=1, fontsize=10,fmt='%3.1f') p.xlabel(r'$x$') p.ylabel(r'$z$') # End contour plot # Start fieldline plot Fx = mu / (4 * np.pi * (x**2+z**2)**(5/2)) * 2*x*z Fz = mu / (4 * np.pi * (x**2+z**2)**(5/2)) * (z**2-x**2) p.streamplot(x,z,Fx,Fz) # End fieldline plot CS = p.contour(x,z,phi,heights,colors='k') p.clabel(CS, inline=1, fontsize=10,fmt='%3.1f') p.savefig('dipole_fieldplot.png') #p.show()
# contor grid res = 0.4 xlim, zlim = ([-10,10], [-5,10]) dx, dz = (xlim[1]-xlim[0], zlim[1]-zlim[0]) nx, nz = (int(dx/res), int(dz/res)) x = np.linspace(xlim[0], xlim[1], nx) z = np.linspace(zlim[0], zlim[1], nz) xm, zm = np.meshgrid(x, z) feild = np.zeros((nz,nx)) Bx = np.zeros((nz,nx)) Bz = np.zeros((nz,nx)) for i in range(nz): for j in range(nx): B = Bcoil(coil, [xm[i,j],zm[i,j]]) Bx[i,j] = B[0] Bz[i,j] = B[2] #feild[i,j] = B[2]#sum(B*B)**0.5 feild[i,j] = sum(B*B)**0.5 pl.figure(figsize=(12,12)) V = np.linspace(0,2,30) #pl.contour(xm, zm, feild,V) pl.plot(xm,zm,'k.') pl.quiver(xm, zm, Bx, Bz) pl.streamplot(xm, zm, Bx, Bz) pl.axis('equal') pl.xlim(xlim) pl.ylim(zlim)
CS = py.contour(xi, yi, Fi, levels=levels, colors='k', linewidths=linewidth) clabels = py.clabel(CS, levels, inline=True, use_clabeltext=True, fmt='%g', manual=labelpos, fontsize=fontsize) [ txt.set_backgroundcolor('white') for txt in clabels ] [ txt.set_bbox(dict(facecolor='white', edgecolor='none', pad=0)) for txt in clabels ] ### Add a streamplot for the vector field # NB: py.streamplot relies on evenly grid if len(F.shape) > 1: py.streamplot(xi, yi, Ui, Vi, density=0.89, minlength=.2, arrowstyle='->', color='k', linewidth=1) py.text(-.05, .4, r'$\displaystyle %s$' % args.latex) py.xlabel(r'$x$', labelpad=-5) py.ylabel(r'$y$', labelpad=-5, rotation=0) py.xlim(xmin, xmax) py.ylim(ymin, ymax) ax = py.axes() ax.set_aspect('equal') ax.set_yticks([xmin, xmax]) ax.set_xticks([ymin, ymax]) py.tick_params(axis='both', direction='out') py.savefig(args.pdffile, bbox_inches='tight', transparent=True)
import numpy as np import pylab as pl """ A = np.array([[-1, 2], [2, -2]]) eig = np.linalg.eig(A)[0] eigV = np.linalg.eig(A)[1] x, y = np.meshgrid(np.arange(0, 3, 0.1), np.arange(0, 3, 0.1)) xv = -x + 2*y yv = 2*x - 2*y pl.streamplot(x, y, xv, yv) pl.plot([0,0.7882], [0, 0.6154], 'r') ####################### # LATER ON IN LECTURE # ####################### from sympy import symbols, Matrix a, b, c, d, x, y = symbols('a b c d x y') # a, b, c, d > 0 dx = a*x - b*x*y dy = -c*y + d*x*y J = Matrix( [[dx.diff(x), dx.diff(y)], # column 1 [dy.diff(x), dy.diff(y)]]) # column 2
density = density - density_bg density_min = np.min(density) density_max = np.max(density) #plot_grid(x[::5, ::5], y[::5, ::5], alpha=0.5) #pl.contourf(x, y, density.T, 100, cmap='bwr') #pl.contourf(x, y, density.T, 100, norm=MidpointNormalize(midpoint=0, vmin=density_min, vmax=density_max), cmap='bwr') #pl.contourf(x, y, density.T, 1000, norm=colors.DivergingNorm(vcenter=0, vmin=density_min, vmax=density_max), cmap='bwr') #pl.colorbar() #pl.title(r'Time = ' + "%.2f"%(time_array[start_index+file_number]) + " ps") pl.streamplot(x[:, 0], y[0, :], vel_drift_x, vel_drift_y, density=4., color='k', linewidth=1.5, arrowsize=1.2) #pl.xlim([q1[0], q1[-1]]) #pl.ylim([q2[0], q2[-1]]) pl.xlim([0.5, 1.5]) pl.ylim([q2[0], 0.625]) pl.gca().spines['right'].set_visible(False) pl.gca().spines['top'].set_visible(False) pl.gca().spines['bottom'].set_visible(False) pl.gca().spines['left'].set_visible(False)
M = X.max() X = np.reshape(X,(N,N)) * L/M Y = np.reshape(Y,(N,N)) * L/M x,y = X[0,:], Y[:,0] U = np.reshape(U/rho,(N,N)) / k V = np.reshape(V/rho,(N,N)) / k return U,V,x,y data = py.loadtxt(sys.argv[2]).T U,V,x,y = load_data() magU = np.sqrt(U*U+V*V) cmap = py.cm.get_cmap('coolwarm') CF = py.contourf(x, y, magU, cmap=cmap) py.colorbar(CF, use_gridspec=True) # streamplot version (need matplotlib 1.2.1, use only evenly grid) py.streamplot(x, y, U, V, color='k', density=.8, minlength=.4) py.text(-.06, .37, r'$\displaystyle\frac{u_i}k$', fontsize=11) py.xlabel(r'$x$', labelpad=-5) py.ylabel(r'$z$', labelpad=-5, rotation=0) py.xlim(0,0.5) py.ylim(0,0.5) ax = py.axes() ax.set_aspect('equal') ax.set_yticks([0,0.5]) ax.set_xticks([0,0.5]) py.tick_params(axis='both', direction='out') py.savefig(sys.argv[3], bbox_inches='tight')
def velocity_image(sim, width="10 kpc", vector_color='black', edgecolor='black', quiverkey_bg_color=None, vector_resolution=40, scale=None, mode='quiver', key_x=0.3, key_y=0.9, key_color='white', key_length="100 km s**-1", quiverkey=True, density=1.0, vector_qty='vel', **kwargs): """ Make an SPH image of the given simulation with velocity vectors overlaid on top. For a description of additional keyword arguments see :func:`~pynbody.plot.sph.image`, or see the `tutorial <http://pynbody.github.io/pynbody/tutorials/pictures.html#velocity-vectors>`_. **Keyword arguments:** *vector_color* (black): The color for the velocity vectors *edgecolor* (black): edge color used for the lines - using a color other than black for the *vector_color* and a black *edgecolor* can result in poor readability in pdfs *vector_resolution* (40): How many vectors in each dimension (default is 40x40) *quiverkey_bg_color* (none): The color for the legend (scale) background *scale* (None): The length of a vector that would result in a displayed length of the figure width/height. *mode* ('quiver'): make a 'quiver' or 'stream' plot *key_x* (0.3): Display x (width) position for the vector key (quiver mode only) *key_y* (0.9): Display y (height) position for the vector key (quiver mode only) *key_color* (white): Color for the vector key (quiver mode only) *key_length* (100 km/s): Velocity to use for the vector key (quiver mode only) *density* (1.0): Density of stream lines (stream mode only) *quiverkey* (True): Whether or not to inset the key *vector_qty* ('vel'): The name of the vector field to plot """ subplot = kwargs.get('subplot', False) av_z = kwargs.get('av_z', None) if subplot: p = subplot else: import matplotlib.pylab as p vx_name, vy_name, _ = sim._array_name_ND_to_1D(vector_qty) vx = image(sim, qty=vx_name, width=width, log=False, resolution=vector_resolution, noplot=True, av_z=av_z) vy = image(sim, qty=vy_name, width=width, log=False, resolution=vector_resolution, noplot=True, av_z=av_z) key_unit = _units.Unit(key_length) if isinstance(width, str) or issubclass(width.__class__, _units.UnitBase): if isinstance(width, str): width = _units.Unit(width) width = width.in_units(sim['pos'].units, **sim.conversion_context()) width = float(width) pixel_size = width / vector_resolution X, Y = np.meshgrid( np.arange(-width / 2 + pixel_size / 2, width / 2 + pixel_size / 2, pixel_size), np.arange(-width / 2 + pixel_size / 2, width / 2 + pixel_size / 2, pixel_size)) im = image(sim, width=width, **kwargs) if mode == 'quiver': if scale is None: Q = p.quiver(X, Y, vx, vy, color=vector_color, edgecolor=edgecolor) else: Q = p.quiver(X, Y, vx, vy, scale=_units.Unit(scale).in_units(sim['vel'].units), color=vector_color, edgecolor=edgecolor) if quiverkey: qk = p.quiverkey(Q, key_x, key_y, key_unit.in_units(sim['vel'].units, **sim.conversion_context()), r"$\mathbf{" + key_unit.latex() + "}$", labelcolor=key_color, color=key_color, fontproperties={'size': 24}) if quiverkey_bg_color is not None: qk.text.set_backgroundcolor(quiverkey_bg_color) elif mode == 'stream': Q = p.streamplot(X, Y, vx, vy, color=vector_color, density=density) # RS - if a axis object is passed in, use the right limit call if subplot: p.set_xlim(-width / 2, width / 2) p.set_ylim(-width / 2, width / 2) else: p.xlim(-width / 2, width / 2) p.ylim(-width / 2, width / 2) return im
r = np.linspace(rlim[0], rlim[1], nr) z = np.linspace(zlim[0], zlim[1], nz) rm, zm = np.meshgrid(r, z) Br = np.zeros((nz, nr)) Bz = np.zeros((nz, nr)) Bmag = np.zeros((nz, nr)) for i in range(nz): for j in range(nr): B = Bcoil(mu_o, coil, [rm[i, j], zm[i, j]]) Br[i, j] = B[0] Bz[i, j] = B[1] Bmag[i, j] = sum(B * B)**0.5 V = np.linspace(0, 10, 30) pl.streamplot(rm, zm, Br, Bz, density=[2 * nr / 25, 2 * nz / 25]) pl.contour(rm, zm, Bmag, levels=[5 * np.min(Bmag)]) pl.axis('equal') pl.xlim(rlim) pl.ylim(zlim) if I > 0: plasma_dir = 'pos' elif I == 0: plasma_dir = 'off' else: plasma_dir = 'neg' #pl.savefig(fig_path+config+'_flux_conv_'+plasma_dir+'.png', dpi=300) fig = pl.figure(figsize=(9, 12)) ax = fig.add_subplot(111)
mu = lagrange_multipliers[:, :, 0] mu_ee = lagrange_multipliers[:, :, 1] T_ee = lagrange_multipliers[:, :, 2] vel_drift_x = lagrange_multipliers[:, :, 3] vel_drift_y = lagrange_multipliers[:, :, 4] print(vel_drift_x.shape) print(density.shape) pl.contourf(q1_meshgrid, q2_meshgrid, density.T, 100, cmap='bwr') pl.title(r'Time = ' + "%.2f" % (time_array[file_number]) + " ps") pl.streamplot(q1, q2, vel_drift_x, vel_drift_y, density=2, color='k', linewidth=0.7, arrowsize=1) pl.xlim([q1[0], q1[-1]]) pl.ylim([q2[0], q2[-1]]) pl.gca().set_aspect('equal') pl.xlabel(r'$x\;(\mu \mathrm{m})$') pl.ylabel(r'$y\;(\mu \mathrm{m})$') pl.suptitle('$\\tau_\mathrm{mc} = 0.2$ ps, $\\tau_\mathrm{mr} = 1.0$ ps') pl.savefig('images/dump_' + '%06d' % file_number + '.png') pl.clf()
ax = fig.gca() if value == 'Density': data = rawData[:,:,0,t] if value == 'Velocity': Vx = rawData[:,:,2,t]/rawData[:,:,0,t] # x velocity Vy = rawData[:,:,1,t]/rawData[:,:,0,t] # y velocity (seem reversed cause of poor definitions in earlier code data = np.sqrt(Vx*Vx+Vy*Vy) #total speed # print data X, Y = np.linspace(-0.5,0.5,Nx), np.linspace(0,5,Ny) ## CHANGE THIS MANUALLY FOR DIFFERENT SYSTEMS so far if value =='Density': plt.imshow(data, origin = 'lower',cmap = colormap) if value == 'Velocity': plt.streamplot(X, Y, Vx, Vy ,color='k', linewidth=2) plt.tick_params(labelsize=tickSize) plt.title(title, fontsize = titleSize) if value == 'Density': plt.xlabel('X Cell Number', fontsize = labelSize) plt.ylabel('Y Cell Number', fontsize = labelSize) plt.xlim([3,Nx-2]) plt.ylim([3,Ny-2]) m = cm.ScalarMappable(cmap= colormap) m.set_array(data) plt.colorbar(m) if value == 'Velocity': plt.xlabel('X Position', fontsize = labelSize) plt.ylabel('Y Position', fontsize = labelSize) plt.xlim([min(X),max(X)]) plt.ylim([min(Y),max(Y)])
def velocity_image(sim, width="10 kpc", vector_color='black', edgecolor='black', quiverkey_bg_color=None, vector_resolution=40, scale=None, mode='quiver', key_x=0.3, key_y=0.9, key_color='white', key_length="100 km s**-1", quiverkey=True, density=1.0, **kwargs): """ Make an SPH image of the given simulation with velocity vectors overlaid on top. For a description of additional keyword arguments see :func:`~pynbody.plot.sph.image`, or see the `tutorial <http://pynbody.github.io/pynbody/tutorials/pictures.html#velocity-vectors>`_. **Keyword arguments:** *vector_color* (black): The color for the velocity vectors *edgecolor* (black): edge color used for the lines - using a color other than black for the *vector_color* and a black *edgecolor* can result in poor readability in pdfs *vector_resolution* (40): How many vectors in each dimension (default is 40x40) *quiverkey_bg_color* (none): The color for the legend (scale) background *scale* (None): The length of a vector that would result in a displayed length of the figure width/height. *mode* ('quiver'): make a 'quiver' or 'stream' plot *key_x* (0.3): Display x (width) position for the vector key (quiver mode only) *key_y* (0.9): Display y (height) position for the vector key (quiver mode only) *key_color* (white): Color for the vector key (quiver mode only) *key_length* (100 km/s): Velocity to use for the vector key (quiver mode only) *density* (1.0): Density of stream lines (stream mode only) *quiverkey* (True): Whether or not to inset the key """ subplot = kwargs.get('subplot', False) av_z = kwargs.get('av_z',None) if subplot: p = subplot else: import matplotlib.pylab as p vx = image(sim, qty='vx', width=width, log=False, resolution=vector_resolution, noplot=True,av_z=av_z) vy = image(sim, qty='vy', width=width, log=False, resolution=vector_resolution, noplot=True,av_z=av_z) key_unit = _units.Unit(key_length) if isinstance(width, str) or issubclass(width.__class__, _units.UnitBase): if isinstance(width, str): width = _units.Unit(width) width = width.in_units(sim['pos'].units, **sim.conversion_context()) width = float(width) X, Y = np.meshgrid(np.arange(-width / 2, width / 2, width / vector_resolution), np.arange(-width / 2, width / 2, width / vector_resolution)) im = image(sim, width=width, **kwargs) if mode == 'quiver': if scale is None: Q = p.quiver(X, Y, vx, vy, color=vector_color, edgecolor=edgecolor) else: Q = p.quiver(X, Y, vx, vy, scale=_units.Unit(scale).in_units( sim['vel'].units), color=vector_color, edgecolor=edgecolor) if quiverkey: qk = p.quiverkey(Q, key_x, key_y, key_unit.in_units(sim['vel'].units, **sim.conversion_context()), r"$\mathbf{" + key_unit.latex() + "}$", labelcolor=key_color, color=key_color, fontproperties={'size': 24}) if quiverkey_bg_color is not None: qk.text.set_backgroundcolor(quiverkey_bg_color) elif mode == 'stream' : Q = p.streamplot(X, Y, vx, vy, color=vector_color, density=density) return im
def View2D(g, option=0): # plot and check the field fig = figure(num=2, figsize=(16, 6)) # fig.suptitle('Efit Analysis', fontsize=20) ax = subplot2grid((3, 3), (0, 0), colspan=1, rowspan=3) nlev = 100 minf = np.min(g.psi) maxf = np.max(g.psi) levels = np.arange(np.float(nlev)) * (maxf - minf) / np.float(nlev - 1) + minf ax.contour(g.r, g.z, g.psi, levels=levels) # ax.set_xlim([0,6]) ax.set_xlabel("R") ax.set_ylabel("Z") ax.yaxis.label.set_rotation("horizontal") ax.set_aspect("equal") # fig.suptitle('Efit Analysis', fontsize=20) # title('Efit Analysis', fontsize=20) text(0.5, 1.08, "Efit Analysis", horizontalalignment="center", fontsize=20, transform=ax.transAxes) draw() if option == 0: show(block=False) plot(g.xlim, g.ylim, "g-") draw() csb = contour(g.r, g.z, g.psi, levels=[g.sibdry]) clabel(csb, [g.sibdry], inline=1, fmt="%9.6f", fontsize=14) # label the level csb.collections[0].set_label("boundary") # pl1=plot(g.rbdry,g.zbdry,'b-',marker='x', label='$\psi=$'+ np.str(g.sibdry)) # legend(bbox_to_anchor=(0., 1.05, 1., .105), loc='upper left') draw() # fig.set_tight_layout(True) # show(block=False) # Function fpol and qpsi are given between simagx (psi on the axis) and sibdry ( # psi on limiter or separatrix). So the toroidal field (fpol/R) and the q profile are within these boundaries npsigrid = old_div(np.arange(np.size(g.pres)).astype(float), (np.size(g.pres) - 1)) fpsi = np.zeros((2, np.size(g.fpol)), np.float64) fpsi[0, :] = g.simagx + npsigrid * (g.sibdry - g.simagx) fpsi[1, :] = g.fpol boundary = np.array([g.xlim, g.ylim]) rz_grid = Bunch( nr=g.nx, nz=g.ny, # Number of grid points r=g.r[:, 0], z=g.z[0, :], # R and Z as 1D arrays simagx=g.simagx, sibdry=g.sibdry, # Range of psi psi=g.psi, # Poloidal flux in Weber/rad on grid points npsigrid=npsigrid, # Normalised psi grid for fpol, pres and qpsi fpol=g.fpol, # Poloidal current function on uniform flux grid pres=g.pres, # Plasma pressure in nt/m^2 on uniform flux grid qpsi=g.qpsi, # q values on uniform flux grid nlim=g.nlim, rlim=g.xlim, zlim=g.ylim, ) # Wall boundary critical = analyse_equil(g.psi, g.r[:, 0], g.z[0, :]) n_opoint = critical.n_opoint n_xpoint = critical.n_xpoint primary_opt = critical.primary_opt inner_sep = critical.inner_sep opt_ri = critical.opt_ri opt_zi = critical.opt_zi opt_f = critical.opt_f xpt_ri = critical.xpt_ri xpt_zi = critical.xpt_zi xpt_f = critical.xpt_f psi_inner = 0.6 psi_outer = (0.8,) nrad = 68 npol = 64 rad_peaking = [0.0] pol_peaking = [0.0] parweight = 0.0 boundary = np.array([rz_grid.rlim, rz_grid.zlim]) # Psi normalisation factors faxis = critical.opt_f[critical.primary_opt] fnorm = critical.xpt_f[critical.inner_sep] - critical.opt_f[critical.primary_opt] # From normalised psi, get range of f f_inner = faxis + np.min(psi_inner) * fnorm f_outer = faxis + np.max(psi_outer) * fnorm fvals = radial_grid(nrad, f_inner, f_outer, 1, 1, [xpt_f[inner_sep]], rad_peaking) ## Create a starting surface # sind = np.int(nrad / 2) # start_f = 0. #fvals[sind] # Find where we have rational surfaces # define an interpolation of psi(q) psiq = np.arange(np.float(g.qpsi.size)) * (g.sibdry - g.simagx) / np.float(g.qpsi.size - 1) + g.simagx fpsiq = interpolate.interp1d(g.qpsi, psiq) # Find how many rational surfaces we have within the boundary and locate x,y position of curves nmax = g.qpsi.max().astype(int) nmin = g.qpsi.min().astype(int) nr = np.arange(nmin + 1, nmax + 1) psi = fpsiq(nr) cs = contour(g.r, g.z, g.psi, levels=psi) labels = ["$q=" + np.str(x) + "$\n" for x in range(nr[0], nr[-1] + 1)] for i in range(len(labels)): cs.collections[i].set_label(labels[i]) style = ["--", ":", "--", ":", "-."] # gca().set_color_cycle(col) # proxy = [Rectangle((0,0),1,1, fc=col[:i+1]) # for pc in cs.collections] # # l2=legend(proxy, textstr[:i) # # gca().add_artist(l1) x = [] y = [] for i in range(psi.size): xx, yy = surface(cs, i, psi[i], opt_ri[primary_opt], opt_zi[primary_opt], style, option) x.append(xx) y.append(yy) # props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) # textstr = ['$q='+np.str(x)+'$\n' for x in range(psi.size)] # # ax.text(0.85, 1.15, ''.join(textstr), transform=ax.transAxes, fontsize=14, # verticalalignment='top', bbox=props) legend(bbox_to_anchor=(-0.8, 1), loc="upper left", borderaxespad=0.0) draw() # compute B - field Bp = np.gradient(g.psi) dr = old_div((np.max(g.r[:, 0]) - np.min(g.r[:, 0])), np.size(g.r[:, 0])) dz = old_div((np.max(g.z[0, :]) - np.min(g.z[0, :])), np.size(g.z[0, :])) dpsidr = Bp[0] dpsidz = Bp[1] Br = -dpsidz / dz / g.r Bz = dpsidr / dr / g.r Bprz = np.sqrt(Br * Br + Bz * Bz) # plot Bp field if option == 0: sm = query_yes_no("Overplot vector field") if sm == 1: lw = 50 * Bprz / Bprz.max() streamplot( g.r.T, g.z.T, Br.T, Bz.T, color=Bprz, linewidth=2, cmap=cm.bone ) # density =[.5, 1], color='k')#, linewidth=lw) draw() # plot toroidal field ax = subplot2grid((3, 3), (0, 1), colspan=2, rowspan=1) ax.plot(psiq, fpsi[1, :]) # ax.set_xlim([0,6]) # ax.set_xlabel('$\psi$') ax.set_ylabel("$fpol$") ax.yaxis.label.set_size(20) # ax.xaxis.label.set_size(20) ax.set_xticks([]) ax.yaxis.label.set_rotation("horizontal") # ax.xaxis.labelpad = 10 ax.yaxis.labelpad = 20 # props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) # ax.text(0.85, 0.95, '$B_t$', transform=ax.transAxes, fontsize=14, # verticalalignment='top', bbox=props) # draw() # plot pressure ax = subplot2grid((3, 3), (1, 1), colspan=2, rowspan=1) ax.plot(psiq, g.pres) # ax.set_xlim([0,6]) # ax.set_xlabel('$\psi$') ax.set_ylabel("$P$") ax.yaxis.label.set_size(20) # ax.xaxis.label.set_size(20) ax.set_xticks([]) ax.yaxis.label.set_rotation("horizontal") # ax.xaxis.labelpad = 10 ax.yaxis.labelpad = 20 # props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) # ax.text(0.85, 0.95, '$B_t$', transform=ax.transAxes, fontsize=14, # verticalalignment='top', bbox=props) # draw() # plot qpsi ax = subplot2grid((3, 3), (2, 1), colspan=2, rowspan=1) ax.plot(psiq, g.qpsi) ax.set_xlabel("$\psi$") ax.set_ylabel("$q$") ax.yaxis.label.set_rotation("horizontal") ax.yaxis.label.set_size(20) ax.xaxis.label.set_size(20) ax.xaxis.labelpad = 10 ax.yaxis.labelpad = 20 tick_params( axis="x", # changes apply to the x-axis which="both", # both major and minor ticks are affected bottom="on", # ticks along the bottom edge are off top="off", # ticks along the top edge are off labelbottom="on", ) draw() # Compute and draw Jpar # # MU = 4.e-7*np.pi # # jpar0 = - Bxy * fprime / MU - Rxy*Btxy * dpdpsi / Bxy # # fig.set_tight_layout(True) fig.subplots_adjust(left=0.2, top=0.9, hspace=0.1, wspace=0.5) draw() if option == 0: show(block=False) if option != 0: return Br, Bz, x, y, psi
density_min = np.min(density) density_max = np.max(density) ground_indices = y[0, :] < 0.25 # Ground the right contact #density = density - np.mean(density[ground_indices, -1]) #plot_grid(x[::5, ::5], y[::5, ::5], alpha=0.5) #pl.contourf(x, y, density.T, 100, cmap='bwr') pl.contourf(x, y, density.T, 100, norm=MidpointNormalize(midpoint=0, vmin=density_min, vmax=density_max), cmap='bwr') pl.title(r'Time = ' + "%.2f"%(time_array[start_index+file_number]) + " ps") #pl.colorbar() pl.streamplot(x[:, 0], y[0, :], vel_drift_x, vel_drift_y, density=2., color='k', linewidth=0.7, arrowsize=1 ) #pl.axvline(1.5, color = 'k', ls = '--') #pl.axvline(3.5, color = 'k', ls = '--') pl.axvspan(4.8, 4.9, color = 'k', alpha = 0.3) #pl.axvspan(3.45, 3.55, color = 'k', alpha = 0.5) pl.xlim([0, 2]) pl.ylim([0, 1.5]) pl.gca().set_aspect('equal') pl.xlabel(r'$x\;(\mu \mathrm{m})$') pl.ylabel(r'$y\;(\mu \mathrm{m})$') # pl.suptitle('$\\tau_\mathrm{mc} = \infty$, $\\tau_\mathrm{mr} = \infty$')
plot.coil_loc() pl.plot(r,z,'b-x') pl.axis('equal') # contor grid res = 0.4 xlim, zlim = ([3,14], [-11,5]) dx, dz = (xlim[1]-xlim[0], zlim[1]-zlim[0]) nx, nz = (int(dx/res), int(dz/res)) x = np.linspace(xlim[0], xlim[1], nx) z = np.linspace(zlim[0], zlim[1], nz) xm, zm = np.meshgrid(x, z) feild = np.zeros((nz,nx)) Bx = np.zeros((nz,nx)) Bz = np.zeros((nz,nx)) for i in range(nz): for j in range(nx): B = Bcoil(mu_o, coil, [xm[i,j],0,zm[i,j]]) Bx[i,j] = B[0] Bz[i,j] = B[2] feild[i,j] = sum(B*B)**0.5 V = np.linspace(0,10,30) pl.streamplot(xm, zm, Bx, Bz, density = [2*nx/25,2*nz/25]) pl.axis('equal') pl.xlim(xlim) pl.ylim(zlim)