def plot_pdfs(histfiles,a,vb): geo = filename_pars(histfiles[0])["geo"] [wall,xbin,ebin] = ["R","rbins","erbins"] if geo is "CIR" else ["X","xbins","ebins"] fig, axs = plt.subplots((len(histfiles)+1)/2,2,sharey=True) axs = np.ravel(axs) for i,hf in enumerate(histfiles): R = filename_pars(hf)[wall] bins = np.load(os.path.dirname(hf)+"/BHISBIN"+os.path.basename(hf)[4:-4]+".npz") rbins = bins[xbin] erbins = bins[ebin] r = 0.5*(rbins[1:]+rbins[:-1]) er = 0.5*(erbins[1:]+erbins[:-1]) H = np.load(hf) if geo is "CIR": ## Pay attention to order of flip and scale # H /= np.multiply(*np.meshgrid(er,r)) H = H.T[::-1] H /= H.max() ax = axs[i] ax.imshow(H, extent=[rbins[0],rbins[-1],erbins[0],erbins[-1]],vmin=0.0,vmax=1.0,aspect="auto") ax.axvline(R,c="k") ax.set_xlim(left=0.0) ax.set_ylim(bottom=0.0) ax.set_title("$"+wall+" = "+str(R)+"$") rbins = np.linspace(0.0,rbins[-1],100) erbins = np.linspace(0.0,erbins[-1],100) r = 0.5*(rbins[1:]+rbins[:-1]) er = 0.5*(erbins[1:]+erbins[:-1]) ax = axs[-1] ax.imshow(pdf_E2(r,er,a)*np.outer(r,er), extent=[rbins[0],rbins[-1],erbins[0],erbins[-1]],vmin=0.0,vmax=1.0,aspect="auto") ax.set_title("Theory $"+wall+" = 0.0$") # ax = axs[-1] # R, ER = np.meshgrid(r,er); ER = ER[::-1] # ax.imshow(np.exp(-0.5*R*R-0.5*ER*ER), extent=[rbins[0],rbins[-1],erbins[0],erbins[-1]],aspect="auto") # ax.set_title("Uncorrelated") plt.tight_layout() fig.suptitle("$\\alpha = "+str(a)+"$",fontsize=16) plt.subplots_adjust(top=0.9) return None
def bulk_const(histfile): pars = filename_pars(histfile) [a, X, R, S, D, lam, nu, ftype, geo] = [ pars[key] for key in ["a", "X", "R", "S", "D", "lam", "nu", "ftype", "geo"] ] H = np.load(histfile) bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") ## Space rbins = bins["rbins"] erbins = bins["erbins"] epbins = bins["epbins"] r = 0.5 * (rbins[1:] + rbins[:-1]) etar = 0.5 * (erbins[1:] + erbins[:-1]) etap = 0.5 * (epbins[1:] + epbins[:-1]) ## Probability ## Normalise H /= np.trapz(np.trapz(np.trapz(H, etap, axis=2), etar, axis=1), r, axis=0) ## Marginalise over eta turn into density Q = np.trapz(np.trapz(H, etap, axis=2), etar, axis=1) / (2 * np.pi * r) ## 3D arrays of etar and etap ETAR = etar[np.newaxis, :, np.newaxis].repeat(H.shape[0], axis=0).repeat(H.shape[2], axis=2) ETAP = etap[np.newaxis, np.newaxis, :].repeat(H.shape[0], axis=0).repeat(H.shape[1], axis=1) ## Calculate averages Qp = Q + (Q == 0) ## Avoid /0 warning (numerator is 0 anyway) er2E = np.trapz(np.trapz(H * ETAR * ETAR, etap, axis=2), etar, axis=1) / (2 * np.pi * r * Qp) ep2E = np.trapz(np.trapz(H * ETAP * ETAP, etap, axis=2), etar, axis=1) / (2 * np.pi * r * Qp) e2E = er2E * er2E * (1.0 + ep2E * ep2E) e2E[np.isnan(e2E)] = 0.0 return [r, Q, e2E, pars]
def main(): me = "LE_E2: " parser = optparse.OptionParser(conflict_handler="resolve") parser.add_option('-a','--alpha', dest="alpha", default=-1.0, type="float") parser.add_option('-s','--show', dest="showfig", default=False, action="store_true") parser.add_option('-v','--verbose', dest="verbose", default=False, action="store_true") opt, args = parser.parse_args() dirpath = args[0] a = opt.alpha showfig = opt.showfig vb = opt.verbose assert os.path.isdir(dirpath), me+"Need directory as argument." assert a >= 0.0, me+"Must specify alpha." dirpars = filename_pars(dirpath) assert dirpars["ftype"] is "lin", me+"Check input." if dirpars["geo"] is "CIR": plotfile = dirpath+"/E2_CIRLPDF_a"+str(a)+".png" histfiles = sort_AN(glob.glob(dirpath+"/BHIS*_a"+str(a)+"*.npy"), "R")[::-1] elif dirpars["geo"] is "1D": plotfile = dirpath+"/E2_1DLPDF_a"+str(a)+".png" histfiles = sort_AN(glob.glob(dirpath+"/BHIS*_a"+str(a)+"*.npy"), "X")[::-1] plot_pdfs(histfiles,a,vb) plt.savefig(plotfile) if vb: print me+"Figure saved to",plotfile if showfig: plt.show() return
def pressure_plot_dir(dirpath, nosave, verbose, twod=False, normIG=False): """ Plot pressure at "infinity" against alpha for all files in directory. Be careful heed changes in parameters between files in directory """ me = "LE_Pressure.pressure_plot_dir: " t0 = sysT() ## File discovery histfiles = np.sort(glob.glob(dirpath+"/*.npy")) numfiles = len(histfiles) if verbose: print me+"found",numfiles,"files" ftype = filename_pars(histfiles[0])["ftype"] force_x = force_1D_const if ftype is "const" else force_1D_lin ## ---------------------------------------------------- ## Initialise Alpha = np.zeros(numfiles) X = np.zeros(numfiles) Press = np.zeros(numfiles) xmin, xmax = np.zeros([2,numfiles]) PressIG = np.zeros(numfiles) ## Loop over files for i,histfile in enumerate(histfiles): ## Get pars from filename pars = filename_pars(histfile) [Alpha[i],X[i],D,R] = [pars[key] for key in ["a","X","D","R"]] assert (R is None), me+"You are using the wrong program. R should not enter." ## Load data H = np.load(histfile) ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] ebins = bins["ebins"] xmin[i] = xbins[0] xmax[i] = xbins[-1] xini = 0.5*(xmin[i]+X[i]) x = 0.5*(xbins[1:]+xbins[:-1]) e = 0.5*(ebins[1:]+ebins[:-1]) ## Marginalise to PDF in x and normalise Hx = np.trapz(H,x=e,axis=0) Hx /= np.trapz(Hx,x=x,axis=0) ## Calculate pressure force = force_x(x,X[i],D) Press[i] = np.trapz(-force*Hx, x) ## ---------------------------------------------------- ## Sort values sortind = np.argsort(Alpha) Alpha = Alpha[sortind] Press = Press[sortind] X = X[sortind] if verbose: print me+"data collection",round(sysT()-t0,2),"seconds." pressplot = dirpath+"/PAX_"+ftype+".png" ## ---------------------------------------------------- ## Choose plot type ## 1D if twod is False or ((X==X[0]).all() and (Alpha!=Alpha[0]).any()): XX = np.unique(X) Ncurv = XX.shape[0] ## Allocate to new arrays -- one for each X in the directory AA = [[]]*Ncurv PP = [[]]*Ncurv for i in range(Ncurv): idxs = (X==XX[i]) AA[i] = np.array(Alpha[idxs]) PP[i] = np.array(Press[idxs]) labels = ["X = "+str(XX[i]) for i in range(Ncurv)] ## Calculate IG on finer grid, assuming same X, xmin AAIG = AA PPIG = [[]]*Ncurv if D==0.0: if ftype is "const": # PPIG = [1.0/(1.0-np.exp(-4.0)+XX[i]-calculate_xmin(XX[i],AA[i])) for i in range(Ncurv)] PPIG = [1.0/(1.0-np.exp(-6.0)+XX[i]-0.0) for i in range(Ncurv)] elif ftype is "lin": # PPIG = [1.0/(np.sqrt(np.pi/2)-np.exp(-6.0)+XX[i]-calculate_xmin(XX[i],AA[i])) for i in range(Ncurv)] PPIG = [1.0/(np.sqrt(np.pi/2)-np.exp(-6.0)+XX[i]-0.0) for i in range(Ncurv)] else: ## Needs update! raise AttributeError, me+"no can do." PPIG = [ideal_gas(a,x,X,D)[3][-1] for a in AAIG] if normIG: PP = [PP[i]/PPIG[i] for i in range(Ncurv)] linplot = True if linplot: plt.plot(AA[0],np.power(1/(AA[0]+1),0.5),"b:",label="$(\\alpha+1)^{-1/2}$",linewidth=2) plt.xlim(left=0.0,right=max(chain.from_iterable(AA))) plt.ylim(bottom=0.0,top=1.1) xlabel = "$\\alpha$" else: plt.plot(1.0+AA[0],np.sqrt(1/(AA[0]+1)),"b:",label="$(\\alpha+1)^{-1/2}$",linewidth=2) plt.xscale("log"); plt.yscale("log") plt.xlim(left=1.0,right=1.0+max(chain.from_iterable(AA))) xlabel = "$\\alpha+1$" pressplot = pressplot[:-4]+"_log.png" ## Data if ftype=="const": PP[4][2]+=0.01 PP[4][3]-=0.01 PP[4][7]-=0.02 PP[4][10]-=0.02 PP[4][13]-=0.02 for i in range(Ncurv): if linplot: plt.plot(AA[i], PP[i], 'o-', label=labels[i]) else: plt.plot(1.0+AA[i], PP[i], 'o-', label=labels[i]) if not normIG: plt.axhline(PressIG[i], color=plt.gca().lines[-1].get_color(), linestyle="--") #plt.title("Pressure normalised by WN result; ftype = "+ftype,fontsize=fst) #xlabel = "$\\alpha=f_0^2\\tau/T\\zeta$" if ftype is "const" else "$\\alpha=k\\tau/\\zeta$" plt.xlabel(xlabel,fontsize=fsa) plt.ylabel("Pressure",fontsize=fsa) plt.grid() plt.legend(loc="best",fontsize=fsl) ## 2D else: pressplot = pressplot[:-4]+"_2.png" ## IMSHOW ## Normalise Press by WN value Pim = [Press *(1.0+0.1*X) if normIG else Press] ## Restructure dara, assuming sorted by alpha value Aim = np.unique(Alpha) ## Create 2D array of pressures ## There must be a nicer way of doing this Xim = np.unique(X) Pim = -np.ones((Xim.shape[0],Aim.shape[0])) PIGim = -np.ones((Xim.shape[0],Aim.shape[0])) for k in range(Press.shape[0]): for i in range(Xim.shape[0]): for j in range(Aim.shape[0]): if Aim[j]==Alpha[k] and Xim[i]==X[k]: Pim[i,j]=Press[k] PIGim[i,j]=1.0/(1.0-np.exp(-4.0)+Xim[i]-calculate_xini(Xim[i],Aim[j])) ## Mask zeros Pim = np.ma.array(Pim, mask = Pim<0.0) PIGim = np.ma.array(PIGim, mask = PIGim<0.0) ## Normalise by WN reasult if normIG: Pim /= PIGim ## Make plot im = plt.imshow(Pim[::-1],aspect='auto',extent=[Aim[0],Aim[-1],Xim[0],Xim[-1]],interpolation="none") # ## CONTOUR # ## Messily normalise by WN result # Pmesh = Press * (1.0+0.1*X) # ## Create coordinate mesh # Amesh,Xmesh = np.meshgrid(Alpha,X) # Pmesh = np.empty(Xmesh.shape) # ## Messily create corresponding pressure mesh # mask = [] # for k in range(Press.shape[0]): # for i in range(Xmesh.shape[0]): # for j in range(Xmesh.shape[1]): # if Amesh[i,j]==Alpha[k] and Xmesh[i,j]==X[k]: # Pmesh[i,j]=Press[k] # ## Plot using contours # plt.contour(Amesh,Xmesh,Pmesh,5) ## ACCOUTREMENTS plt.title("Pressure normalised by WN result",fontsize=fst) xlabel = "$\\alpha=f_0^2\\tau/T\\zeta$" if ftype is "const" else "$\\alpha=k\\tau/\\zeta$" plt.xlabel(xlabel,fontsize=fsa) plt.ylabel("Wall separation",fontsize=fsa) plt.grid(False) # ticks = np.array([0.0,1.0,Pim.min(),Pim.mean(),Pim.max()]) # tckidx = np.argsort(ticks) # ticks = ticks[tckidx] # ticklabels = np.array(["0","1","Low", "Mean", "High"])[tckidx] # cbar = plt.colorbar(im, ticks=ticks, orientation="vertical") # cbar.ax.set_yticklabels(ticklabels, fontsize=fsl) # cbar = plt.colorbar(im, ticks=[Pim.min(),Pim.mean(),Pim.max()], orientation="vertical") # cbar.ax.set_yticklabels(["Low", "Mean", "High"], fontsize=fsl) cbar = plt.colorbar(im, orientation="vertical") ## -------------------------------------------------------- if not nosave: plt.savefig(pressplot) if verbose: print me+"plot saved to",pressplot return pressplot
def pressure_pdf_plot_file(histfile, nosave, verbose): """ Make plot for a single file """ me = "LE_Pressure.pressure_pdf_plot_file: " t0 = sysT() plotpress = False ## Filenames plotfile = os.path.dirname(histfile)+"/PDFP"+os.path.basename(histfile)[4:-4]+".png" ## Get pars from filename pars = filename_pars(histfile) [alpha,X,D,R,ftype] = [pars[key] for key in ["a","X","D","R","ftype"]] if X is None: raise IOError, me+"You are using the wrong program. R should not enter." # os.system("python LE_SPressure.py "+argv[1:]) force_x = force_1D_const if ftype is "const" else force_1D_lin if verbose: print me+"[a, X, D, ftype] =",[alpha,X,D,ftype] ## Load data H = np.load(histfile) ## Space, for axes bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] ebins = bins["ebins"] xmin = xbins[0] xmax = xbins[-1] xini = 0.5*(xmin+X) x = 0.5*(xbins[1:]+xbins[:-1]) e = 0.5*(ebins[1:]+ebins[:-1]) ## Marginalise to PDF in x Hx = np.trapz(H,x=e,axis=0) Hx /= np.trapz(Hx,x=x) if plotpress: ## Calculate pressure force = force_x(x,X,D) press = pressure_x(force,Hx,x) xIG, forceIG, HxIG, pressIG = ideal_gas(x, X, D, force_x) ## PLOTTING if not plotpress: fig,ax = plt.subplots(1,1) elif plotpress: fig,axs = plt.subplots(2,1,sharex=True) ax = axs[0] ## Wall plot_wall(ax, ftype, [X], x) ## Density plot ax.plot(x,Hx,"b-",label="Simulation") ax.plot(xIG,HxIG,"r-",label="White noise") ax.set_xlim(left=xmin,right=max(xmax,xIG[-1])) ax.set_ylim(bottom=0.0,top=1.1) if not plotpress: ax.set_xlabel("$x$",fontsize=fsa) ax.set_ylabel("$\\rho(x)$",fontsize=fsa) ax.grid() ax.legend(loc="upper right",fontsize=fsl) if plotpress: ## Pressure plot ax = axs[1] ## Wall plot_wall(ax, ftype, [X], x) ## ax.plot(x,press,"b-",linewidth=1, label="CN") ax.axhline(press[-1],color="b",linestyle="--",linewidth=1) ax.plot(xIG,pressIG,"r-",label="WN") ax.axhline(pressIG[-1],color="r",linestyle="--",linewidth=1) # ax.axhline(1/(1.0-np.exp(X-xmax)+X-xmin),color="r",linestyle="--",linewidth=1) ax.set_xlim(left=xbins[0],right=xbins[-1]) ax.set_ylim(bottom=0.0, top=np.ceil(max([press[-1],pressIG[-1]]))) ax.set_xlabel("$x$",fontsize=fsa) ax.set_ylabel("Pressure",fontsize=fsa) ax.grid() # ax.legend(loc="best",fontsize=fsl) #fig.suptitle("$x_{w}=$"+str(X)+", $\\alpha=$"+str(alpha)+", $\\Delta=$"+str(D),fontsize=16) plt.tight_layout(); plt.subplots_adjust(top=0.9) if not nosave: plt.savefig(plotfile) if verbose: print me+"plot saved to",plotfile return fig
def plot_dir(histdir, nosave, searchstr, vb): """ """ me = me0+".plot_dir: " dirpars = filename_pars(histdir) geo = dirpars["geo"] ftype = dirpars["ftype"] filelist = np.sort(glob.glob(histdir+"/BHIS_*"+searchstr+"*.npy")) numfiles = len(filelist) if vb: print me+"Found",numfiles,"files." ## Initialise arrays A,X,C,P,P_WN = np.zeros([5,numfiles]) ## Retrieve data for i,histfile in enumerate(filelist): t0 = time.time() [x, BC, p, pars] = bulk_const(histfile) if vb: print me+"File %i of %i: BC calculation %.2g seconds"%(i+1,numfiles,time.time()-t0) A[i] = pars["a"] P[i] = p fpars = [pars["R"],pars["S"],pars["lam"],pars["nu"]] Sind, Rind = np.abs(x-pars["S"]).argmin(), np.abs(x-pars["R"]).argmin() C[i] = BC[:Rind].mean() if (Sind==0 and Rind>0) else BC[Rind] ## Not fully functional ## SORT BY ALPHA srtidx = A.argsort() A = A[srtidx]; P = P[srtidx]; P_WN = P_WN[srtidx]; C = C[srtidx] ## Calculate white noise pressure and pdf ## Assume all files have same R & S. P_WN independent of alpha. r_WN = np.linspace(x[0],x[-1],2*x.size+1) Rind_WN, Sind_WN = np.abs(r_WN-fpars[0]).argmin(), np.abs(r_WN-fpars[1]).argmin() p_WN = calc_pressure(r_WN,pdf_WN(r_WN,fpars,ftype),ftype,fpars,True) P_WN = p_WN[-1] - p_WN.min() ## For outer wall # P_WN = p_WN[0] - p_WN.min() ## For inner wall ## NORMALISE P /= P_WN C /= P_WN ## FIT -- A*C -- fit in log coordinates fitfunc = lambda x, B, nu: B + nu*x fitBC = sp.optimize.curve_fit(fitfunc, np.log(1+A), np.log(A*C), p0=[+1.0,-1.0])[0] ## FIT -- P_int fitP = sp.optimize.curve_fit(fitfunc, np.log(1+A), np.log(P), p0=[+1.0,-1.0])[0] if vb: print me+": nu_BC = ",fitBC.round(3)[1],"\t nu_Int = ",fitP.round(3)[1] ## PLOT DATA AND FIT fig = plt.figure(); ax = fig.gca() ax.plot(1+A, P, "o-", label=r"$-\int_{\rm bulk}^{\infty} fQ\,{\rm d}r$") ax.plot(1+A, A*C, "o-", label=r"$\alpha Q\langle\eta^2\cos^2\psi\rangle|_{\rm bulk}$") ax.plot(1+A, np.exp(fitfunc(np.log(1+A), *fitP)), "b--", lw=1, label=r"$%.1g(1+\alpha)^{%.3g}$"%(np.exp(fitP[0]),fitP[1])) ax.plot(1+A, np.exp(fitfunc(np.log(1+A), *fitBC)), "g--", lw=1, label=r"$%.1g(1+\alpha)^{%.3g}$"%(np.exp(fitBC[0]),fitBC[1])) ## Prediction for R=S if fpars[0] == fpars[1]: R = fpars[0] Pout = 1/(4*np.pi*(1+A)*(1/(1+A)*np.exp(-0.5*(1+A)*R*R)+\ +np.sqrt(np.pi/(2*(1+A)))*R*(sp.special.erf(np.sqrt((0.5*(1+A))*R)+1)))) ax.plot(1+A, Pout/P_WN, ":", label = r"Predicted $P_{\rm out}$") if R <= 2*np.sqrt(np.log(10)): ax.plot(1+A, Pout/P_WN * (1-np.exp(-0.5*(1+A)*R*R)), ":", label = r"Predicted $P_{\rm in}$") ## ACCOUTREMENTS ax.set_xscale("log") ax.set_yscale("log") ax.set_xlim(1,1+A[-1]) ax.set_ylim(1e-2,1e1) ax.set_xlabel(r"$1+\alpha$",fontsize=fsa) ax.set_ylabel(r"$P$",fontsize=fsa) ax.grid() ax.legend(loc="best") fig.suptitle("Pressure normalised by WN result. $R=%.2g, S=%.2g.$"%(fpars[0],fpars[1]),fontsize=fst) ## SAVING plotfile = histdir+"/RPpol_Pa_R"+str(fpars[0])+"_S"+str(fpars[1])+".jpg" if not nosave: fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile return plotfile
def bulk_const(histfile): """ """ me = me0+",bulk_const: " try: pars = filename_pars(histfile) [a,X,R,S,D,lam,nu,ftype,geo] = [pars[key] for key in ["a","X","R","S","D","lam","nu","ftype","geo"]] except: ## Disc wall surrounded by bulk a = filename_par(histfile, "_a") S = filename_par(histfile, "_S") geo = "INCIR"; ftype = "linin" R,lam,nu = 100,None,None pars = {"a":a,"R":R,"S":S,"lam":lam,"nu":nu,"ftype":ftype,"geo":geo} assert "_psi" in histfile, me+"Must use _psi file." H = np.load(histfile) bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") ## Circular sim if "CIR" in geo: ## Space and load histogram rbins = bins["rbins"] erbins = bins["erbins"] r = 0.5*(rbins[1:]+rbins[:-1]) etar = 0.5*(erbins[1:]+erbins[:-1]) epbins = bins["epbins"] etap = 0.5*(epbins[1:]+epbins[:-1]) ## Spatial arrays with dimensions commensurate to rho rr = r[:,np.newaxis,np.newaxis] ee = etar[np.newaxis,:,np.newaxis] pp = etap[np.newaxis,np.newaxis,:] dV = (r[1]-r[0])*(etar[1]-etar[0])*(etap[1]-etap[0]) ## Assumes regular grid ## Wall indices Rind, Sind = np.abs(r-R).argmin(), np.abs(r-S).argmin() ## -------------------------------------------------------------------- ## Normalise histogram and convert to density H /= H.sum()*dV rho = H / ( (2*np.pi)**2.0 * rr*ee ) ## Marginalise over eta and calculate BC ## Radial density Q = np.trapz(np.trapz(rho, etap, axis=2)*etar, etar, axis=1) * 2*np.pi ## Bulk constant f = -np.hstack([np.linspace(S-r[0],0.0,Sind),np.zeros(Rind-Sind),np.linspace(0.0,r[-1]-R,r.size-Rind)]) ## <\eta^2\cos^2\psi>Q e2c2Q = np.trapz(np.trapz(rho * np.cos(pp)*np.cos(pp), etap, axis=2)*etar*etar * 2*np.pi*etar, etar, axis=1) e2s2Q = np.trapz(np.trapz(rho * np.sin(pp)*np.sin(pp), etap, axis=2)*etar*etar * 2*np.pi*etar, etar, axis=1) ## <\eta^2>Q # e2Q = np.trapz(np.trapz(rho, etap, axis=2)*etar*etar * 2*np.pi*etar, etar, axis=1) ## -\int_{bulk}^{\infty} (2<\eta^2\cos^2\psi>-<\eta^2>-f^2)*Q/r' dr' intgl = -sp.integrate.cumtrapz(((e2c2Q-e2s2Q-f*f*Q)/r)[::-1], r, axis=0, initial=0.0)[::-1] if S!=0.0: intgl -= intgl[(Rind+Sind)/2] BC = e2c2Q + intgl ## -------------------------------------------------------------------- ## Plot "bulk constant" components if 1: zoom = False t0 = time.time() fig = plt.figure(); ax = fig.gca() ax.plot(r,-f/np.abs(f).max(),"k--",label=r"$-f(r)$") ax.plot(r,Q/np.abs(Q).max(),":",label=r"$Q(r)$") ax.plot(r,e2Q/np.abs(e2Q).max(), label=r"$\langle\eta^2\rangle (r)Q(r)$") ax.plot(r,e2c2Q/np.abs(e2c2Q).max(), label=r"$\langle\eta^2 \cos^2\psi\rangle (r)Q(r)$") ax.plot(r,intgl/np.abs(intgl).max(), label=r"$-\int_r^\infty\frac{1}{r^\prime}\left(\langle\eta^2\cos^2\psi\rangle-\langle\eta^2\rangle-f^2\right)Q\,dr^\prime$") ax.plot(r,BC/np.abs(BC).max(), label=r"$P(r_{\rm bulk})/\alpha$") ax.axvline(S, color="k", linewidth=1); ax.axvline(R, color="k", linewidth=1) if S!=R: ax.axvspan(S,R, color="y", alpha=0.1) if zoom: ax.set_ylim(np.around((np.array([-0.1,+0.1])+BC[Sind:Rind].mean()/np.abs(BC).max()),1)) ax.set_xlabel(r"$r$", fontsize=fsa) ax.set_ylabel(r"Rescaled variable", fontsize=fsa) ax.legend(loc="best", fontsize=12).get_frame().set_alpha(0.5) ax.grid() ax.set_title(r"$a=%.1f, R=%.1f, S=%.1f$"%(a,R,S), fontsize=fst) plotfile = os.path.dirname(histfile)+("/RPpol_a%.1f_R%.1f_S%.1f"+"_zoom"*zoom+".jpg")%(a,R,S) fig.savefig(plotfile) print me+"Figure saved",plotfile print me+"BC components plot:",round(time.time()-t0,1),"seconds." plt.show() plt.close() exit() ## -------------------------------------------------------------------- ## Integral pressure calculation ## Integrate from bulk to infinity (outer wall) p = +calc_pressure(r[Rind:],Q[Rind:],ftype,[R,S,lam,nu]) ## For outer wall # p = -calc_pressure(r[:Sind],Q[:Sind],ftype,[R,S,lam,nu]) ## For inner wall return [r, BC, p, pars]
def pressure_plot_dir(dirpath, verbose): """ Plot pressure at "infinity" against alpha for all files in directory. Be careful heed changes in parameters between files in directory """ me = "LE_Pressure.pressure_plot_dir: " t0 = sysT() ## File discovery histfiles = np.sort(glob.glob(dirpath+"/BHIS_2D_*.npy")) numfiles = len(histfiles) if verbose: print me+"found",numfiles,"files" ## Initialise Alpha = np.zeros(numfiles) X = np.zeros(numfiles) R = np.zeros(numfiles) Press = np.zeros(numfiles) xini = np.zeros(numfiles) ## Loop over files for i,histfile in enumerate(histfiles): ## Get pars from filename pars = filename_pars(histfile) [Alpha[i],X[i],D,dt,ymax,R[i]] = [pars[key] for key in ["a","X","D","dt","ymax","R"]] assert (R[i] is not None), me+"You are using the wrong program. R should be defined." assert (D == 0.0), me+"Cannot yet handle soft potential. D should be 0.0." ## Load data and normalise H = np.load(histfile) H /= H.sum() ## Centre of circle for curved boundary c = circle_centre(X[i],R[i],ymax) ## Space (for axes) try: bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] ybins = bins["ybins"] xini[i] = xbins[0] xmax = xbins[-1] except (IOError, KeyError): xini[i] = calculate_xini(X[i],Alpha[i]) xmax = lookup_xmax(c[0]+R[i],Alpha[i]) xbins = calculate_xbin(xini,X[i],xmax,H.shape[1]) ybins = calculate_ybin(0.0,ymax,H.shape[0]+1) x = 0.5*(xbins[1:]+xbins[:-1]) y = 0.5*(ybins[1:]+ybins[:-1]) ## Calculate force array (2D) Xm,Ym = np.meshgrid(x,y) force = -1.0 * ( (Xm-c[0])**2 + (Ym-c[1])**2 > R[i]*R[i] ) * ( Xm-c[0]>0.0 ) ## Pressure array (2d) -- sum rather than trapz Press[i] = -1.0*(force*H).sum(axis=0).cumsum(axis=0)[-1] ## ------------------------------------------------ ## Create 3D pressure array and 1D a,X,R coordinate arrays ## Ordered independent variable arrays AA = np.unique(Alpha) XX = np.unique(X) RR = np.unique(R) ## 3D pressure array: [X,R,A] PP = np.zeros([XX.size,RR.size,AA.size]) PPWN = np.zeros(PP.shape) for i in range(XX.size): Xidx = (X==XX[i]) for j in range(RR.size): Ridx = (R==RR[j]) for k in range(AA.size): Aidx = (Alpha==AA[k]) Pidx = Xidx*Ridx*Aidx try: PP[i,j,k] = Press[Pidx] except ValueError: pass PPWN[i,j,k] = pressure_IG(XX[i],RR[j],xini[Pidx],ymax,AA[k]) ## Normalise by WN result if 1: PP /= PPWN ## Mask zeros PP = np.ma.array(PP, mask = PP==0.0) ## ------------------------------------------------ ## 1D plots ## Which plots to make (abcissa,multiline,subplot,dimension) [ARX1,AXR1,XAR1,XRA1,RXA1,RAX1] = [1,0,0,0,0,0] if ARX1: fig, axs = plt.subplots(1,2,sharey=True) for i in range(RR.size): axs[0].plot(AA,PP[0,i,:], "o-", label="$R = "+str(RR[i])+"$") axs[1].plot(AA,PP[-1,i,:], "o-", label="$R = "+str(RR[i])+"$") for j in range(len(axs)): axs[j].set_xlim((AA[0],AA[-1])) axs[j].set_ylim((0.0,np.array([PP[0,:,:],PP[-1,:,:]]).max())) axs[j].set_xlabel("$\\alpha$",fontsize=fsa) axs[j].set_title("$X = "+str(XX[0-j])+"$",fontsize=fsa) axs[j].grid() axs[0].set_ylabel("Pressure",fontsize=fsa) axs[1].legend(loc="best",fontsize=fsl) plt.tight_layout() pressplot = dirpath+"/PARX1_dt"+str(dt)+".png" plt.savefig(pressplot) if verbose: print me+"plot saved to",pressplot if AXR1: fig, axs = plt.subplots(1,2,sharey=True) for i in range(XX.size): axs[0].plot(AA,PP[i, 0,:], "o-", label="$x_{\\rm wal} = "+str(XX[i])+"$") axs[1].plot(AA,PP[i,-1,:], "o-", label="$x_{\\rm wal} = "+str(XX[i])+"$") for j in range(len(axs)): axs[j].set_xlim((AA[0],AA[-1])) axs[j].set_ylim((0.0,np.array([PP[:,0,:],PP[:,-1,:]]).max())) axs[j].set_xlabel("$\\alpha$",fontsize=fsa) axs[j].set_title("$R = "+str(RR[0-j])+"$",fontsize=fsa) axs[j].grid() axs[0].set_ylabel("Pressure",fontsize=fsa) axs[1].legend(loc="best",fontsize=fsl) plt.tight_layout() pressplot = dirpath+"/PAXR1_dt"+str(dt)+".png" plt.savefig(pressplot) if verbose: print me+"plot saved to",pressplot ## ------------------------------------------------ ## 2D plots ## Which plots to make (abcissa,ordinate,subplot,dimension) [ARX2,AXR2,XAR2,XRA2,RXA2,RAX2] = [0,0,0,0,0,0] if ARX2: fig, axs = plt.subplots(1,2,sharey=True) for i in range(RR.size): axs[0].contourf(AA,RR,PP[0,:,:], vmin=0.0) axs[1].contourf(AA,RR,PP[-1,:,:], vmin=0.0) for j in range(len(axs)): axs[j].set_xlim((AA[0],AA[-1])) axs[j].set_ylim((RR[0],RR[-1])) axs[j].set_xlabel("$\\alpha$",fontsize=fsa) axs[j].set_title("$X = "+str(X[0-j])+"$",fontsize=fsa) axs[0].set_ylabel("$R$",fontsize=fsa) plt.tight_layout() pressplot = dirpath+"/PARX2_dt"+str(dt)+".png" plt.savefig(pressplot) if verbose: print me+"plot saved to",pressplot ## ------------------------------------------------ return
elif float(sys.argv[1])==0.2: histfiles = ["Pressure/160619_CIR_DLN_R100.0_Pa/DL_R100.0/BHIS_CIR_DL_a0.2_R100.0_S100.0_dt0.01.npy",\ "Pressure/160701_CIR_DL_dt0.01_smallbulk/DL_0.1b/BHIS_CIR_DL_a0.2_R100.0_S99.9_dt0.005.npy",\ # "Pressure/160701_CIR_DL_dt0.01_smallbulk/DL_0.5b/BHIS_CIR_DL_a0.2_R100.0_S99.5_dt0.005.npy",\ "Pressure/160619_CIR_DLN_R100.0_Pa/DL_R100.0/BHIS_CIR_DL_a0.2_R100.0_S99.0_dt0.01.npy",\ "Pressure/160619_CIR_DLN_R100.0_Pa/DL_R100.0/BHIS_CIR_DL_a0.2_R100.0_S90.0_dt0.01.npy"] else: print "argv must be 10 or 0.2 depending on alpha." fig, ax = plt.subplots(1,1,sharex=True) for histfile in histfiles: ## Get pars from filename pars = filename_pars(histfile) [a,ftype,R,S,lam,nu] = [pars[key] for key in ["a","ftype","R","S","lam","nu"]] fpars = [R,S,lam,nu] ## Space (for axes) bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") rbins = bins["rbins"] rmax = rbins[-1] r = 0.5*(rbins[1:]+rbins[:-1]) erbins = bins["erbins"] er = 0.5*(erbins[1:]+erbins[-1]) rini = 0.5*(max(rbins[0],S)+R) ## Start point for computing pressures rinid = np.argmin(np.abs(r-rini)) ## Load histogram, convert to normalised pdf H = np.load(histfile)
def pressure_pdf_plot_file(histfile, nosave, verbose): """ Make plot for a single file """ me = "LE_Pressure.pressure_pdf_plot_file: " t0 = sysT() plotpress = False ## Filenames plotfile = os.path.dirname(histfile) + "/PDFP" + os.path.basename( histfile)[4:-4] + ".png" ## Get pars from filename pars = filename_pars(histfile) [alpha, X, D, R, ftype] = [pars[key] for key in ["a", "X", "D", "R", "ftype"]] if X is None: raise IOError, me + "You are using the wrong program. R should not enter." # os.system("python LE_SPressure.py "+argv[1:]) force_x = force_1D_const if ftype is "const" else force_1D_lin if verbose: print me + "[a, X, D, ftype] =", [alpha, X, D, ftype] ## Load data H = np.load(histfile) ## Space, for axes bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] ebins = bins["ebins"] xmin = xbins[0] xmax = xbins[-1] xini = 0.5 * (xmin + X) x = 0.5 * (xbins[1:] + xbins[:-1]) e = 0.5 * (ebins[1:] + ebins[:-1]) ## Marginalise to PDF in x Hx = np.trapz(H, x=e, axis=0) Hx /= np.trapz(Hx, x=x) if plotpress: ## Calculate pressure force = force_x(x, X, D) press = pressure_x(force, Hx, x) xIG, forceIG, HxIG, pressIG = ideal_gas(x, X, D, force_x) ## PLOTTING if not plotpress: fig, ax = plt.subplots(1, 1) elif plotpress: fig, axs = plt.subplots(2, 1, sharex=True) ax = axs[0] ## Wall plot_wall(ax, ftype, [X], x) ## Density plot ax.plot(x, Hx, "b-", label="Simulation") ax.plot(xIG, HxIG, "r-", label="White noise") ax.set_xlim(left=xmin, right=max(xmax, xIG[-1])) ax.set_ylim(bottom=0.0, top=1.1) if not plotpress: ax.set_xlabel("$x$", fontsize=fsa) ax.set_ylabel("$\\rho(x)$", fontsize=fsa) ax.grid() ax.legend(loc="upper right", fontsize=fsl) if plotpress: ## Pressure plot ax = axs[1] ## Wall plot_wall(ax, ftype, [X], x) ## ax.plot(x, press, "b-", linewidth=1, label="CN") ax.axhline(press[-1], color="b", linestyle="--", linewidth=1) ax.plot(xIG, pressIG, "r-", label="WN") ax.axhline(pressIG[-1], color="r", linestyle="--", linewidth=1) # ax.axhline(1/(1.0-np.exp(X-xmax)+X-xmin),color="r",linestyle="--",linewidth=1) ax.set_xlim(left=xbins[0], right=xbins[-1]) ax.set_ylim(bottom=0.0, top=np.ceil(max([press[-1], pressIG[-1]]))) ax.set_xlabel("$x$", fontsize=fsa) ax.set_ylabel("Pressure", fontsize=fsa) ax.grid() # ax.legend(loc="best",fontsize=fsl) #fig.suptitle("$x_{w}=$"+str(X)+", $\\alpha=$"+str(alpha)+", $\\Delta=$"+str(D),fontsize=16) plt.tight_layout() plt.subplots_adjust(top=0.9) if not nosave: plt.savefig(plotfile) if verbose: print me + "plot saved to", plotfile return fig
def sort_AN(filelist, var): varlist = [filename_pars(filename)[var] for filename in filelist] idxs = np.argsort(varlist) return [filelist[idx] for idx in idxs]
"Pressure/160619_CIR_DLN_R100.0_Pa/DL_R100.0/BHIS_CIR_DL_a10.0_R100.0_S90.0_dt0.02.npy"] elif float(sys.argv[1]) == 0.2: histfiles = ["Pressure/160619_CIR_DLN_R100.0_Pa/DL_R100.0/BHIS_CIR_DL_a0.2_R100.0_S100.0_dt0.01.npy",\ "Pressure/160701_CIR_DL_dt0.01_smallbulk/DL_0.1b/BHIS_CIR_DL_a0.2_R100.0_S99.9_dt0.005.npy",\ # "Pressure/160701_CIR_DL_dt0.01_smallbulk/DL_0.5b/BHIS_CIR_DL_a0.2_R100.0_S99.5_dt0.005.npy",\ "Pressure/160619_CIR_DLN_R100.0_Pa/DL_R100.0/BHIS_CIR_DL_a0.2_R100.0_S99.0_dt0.01.npy",\ "Pressure/160619_CIR_DLN_R100.0_Pa/DL_R100.0/BHIS_CIR_DL_a0.2_R100.0_S90.0_dt0.01.npy"] else: print "argv must be 10 or 0.2 depending on alpha." fig, ax = plt.subplots(1, 1, sharex=True) for histfile in histfiles: ## Get pars from filename pars = filename_pars(histfile) [a, ftype, R, S, lam, nu] = [pars[key] for key in ["a", "ftype", "R", "S", "lam", "nu"]] fpars = [R, S, lam, nu] ## Space (for axes) bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") rbins = bins["rbins"] rmax = rbins[-1] r = 0.5 * (rbins[1:] + rbins[:-1]) erbins = bins["erbins"] er = 0.5 * (erbins[1:] + erbins[-1]) rini = 0.5 * (max(rbins[0], S) + R) ## Start point for computing pressures rinid = np.argmin(np.abs(r - rini))
def bulk_const(histfile): """ Calculate various quantities pertaining to the moment-pressure calculation. """ me = me0+",bulk_const: " a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") pars = filename_pars(histfile) ftype, lam, nu = pars["ftype"], pars["lam"], pars["nu"] psifile = "_psi" in histfile phifile = "_phi" in histfile H = np.load(histfile) bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") ## Space and load histogram rbins = bins["rbins"] ebins = bins["erbins"] r = 0.5*(rbins[1:]+rbins[:-1]) eta = 0.5*(ebins[1:]+ebins[:-1]) if psifile: pbins = bins["epbins"] psi = 0.5*(pbins[1:]+pbins[:-1]) ## For old _phi files if phifile: epbins = bins["epbins"] H = H.sum(axis=2) * (epbins[1]-epbins[0]) ## Spatial arrays with dimensions commensurate to rho if psifile: rr = r[:,np.newaxis,np.newaxis] ee = eta[np.newaxis,:,np.newaxis] pp = psi[np.newaxis,np.newaxis,:] dV = (r[1]-r[0])*(eta[1]-eta[0])*(psi[1]-psi[0]) ## Assumes regular grid else: rr = r[:,np.newaxis] ee = eta[np.newaxis,:] dV = (r[1]-r[0])*(eta[1]-eta[0]) ## Assumes regular grid ## Wall indices Rind, Sind = np.abs(r-R).argmin(), np.abs(r-S).argmin() ## -------------------------------------------------------------------- ## Normalise histogram and convert to density H /= H.sum()*dV rho = H / ( (2*np.pi)**2.0 * rr*ee ) ## Marginalise over eta and calculate BC if psifile: ## Radial density Q = np.trapz(np.trapz(rho, psi, axis=2)*eta, eta, axis=1) * 2*np.pi assert "_DL_" in histfile, me+"Only dlin force supported at the moment." f = force_dlin(r,r,R,S) ## <\eta^2\cos^2\psi>Q, <\eta^2\sin^2\psi>Q e2c2Q = np.trapz(np.trapz(rho * np.cos(pp)*np.cos(pp), psi, axis=2)*eta*eta * 2*np.pi*eta, eta, axis=1) e2s2Q = np.trapz(np.trapz(rho * np.sin(pp)*np.sin(pp), psi, axis=2)*eta*eta * 2*np.pi*eta, eta, axis=1) ## \int_0^r (<\eta^2\cos^2\psi>-<\eta^2\sin^2\psi>-f^2)*Q/r' dr' intgl = sp.integrate.cumtrapz(((e2c2Q-e2s2Q-f*f*Q)/r), r, axis=0, initial=0.0) ## Line sometimes gets choppy towards r=0, especially for low alpha and S. ## This throws the evaluation of e2c2Q at r=0, necessary for BCin. ## Here, I fit a low-r portion of e2c2Q to a quadratic and use that intercept. if (S<=2.0 and S>0.0 and a<2.0): fitfunc = lambda x, c2, c1, c0: c2*x*x + c1*x + c0 fitE2C2Q = sp.optimize.curve_fit(fitfunc, r[10:30], e2c2Q[10:30])[0] e2c2Q[0] = fitfunc(r[0], *fitE2C2Q) ## Bulk constants BCout = e2c2Q + intgl - intgl[-1] ## Attention to integral limits BCin = e2c2Q + intgl - (e2c2Q[0]-f[0]*f[0]*Q[0]) else: ## Radial density Q = np.trapz(H,eta,axis=1) / (2*np.pi*r) ## Bulk constant <eta^2> Q BC = np.trapz(rho * eta*eta * 2*np.pi*eta, eta, axis=1) ## -------------------------------------------------------------------- ## psi diagnostics plot if (0 and psifile): plot_psi_diagnostics(rho,Q,r,eta,psi,rr,ee,pp,R,Rind,S,Sind,a,histfile,showfig=False) ## Integral pressure calculation Pout = +calc_pressure(r[Rind:],Q[Rind:],ftype,[R,S,lam,nu]) ## For outer wall Pin = -calc_pressure(r[:Sind],Q[:Sind],ftype,[R,S,lam,nu]) ## For inner wall return r, Q, BCout, BCin, Pout, Pin, e2c2Q, e2s2Q, intgl, pars
def plot_dir(histdir, nosave, searchstr, vb): """ For each file in directory, calculate the pressure in both ways for both walls (where applicable) and plot against alpha. """ me = me0+".plot_dir: " ftype = filename_pars(histdir)["ftype"] filelist = np.sort(glob.glob(histdir+"/BHIS_*"+searchstr+"*.npy")) numfiles = filelist.size if vb: print me+"Found",numfiles,"files." ## Initialise arrays A,Cout,Cin,Pout,Pin = np.zeros([5,numfiles]) ## Retrieve data for i,histfile in enumerate(filelist): t0 = time.time() r, Q, BCout, BCin, Pout[i], Pin[i], e2c2Q, e2s2Q, intgl, pars = bulk_const(histfile) if vb: print me+"a=%.1f:\tBC calculation %.2g seconds"%(pars["a"],time.time()-t0) A[i], R, S = pars["a"], pars["R"], pars["S"] fpars = [R,S,pars["lam"],pars["nu"]] Rind, Sind = np.abs(r-R).argmin(), np.abs(r-S).argmin() Cout[i] = BCout[Sind+10:Rind-10].mean() if Rind!=Sind else BCout[max(0,Sind):Rind+1].mean() if S>0.0: Cin[i] = BCin[Sind+10:Rind-10].mean() if Rind!=Sind else BCin[max(0,Sind):Rind+1].mean() ## SORT BY ALPHA srtidx = A.argsort() A = A[srtidx] Pout, Pin = Pout[srtidx], Pin[srtidx] Cout, Cin = Cout[srtidx], Cin[srtidx] ##------------------------------------------------------------------------- ## Calculate white noise pressure and pdf ## Assume all files have same R & S. P_WN independent of alpha. r_WN = np.linspace(r[0],r[-1],2*r.size+1) Rind_WN, Sind_WN = np.abs(r_WN-R).argmin(), np.abs(r_WN-S).argmin() p_WN = calc_pressure(r_WN,pdf_WN(r_WN,fpars,ftype),ftype,fpars,True) Pout_WN = p_WN[-1] - p_WN.min() ## For outer wall Pin_WN = p_WN[0] - p_WN.min() ## For inner wall ## NORMALISE Pout /= Pout_WN Cout /= Pout_WN if S>0.0: Pin /= Pin_WN Cin /= Pin_WN ##------------------------------------------------------------------------- ## FIT -- A*C -- fit in log coordinates fitfunc = lambda x, B, nu: B + nu*x ## Outer C and P fitCout = sp.optimize.curve_fit(fitfunc, np.log(1+A), np.log(A*Cout), p0=[+1.0,-1.0])[0] fitPout = sp.optimize.curve_fit(fitfunc, np.log(1+A), np.log(Pout), p0=[+1.0,-1.0])[0] if vb: print me+"nu_Cout = ",fitCout.round(3)[1],"\t nu_Pout = ",fitPout.round(3)[1] ## Inner C and P if S>0.0: fitCin = sp.optimize.curve_fit(fitfunc, np.log(1+A), np.log(A*Cin), p0=[+1.0,-1.0])[0] fitPin = sp.optimize.curve_fit(fitfunc, np.log(1+A), np.log(Pin), p0=[+1.0,-1.0])[0] if vb: print me+"nu_Cin = ",fitCin.round(3)[1],"\t nu_Pin = ",fitPin.round(3)[1] ##------------------------------------------------------------------------- ## Add A=0 point if 1: A = np.hstack([[0.0],A]) Pout = np.hstack([[1.0],Pout]) Pin = np.hstack([[1.0],Pin]) Cout = np.hstack([[1.0],A[1:]*Cout]) Cin = np.hstack([[1.0],A[1:]*Cin]) ## I HAVE REMOVED A* FROM PLOT LINES ##------------------------------------------------------------------------- ## PLOT DATA fig = plt.figure(figsize=fs["figsize"]); ax = fig.gca() linePo = ax.plot(1+A, Pout, "o--", label=r"$-\int_{\rm bulk}^{\infty} fQ\,{\rm d}r$") lineCo = ax.plot(1+A, Cout, "v--", label=r"Eq. (20) (outer)") if S>0.0: linePi = ax.plot(1+A, Pin, "o--", label=r"$-\int_{0}^{\rm bulk} fQ\,{\rm d}r$") lineCi = ax.plot(1+A, Cin, "v--", label=r"Eq. (20) (inner)") ## PLOT FIT # ## Cout, Pout # ax.plot(1+A, np.exp(fitfunc(np.log(1+A), *fitPout)), linePo[0].get_color()+"--", lw=1, # label=r"$%.1g(1+\alpha)^{%.3g}$"%(np.exp(fitPout[0]),fitPout[1])) # ax.plot(1+A, np.exp(fitfunc(np.log(1+A), *fitCout)), lineCo[0].get_color()+"--", lw=1, # label=r"$%.1g(1+\alpha)^{%.3g}$"%(np.exp(fitCout[0]),fitCout[1])) # ## Cin, Pin # if S>0.0: # ax.plot(1+A, np.exp(fitfunc(np.log(1+A), *fitPin)), linePi[0].get_color()+"--", lw=1, # label=r"$%.1g(1+\alpha)^{%.3g}$"%(np.exp(fitPin[0]),fitPin[1])) # ax.plot(1+A, np.exp(fitfunc(np.log(1+A), *fitCin)), lineCi[0].get_color()+"--", lw=1, # label=r"$%.1g(1+\alpha)^{%.3g}$"%(np.exp(fitCin[0]),fitCin[1])) # ## PLOT PREDICTION for R=S # if R == S: # ## Outer: see notes 09/11/2016 # b = lambda c, m: 1/(c*(A+1))*np.exp(-0.5*c*(A+1)*m*m) +\ # + m*np.sqrt(np.pi/(2*c*(A+1)))*(1+sp.special.erf(m*np.sqrt(0.5*c*(A+1)))) # Pout = 1/(2*np.pi*np.pi)*b(0.01, 0.1)/b(0.01, R+0.1) # ax.plot(1+A, Pout/Pout_WN, "m:", label = r"Predicted $P_{\rm out}$", lw=2) ##------------------------------------------------------------------------- ## ACCOUTREMENTS ax.set_xscale("log") ax.set_yscale("log") ax.set_xlim(1,1+A[-1]) ax.set_ylim(top=1e1) ax.set_xlabel(r"$1+\alpha$",fontsize=fs["fsa"]) ax.set_ylabel(r"$P(\alpha)/P^{\rm passive}$",fontsize=fs["fsa"]) ax.grid() # ax.legend(loc="best", fontsize=(fs["fsl"]/2 if S>0.0 else fs["fsl"])).get_frame().set_alpha(0.5) ax.legend(loc="best", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) # ax.set_title("Pressure normalised by WN result. $R=%.1f, S=%.1f.$"%(fpars[0],fpars[1]),fontsize=fs["fst"]) ## SAVING plotfile = histdir+"/QEe2_Pa_R"+str(fpars[0])+"_S"+str(fpars[1])+"."+fs["saveext"] if not nosave: fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile return plotfile
def bulk_const(histfile): """ """ me = me0 + ",bulk_const: " try: pars = filename_pars(histfile) [a, X, R, S, D, lam, nu, ftype, geo] = [ pars[key] for key in ["a", "X", "R", "S", "D", "lam", "nu", "ftype", "geo"] ] except: ## Disc wall surrounded by bulk a = filename_par(histfile, "_a") S = filename_par(histfile, "_S") geo = "INCIR" ftype = "linin" R, lam, nu = 100, None, None pars = { "a": a, "R": R, "S": S, "lam": lam, "nu": nu, "ftype": ftype, "geo": geo } assert "_psi" in histfile, me + "Must use _psi file." H = np.load(histfile) bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") ## Circular sim if "CIR" in geo: ## Space and load histogram rbins = bins["rbins"] erbins = bins["erbins"] r = 0.5 * (rbins[1:] + rbins[:-1]) etar = 0.5 * (erbins[1:] + erbins[:-1]) epbins = bins["epbins"] etap = 0.5 * (epbins[1:] + epbins[:-1]) ## Spatial arrays with dimensions commensurate to rho rr = r[:, np.newaxis, np.newaxis] ee = etar[np.newaxis, :, np.newaxis] pp = etap[np.newaxis, np.newaxis, :] dV = (r[1] - r[0]) * (etar[1] - etar[0]) * (etap[1] - etap[0] ) ## Assumes regular grid ## Wall indices Rind, Sind = np.abs(r - R).argmin(), np.abs(r - S).argmin() ## -------------------------------------------------------------------- ## Normalise histogram and convert to density H /= H.sum() * dV rho = H / ((2 * np.pi)**2.0 * rr * ee) ## Marginalise over eta and calculate BC ## Radial density Q = np.trapz(np.trapz(rho, etap, axis=2) * etar, etar, axis=1) * 2 * np.pi ## Bulk constant f = -np.hstack([ np.linspace(S - r[0], 0.0, Sind), np.zeros(Rind - Sind), np.linspace(0.0, r[-1] - R, r.size - Rind) ]) ## <\eta^2\cos^2\psi>Q e2c2Q = np.trapz( np.trapz(rho * np.cos(pp) * np.cos(pp), etap, axis=2) * etar * etar * 2 * np.pi * etar, etar, axis=1) e2s2Q = np.trapz( np.trapz(rho * np.sin(pp) * np.sin(pp), etap, axis=2) * etar * etar * 2 * np.pi * etar, etar, axis=1) ## <\eta^2>Q # e2Q = np.trapz(np.trapz(rho, etap, axis=2)*etar*etar * 2*np.pi*etar, etar, axis=1) ## -\int_{bulk}^{\infty} (2<\eta^2\cos^2\psi>-<\eta^2>-f^2)*Q/r' dr' intgl = -sp.integrate.cumtrapz( ((e2c2Q - e2s2Q - f * f * Q) / r)[::-1], r, axis=0, initial=0.0)[::-1] if S != 0.0: intgl -= intgl[(Rind + Sind) / 2] BC = e2c2Q + intgl ## -------------------------------------------------------------------- ## Plot "bulk constant" components if 1: zoom = False t0 = time.time() fig = plt.figure() ax = fig.gca() ax.plot(r, -f / np.abs(f).max(), "k--", label=r"$-f(r)$") ax.plot(r, Q / np.abs(Q).max(), ":", label=r"$Q(r)$") ax.plot(r, e2Q / np.abs(e2Q).max(), label=r"$\langle\eta^2\rangle (r)Q(r)$") ax.plot(r, e2c2Q / np.abs(e2c2Q).max(), label=r"$\langle\eta^2 \cos^2\psi\rangle (r)Q(r)$") ax.plot( r, intgl / np.abs(intgl).max(), label= r"$-\int_r^\infty\frac{1}{r^\prime}\left(\langle\eta^2\cos^2\psi\rangle-\langle\eta^2\rangle-f^2\right)Q\,dr^\prime$" ) ax.plot(r, BC / np.abs(BC).max(), label=r"$P(r_{\rm bulk})/\alpha$") ax.axvline(S, color="k", linewidth=1) ax.axvline(R, color="k", linewidth=1) if S != R: ax.axvspan(S, R, color="y", alpha=0.1) if zoom: ax.set_ylim( np.around((np.array([-0.1, +0.1]) + BC[Sind:Rind].mean() / np.abs(BC).max()), 1)) ax.set_xlabel(r"$r$", fontsize=fsa) ax.set_ylabel(r"Rescaled variable", fontsize=fsa) ax.legend(loc="best", fontsize=12).get_frame().set_alpha(0.5) ax.grid() ax.set_title(r"$a=%.1f, R=%.1f, S=%.1f$" % (a, R, S), fontsize=fst) plotfile = os.path.dirname( histfile) + ("/RPpol_a%.1f_R%.1f_S%.1f" + "_zoom" * zoom + ".jpg") % (a, R, S) fig.savefig(plotfile) print me + "Figure saved", plotfile print me + "BC components plot:", round(time.time() - t0, 1), "seconds." plt.show() plt.close() exit() ## -------------------------------------------------------------------- ## Integral pressure calculation ## Integrate from bulk to infinity (outer wall) p = +calc_pressure(r[Rind:], Q[Rind:], ftype, [R, S, lam, nu]) ## For outer wall # p = -calc_pressure(r[:Sind],Q[:Sind],ftype,[R,S,lam,nu]) ## For inner wall return [r, BC, p, pars]
def plot_dir(histdir, nosave, searchstr, vb): """ """ me = me0 + ".plot_dir: " dirpars = filename_pars(histdir) geo = dirpars["geo"] ftype = dirpars["ftype"] filelist = np.sort(glob.glob(histdir + "/BHIS_*" + searchstr + "*.npy")) numfiles = len(filelist) if vb: print me + "Found", numfiles, "files." ## Initialise arrays A, X, C, P, P_WN = np.zeros([5, numfiles]) ## Retrieve data for i, histfile in enumerate(filelist): t0 = time.time() [x, BC, p, pars] = bulk_const(histfile) if vb: print me + "File %i of %i: BC calculation %.2g seconds" % ( i + 1, numfiles, time.time() - t0) A[i] = pars["a"] P[i] = p fpars = [pars["R"], pars["S"], pars["lam"], pars["nu"]] Sind, Rind = np.abs(x - pars["S"]).argmin(), np.abs(x - pars["R"]).argmin() C[i] = BC[:Rind].mean() if ( Sind == 0 and Rind > 0) else BC[Rind] ## Not fully functional ## SORT BY ALPHA srtidx = A.argsort() A = A[srtidx] P = P[srtidx] P_WN = P_WN[srtidx] C = C[srtidx] ## Calculate white noise pressure and pdf ## Assume all files have same R & S. P_WN independent of alpha. r_WN = np.linspace(x[0], x[-1], 2 * x.size + 1) Rind_WN, Sind_WN = np.abs(r_WN - fpars[0]).argmin(), np.abs(r_WN - fpars[1]).argmin() p_WN = calc_pressure(r_WN, pdf_WN(r_WN, fpars, ftype), ftype, fpars, True) P_WN = p_WN[-1] - p_WN.min() ## For outer wall # P_WN = p_WN[0] - p_WN.min() ## For inner wall ## NORMALISE P /= P_WN C /= P_WN ## FIT -- A*C -- fit in log coordinates fitfunc = lambda x, B, nu: B + nu * x fitBC = sp.optimize.curve_fit(fitfunc, np.log(1 + A), np.log(A * C), p0=[+1.0, -1.0])[0] ## FIT -- P_int fitP = sp.optimize.curve_fit(fitfunc, np.log(1 + A), np.log(P), p0=[+1.0, -1.0])[0] if vb: print me + ": nu_BC = ", fitBC.round(3)[1], "\t nu_Int = ", fitP.round( 3)[1] ## PLOT DATA AND FIT fig = plt.figure() ax = fig.gca() ax.plot(1 + A, P, "o-", label=r"$-\int_{\rm bulk}^{\infty} fQ\,{\rm d}r$") ax.plot(1 + A, A * C, "o-", label=r"$\alpha Q\langle\eta^2\cos^2\psi\rangle|_{\rm bulk}$") ax.plot(1 + A, np.exp(fitfunc(np.log(1 + A), *fitP)), "b--", lw=1, label=r"$%.1g(1+\alpha)^{%.3g}$" % (np.exp(fitP[0]), fitP[1])) ax.plot(1 + A, np.exp(fitfunc(np.log(1 + A), *fitBC)), "g--", lw=1, label=r"$%.1g(1+\alpha)^{%.3g}$" % (np.exp(fitBC[0]), fitBC[1])) ## Prediction for R=S if fpars[0] == fpars[1]: R = fpars[0] Pout = 1/(4*np.pi*(1+A)*(1/(1+A)*np.exp(-0.5*(1+A)*R*R)+\ +np.sqrt(np.pi/(2*(1+A)))*R*(sp.special.erf(np.sqrt((0.5*(1+A))*R)+1)))) ax.plot(1 + A, Pout / P_WN, ":", label=r"Predicted $P_{\rm out}$") if R <= 2 * np.sqrt(np.log(10)): ax.plot(1 + A, Pout / P_WN * (1 - np.exp(-0.5 * (1 + A) * R * R)), ":", label=r"Predicted $P_{\rm in}$") ## ACCOUTREMENTS ax.set_xscale("log") ax.set_yscale("log") ax.set_xlim(1, 1 + A[-1]) ax.set_ylim(1e-2, 1e1) ax.set_xlabel(r"$1+\alpha$", fontsize=fsa) ax.set_ylabel(r"$P$", fontsize=fsa) ax.grid() ax.legend(loc="best") fig.suptitle("Pressure normalised by WN result. $R=%.2g, S=%.2g.$" % (fpars[0], fpars[1]), fontsize=fst) ## SAVING plotfile = histdir + "/RPpol_Pa_R" + str(fpars[0]) + "_S" + str( fpars[1]) + ".jpg" if not nosave: fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile return plotfile
def pressure_pdf_file(histfile, plotpress, vb): """ Make plot for a single file """ me = me0+".pressure_pdf_file: " t0 = time() ## Filename plotfile = os.path.dirname(histfile)+"/PDF"+os.path.basename(histfile)[4:-4]+"."+fs["saveext"] ## Get pars from filename assert "_POL_" in histfile or "_CIR_" in histfile, me+"Check input file." pars = filename_pars(histfile) [a,ftype,R,S,lam,nu] = [pars[key] for key in ["a","ftype","R","S","lam","nu"]] assert (R is not None), me+"You are using the wrong program. R must be defined." if vb: print me+"alpha =",a,"and R =",R if S is None: S = 0.0 fpars = [R,S,lam,nu] ## Space (for axes) bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") rbins = bins["rbins"] rmax = rbins[-1] r = 0.5*(rbins[1:]+rbins[:-1]) erbins = bins["erbins"] er = 0.5*(erbins[1:]+erbins[:-1]) rini = 0.5*(max(rbins[0],S)+R) ## Start point for computing pressures rinid = np.argmin(np.abs(r-rini)) ## Load histogram, convert to normalised pdf H = np.load(histfile) try: H = H.sum(axis=2) except ValueError: pass ## Noise dimension irrelevant here H = np.trapz(H, x=er, axis=1) ## rho is probability density. H is probability at r rho = H/(2*np.pi*r) / np.trapz(H, r, axis=0) ## White noise result r_WN = np.linspace(r[0],r[-1]*(1+0.5/r.size),r.size*5+1) rho_WN = pdf_WN(r_WN,fpars,ftype,vb) ## If we want density = 1.0 in bulk HACKY #rho /= rho[:np.argmin(np.abs(r-R))/2].mean() #rho_WN /= rho_WN[:np.argmin(np.abs(r-R))/2].mean() ##--------------------------------------------------------------- ## PLOT SET-UP if not plotpress: ## Only pdf plot figtit = "Density; " fig, ax = plt.subplots(1,1) elif plotpress: figtit = "Density and pressure; " fig, axs = plt.subplots(2,1,sharex=True) ax = axs[0] plotfile = os.path.dirname(plotfile)+"/PDFP"+os.path.basename(plotfile)[3:] figtit += ftype+"; $\\alpha="+str(a)+"$, $R = "+str(R)+"$" if ftype[0] == "d": figtit += r", $S = "+str(S)+"$" if ftype[-3:] == "tan": figtit += r", $\lambda="+str(lam)+"$" if ftype[-2:] == "nu": figtit += r", $\lambda="+str(lam)+"$, $\nu="+str(nu)+"$" xlim = [S-2*lam,R+2*lam] if (ftype[-3:]=="tan" or ftype[-2:]=="nu") else [S-4.0,R+4.0] xlim[0] = max(xlim[0],0.0) ##--------------------------------------------------------------- ## Calculate force array if ftype == "const": force = force_const(r,r,R) elif ftype == "lin": force = force_lin(r,r,R) elif ftype == "lico": force = force_lico(r,r,R) elif ftype == "dcon": force = force_dcon(r,r,R,S) elif ftype == "dlin": force = force_dlin(r,r,R,S) elif ftype == "tan": force = force_tan(r,r,R,lam) elif ftype == "dtan": force = force_dtan(r,r,R,S,lam) elif ftype == "nu": force = force_nu(r,r,R,lam,nu) elif ftype == "dnu": force = force_dnu(r,r,R,S,lam,nu) else: raise ValueError, me+"ftype not recognised." U = -sp.integrate.cumtrapz(force, r, initial=0.0); U -= U.min() ##--------------------------------------------------------------- ## PDF PLOT ## PDF and WN PDF sp.ndimage.gaussian_filter1d(rho,sigma=2.0,order=0,output=rho) ax.plot(r,rho, "b-", label="OUP") ax.fill_between(r,0,rho,facecolor="b",alpha=0.1) ax.plot(r_WN,rho_WN,"r-", label="Passive") ax.fill_between(r_WN,0,rho_WN,facecolor="r",alpha=0.1) ## Wall ax.plot(r, U/U.max()*ax.get_ylim()[1], "k--", label=r"$U(x)$") ## Accoutrements ax.set_xlim(xlim) ax.set_ylim(bottom=0.0, top=min(20,1.2*max(rho.max(),rho_WN.max()))) if not plotpress: ax.set_xlabel("$r$", fontsize=fs["fsa"]) # ax.set_ylabel(r"$\rho(r,\phi)$", fontsize=fs["fsa"]) ax.set_ylabel(r"$n(r)$", fontsize=fs["fsa"]) ax.grid() ax.legend(loc="upper right") ##--------------------------------------------------------------- ## PRESSURE if plotpress: ## CALCULATIONS p = calc_pressure(r,rho,ftype,[R,S,lam,nu],spatial=True) p_WN = calc_pressure(r_WN,rho_WN,ftype,[R,S,lam,nu],spatial=True) ## Eliminate negative values if ftype[0] == "d": p -= p.min() p_WN -= p_WN.min() # print [a,R],"\t",np.around([p[:20].mean(),p[-20:].mean()],6) ##----------------------------------------------------------- ## PRESSURE PLOT ax = axs[1] ## Pressure and WN pressure ax.plot(r,p,"b-",label="CN simulation") ax.plot(r_WN,p_WN,"r-",label="WN theory") ## Wall ax.plot(r, U/U.max()*ax.get_ylim()[1], "k--", label=r"$U(x)$") # plot_wall(ax, ftype, fpars, r) ## Accoutrements # ax.set_ylim(bottom=0.0, top=round(max(p.max(),p_WN.max())+0.05,1)) ax.set_ylim(bottom=0.0, top=min(20,float(1.2*max(p.max(),p_WN.max())))) ax.set_xlabel("$r$", fontsize=fs["fsa"]) ax.set_ylabel("$P(r)$", fontsize=fs["fsa"]) ax.grid() fig.tight_layout(); plt.subplots_adjust(top=0.9) ##--------------------------------------------------------------- # fig.suptitle(figtit,fontsize=fs["fst"]) fig.savefig(plotfile) if vb: print me+"plot saved to",plotfile return
def pressure_plot_dir(dirpath, nosave, verbose, twod=False, normIG=False): """ Plot pressure at "infinity" against alpha for all files in directory. Be careful heed changes in parameters between files in directory """ me = "LE_Pressure.pressure_plot_dir: " t0 = sysT() ## File discovery histfiles = np.sort(glob.glob(dirpath + "/*.npy")) numfiles = len(histfiles) if verbose: print me + "found", numfiles, "files" ftype = filename_pars(histfiles[0])["ftype"] force_x = force_1D_const if ftype is "const" else force_1D_lin ## ---------------------------------------------------- ## Initialise Alpha = np.zeros(numfiles) X = np.zeros(numfiles) Press = np.zeros(numfiles) xmin, xmax = np.zeros([2, numfiles]) PressIG = np.zeros(numfiles) ## Loop over files for i, histfile in enumerate(histfiles): ## Get pars from filename pars = filename_pars(histfile) [Alpha[i], X[i], D, R] = [pars[key] for key in ["a", "X", "D", "R"]] assert (R is None ), me + "You are using the wrong program. R should not enter." ## Load data H = np.load(histfile) ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] ebins = bins["ebins"] xmin[i] = xbins[0] xmax[i] = xbins[-1] xini = 0.5 * (xmin[i] + X[i]) x = 0.5 * (xbins[1:] + xbins[:-1]) e = 0.5 * (ebins[1:] + ebins[:-1]) ## Marginalise to PDF in x and normalise Hx = np.trapz(H, x=e, axis=0) Hx /= np.trapz(Hx, x=x, axis=0) ## Calculate pressure force = force_x(x, X[i], D) Press[i] = np.trapz(-force * Hx, x) ## ---------------------------------------------------- ## Sort values sortind = np.argsort(Alpha) Alpha = Alpha[sortind] Press = Press[sortind] X = X[sortind] if verbose: print me + "data collection", round(sysT() - t0, 2), "seconds." pressplot = dirpath + "/PAX_" + ftype + ".png" ## ---------------------------------------------------- ## Choose plot type ## 1D if twod is False or ((X == X[0]).all() and (Alpha != Alpha[0]).any()): XX = np.unique(X) Ncurv = XX.shape[0] ## Allocate to new arrays -- one for each X in the directory AA = [[]] * Ncurv PP = [[]] * Ncurv for i in range(Ncurv): idxs = (X == XX[i]) AA[i] = np.array(Alpha[idxs]) PP[i] = np.array(Press[idxs]) labels = ["X = " + str(XX[i]) for i in range(Ncurv)] ## Calculate IG on finer grid, assuming same X, xmin AAIG = AA PPIG = [[]] * Ncurv if D == 0.0: if ftype is "const": # PPIG = [1.0/(1.0-np.exp(-4.0)+XX[i]-calculate_xmin(XX[i],AA[i])) for i in range(Ncurv)] PPIG = [ 1.0 / (1.0 - np.exp(-6.0) + XX[i] - 0.0) for i in range(Ncurv) ] elif ftype is "lin": # PPIG = [1.0/(np.sqrt(np.pi/2)-np.exp(-6.0)+XX[i]-calculate_xmin(XX[i],AA[i])) for i in range(Ncurv)] PPIG = [ 1.0 / (np.sqrt(np.pi / 2) - np.exp(-6.0) + XX[i] - 0.0) for i in range(Ncurv) ] else: ## Needs update! raise AttributeError, me + "no can do." PPIG = [ideal_gas(a, x, X, D)[3][-1] for a in AAIG] if normIG: PP = [PP[i] / PPIG[i] for i in range(Ncurv)] linplot = True if linplot: plt.plot(AA[0], np.power(1 / (AA[0] + 1), 0.5), "b:", label="$(\\alpha+1)^{-1/2}$", linewidth=2) plt.xlim(left=0.0, right=max(chain.from_iterable(AA))) plt.ylim(bottom=0.0, top=1.1) xlabel = "$\\alpha$" else: plt.plot(1.0 + AA[0], np.sqrt(1 / (AA[0] + 1)), "b:", label="$(\\alpha+1)^{-1/2}$", linewidth=2) plt.xscale("log") plt.yscale("log") plt.xlim(left=1.0, right=1.0 + max(chain.from_iterable(AA))) xlabel = "$\\alpha+1$" pressplot = pressplot[:-4] + "_log.png" ## Data if ftype == "const": PP[4][2] += 0.01 PP[4][3] -= 0.01 PP[4][7] -= 0.02 PP[4][10] -= 0.02 PP[4][13] -= 0.02 for i in range(Ncurv): if linplot: plt.plot(AA[i], PP[i], 'o-', label=labels[i]) else: plt.plot(1.0 + AA[i], PP[i], 'o-', label=labels[i]) if not normIG: plt.axhline(PressIG[i], color=plt.gca().lines[-1].get_color(), linestyle="--") #plt.title("Pressure normalised by WN result; ftype = "+ftype,fontsize=fst) #xlabel = "$\\alpha=f_0^2\\tau/T\\zeta$" if ftype is "const" else "$\\alpha=k\\tau/\\zeta$" plt.xlabel(xlabel, fontsize=fsa) plt.ylabel("Pressure", fontsize=fsa) plt.grid() plt.legend(loc="best", fontsize=fsl) ## 2D else: pressplot = pressplot[:-4] + "_2.png" ## IMSHOW ## Normalise Press by WN value Pim = [Press * (1.0 + 0.1 * X) if normIG else Press] ## Restructure dara, assuming sorted by alpha value Aim = np.unique(Alpha) ## Create 2D array of pressures ## There must be a nicer way of doing this Xim = np.unique(X) Pim = -np.ones((Xim.shape[0], Aim.shape[0])) PIGim = -np.ones((Xim.shape[0], Aim.shape[0])) for k in range(Press.shape[0]): for i in range(Xim.shape[0]): for j in range(Aim.shape[0]): if Aim[j] == Alpha[k] and Xim[i] == X[k]: Pim[i, j] = Press[k] PIGim[i, j] = 1.0 / (1.0 - np.exp(-4.0) + Xim[i] - calculate_xini(Xim[i], Aim[j])) ## Mask zeros Pim = np.ma.array(Pim, mask=Pim < 0.0) PIGim = np.ma.array(PIGim, mask=PIGim < 0.0) ## Normalise by WN reasult if normIG: Pim /= PIGim ## Make plot im = plt.imshow(Pim[::-1], aspect='auto', extent=[Aim[0], Aim[-1], Xim[0], Xim[-1]], interpolation="none") # ## CONTOUR # ## Messily normalise by WN result # Pmesh = Press * (1.0+0.1*X) # ## Create coordinate mesh # Amesh,Xmesh = np.meshgrid(Alpha,X) # Pmesh = np.empty(Xmesh.shape) # ## Messily create corresponding pressure mesh # mask = [] # for k in range(Press.shape[0]): # for i in range(Xmesh.shape[0]): # for j in range(Xmesh.shape[1]): # if Amesh[i,j]==Alpha[k] and Xmesh[i,j]==X[k]: # Pmesh[i,j]=Press[k] # ## Plot using contours # plt.contour(Amesh,Xmesh,Pmesh,5) ## ACCOUTREMENTS plt.title("Pressure normalised by WN result", fontsize=fst) xlabel = "$\\alpha=f_0^2\\tau/T\\zeta$" if ftype is "const" else "$\\alpha=k\\tau/\\zeta$" plt.xlabel(xlabel, fontsize=fsa) plt.ylabel("Wall separation", fontsize=fsa) plt.grid(False) # ticks = np.array([0.0,1.0,Pim.min(),Pim.mean(),Pim.max()]) # tckidx = np.argsort(ticks) # ticks = ticks[tckidx] # ticklabels = np.array(["0","1","Low", "Mean", "High"])[tckidx] # cbar = plt.colorbar(im, ticks=ticks, orientation="vertical") # cbar.ax.set_yticklabels(ticklabels, fontsize=fsl) # cbar = plt.colorbar(im, ticks=[Pim.min(),Pim.mean(),Pim.max()], orientation="vertical") # cbar.ax.set_yticklabels(["Low", "Mean", "High"], fontsize=fsl) cbar = plt.colorbar(im, orientation="vertical") ## -------------------------------------------------------- if not nosave: plt.savefig(pressplot) if verbose: print me + "plot saved to", pressplot return pressplot
def calc_pressure_dir(dirpath, srchstr, noread, vb): """ Plot pressure at "infinity" against alpha for all files in directory. """ me = me0+".calc_pressure_dir: " t0 = time() ## Directory parameters dirpars = filename_pars(dirpath) ftype, geo = dirpars["ftype"], dirpars["geo"] ## File discovery histfiles = np.sort(glob.glob(dirpath+"/BHIS_POL_*"+srchstr+"*.npy")+glob.glob(dirpath+"/BHIS_CIR_*"+srchstr+"*.npy")) numfiles = len(histfiles) if vb: print me+"found",numfiles,"files" ## Initialise A = np.zeros(numfiles) R = np.zeros(numfiles) ## Outer radii S = np.zeros(numfiles) ## Inner radii L = np.zeros(numfiles) ## Size of wall when finite N = np.zeros(numfiles) ## Wall strength parameter P = np.zeros(numfiles) ## Pressures on outer wall Q = np.zeros(numfiles) ## Pressures on inner wall P_WN = np.zeros(numfiles) Q_WN = np.zeros(numfiles) t0 = time() ## Loop over files for i,histfile in enumerate(histfiles): ## Get pars from filename pars = filename_pars(histfile) [A[i],R[i],S[i],L[i],N[i]] = [pars[key] for key in ["a","R","S","lam","nu"]] fpars = [R[i],S[i],L[i],N[i]] ## Space (for axes) bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") rbins = bins["rbins"] rmax = rbins[-1] r = 0.5*(rbins[1:]+rbins[:-1]) erbins = bins["erbins"] er = 0.5*(erbins[1:]+erbins[:-1]) ## Start point for computing pressures bidx = np.argmin(np.abs(r-0.5*(max(rbins[0],S[i])+R[i]))) ## Load histogram, normalise H = np.load(histfile) try: H = H.sum(axis=2) except ValueError: pass H = np.trapz(H, x=er, axis=1) ## Noise dimension irrelevant here; convert to *pdf* rho = H/(2*np.pi*r) / np.trapz(H, x=r, axis=0) rho_WN = pdf_WN(r,fpars,ftype) ## Pressure array P[i] = calc_pressure(r[bidx:],rho[bidx:],ftype,fpars) P_WN[i] = calc_pressure(r[bidx:],rho_WN[bidx:],ftype,fpars) if ftype[0] is "d": ## Inner pressure Q[i] = -calc_pressure(r[:bidx],rho[:bidx],ftype,fpars) Q_WN[i] = -calc_pressure(r[:bidx],rho_WN[:bidx],ftype,fpars) if vb: print me+"Pressure calculations %.1f seconds."%(time()-t0) ## ------------------------------------------------ ## Create 2D pressure array and 1D a,R coordinate arrays ## Ordered independent variable arrays AA = np.unique(A) RR = np.unique(R) SS = np.unique(S) LL = np.unique(L) NN = np.unique(N) ## 2D pressure array: [R,A] if (ftype[0] != "d" and ftype[-3:] != "tan" and ftype[-2:] != "nu"): PP = -np.ones([RR.size,AA.size]) PP_WN = np.zeros(PP.shape) QQ, QQ_WN = np.zeros(PP.shape), np.zeros(PP.shape) for i in range(RR.size): Ridx = (R==RR[i]) for j in range(AA.size): Aidx = (A==AA[j]) Pidx = Ridx*Aidx try: PP[i,j] = P[Pidx] PP_WN[i,j] = P_WN[Pidx] except ValueError: ## No value there pass ## 3D pressure array: [S,R,A] elif (ftype[0] == "d" and ftype[-3:] != "tan" and ftype[-2:] != "nu"): PP = -np.ones([SS.size,RR.size,AA.size]) QQ = -np.ones([SS.size,RR.size,AA.size]) PP_WN = np.zeros(PP.shape) QQ_WN = np.zeros(QQ.shape) for i in range(SS.size): Sidx = (S==SS[i]) for j in range(RR.size): Ridx = (R==RR[j]) for k in range(AA.size): Aidx = (A==AA[k]) Pidx = Sidx*Ridx*Aidx try: PP[i,j,k] = P[Pidx] QQ[i,j,k] = Q[Pidx] PP_WN[i,j,k] = P_WN[Pidx] QQ_WN[i,j,k] = Q_WN[Pidx] except ValueError: ## No value there pass ## 3D pressure array for TAN force: [L,R,A] elif ftype == "tan": PP = -np.ones([LL.size,RR.size,AA.size]) QQ = -np.ones([LL.size,RR.size,AA.size]) PP_WN = np.zeros(PP.shape) QQ_WN = np.zeros(QQ.shape) for i in range(LL.size): Lidx = (L==LL[i]) for j in range(RR.size): Ridx = (R==RR[j]) for k in range(AA.size): Aidx = (A==AA[k]) Pidx = Lidx*Ridx*Aidx try: PP[i,j,k] = P[Pidx] QQ[i,j,k] = Q[Pidx] PP_WN[i,j,k] = P_WN[Pidx] QQ_WN[i,j,k] = Q_WN[Pidx] except ValueError: ## No value there pass ## 4D pressure array for TAN force: [L,R,S,A] elif ftype == "dtan": PP = -np.ones([LL.size,RR.size,SS.size,AA.size]) QQ = -np.ones([LL.size,RR.size,SS.size,AA.size]) PP_WN = np.zeros(PP.shape) QQ_WN = np.zeros(QQ.shape) for i in range(LL.size): Lidx = (L==LL[i]) for j in range(RR.size): Ridx = (R==RR[j]) for k in range(SS.size): Sidx = (S==SS[k]) for l in range(AA.size): Aidx = (A==AA[l]) Pidx = Lidx*Ridx*Sidx*Aidx try: PP[i,j,k,l] = P[Pidx] QQ[i,j,k,l] = Q[Pidx] PP_WN[i,j,k,l] = P_WN[Pidx] QQ_WN[i,j,k,l] = Q_WN[Pidx] except ValueError: ## No value there pass ## 3D pressure array for NU force: [N,L,A] ## Assume all R equal elif ftype == "nu": PP = -np.ones([NN.size,LL.size,AA.size]) QQ = -np.ones([NN.size,LL.size,AA.size]) PP_WN = np.zeros(PP.shape) QQ_WN = np.zeros(QQ.shape) for i in range(NN.size): Nidx = (N==NN[i]) for j in range(LL.size): Lidx = (L==LL[j]) for k in range(AA.size): Aidx = (A==AA[k]) Pidx = Nidx*Lidx*Aidx try: PP[i,j,k] = P[Pidx] PP_WN[i,j,k] = P_WN[Pidx] except ValueError: ## No value there pass ## 4D pressure array for DNU force: [N,L,R,A] ## Assume all N equal elif ftype == "dnu": PP = -np.ones([NN.size,LL.size,RR.size,AA.size]) QQ = -np.ones([NN.size,LL.size,RR.size,AA.size]) PP_WN = np.zeros(PP.shape) QQ_WN = np.zeros(QQ.shape) for i in range(NN.size): Nidx = (N==NN[i]) for j in range(LL.size): Lidx = (L==LL[j]) for k in range(RR.size): Ridx = (R==RR[k]) for l in range(AA.size): Aidx = (A==AA[l]) Pidx = Nidx*Lidx*Ridx*Aidx try: PP[i,j,k,l] = P[Pidx] QQ[i,j,k,l] = Q[Pidx] PP_WN[i,j,k,l] = P_WN[Pidx] QQ_WN[i,j,k,l] = Q_WN[Pidx] except ValueError: ## No value there pass # ## Mask zeros # mask = (PP==0.0)+(PP==-1.0) # PP_WN = np.ma.array(PP_WN, mask=mask) # QQ_WN = np.ma.array(QQ_WN, mask=mask) # PP = np.ma.array(PP, mask=mask) # QQ = np.ma.array(QQ, mask=mask) ## SAVING if not noread: pressfile = dirpath+"/PRESS.npz" np.savez(pressfile, PP=PP, QQ=QQ, PP_WN=PP_WN, QQ_WN=QQ_WN, AA=AA, RR=RR, SS=SS, LL=LL, NN=NN) if vb: print me+"Calculations saved to",pressfile return {"PP":PP, "QQ":QQ, "PP_WN":PP_WN, "QQ_WN":QQ_WN, "AA":AA, "RR":RR, "SS":SS, "LL":LL, "NN":NN}
def plot_pressure_dir(dirpath, srchstr, logplot, nosave, noread, vb): """ Plot some slice of pressure array. """ me = me0+".plot_pressure_dir: " try: assert noread == False pressdata = np.load(dirpath+"/PRESS.npz") print me+"Pressure data file found:",dirpath+"/PRESS.npz" except (IOError, AssertionError): print me+"No pressure data found. Calculating from histfiles." pressdata = calc_pressure_dir(dirpath, srchstr, noread, vb) ftype = filename_pars(dirpath)["ftype"] PP = pressdata["PP"] QQ = pressdata["QQ"] PP_WN = pressdata["PP_WN"] QQ_WN = pressdata["QQ_WN"] AA = pressdata["AA"] RR = pressdata["RR"] SS = pressdata["SS"] LL = pressdata["LL"] NN = pressdata["NN"] del pressdata ## ------------------------------------------------ ## Mask zeros mask = (PP==-1.0) PP_WN = np.ma.array(PP_WN, mask=mask) QQ_WN = np.ma.array(QQ_WN, mask=mask) PP = np.ma.array(PP, mask=mask) QQ = np.ma.array(QQ, mask=mask) ## ------------------------------------------------ ## PLOTS t0 = time() fig, ax = plt.subplots(1,1, figsize=fs["figsize"]) ## Default labels etc. PP /= PP_WN + 1*(PP_WN==0.0) if ftype[0] is "d": QQ /= QQ_WN + 1*(QQ_WN==0.0) title = "Pressure normalised by WN; ftype = "+ftype plotfile = dirpath+"/PAR" ylabel = "Pressure (normalised)" xlabel = "$\\alpha$" xlim = [AA[0],AA[-1]] DPplot = False ## ------------------------------------------------ ## Plot pressure ## E2 prediction # if ftype == "lin": # plt.plot(AA,np.power(AA+1.0,-0.5),"b:",label=r"$(\alpha+1)^{-1/2}$",lw=2) ## Disc; non-finite ## Plot pressure against alpha for R or for S # if ((ftype[0]!="d" and SS.sum()!=0.0) or (ftype[0]=="d" and SS.sum()==0.0) and ftype[-3:]!="tan" and ftype[-2:]!="nu"): if SS.sum()==0.0: ## In case run with DL but S=0 for all files, will need to restructure array if SS.all()==0.0: PP=PP[0] ## Shunt on the a=0 values if 0.0 not in AA: AA = np.hstack([0.0,AA]) PP = np.vstack([np.ones(RR.size),PP.T]).T xlim = [AA[0],AA[-1]] ## PLOTTING ## Plot against ALPHA if 0: for i in range(RR.size): ax.plot(AA,PP[i,:], "o-", label=r"$R = "+str(RR[i])+"$") ## Plot against R else: plotfile = dirpath+"PRA" for i in range(AA.size): ax.plot(RR,PP[:,i], "o-", label=r"$\alpha = %.1f$"%(AA[i])) xlim = [RR[0],RR[-1]] ax.xaxis.set_major_locator(MaxNLocator(3)) xlabel = r"$R$" ## ------------------------------------------------ ## ## Annulus; finite; [S,R,A] elif (ftype[0] == "d" and ftype[-3:] != "tan" and ftype[-2:] != "nu"): QQ, QQ_WN = np.nan_to_num(QQ), np.nan_to_num(QQ_WN) ## Holding R fixed if RR.size == 1: if 1: ## Plot normalised Pout and Pin individually against ALPHA title = "Pressure normalised by WN, $R = "+str(RR[0])+"$; ftype = "+ftype plotfile = dirpath+"/PQAS" xlabel = r"$1+\alpha$" if logplot else r"$\alpha$" xlim = (int(logplot), int(logplot)+AA[-1]) ## Shunt on the a=0 values if 0.0 not in AA: AA = np.hstack([0.0,AA]) PP = np.dstack([np.ones([SS.size,RR.size]),PP]) QQ = np.dstack([np.ones([SS.size,RR.size]),QQ]) for i in range(SS.size): ax.plot(int(logplot)+AA,PP[i,0,:], "o-", label="$S = "+str(SS[i])+"$") ax.plot(int(logplot)+AA,QQ[i,0,:], "v--", color=ax.lines[-1].get_color()) elif 0: ## Plot normalised Pout and Pin individually against S, for multiple ALPHA title = "Pressures $P_R,P_S$ (normalised); $R = "+str(RR[0])+"$; ftype = "+ftype plotfile = dirpath+"/PQSA" xlabel = r"$S$" xlim = [SS[0],SS[-1]] ## Shunt on the a=0 values if 0.0 not in AA: AA = np.hstack([0.0,AA]) PP = np.dstack([np.ones([SS.size,RR.size]),PP]) QQ = np.dstack([np.ones([SS.size,RR.size]),QQ]) ## Avoid plotting QQ for S=0 point idx = 1 if 0.0 in SS else 0 for i in range(0,AA.size,1): ax.plot(SS,PP[:,0,i], "o-", label=r"$\alpha = "+str(AA[i])+"$") ax.plot(SS[idx:],QQ[idx:,0,i], "v--", color=ax.lines[-1].get_color()) elif 1: ## Plot difference Pout-Pin against ALPHA, for multiple S DPplot = True PP *= PP_WN; QQ *= QQ_WN title = r"Pressure difference, $(P_R-P_S)/P_R^{\rm wn}$; $R = "+str(RR[0])+"$; ftype = "+ftype ylabel = "Pressure Difference (normalised)" xlabel = r"$\alpha$" xlim = [0.0, AA[-1]] plotfile = dirpath+"/DPAS" ## Messy shunting a=0 onto the plot because PP,QQ too complicated to modify directly if 0.0 not in AA and not logplot: DP_WN = ((PP_WN-QQ_WN)/(PP_WN))[:,0,:] ## Data for the a=0 point for i in range(SS.size): ax.plot(np.hstack([0.0,AA]),np.hstack([DP_WN[i,0],((PP-QQ)/(PP_WN))[i,0,:]]), "o-", label="$S = "+str(SS[i])+"$") else: for i in range(SS.size): ax.plot(AA,((PP-QQ)/(PP_WN))[i,0,:], "o-", label="$S = "+str(SS[i])+"$") else: ## Plot difference Pout-Pin against S DPplot = True PP *= PP_WN; QQ *= QQ_WN title = r"Pressure difference, $(P_R-P_S)/P_R^{\rm wn}$; $R = "+str(RR[0])+"$; ftype = "+ftype plotfile = dirpath+"/DPSA" xlim = [SS[0],SS[-1]] xlabel = r"$S$" ylabel = "Pressure Difference (normalised)" for i in range(0,AA.size,1): ax.plot(SS,(PP-QQ)[:,0,i]/(PP_WN)[:,0,i], "o-", label=r"$\alpha = "+str(AA[i])+"$") ## Constant interval elif np.unique(RR-SS).size == 1: if 0: ## Plot Pout and Pin individually against R title = "Pressures $P_R,P_S$ (normalised); $R-S = "+str((RR-SS)[0])+"$; ftype = "+ftype plotfile = dirpath+"/PQRA" xlabel = r"$R\;(=S+%.1f)$"%((RR-SS)[0]) if (RR-SS)[0]>0.0 else r"$R$" xlim = [RR[0],RR[-1]] for i in range(0,AA.size,1): ## To plot against R ax.plot(RR,np.diagonal(PP).T[:,i], "o-", label=r"$\alpha = "+str(AA[i])+"$") ax.plot(RR,np.diagonal(QQ).T[:,i], "v--", color=ax.lines[-1].get_color()) elif 1: ## Plot difference Pout-Pin against ALPHA, for multiple S DPplot = True PP *= PP_WN; QQ *= QQ_WN if AA[0]==0.0 and logplot: AA = AA[1:]; PP = PP[:,:,1:]; QQ = QQ[:,:,1:]; PP_WN = PP_WN[:,:,1:] title = r"Pressure difference, $(P_R-P_S)/P_R^{\rm wn}$; $R-S = "+str((RR-SS)[0])+"$; ftype = "+ftype ylabel = "Pressure Difference (normalised)" legloc = "upper right"#(0.25,0.54) plotfile = dirpath+"/DPAS" # ## Advance colour cycle for consistent colour between diffrent R-S plots # [ax.plot([],[]) for i in range(np.sum([Ri not in RR for Ri in [0.0,1.0,2.0,5.0]])-1)] ## Messy shunting a=0 onto the plot because PP,QQ too complicated to modify directly if 0.0 not in AA and not logplot: if vb: print me+"Adding alpha=0 points." DP_WN = np.diagonal((PP_WN-QQ_WN)/(PP_WN)).T ## To plot the a=0 point for i in range(SS.size): ax.plot(np.hstack([0.0,AA]),np.hstack([DP_WN[i,0],np.diagonal((PP-QQ)/(PP_WN)).T[i,:]]), "o-", label="$R = "+str(RR[i])+"$") xlim[0]=0.0 else: for i in range(SS.size): ax.plot(AA,np.diagonal((PP-QQ)/(PP_WN)).T[i,:], "o-", label="$R = "+str(RR[i])+"$") ## POTENTIAL INSET left, bottom, width, height = [0.53, 0.39, 0.33, 0.30] if np.unique(RR-SS) == 0 else [0.52, 0.43, 0.33, 0.31] axin = fig.add_axes([left, bottom, width, height], projection="3d") Rschem, Sschem = (1.7,1.7) if np.unique(RR-SS) == 0 else (5,1.7) plot_U3D_polar(axin, Rschem, Sschem) axin.patch.set_alpha(0.3) elif 0: ## Plot difference Pout-Pin against R DPplot = True PP *= PP_WN; QQ *= QQ_WN if AA[0]==0.0: AA = AA[1:]; PP = PP[:,:,1:]; QQ = QQ[:,:,1:]; PP_WN = PP_WN[:,:,1:] title = r"Pressure difference, $(P_R-P_S)/P_R^{\rm wn}$; $R-S = "+str((RR-SS)[0])+"$; ftype = "+ftype ylabel = "Pressure Difference (normalised)" plotfile = dirpath+"/DPRA" xlabel = r"$R\;(=S+%.1f)$"%((RR-SS)[0]) if (RR-SS)[0]>0.0 else r"$R$" xlim = [RR[0],RR[-1]] for i in range(0,AA.size,1): ## To plot against R ax.plot(RR,np.diagonal((PP-QQ)/(PP_WN)).T[:,i], "o-", label=r"$\alpha = "+str(AA[i])+"$") if logplot: RRR = np.linspace(1,RR[-1],10) ax.plot(RRR,2/(RRR),"k:",lw=3,label=r"$2R^{-1}$") # ax.set_color_cycle(None) # for i in range(0,AA.size,1): # ax.plot(RR,2/(RR)*(AA[i]/(AA[i]+1))*(1+0.5*np.unique(RR-SS)/RR*np.sqrt(AA[i]/(AA[i]+1))),":",lw=3) ax.set_ylim(1e-3,1e1) xlim = [1.0,RR[-1]] ## POTENTIAL INSET left, bottom, width, height = [0.51, 0.58, 0.35, 0.31] ## For upper right # left, bottom, width, height = [0.13, 0.14, 0.35, 0.31] ## For lower left axin = fig.add_axes([left, bottom, width, height], projection="3d") Rschem, Sschem = (1.7,1.7) if np.unique(RR-SS) == 0 else (5,1.7) plot_U3D_polar(axin, Rschem, Sschem) axin.patch.set_alpha(0.3) else: ## SHURA REQUEST Plot difference (Pout-Pin)/(PE2*sqrt(a)) against R DPplot = True PP *= PP_WN; QQ *= QQ_WN ylabel = r"Pressure Difference (normalised)" plotfile = dirpath+"/DPRA_AG" xlabel = r"$R\;(=S+%.1f)$"%((RR-SS)[0]) if (RR-SS)[0]>0.0 else r"$R$" xlim = [RR[0],RR[-1]] PP_E2 = 1/np.sqrt(1+AA)[:,np.newaxis]/(2*np.pi*RR) ## /R for 2D for i in range(0,AA.size,1): ## To plot against R ## Normalise by PEN # ax.plot(RR,np.diagonal(PP-QQ).T[:,i]/np.diagonal(PP_WN).T[:,i]/np.sqrt(AA[i]), "o-", label=r"$\alpha = "+str(AA[i])+"$") ## Normalise by PE2 ax.plot(RR,np.diagonal(PP-QQ).T[:,i]/PP_E2[i]/np.sqrt(AA[i]), "o-", label=r"$"+str(AA[i])+"$") ## Normalise by Pout # ax.plot(RR,np.diagonal(1-QQ/PP).T[:,i], "o-", label=r"$\alpha = "+str(AA[i])+"$") ## Individual # ax.plot(RR,np.diagonal(PP/PP_WN).T[:,i],"o-", label=r"$\alpha = "+str(AA[i])+"$") # ax.plot(RR,np.diagonal(QQ/QQ_WN).T[:,i],"o--", color=ax.lines[-1].get_color()) # ax.plot(RR,PP_E2[i,:]/np.diagonal(PP_WN).T[:,i],"o:", color=ax.lines[-1].get_color()) ## if logplot: RRR = np.linspace(1,RR[-1],10) ax.plot(RRR,1/(RRR),"k:",lw=3,label=r"$R^{-1}$") # ax.set_ylim(1e-5,1e0) xlim = [1.0,RR[-1]] fig.subplots_adjust(left=0.15) ## POTENTIAL INSET left, bottom, width, height = [0.51, 0.60, 0.35, 0.31] ## For upper right # left, bottom, width, height = [0.13, 0.14, 0.35, 0.31] ## For lower left axin = fig.add_axes([left, bottom, width, height], projection="3d") Rschem, Sschem = (1.7,1.7) if np.unique(RR-SS) == 0 else (5,1.7) plot_U3D_polar(axin, Rschem, Sschem) axin.patch.set_alpha(0.3) axin.patch.set_facecolor("None") ## ------------------------------------------------ ## Single circus; TAN elif ftype == "tan": plotfile = dirpath+"/PAL" title = "Pressure normalised by WN, $R = "+str(RR[0])+"$; ftype = "+ftype for i in range(LL.size): ax.plot(AA,PP[i,0,:], "o-", label="$\\lambda = "+str(LL[i])+"$") ## Double circus; DTAN elif (ftype == "dtan"): ## Dodgy points ax.axvspan(0.0,0.2,color="r",alpha=0.1) ## P[L,R,S,A] plotbool = [0,0,1,1] ## R,S fixed if plotbool[0]: if vb: print me+"Plotting P_R and P_S against alpha for different values of lambda. R and S fixed." Ridx = 1 Sidx = np.where(SS==RR[Ridx]-1.0)[0][0] plotfile = dirpath+"/PAL" title = "Pressure normalised by WN, $R = "+str(RR[Ridx])+"$, $S = "+str(SS[Sidx])+"$; ftype = "+ftype for i in range(LL.size): ax.plot(AA[1:],PP[i,Ridx,Sidx,1:], "o-", label="$\\lambda = "+str(LL[i])+"$") ax.plot(AA[1:],QQ[i,Ridx,Sidx,1:], "o--", color=ax.lines[-1].get_color()) ## lam fixed; R-S fixed elif plotbool[1]: if vb: print me+"Plotting P_R and P_S against alpha for different values of R. lambda is fixed." Lidx = 0 plotfile = dirpath+"/PAR" title = "Pressure normalised by WN, $\\lambda = "+str(LL[0])+"$; ftype = "+ftype for i in range(RR.size): Sidx = np.where(SS==RR[i]-1.0)[0][0] ax.plot(AA[1:],PP[0,i,Sidx,1:], "o-", label="$R,S = "+str(RR[i])+", "+str(SS[Sidx])+"$") ax.plot(AA[1:],QQ[0,i,Sidx,1:], "o--", color=ax.lines[-1].get_color()) ## Difference in pressure; R,S fixed elif plotbool[2]: DPplot = True if vb: print me+"Plotting P_R-P_S against alpha for different values of lambda. R-S fixed." PP *= PP_WN; QQ *= QQ_WN DP = PP-QQ ## Find S indices corresponding to R-1.0 Ridx = range(RR.size) Sidx = [np.where(SS==RR[Ridx[i]]-1.0)[0][0] for i in range(len(Ridx))] plotfile = dirpath+"/DPALDR" title = "Pressure difference, $P_R-P_S$; $R-S = "+str(RR[Ridx[0]]-SS[Sidx[0]])+"$; ftype = "+ftype for i in range(LL.size): ax.plot(AA[1:],DP[i,Ridx[0],Sidx[0],1:], "o-", label="$\\lambda = "+str(LL[i])+"$. $R,S = "+str(RR[Ridx[0]])+", "+str(SS[Sidx[0]])+"$") ax.plot(AA[1:],DP[i,Ridx[1],Sidx[1],1:], "o--", color=ax.lines[-1].get_color(), label="$\\lambda = "+str(LL[i])+"$. $R,S = "+str(RR[Ridx[1]])+", "+str(SS[Sidx[1]])+"$") ax.plot(AA[1:],DP[i,Ridx[2],Sidx[2],1:], "o:", color=ax.lines[-1].get_color(), label="$\\lambda = "+str(LL[i])+"$. $R,S = "+str(RR[Ridx[2]])+", "+str(SS[Sidx[2]])+"$") elif plotbool[3]: print me+"ABORT"; exit() DPplot = True if vb: print me+"Plotting P_R-P_S against R for single value of lambda and several alpha. R-S fixed." DP = PP*PP_WN-QQ*QQ_WN ## Fix lambda index Lidx = 1 plotfile = dirpath+"/DPRA" title = "Pressure difference, $P_R-P_S$; $R-S = "+str(RR[Ridx[0]]-SS[Sidx[0]])+"$; ftype = "+ftype for i in range(0,AA.size,2): ## To plot against S ax.plot(SS,DP[Lidx,Ridx,Sidx,i], "o-", label="$\\alpha = "+str(AA[i])+"$") xlabel = "$S\\;(=R-"+str((RR-SS)[0])+")$"; ylabel = "Pressure Difference"; xlim = (SS[0],SS[-1]) ## Disc; NU elif ftype == "nu": ## All R equal; plot against a; large and small l """ plotfile = dirpath+"/PALN" title = "Pressure normalised by WN, $R = "+str(RR[0])+"$; ftype = "+ftype for i in range(LL.size): ax.plot(AA,PP[0,i,:], "o-", label="$\\lambda, \\nu = "+str(LL[i])+", "+str(NN[0]) +"$") ax.plot(AA,PP[-1,i,:], "o--", color=ax.lines[-1].get_color(), label="$\\lambda, \\nu = "+str(LL[i])+", "+str(NN[-1])+"$") """ ## All R equal; plot against nu; assume same L; [N,L,A] plotfile = dirpath+"/PNA" title = "Pressure normalised by WN, $R = "+str(RR[0])+"$; ftype = "+ftype+"; $\\lambda = "+str(LL[0])+"$" fitfunc = lambda NN, M, b: M*np.power(NN, b) for i in range(AA.size): print curve_fit(fitfunc, NN[1:], np.nan_to_num(PP[1:,0,i]))[0] ax.plot(NN,PP[:,0,i], "o-", label="$\\alpha = "+str(AA[i])+"$") xlabel = "$\\nu$"; xlim = (NN[0],NN[-1]) ## Annulus DNU [N,L,R,A] elif (ftype == "dnu"): ## Pressure difference as function of R. Assume nu and lam equal. if (np.unique(RR-SS).size == 1 and PP.shape[0]==1 and PP.shape[1]==1): PP = PP[0,0]; QQ = QQ[0,0]; PP_WN = PP_WN[0,0]; QQ_WN = QQ_WN[0,0] if 0: ## Plot individually title = "Pressures $P_R,P_S$ (normalised); $R-S = "+str((RR-SS)[0])+"$; ftype = "+ftype plotfile = dirpath+"/PQRA" xlabel = "$R\\;(=S+"+str((RR-SS)[0])+")$"; xlim = (RR[0],RR[-1]) for i in range(0,AA.size,1): ## To plot against R ax.plot(RR[:],PP[:,i], "o-", label="$\\alpha = "+str(AA[i])+"$") ax.plot(RR[1:],QQ[1:,i], "v--", color=ax.lines[-1].get_color()) # if logplot: # ax.plot(RR,0.01/(RR),"k:",lw=3) else: ## Plot difference DPplot = True PP *= PP_WN; QQ *= QQ_WN plotfile = dirpath+"/DPRA" title = "Pressure difference, $P_R-P_S$; $R-S = "+str((RR-SS)[0])+"$; ftype = "+ftype xlabel = "$R\\;(=S+"+str((RR-SS)[0])+")$"; ylabel = "Pressure Difference" xlim = (RR[0],RR[-1]) for i in range(0,AA.size,1): ax.plot(RR,np.abs(PP-QQ)[:,i], "o-", label="$\\alpha = "+str(AA[i])+"$") # ax.plot(RR,np.abs(PP_WN-QQ_WN)[:,i], "--", color=ax.lines[-1].get_color()) if logplot: ax.plot(RR,0.1/(RR),"k:",lw=3) ax.plot(RR,0.1/(RR*RR),"k:",lw=3,label="$R^{-1}, R^{-2}$") else: raise IOError, me+"Check functionality for this plot exists." ## ------------------------------------------------ ## Accoutrements if logplot: ax.set_xscale("log"); ax.set_yscale("log") ax.set_xlim(left=(xlim[0] if xlim[0]!=0.0 else ax.get_xlim()[0]), right=xlim[1]) plotfile = plotfile+"_loglog" elif not (logplot or DPplot): ax.set_xlim(xlim) ax.set_ylim(bottom=0.0, top=max(ax.get_ylim()[1],1.0)) else: ax.set_xlim(xlim) ## AD HOC if not logplot: ax.set_ylim(bottom=0.0) ax.set_ylim(top=1.4) # ax.set_ylim(1e-3,1e1) ax.set_xlabel(xlabel,fontsize=fs["fsa"]) ax.set_ylabel(ylabel,fontsize=fs["fsa"]) ax.grid() try: leg = ax.legend(loc=legloc,fontsize=fs["fsl"]-2, ncol=2) except UnboundLocalError: leg = ax.legend(loc="best",fontsize=fs["fsl"], ncol=2) leg.get_frame().set_alpha(0.5) leg.set_title(r"${k\tau}/{\zeta}$", prop={"size":fs["fsl"]}) # fig.suptitle(title,fontsize=fs["fst"]) #plt.tight_layout(); plt.subplots_adjust(top=0.9) if not nosave: fig.savefig(plotfile+"."+fs["saveext"]) if vb: print me+"plot saved to",plotfile+"."+fs["saveext"] if vb: print me+"Plotting %.2f seconds."%(time()-t0) return
def pressure_pdf_plot_file(histfile, verbose): """ Make plot for a single file """ me = "LE_Pressure.pressure_pdf_plot_file: " t0 = sysT() ## Filenames plotfile = os.path.dirname(histfile)+"/PDFP"+os.path.basename(histfile)[4:-4]+".png" ## Get pars from filename pars = filename_pars(histfile) [alpha,X,D,dt,ymax,R] = [pars[key] for key in ["a","X","D","dt","ymax","R"]] assert (R is not None), me+"You are using the wrong program. R should be defined." assert (D == 0.0), me+"Cannot yet handle soft potential. D should be 0.0." if verbose: print me+"alpha =",alpha,"and X =",X,"and D =",D ## Load data and normalise H = np.load(histfile) H /= H.sum() ## Centre of circle for curved boundary c = circle_centre(X,R,ymax) ## Space (for axes) try: bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] ybins = bins["ybins"] xini = xbins[0] xmax = xbins[-1] except (IOError, KeyError): xini = calculate_xini(X,alpha) xmax = lookup_xmax(c[0]+R,alpha) xbins = calculate_xbin(xini,X,xmax,H.shape[1]) ybins = calculate_ybin(0.0,ymax,H.shape[0]+1) x = 0.5*(xbins[1:]+xbins[:-1]) y = 0.5*(ybins[1:]+ybins[:-1]) ## Set up plot fig,axs = plt.subplots(1,2) ## pdf plot ax = axs[0] H[:,0]=H[:,1] Xm,Ym = np.meshgrid(x,y) CS = ax.contourf(Xm,Ym[::-1],H,10) ## Colourbar divider = make_axes_locatable(ax) cax = divider.append_axes("top", size="5%", pad=0.4) cbar = fig.colorbar(CS, cax=cax, ax=ax, orientation="horizontal", use_gridspec=True, ticks=[H.min(),H.mean(),H.max()]) cbar.ax.set_xticklabels(["Low", "Mean", "High"]) ### http://stackoverflow.com/questions/13310594/positioning-the-colorbar ## Plot curved wall wallx = np.linspace(X,c[0]+R,201) wally = c[1]+np.sqrt(R*R-(wallx-c[0])**2) ax.plot(wallx,wally, "r--",linewidth=2) ## Accoutrements ax.set_xlim([xini,xmax]) ax.set_ylim([0.0,ymax]) ax.set_xlabel("$x$", fontsize=fsa) ax.set_ylabel("$y$", fontsize=fsa) ## Calculate force array (2d) force = -1.0 * ( (Xm-c[0])**2 + (Ym-c[1])**2 > R*R ) * ( Xm-c[0]>0.0 ) ## Pressure array (2d) -- sum rather than trapz press = -1.0*(force*H).sum(axis=0).cumsum(axis=0) ## Pressure plot ax = axs[1] ax.plot(x,press,label="CN simulation") ## Bulk and wall regions ax.axvspan(xini,X, color="b",alpha=0.1) ax.axvspan(X,c[0]+R, color="m",alpha=0.05) ax.axvspan(R,xmax, color="r",alpha=0.05) ## Ideal gas result ax.hlines(pressure_IG(X,R,ymax,alpha),xini,xmax,linestyle="-",color="g",label="WN theory") ax.hlines(0.5/ymax/(1.0+X-xini),xini,xmax,linestyle="--",color="g",label="WN flat theory") ## Accoutrements ax.set_xlim([xini,xmax]) ax.set_xlabel("$x$", fontsize=fsa) ax.set_ylabel("Pressure", fontsize=fsa) ax.grid() ax.legend(loc="best",fontsize=fsl) ## Tidy figure fig.suptitle(os.path.basename(plotfile),fontsize=fst) fig.tight_layout() plt.subplots_adjust(top=0.9) plt.savefig(plotfile) if verbose: print me+"plot saved to",plotfile return fig