def plot_limb_a(histdir, noshow=False): """ Find directories in """ me = me0 + ".plot_limb_a: " filelist = np.sort(glob.glob(histdir + "/BHIS_*R10.0_S0.0*.npy")) assert len(filelist) > 1, me + "Check directory." A = np.zeros(len(filelist)) LQ, LC, LS = np.zeros((3, len(filelist))) for i, histfile in enumerate(filelist): A[i] = filename_par(histfile, "_a") R = filename_par(histfile, "_R") assert filename_par(histfile, "_S") == 0.0 r, Q, e2c2, e2s2 = calculate_arrs(histfile) LQ[i] = R - get_limb(r, Q, R) LC[i] = R - get_limb(r, e2c2, R) LS[i] = R - get_limb(r, e2s2, R) ## -------------------------------------------------------------------- srtind = np.argsort(A) A = A[srtind] LQ = (LQ[srtind]) LC = (LC[srtind]) LS = (LS[srtind]) ## -------------------------------------------------------------------- fig = plt.figure() ax = fig.gca() ax.plot(A, LQ, "o-", label=r"$Q$") ax.plot(A, LC, "o-", label=r"$\langle\eta^2 \cos^2\psi\rangle$") ax.plot(A, LS, "o-", label=r"$\langle\eta^2 \sin^2\psi\rangle$") AA = np.linspace(0.0, A[-1], 100) ax.plot(AA, AA**0.5, "--", label=r"$\alpha^{1/2}$") ax.set_xlabel(r"$\alpha$", fontsize=fsa) ax.set_ylabel(r"Limb length", fontsize=fsa) ax.set_title(r"$R=%.1f$, $S=0.0$" % (R), fontsize=fst) ax.grid() ax.legend(loc="best", fontsize=fsl).get_frame().set_alpha(0.5) plotfile = histdir + "/LIMB_a.jpg" fig.savefig(plotfile) print me + "Plot saved to", plotfile if not noshow: plt.show() return
def plot_bulkconst(histfile, noshow=False): """ Plot bulk constant with limb onset indicated. """ me = me0 + ".plot_bulkconst: " zoom = False a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") assert filename_par(histfile, "_S") == 0.0 r, Q, e2c2, e2s2 = calculate_arrs(histfile) Q /= Q.mean() e2c2 /= e2c2.mean() e2s2 /= e2s2.mean() limbQ = get_limb(r, Q, R) limbC = get_limb(r, e2c2, R) limbS = get_limb(r, e2s2, R) fig = plt.figure() ax = fig.gca() lineQ = ax.plot(r, Q, label=r"$Q(r)$") lineC = ax.plot(r, e2c2, label=r"$\langle\eta^2\cos^2\psi\rangle(r)$") lineS = ax.plot(r, e2s2, label=r"$\langle\eta^2\sin^2\psi\rangle(r)$") ax.axvline(limbQ, c=lineQ[0].get_color(), lw=2) ax.axvline(limbC, c=lineC[0].get_color(), lw=2) ax.axvline(limbS, c=lineS[0].get_color(), lw=2) ax.axvline(R, c="k", lw=2) ax.axvspan(0, R, color="yellow", alpha=0.2) if zoom: ax.set_xlim(np.floor(limb), R) filesuf = "_zoom" else: filesuf = "" ax.set_xlabel(r"$r$", fontsize=fsa) ax.set_ylabel(r"Rescaled variable", fontsize=fsa) ax.set_title(r"$a = %.1f$, $R = %.1f$" % (a, R), fontsize=fst) ax.grid() ax.legend(loc="upper left", fontsize=fsl) plotfile = os.path.dirname(histfile) + "/LIMB" + os.path.basename( histfile)[4:-4] + filesuf + ".jpg" fig.savefig(plotfile) print me + "Plot saved to", plotfile if not noshow: plt.show() return
def plot_limb_a(histdir, noshow=False): """ Find directories in """ me = me0+".plot_limb_a: " filelist = np.sort(glob.glob(histdir+"/BHIS_*R10.0_S0.0*.npy")) assert len(filelist)>1, me+"Check directory." A = np.zeros(len(filelist)) LQ, LC, LS = np.zeros((3,len(filelist))) for i, histfile in enumerate(filelist): A[i] = filename_par(histfile,"_a") R = filename_par(histfile,"_R") assert filename_par(histfile,"_S") == 0.0 r, Q, e2c2, e2s2 = calculate_arrs(histfile) LQ[i] = R - get_limb(r, Q, R) LC[i] = R - get_limb(r, e2c2, R) LS[i] = R - get_limb(r, e2s2, R) ## -------------------------------------------------------------------- srtind = np.argsort(A) A = A[srtind] LQ = ( LQ[srtind] ) LC = ( LC[srtind] ) LS = ( LS[srtind] ) ## -------------------------------------------------------------------- fig = plt.figure(); ax = fig.gca() ax.plot(A, LQ, "o-", label=r"$Q$") ax.plot(A, LC, "o-", label=r"$\langle\eta^2 \cos^2\psi\rangle$") ax.plot(A, LS, "o-", label=r"$\langle\eta^2 \sin^2\psi\rangle$") AA = np.linspace(0.0,A[-1],100) ax.plot(AA, AA**0.5, "--", label=r"$\alpha^{1/2}$") ax.set_xlabel(r"$\alpha$", fontsize=fsa) ax.set_ylabel(r"Limb length", fontsize=fsa) ax.set_title(r"$R=%.1f$, $S=0.0$"%(R), fontsize=fst) ax.grid() ax.legend(loc="best",fontsize=fsl).get_frame().set_alpha(0.5) plotfile = histdir+"/LIMB_a.jpg" fig.savefig(plotfile) print me+"Plot saved to",plotfile if not noshow: plt.show() return
def plot_bulkconst(histfile, noshow=False): """ Plot bulk constant with limb onset indicated. """ me = me0+".plot_bulkconst: " zoom = False a = filename_par(histfile,"_a") R = filename_par(histfile,"_R") assert filename_par(histfile,"_S") == 0.0 r, Q, e2c2, e2s2 = calculate_arrs(histfile) Q /= Q.mean() e2c2 /= e2c2.mean() e2s2 /= e2s2.mean() limbQ = get_limb(r, Q, R) limbC = get_limb(r, e2c2, R) limbS = get_limb(r, e2s2, R) fig = plt.figure(); ax = fig.gca() lineQ = ax.plot(r, Q, label=r"$Q(r)$") lineC = ax.plot(r, e2c2, label=r"$\langle\eta^2\cos^2\psi\rangle(r)$") lineS = ax.plot(r, e2s2, label=r"$\langle\eta^2\sin^2\psi\rangle(r)$") ax.axvline(limbQ, c=lineQ[0].get_color(), lw=2) ax.axvline(limbC, c=lineC[0].get_color(), lw=2) ax.axvline(limbS, c=lineS[0].get_color(), lw=2) ax.axvline(R,c="k",lw=2) ax.axvspan(0,R,color="yellow",alpha=0.2) if zoom: ax.set_xlim(np.floor(limb),R) filesuf = "_zoom" else: filesuf = "" ax.set_xlabel(r"$r$", fontsize=fsa) ax.set_ylabel(r"Rescaled variable", fontsize=fsa) ax.set_title(r"$a = %.1f$, $R = %.1f$"%(a,R), fontsize=fst) ax.grid() ax.legend(loc="upper left",fontsize=fsl) plotfile = os.path.dirname(histfile)+"/LIMB"+os.path.basename(histfile)[4:-4]+filesuf+".jpg" fig.savefig(plotfile) print me+"Plot saved to",plotfile if not noshow: plt.show() return
def plot_DP_a(histdir, nosave, searchstr, vb): """ Compile list of DPs and plot. """ me = me0+"plot_DP_a: " filelist = np.sort(glob.glob(histdir+"/BHIS_*"+searchstr+"*.npy")) A, DPm, DPi, DPp = np.zeros((4,filelist.size)) for i, histfile in enumerate(filelist): ## Parameters A[i] = filename_par(histfile,"_a") R = filename_par(histfile,"_R") assert filename_par(histfile,"_S")==R, me+"Must have R=S for this operation." ## PDF r, eta, psi, rho, Q = get_pdf(histfile) f = force_dlin(r,r,R,R) ## DP DPm[i] = calc_DPm(r, eta, psi, rho, Q, f, A[i])[0] DPi[i] = calc_DPi(r, Q, f, R) DPp[i] = calc_DPp(r, Q, A[i], R) srtidx = A.argsort() A = A[srtidx] DPm = DPi[srtidx] DPi = DPi[srtidx] ##------------------------------------------------------------------------- fig, ax = plt.subplots(1,1, figsize=(10,10)) ax.plot(A, DPm, "o-", label=r"M-(1,1)") ax.plot(A, DPi, "o-", label=r"Integral") ax.plot(A, DPp, "o-", label=r"Predict") ##------------------------------------------------------------------------- ax.set_xlabel(r"$\alpha$",fontsize=fsa) ax.set_ylabel(r"$P_{\rm out}-P_{\rm in}$",fontsize=fsa) ax.grid() ax.legend(loc="best", fontsize=fsl).get_frame().set_alpha(0.5) ax.set_title("Pressure difference. $R=S=%.2g$"%(R),fontsize=fst) ## SAVING plotfile = histdir+"/DPa_R"+str(R)+".jpg" if not nosave: fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile return
def main(): """ Test approximation for perturbed harmonic well in Cartesian geometry. """ histfile = argv[1] assert "_NL_" in histfile assert "_T" not in histfile a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") ## Data bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] x = 0.5*(xbins[1:]+xbins[:-1]) H = np.load(histfile) Q = H.sum(axis=2).sum(axis=1) / (H.sum()*(x[1]-x[0])) ## Prediction xp = np.linspace(-4.0,4.0,1001) Qp = calc_Q_NLsmallR(xp,a,R,S) Qp /= np.trapz(Qp, xp) ## Plotting fig, ax = plt.subplots(1,1, figsize=fs["figsize"]) ax.plot(x, Q, lw=2, label="Simulation") ax.plot(xp,Qp, lw=2, label="Prediction") ax.set_xlim((x[0],x[-1])) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$Q(x)$", fontsize=fs["fsa"]) ax.grid() ax.legend(loc="upper left", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) fig.tight_layout() fig.subplots_adjust(top=0.90) title = r"Approximate Spatial PDF. $\alpha=%.1f, R=%.1f, S=%.1f$"%(a,R,S) fig.suptitle(title, fontsize=fs["fst"]) plotfile = os.path.dirname(histfile)+"/APPR"+os.path.basename(histfile)[4:-4]+".jpg" fig.savefig(plotfile) plt.show() return
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_pdf2d(histfile, nosave, vb): """ Read in data for a single file and plot 2D PDF projections. """ me = me0+".plot_pdf2D: " t0 = time.time() ##------------------------------------------------------------------------- ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") try: P = filename_par(histfile, "_P") except: P = 0.0 ##------------------------------------------------------------------------- ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] ybins = bins["ybins"] x = 0.5*(xbins[1:]+xbins[:-1]) y = 0.5*(ybins[1:]+ybins[:-1]) ## Wall indices Rind = np.abs(x-R).argmin() ##------------------------------------------------------------------------- ## Histogram / density H = np.load(histfile) rho = H / (H.sum() * (x[1]-x[0])*(y[1]-y[0])) ## For comparison with Nik++16 rho = rho[:,::-1] ## ------------------------------------------------------------------------ ## Plotting fig, ax = plt.subplots(1,1, figsize=fs["figsize"]) fig.canvas.set_window_title("2D PDF") lvls = 20 plt.set_cmap("Greys")#Greys coolwarm ## Plot density cax = ax.contourf(x, y, rho.T, lvls) # cbar = fig.colorbar(cax,) # cbar.locator = MaxNLocator(nbins=5); cbar.update_ticks() ## Indicate bulk yfine = np.linspace(y[0],y[-1],1000) ax.scatter(+R-S*np.sin(2*np.pi*yfine/T), yfine, c="k", s=1) ax.set_xlim(xbins[0],xbins[-1]) ax.set_ylim(ybins[0],ybins[-1]) ax.set_xlabel(r"$x/\lambda$", fontsize=fs["fsa"]) ax.set_ylabel(r"$y/\lambda$", fontsize=fs["fsa"]) ax.xaxis.set_major_locator(MaxNLocator(5)) ax.grid() ## ------------------------------------------------------------------------ ## Potential inset ## Plot potential in 3D # left, bottom, width, height = [0.44, 0.16, 0.30, 0.30] ## For lower right # axin = fig.add_axes([left, bottom, width, height], projection="3d") # Rschem, Sschem, Tschem = (2.0,1.0,1.0) # plot_U3D_ulin(axin, Rschem, Sschem, Tschem) ## Plot potential in 2D try: cbar left, bottom, width, height = [0.47, 0.16, 0.25, 0.25] ## For lower right except: left, bottom, width, height = [0.57, 0.16, 0.30, 0.30] axin = fig.add_axes([left, bottom, width, height]) Rschem, Sschem, Tschem = (2.0,1.0,1.0) plot_U2D_ulin(axin, Rschem, Sschem, Tschem) axin.set_axis_bgcolor(plt.get_cmap()(0.00)) axin.patch.set_facecolor("None") ## ------------------------------------------------------------------------ title = r"PDF projections. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f, P=%.1f\pi$"%(a,R,S,T,P) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname(histfile)+"/PDFxy2d"+os.path.basename(histfile)[4:-4] plotfile += "."+fs["saveext"] fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile if vb: print me+"Execution time %.1f seconds."%(time.time()-t0) return
def plot_pdf1d(histfile, nosave, vb): """ Calculate Q(r) and q(eta) from file and plot. """ me = me0+".plot_pdf1d: " t0 = time.time() ##------------------------------------------------------------------------- ## Filename pars assert "_CAR_" in histfile, me+"Functional only for Cartesian geometry." Casimir = "_CL_" in histfile or "_ML_" in histfile or "_NL_" in histfile a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") try: T = filename_par(histfile, "_T") except ValueError: T= -S doQfit = (R==S and "_DL_" in histfile) plotq = int(False) ##------------------------------------------------------------------------- ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] exbins = bins["exbins"] eybins = bins["eybins"] x = 0.5*(xbins[1:]+xbins[:-1]) etax = 0.5*(exbins[1:]+exbins[:-1]) etay = 0.5*(eybins[1:]+eybins[:-1]) ## Wall indices Rind, Sind = np.abs(x-R).argmin(), np.abs(x-S).argmin() ##------------------------------------------------------------------------- ## Histogram H = np.load(histfile) rho = H / (H.sum() * (x[1]-x[0])*(etax[1]-etax[0])*(etay[1]-etay[0])) ## Spatial density Qx = rho.sum(axis=2).sum(axis=1) * (etax[1]-etax[0])*(etay[1]-etay[0]) ## Force density qx = rho.sum(axis=2).sum(axis=0) * (x[1]-x[0])*(etay[1]-etay[0]) qy = rho.sum(axis=1).sum(axis=0) * (x[1]-x[0])*(etax[1]-etax[0]) ##------------------------------------------------------------------------- ## Fit gauss = lambda x, m, s2: 1/np.sqrt(2*np.pi*s2)*np.exp(-0.5*(x-m)**2/s2) if doQfit: fitQx = sp.optimize.curve_fit(gauss, x, Qx, p0=[R,1/np.sqrt(1+a)])[0] ##------------------------------------------------------------------------- ## PLOTTING fig, axs = plt.subplots(1+plotq,1, figsize=fs["figsize"]) fig.canvas.set_window_title("1D PDFs") ## Set number of ticks for ax in np.ravel([axs]): ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(4)) ##------------------------------------------------------------------------- ## Spatial density plot ax = axs[0] if plotq else axs ## Data ax.plot(x, Qx, label=r"OUP") ax.fill_between(x, 0.0, Qx, color="b", alpha=0.1) ## Gaussian for spatial density if doQfit: ax.plot(x, gauss(x,fitQx[0],1/(1+a)), "c-", label=r"$G\left(\mu, \frac{1}{\alpha+1}\right)$") ## Potential and WN if "_DC_" in histfile: fx = force_dcon([x,0],R,S)[0] elif "_DL_" in histfile: fx = force_dlin([x,0],R,S)[0] elif "_CL_" in histfile: fx = force_clin([x,0],R,S,T)[0] elif "_ML_" in histfile: fx = force_mlin([x,0],R,S,T)[0] elif "_NL_" in histfile: fx = force_nlin([x,0],R,S)[0] else: raise IOError, me+"Force not recognised." U = -sp.integrate.cumtrapz(fx, x, initial=0.0); U -= U.min() ## Plot passive density Qx_WN = np.exp(-U)/np.trapz(np.exp(-U),x) ax.plot(x, Qx_WN, "r-", label="Passive") ax.fill_between(x, 0.0, Qx_WN, color="r", alpha=0.1) ## Plot potential ax.plot(x, U/U.max()*ax.get_ylim()[1], "k--",label=r"$U(x)$") ## Indicate bulk ax.axvline(S,c="k",lw=1) ax.axvline(R,c="k",lw=1) if T>=0.0: ax.axvspan(S,R,color="y",alpha=0.1) ax.axvline(T,c="k",lw=1) ax.axvspan(-R,T,color="y",alpha=0.1) ax.axvline(-R,c="k",lw=1) elif T<0.0: ax.axvline(-R,c="k",lw=1) ax.set_xlim(left=x[0],right=x[-1]) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$n(x)$", fontsize=fs["fsa"]) ax.grid() ax.legend(loc="upper right", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ##------------------------------------------------------------------------- if plotq: ## Force density plot ax = axs[1] ## Data ax.plot(etax, qx, label=r"Simulation $x$") ax.plot(etay, qy, label=r"Simulation $y$") ## Gaussian ax.plot(etax, gauss(etax,0.0,1/a), "c-", label=r"$G\left(0, \frac{1}{\alpha}\right)$") ax.set_xlabel(r"$\eta$", fontsize=fs["fsa"]) ax.set_ylabel(r"$q(\eta)$", fontsize=fs["fsa"]) ax.grid() ax.legend(loc="upper right", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ##------------------------------------------------------------------------- fig.tight_layout() fig.subplots_adjust(top=0.95) title = r"PDFs in $r$ and $\eta$. $\alpha=%.1f, R=%.1f, S=%.1f$"%(a,R,S) if T<0.0\ else r"PDFs in $r$ and $\eta$. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f$"%(a,R,S,T) else: title = r"Spatial PDF. $\alpha=%.1f, R=%.1g, S=%.1g$"%(a,R,S) if T<0.0\ else r"Spatial PDF. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.f$"%(a,R,S,T) # fig.suptitle(title, fontsize=fs["fst"]) if not nosave: plotfile = os.path.dirname(histfile)+"/PDFxy1d"+os.path.basename(histfile)[4:-4] plotfile += "."+fs["saveext"] fig.savefig(plotfile, format=fs["saveext"]) if vb: print me+"Figure saved to",plotfile if vb: print me+"Execution time %.1f seconds."%(time.time()-t0) return
def plot_file(histfile, nosave, vb): """ """ me = me0+".plot_file: " ##------------------------------------------------------------------------- ## Dir pars assert "_CAR_" in histfile, me+"Functional only for Cartesian geometry." Casimir = "_CL_" in histfile or "_ML_" in histfile ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") if Casimir else -S ## Calculate quantities x, Q, BC = bulk_const(histfile)[:3] ex2 = BC/(Q+(Q==0.0)) ##------------------------------------------------------------------------- ## Potential if "_DL_" in histfile: fx = force_dlin([x,0],R,S)[0] elif "_CL_" in histfile: fx = force_clin([x,0],R,S,T)[0] elif "_ML_" in histfile: fx = force_mlin([x,0],R,S,T)[0] elif "_NL_" in histfile: fx = force_nlin([x,0],R,S)[0] U = -sp.integrate.cumtrapz(fx, x, initial=0.0); U -= U.min() ##------------------------------------------------------------------------- ## Smooth sp.ndimage.gaussian_filter1d(Q,1.0,order=0,output=Q) sp.ndimage.gaussian_filter1d(BC,1.0,order=0,output=BC) sp.ndimage.gaussian_filter1d(ex2,1.0,order=0,output=ex2) ##------------------------------------------------------------------------- ## PLOT fig, ax = plt.subplots(1,1, figsize=fs["figsize"]) ## Data ax.plot(x, Q/Q.max(), label=r"$n(x)$",lw=2) ax.plot(x, ex2/ex2.max(), label=r"$\langle\eta_x^2\rangle(x)$",lw=2) ax.plot(x, BC/BC.max(), label=r"$\langle\eta_x^2\rangle \cdot n$",lw=2) ax.plot(x, U/U.max()*ax.get_ylim()[1], "k--", label=r"$U(x)$") ## Indicate bulk region if "_DL_" in histfile: ax.axvspan(S,R, color="yellow",alpha=0.2) ax.axvline(S, c="k",lw=2); ax.axvline(R, c="k",lw=2) elif "_ML_" in histfile: ax.axvspan(S,R, color="yellow",alpha=0.2) ax.axvspan(-R,T, color="yellow",alpha=0.2) ax.axvline(S, c="k",lw=2); ax.axvline(R, c="k",lw=2) ax.axvline(T, c="k",lw=2); ax.axvline(-R, c="k",lw=2) elif "_CL_" in histfile: ax.axvspan(S,R, color="yellow",alpha=0.2) ax.axvspan(0,T, color="yellow",alpha=0.2) ax.axvline(S, c="k",lw=2); ax.axvline(R, c="k",lw=2) ax.axvline(T, c="k",lw=2); ax.axvline(-R, c="k",lw=2) ##------------------------------------------------------------------------- ## ATTRIBUTES ax.set_xlim(left=x[0],right=x[-1]) ax.xaxis.set_major_locator(NullLocator()) ax.yaxis.set_major_locator(NullLocator()) ax.set_xlabel("$x$",fontsize=fs["fsa"]) ax.set_ylabel("Rescaled variable",fontsize=fs["fsa"]) ax.grid() legloc = [0.35,0.25] if "_ML_" in histfile else [0.32,0.67] ax.legend(loc=legloc,fontsize=fs["fsl"]).get_frame().set_alpha(0.8) title = r"Bulk Constant. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f$."%(a,R,S,T) if T>=0.0\ else r"Bulk Constant. $\alpha=%.1f, R=%.1f, S=%.1f$."%(a,R,S) # fig.suptitle(title,fontsize=fs["fst"]) ## SAVE # ax.set_ylim(top=BC.max()) plotfile = os.path.dirname(histfile)+"/QEe2"+os.path.basename(histfile)[4:-4]+"."+fs["saveext"] if not nosave: fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile ##------------------------------------------------------------------------- return plotfile
def plot_file(histfile, nosave, vb): """ """ me = me0+".plot_file: " ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") ## Calculate quantities r, Q, BCout, BCin, Pout, Pin, e2c2Q, e2s2Q, intgl = bulk_const(histfile)[:9] ## Wall indices Rind, Sind = np.abs(r-R).argmin(), np.abs(r-S).argmin() ##------------------------------------------------------------------------- ## PLOT fig = plt.figure(figsize=fs["figsize"]); ax = fig.gca() ## Data ax.plot(r,Q, label=r"$Q(r)$") ax.plot(r,BCout, label=r"BC (out)", lw=2) if S>0.0: ax.plot(r,BCin,label=r"BC (in)", lw=2) ax.plot(r,e2c2Q, label=r"$\langle\eta^2\cos^2\psi\rangle Q(r)$") ax.plot(r,e2s2Q, label=r"$\langle\eta^2\sin^2\psi\rangle Q(r)$") ax.plot(r,intgl, label=r"$\int_0^r\frac{1}{r^\prime}(\cdots)Q\,dr^\prime$") ## Potential ymax = ax.get_ylim()[1] if "_DL" in histfile: U = np.hstack([np.linspace(S-r[0],0,Sind)**2,np.zeros(Rind-Sind),np.linspace(0.0,r[-1]-R,r.size-Rind)**2]) ax.plot(r, U/U.max()*ymax, "k--", label=r"$U(r)$") ## Indicate bulk region ax.axvspan(S,R, color="yellow",alpha=0.2) ax.axvline(S, c="k",lw=2); ax.axvline(R, c="k",lw=2) ##------------------------------------------------------------------------- ## ATTRIBUTES ax.set_xlim(left=r[0],right=r[-1]) ax.set_xlabel("$r$",fontsize=fs["fsa"]) ax.set_ylabel("Rescaled variable",fontsize=fs["fsa"]) ax.grid() ax.legend(loc="lower right",fontsize=fs["fsl"]).get_frame().set_alpha(0.5) fig.suptitle(r"Bulk Constant. $\alpha=%.1f, R=%.1f, S=%.1f$."%(a,R,S),fontsize=fs["fst"]) ## SAVE plotfile = os.path.dirname(histfile)+"/QEe2"+os.path.basename(histfile)[4:-4]+".jpg" if not nosave: fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile ##------------------------------------------------------------------------- return plotfile
def plot_pdf2d(histfile, nosave, vb): """ Read in data for a single file and plot 2D PDF projections. """ me = me0+".plot_pdf2D: " t0 = time.time() ##------------------------------------------------------------------------- ## Get pars from filename assert "_CAR_" in histfile, me+"Functional only for Cartesian geometry." Casimir = "_CL_" in histfile a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") if Casimir else -S ##------------------------------------------------------------------------- ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] exbins = bins["exbins"] eybins = bins["eybins"] x = 0.5*(xbins[1:]+xbins[:-1]) etax = 0.5*(exbins[1:]+exbins[:-1]) etay = 0.5*(eybins[1:]+eybins[:-1]) X, EX, EY = np.meshgrid(x, etax, etay, indexing="ij") ## Wall indices Rind, Sind = np.abs(x-R).argmin(), np.abs(x-S).argmin() ##------------------------------------------------------------------------- ## Histogram / density H = np.load(histfile) rho = H / (H.sum() * (x[1]-x[0])*(etax[1]-etax[0])*(etay[1]-etay[0])) ## Prediction for when R=S and potential is quadratic pred = int(R==S and "_DL_" in histfile) if pred: Xc = 0.5*(R+S) ## To centre the prediction rhoP = a*(a+1)/(2*np.sqrt(2)*np.pi**1.5)*\ np.exp(-0.5*(a+1)**2*(X-Xc)*(X-Xc)-0.5*a*(a+1)*EX*EX+a*(a+1)*(X-Xc)*EX-0.5*a*EY*EY) ## ------------------------------------------------------------------------ ## Projections rhoxex = rho.sum(axis=2) rhoxey = rho.sum(axis=1) rhoexey = rho.sum(axis=0) if pred: rhoPxex = rhoP.sum(axis=2) rhoPxey = rhoP.sum(axis=1) rhoPexey = rhoP.sum(axis=0) ## ------------------------------------------------------------------------ ## Plotting fig, axs = plt.subplots(3,1+pred, sharey=True, figsize=fs["figsize"]) fig.canvas.set_window_title("2D PDFs") ## Set number of ticks for ax in np.ravel([axs]): Nxtick = 5 if pred else 7 ax.xaxis.set_major_locator(MaxNLocator(Nxtick)) ax.yaxis.set_major_locator(MaxNLocator(4)) plt.rcParams["image.cmap"] = "Greys"#"coolwarm" ## ------------------------------------------------------------------------ ## x-etax ax = axs[0][0] if pred else axs[0] ax.contourf(x,etax,rhoxex.T) ## Indicate bulk ax.axvline(S,c="k",lw=1) ax.axvline(R,c="k",lw=1) if T>=0.0: ax.axvline(T,c="k",lw=1) elif T<0.0 and "_DL_" not in histfile: ax.axvline(-R,c="k",lw=1) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\eta_x$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(x,\eta_x)$ data", fontsize=fs["fsa"]) if pred: ax = axs[0][1] ax.contourf(x,etax,rhoPxex.T) ax.axvline(Xc,c="k") ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(x,\eta_x)$ prediction", fontsize=fs["fsa"]) ## x-etay ax = axs[1][0] if pred else axs[1] ax.contourf(x,etay,rhoxey.T) ## Indicate bulk ax.axvline(S,c="k",lw=1) ax.axvline(R,c="k",lw=1) if T>=0.0: ax.axvline(T,c="k",lw=1) elif T<0.0 and "_DL_" not in histfile: ax.axvline(-R,c="k",lw=1) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\eta_y$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(x,\eta_y)$ data", fontsize=fs["fsa"]) if pred: ax = axs[1][1] ax.contourf(x,etay,rhoPxey.T) ax.axvline(Xc,c="k") ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(x,\eta_y)$ prediction", fontsize=fs["fsa"]) ## etax-etay ax = axs[2][0] if pred else axs[2] ax.contourf(etax,etay,rhoexey.T) ax.set_xlabel(r"$\eta_x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\eta_y$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(\eta_x,\eta_y)$ data", fontsize=fs["fsa"]) if pred: ax = axs[2][1] ax.contourf(etax,etay,rhoPexey.T) ax.set_xlabel(r"$\eta_x$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(\eta_x,\eta_y)$ prediction", fontsize=fs["fsa"]) ## ------------------------------------------------------------------------ title = r"PDF projections. $\alpha=%.1f, R=%.1f, S=%.1f$"%(a,R,S) if T<0.0\ else r"PDF projections. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f$"%(a,R,S,T) fig.suptitle(title, fontsize=fs["fst"]) fig.tight_layout() fig.subplots_adjust(top=0.9) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname(histfile)+"/PDFxy2d"+os.path.basename(histfile)[4:-4] plotfile += "."+fs["saveext"] fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile if vb: print me+"Execution time %.1f seconds."%(time.time()-t0) return
def calc_pressure_dir(histdir, srchstr, noread, vb): """ Calculate the pressure for all files in directory matching string. The """ me = me0 + ".calc_pressure_dir: " t0 = time.time() ##------------------------------------------------------------------------- ## Dir pars assert "_CAR_" in histdir, me + "Functional only for Cartesian geometry." Casimir = "_DL_" not in histdir ## File discovery filelist = np.sort(glob.glob(histdir + "/BHIS_CAR_*" + srchstr + "*.npy")) numfiles = len(filelist) assert numfiles > 1, me + "Check input directory." if vb: print me + "found", numfiles, "files" ##------------------------------------------------------------------------- A, R, S, T, PR, PS, PT, PU, PR_WN, PS_WN, PT_WN, PU_WN = np.zeros( [12, numfiles]) ## Retrieve data for i, histfile in enumerate(filelist): ti = time.time() ## Assuming R, S, T are same for all files A[i] = filename_par(histfile, "_a") R[i] = filename_par(histfile, "_R") S[i] = filename_par(histfile, "_S") try: T[i] = filename_par(histfile, "_T") except ValueError: T[i] = -S[i] ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] x = 0.5 * (xbins[1:] + xbins[:-1]) ## Wall indices Rind, Sind, Tind = np.abs(x - R[i]).argmin( ), np.abs(x - S[i]).argmin() + 1, np.abs(x - T[i]).argmin() STind = 0 if T[i] < 0.0 else (Sind + Tind) / 2 ## Adjust indices for pressure calculation if "_DC_" in histfile: STind = 0 elif "_DL_" in histfile: STind = 0 elif "_NL_" in histfile: STind = Sind Sind = Rind Tind = x.size - Rind ##------------------------------------------------------------------------- ## Histogram H = np.load(histfile) ## Spatial density Qx = H.sum(axis=2).sum(axis=1) / (H.sum() * (x[1] - x[0])) ##------------------------------------------------------------------------- ## Choose force if "_DC_" in histfile: fx = force_dcon([x, 0], R[i], S[i])[0] elif "_DL_" in histfile: fx = force_dlin([x, 0], R[i], S[i])[0] elif "_CL_" in histfile: fx = force_clin([x, 0], R[i], S[i], T[i])[0] elif "_ML_" in histfile: fx = force_mlin([x, 0], R[i], S[i], T[i])[0] elif "_NL_" in histfile: fx = force_nlin([x, 0], R[i], S[i])[0] else: raise IOError, me + "Force not recognised." ## Calculate integral pressure PR[i] = -sp.integrate.trapz(fx[Rind:] * Qx[Rind:], x[Rind:]) PS[i] = +sp.integrate.trapz(fx[STind:Sind] * Qx[STind:Sind], x[STind:Sind]) PT[i] = -sp.integrate.trapz(fx[Tind:STind] * Qx[Tind:STind], x[Tind:STind]) if "_ML_" in histfile: mRind = x.size - Rind ## Index of wall at x=-R PU[i] = +sp.integrate.trapz(fx[:mRind] * Qx[:mRind], x[:mRind]) if vb: print me + "a=%.1f:\tPressure calculation %.2g seconds" % ( A[i], time.time() - ti) ## Potential U = -sp.integrate.cumtrapz(fx, x, initial=0.0) U -= U.min() Qx_WN = np.exp(-U) / np.trapz(np.exp(-U), x) ## WN pressure PR_WN[i] = -sp.integrate.trapz(fx[Rind:] * Qx_WN[Rind:], x[Rind:]) PS_WN[i] = +sp.integrate.trapz(fx[STind:Sind] * Qx_WN[STind:Sind], x[STind:Sind]) if Casimir: PT_WN[i] = -sp.integrate.trapz(fx[Tind:STind] * Qx_WN[Tind:STind], x[Tind:STind]) if "_ML_" in histfile: PU_WN[i] = +sp.integrate.trapz(fx[:mRind] * Qx_WN[:mRind], x[:mRind]) ##------------------------------------------------------------------------- ## SORT BY ALPHA srtidx = A.argsort() A = A[srtidx] R, S, T = R[srtidx], S[srtidx], T[srtidx] PR, PS, PT, PU = PR[srtidx], PS[srtidx], PT[srtidx], PU[srtidx] PR_WN, PS_WN, PT_WN, PU_WN = PR_WN[srtidx], PS_WN[srtidx], PT_WN[ srtidx], PU_WN[srtidx] ## Normalise PR /= PR_WN + (PR_WN == 0) PS /= PS_WN + (PS_WN == 0) if Casimir: PT /= PT_WN + (PT_WN == 0) if "_ML_" in histdir: PU /= PU_WN + (PU_WN == 0) ##------------------------------------------------------------------------- ## SAVING if not noread: pressfile = histdir + "/PRESS_" + srchstr + ".npz" np.savez(pressfile, A=A, R=R, S=S, T=T, PR=PR, PS=PS, PT=PT, PU=PU, PR_WN=PR_WN, PS_WN=PS_WN, PT_WN=PT_WN, PU_WN=PU_WN) if vb: print me + "Calculations saved to", pressfile print me + "Calculation time %.1f seconds." % (time.time() - t0) return { "A": A, "R": R, "S": S, "T": T, "PR": PR, "PS": PS, "PT": PT, "PU": PU, "PR_WN": PR_WN, "PS_WN": PS_WN, "PT_WN": PT_WN, "PU_WN": PU_WN }
def plot_current_2d(currfile, nosave, vb): """ """ me = me0 + ".plot_current_2d: " t0 = time.time() ##------------------------------------------------------------------------- ## Filename pars a = filename_par(currfile, "_a") R = filename_par(currfile, "_R") S = filename_par(currfile, "_S") T = filename_par(currfile, "_T") ##------------------------------------------------------------------------- ## Load data data = np.load(currfile) xbins = data["xbins"] ybins = data["ybins"] vxbins = data["vxbins"] vybins = data["vybins"] Hxy = data["Hxy"][:, ::-1] Vx = data["Vx"][:, ::-1] Vy = data["Vy"][:, ::-1] del data x = 0.5 * (xbins[:-1] + xbins[1:]) y = 0.5 * (ybins[:-1] + ybins[1:]) vx = 0.5 * (vxbins[:-1] + vxbins[1:]) vy = 0.5 * (vybins[:-1] + vybins[1:]) ##------------------------------------------------------------------------- ## SMOOTHING # Vy = sp.ndimage.gaussian_filter(Vy, 1.0, order=0) zx, zy = 0.2, 1.0 Vx = sp.ndimage.interpolation.zoom(Vx, (zx, zy), mode="nearest", cval=0.0) Vy = sp.ndimage.interpolation.zoom(Vy, (zx, zy), mode="nearest", cval=0.0) Vy[:, 0] = 0.0 Vy[:, -1] = 0.0 ##------------------------------------------------------------------------- ## PLOTTING plt.rcParams["image.cmap"] = "Greys" fig, ax = plt.subplots(1, 1, figsize=fs["figsize"]) fig.canvas.set_window_title("Velocity in x-y") ##------------------------------------------------------------------------- ## Data ax.contourf(x, y, Hxy.T) ax.quiver(x[::int(1 / zx)], y[::int(1 / zy)], Vx.T, Vy.T) ## Indicate wall yfine = np.linspace(0, T, 1000) ax.scatter(+R - S * np.sin(2 * np.pi * yfine / T), yfine, c="k", s=1) ## Set number of ticks ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(4)) ax.set_xlim([xbins[0], xbins[-1]]) ax.set_ylim([ybins[0], ybins[-1]]) ax.set_xlabel(r"$x/T$", fontsize=fs["fsa"]) ax.set_ylabel(r"$y/T$", fontsize=fs["fsa"]) ax.grid() # ax.legend(loc="upper right", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ##------------------------------------------------------------------------- if not nosave: plotfile = os.path.dirname(currfile) + "/Jxy" + os.path.basename( currfile)[4:-4] plotfile += "." + fs["saveext"] fig.savefig(plotfile, format=fs["saveext"]) if vb: print me + "Figure saved to", plotfile if vb: print me + "Execution time %.1f seconds." % (time.time() - t0) return
def plot_pdf2d(histfile, nosave, vb): """ Read in data for a single file and plot 2D PDF projections. """ me = me0 + ".plot_pdf2D: " t0 = time.time() ##------------------------------------------------------------------------- ## Get pars from filename assert "_CAR_" in histfile, me + "Functional only for Cartesian geometry." Casimir = "_CL_" in histfile a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") if Casimir else -S ##------------------------------------------------------------------------- ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] exbins = bins["exbins"] eybins = bins["eybins"] x = 0.5 * (xbins[1:] + xbins[:-1]) etax = 0.5 * (exbins[1:] + exbins[:-1]) etay = 0.5 * (eybins[1:] + eybins[:-1]) X, EX, EY = np.meshgrid(x, etax, etay, indexing="ij") ## Wall indices Rind, Sind = np.abs(x - R).argmin(), np.abs(x - S).argmin() ##------------------------------------------------------------------------- ## Histogram / density H = np.load(histfile) rho = H / (H.sum() * (x[1] - x[0]) * (etax[1] - etax[0]) * (etay[1] - etay[0])) ## Prediction for when R=S and potential is quadratic pred = int(R == S and "_DL_" in histfile) if pred: Xc = 0.5 * (R + S) ## To centre the prediction rhoP = a*(a+1)/(2*np.sqrt(2)*np.pi**1.5)*\ np.exp(-0.5*(a+1)**2*(X-Xc)*(X-Xc)-0.5*a*(a+1)*EX*EX+a*(a+1)*(X-Xc)*EX-0.5*a*EY*EY) ## ------------------------------------------------------------------------ ## Projections rhoxex = rho.sum(axis=2) rhoxey = rho.sum(axis=1) rhoexey = rho.sum(axis=0) if pred: rhoPxex = rhoP.sum(axis=2) rhoPxey = rhoP.sum(axis=1) rhoPexey = rhoP.sum(axis=0) ## ------------------------------------------------------------------------ ## Plotting fig, axs = plt.subplots(3, 1 + pred, sharey=True, figsize=fs["figsize"]) fig.canvas.set_window_title("2D PDFs") ## Set number of ticks for ax in np.ravel([axs]): Nxtick = 5 if pred else 7 ax.xaxis.set_major_locator(MaxNLocator(Nxtick)) ax.yaxis.set_major_locator(MaxNLocator(4)) plt.rcParams["image.cmap"] = "Greys" #"coolwarm" ## ------------------------------------------------------------------------ ## x-etax ax = axs[0][0] if pred else axs[0] ax.contourf(x, etax, rhoxex.T) ## Indicate bulk ax.axvline(S, c="k", lw=1) ax.axvline(R, c="k", lw=1) if T >= 0.0: ax.axvline(T, c="k", lw=1) elif T < 0.0 and "_DL_" not in histfile: ax.axvline(-R, c="k", lw=1) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\eta_x$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(x,\eta_x)$ data", fontsize=fs["fsa"]) if pred: ax = axs[0][1] ax.contourf(x, etax, rhoPxex.T) ax.axvline(Xc, c="k") ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(x,\eta_x)$ prediction", fontsize=fs["fsa"]) ## x-etay ax = axs[1][0] if pred else axs[1] ax.contourf(x, etay, rhoxey.T) ## Indicate bulk ax.axvline(S, c="k", lw=1) ax.axvline(R, c="k", lw=1) if T >= 0.0: ax.axvline(T, c="k", lw=1) elif T < 0.0 and "_DL_" not in histfile: ax.axvline(-R, c="k", lw=1) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\eta_y$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(x,\eta_y)$ data", fontsize=fs["fsa"]) if pred: ax = axs[1][1] ax.contourf(x, etay, rhoPxey.T) ax.axvline(Xc, c="k") ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(x,\eta_y)$ prediction", fontsize=fs["fsa"]) ## etax-etay ax = axs[2][0] if pred else axs[2] ax.contourf(etax, etay, rhoexey.T) ax.set_xlabel(r"$\eta_x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\eta_y$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(\eta_x,\eta_y)$ data", fontsize=fs["fsa"]) if pred: ax = axs[2][1] ax.contourf(etax, etay, rhoPexey.T) ax.set_xlabel(r"$\eta_x$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(\eta_x,\eta_y)$ prediction", fontsize=fs["fsa"]) ## ------------------------------------------------------------------------ title = r"PDF projections. $\alpha=%.1f, R=%.1f, S=%.1f$"%(a,R,S) if T<0.0\ else r"PDF projections. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f$"%(a,R,S,T) fig.suptitle(title, fontsize=fs["fst"]) fig.tight_layout() fig.subplots_adjust(top=0.9) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname(histfile) + "/PDFxy2d" + os.path.basename( histfile)[4:-4] plotfile += "." + fs["saveext"] fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile if vb: print me + "Execution time %.1f seconds." % (time.time() - t0) return
def plot_pdf1d_intx(histfile, nosave, vb): """ Read in data for a single file and plot the density integrated from the wall to infinity as a function of y. """ me = me0+".plot_pdf1D_intx: " t0 = time.time() ##------------------------------------------------------------------------- ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") try: P = filename_par(histfile, "_P") except: P = 0.0 ##------------------------------------------------------------------------- ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] ybins = bins["ybins"] x = 0.5*(xbins[1:]+xbins[:-1]) y = 0.5*(ybins[1:]+ybins[:-1]) ##------------------------------------------------------------------------- ## Histogram / density H = np.load(histfile) rho = H / (H.sum() * (x[1]-x[0])*(y[1]-y[0])) ## For comparison with Nik++16 rho = rho[:,::-1] ## Integrate rho over x IN WALL REGION Qy = np.zeros(y.size) wind = +R-S*np.sin(2*np.pi*y/T) ### HARD CODED for i,yi in enumerate(y): Qy[i] = np.trapz(rho[wind[i]:,i],x[wind[i]:],axis=0) ## ------------------------------------------------------------------------ ## Plotting fig, ax = plt.subplots(1,1, figsize=fs["figsize"]) fig.canvas.set_window_title("1D PDF integrated along x") ## Plot density and wall ax.plot(y, Qy) ## Indicate inflexion point ax.axvspan(y[0],0.5*T, color="g",alpha=0.2) ax.set_xlabel(r"$y$", fontsize=fs["fsa"]) ax.set_ylabel(r"$Q_x(y)$", fontsize=fs["fsa"]) ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(7)) ax.grid() ax.legend(loc="upper left") ## ------------------------------------------------------------------------ title = r"PDF slice integrated over x in wall region. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f, P=%.1f\pi$"%(a,R,S,T,P) fig.suptitle(title, fontsize=fs["fst"]) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname(histfile)+"/PDFxy1dintx"+os.path.basename(histfile)[4:-4] plotfile += "."+fs["saveext"] fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile if vb: print me+"Execution time %.1f seconds."%(time.time()-t0) return
def plot_pdf1d(histfile, nosave, vb): """ Read in data for a single file and plot a few 1D PDF slices. """ me = me0+".plot_pdf1D: " t0 = time.time() ##------------------------------------------------------------------------- ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") try: P = filename_par(histfile, "_P") except: P = 0.0 ##------------------------------------------------------------------------- ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] ybins = bins["ybins"] x = 0.5*(xbins[1:]+xbins[:-1]) y = 0.5*(ybins[1:]+ybins[:-1]) ##------------------------------------------------------------------------- ## Histogram / density H = np.load(histfile) rho = H / (H.sum() * (x[1]-x[0])*(y[1]-y[0])) ## For comparison with Nik++16 rho = rho[:,::-1] ## ------------------------------------------------------------------------ ## Plotting fig, ax = plt.subplots(1,1, figsize=fs["figsize"]) fig.canvas.set_window_title("1D PDF") ## Slices to plot idxs = np.linspace(y.size/4,y.size*3/4,11) labs = [r"$%.2f$"%(float(i)/y.size) for i in idxs] ## Plot density and wall for i, idx in enumerate(idxs): sp.ndimage.gaussian_filter1d(rho[:,idx],1.0,order=0,output=rho[:,idx]) off = 0.0*S*np.sin(idxs[i]/y.size*T*2*np.pi) ax.plot(x+off, rho[:,idx], label=labs[i]) ax.axvline(+R-S*np.sin(2*np.pi*y[idx]/T)+off, c=ax.lines[-1].get_color(),ls="--") ax.set_xlim(xbins[0],xbins[-1]) ax.set_xlabel(r"$x/\lambda$", fontsize=fs["fsa"]) ax.set_ylabel(r"$n(x,y^\ast)$", fontsize=fs["fsa"]) ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(7)) ax.grid() leg = ax.legend(loc="upper left",ncol=1) leg.set_title(r"$y^\ast/\lambda$", prop={"size":fs["fsl"]}) # leg.get_frame().set_alpha(0.7) ## ------------------------------------------------------------------------ title = r"PDF slices. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f, P=%.1f\pi$"%(a,R,S,T,P) # fig.suptitle(title, fontsize=fs["fst"]) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname(histfile)+"/PDFxy1d"+os.path.basename(histfile)[4:-4] plotfile += "."+fs["saveext"] fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile if vb: print me+"Execution time %.1f seconds."%(time.time()-t0) return
def plot_FPEres(histfile, nosave, vb): """ Read in data for a single file density, run it through FP operator, and plot. """ me = me0 + ".plot_FPEres: " ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") psifile = "_psi" in histfile phifile = "_phi" in histfile ## ------------------------------------------------------------------------ ## Space (for axes) bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") rbins = bins["rbins"] erbins = bins["erbins"] r = 0.5 * (rbins[1:] + rbins[:-1]) etar = 0.5 * (erbins[1:] + erbins[:-1]) if psifile: epbins = bins["epbins"] etap = 0.5 * (epbins[1:] + epbins[:-1]) ## Force assert histfile.find("_DL_") ftype = "dlin" f = force_dlin(r, r, R, S) ## Spatial arrays with dimensions commensurate to rho if psifile: ff = f[:, np.newaxis, np.newaxis] 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 else: ff = f[:, np.newaxis] rr = r[:, np.newaxis] ee = etar[np.newaxis, :] dV = (r[1] - r[0]) * (etar[1] - etar[0]) ## Assumes regular grid ## ------------------------------------------------------------------------ ## Load histogram H = np.load(histfile) if phifile: H = H.sum(axis=2) ## If old _phi file ## Normalise and convert to density H /= H.sum() * dV rho = H / ((2 * np.pi)**2.0 * rr * ee) ## ------------------------------------------------------------------------ ## Derivative function D = lambda arr, x, order, **kwargs: \ scipy.ndimage.gaussian_filter1d(arr, 1.0, order=order, axis=kwargs["axis"]) / (x[1]-x[0]) ## FPE operator -- caluclate residue (res should be 0) t0 = time.time() if psifile: res = -D((ee*np.cos(pp)+ff)*rho, r, 1, axis=0) -1/rr*(ee*np.cos(pp)+ff)*rho + 1/rr*D(ee*np.sin(pp)*rho, etap, 1, axis=2) +\ + 1/a*D(ee*rho, etar, 1, axis=1) + 1/a*rho +\ + 1/a**2*1/ee*D(rho, etar, 1, axis=1) + 1/a**2*D(rho, etar, 2, axis=1) + 1/a**2*1/(ee*ee)*D(rho, etap, 2, axis=2) else: ## If radial (r,eta) only, or (r,eta,eta_phi) converted to (r,eta) res = -D((ee+ff)*rho, r, 1, axis=0) -1/rr*(ee+ff)*rho + 1/a*D(ee*rho, etar, 1, axis=1) +\ + 1/a*rho + 1/a**2*1/ee*D(rho, etar, 1, axis=1) +\ + 1/a**2*D(rho, etar, 2, axis=1) if vb: print me + "Residue calculation %.2g seconds." % (time.time() - t0) ## ------------------------------------------------------------------------ ## Plotting fig, axs = plt.subplots(2, 1, sharex=True) X, Y = np.meshgrid(r, etar) ## ------------------------------------------------------------------------ ## Plot density ax = axs[0] if psifile: Z = np.trapz(rho, etap, axis=2).T else: Z = rho.T clim = [0.0, float("%.1g" % (Z.mean() + 5 * np.sqrt(a) * Z.std()))] # clim = [0.0,float("%.1g"%(Z.max()))] im = ax.contourf(X, Y, Z, levels=np.linspace(clim[0], clim[1], 11), vmin=0.0, antialiased=True) cax = mplmal(ax).append_axes("right", size="5%", pad=0.05) fig.colorbar(im, cax=cax) axs[0].set_ylabel(r"$\eta_r$", fontsize=fsa) ax.set_title(r"2D Radial Density. $\alpha=%.1f$, $R=%.1f$, $S=%.1f$." % (a, R, S), fontsize=fst) ## ------------------------------------------------------------------------ ## Plot residue ax = axs[1] # res = scipy.ndimage.gaussian_filter(res,sigma=2.0,order=0) if psifile: Z = np.trapz(res, etap, axis=2).T else: Z = res.T p = 1.0 clim = [ float("%.1g" % (Z.mean() - p * Z.std())), float("%.1g" % (Z.mean() + p * Z.std())) ] ## std dominated by choppy r=0. im = ax.contourf(X, Y, Z, levels=np.linspace(clim[0], clim[1], 11), cmap=cm.BrBG, antialiased=True) cax = mplmal(ax).append_axes("right", size="5%", pad=0.05) fig.colorbar(im, cax=cax) axs[1].set_xlabel(r"$r$", fontsize=fsa) axs[1].set_ylabel(r"$\eta_r$", fontsize=fsa) ax.set_title("Radially Symmetric FP Residual", fontsize=fst) ## ------------------------------------------------------------------------ ## Indicate wall for ax in axs: ax.axvline(S, c="k", lw=2) ax.axvline(R, c="k", lw=2) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname(histfile) + "/FPEres" + os.path.basename( histfile)[4:-4] + "_psi" * psifile + ".jpg" fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile return
import scipy as sp from scipy.optimize import curve_fit from matplotlib import pyplot as plt from sys import argv import os from LE_Utils import filename_par """ Plot pdf of eta if given a file. pdf split into three regions. """ try: histfile = argv[1] a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") inner = False if S==0.0 else True bulk = False if R==S else True ## Normalise each pdf individually (True) or have them all sum to 1 normalise = True ## To save, need argv2 try: nosave = not bool(argv[2]) except IndexError: nosave = True ## Space (for axes) bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz")
def plot_pdf1d(histfile, nosave, vb): """ Calculate Q(r) and q(eta) from file and plot. """ me = me0 + ".plot_pdf1d: " t0 = time.time() ##------------------------------------------------------------------------- ## Filename pars assert "_CAR_" in histfile, me + "Functional only for Cartesian geometry." Casimir = "_CL_" in histfile or "_ML_" in histfile or "_NL_" in histfile a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") try: T = filename_par(histfile, "_T") except ValueError: T = -S doQfit = (R == S and "_DL_" in histfile) plotq = int(False) ##------------------------------------------------------------------------- ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] exbins = bins["exbins"] eybins = bins["eybins"] x = 0.5 * (xbins[1:] + xbins[:-1]) etax = 0.5 * (exbins[1:] + exbins[:-1]) etay = 0.5 * (eybins[1:] + eybins[:-1]) ## Wall indices Rind, Sind = np.abs(x - R).argmin(), np.abs(x - S).argmin() ##------------------------------------------------------------------------- ## Histogram H = np.load(histfile) rho = H / (H.sum() * (x[1] - x[0]) * (etax[1] - etax[0]) * (etay[1] - etay[0])) ## Spatial density Qx = rho.sum(axis=2).sum(axis=1) * (etax[1] - etax[0]) * (etay[1] - etay[0]) ## Force density qx = rho.sum(axis=2).sum(axis=0) * (x[1] - x[0]) * (etay[1] - etay[0]) qy = rho.sum(axis=1).sum(axis=0) * (x[1] - x[0]) * (etax[1] - etax[0]) ##------------------------------------------------------------------------- ## Fit gauss = lambda x, m, s2: 1 / np.sqrt(2 * np.pi * s2) * np.exp(-0.5 * ( x - m)**2 / s2) if doQfit: fitQx = sp.optimize.curve_fit(gauss, x, Qx, p0=[R, 1 / np.sqrt(1 + a)])[0] ##------------------------------------------------------------------------- ## PLOTTING fig, axs = plt.subplots(1 + plotq, 1, figsize=fs["figsize"]) fig.canvas.set_window_title("1D PDFs") ## Set number of ticks for ax in np.ravel([axs]): ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(4)) ##------------------------------------------------------------------------- ## Spatial density plot ax = axs[0] if plotq else axs ## Data ax.plot(x, Qx, label=r"OUP") ax.fill_between(x, 0.0, Qx, color="b", alpha=0.1) ## Gaussian for spatial density if doQfit: ax.plot(x, gauss(x, fitQx[0], 1 / (1 + a)), "c-", label=r"$G\left(\mu, \frac{1}{\alpha+1}\right)$") ## Potential and WN if "_DC_" in histfile: fx = force_dcon([x, 0], R, S)[0] elif "_DL_" in histfile: fx = force_dlin([x, 0], R, S)[0] elif "_CL_" in histfile: fx = force_clin([x, 0], R, S, T)[0] elif "_ML_" in histfile: fx = force_mlin([x, 0], R, S, T)[0] elif "_NL_" in histfile: fx = force_nlin([x, 0], R, S)[0] else: raise IOError, me + "Force not recognised." U = -sp.integrate.cumtrapz(fx, x, initial=0.0) U -= U.min() ## Plot passive density Qx_WN = np.exp(-U) / np.trapz(np.exp(-U), x) ax.plot(x, Qx_WN, "r-", label="Passive") ax.fill_between(x, 0.0, Qx_WN, color="r", alpha=0.1) ## Plot potential ax.plot(x, U / U.max() * ax.get_ylim()[1], "k--", label=r"$U(x)$") ## Indicate bulk ax.axvline(S, c="k", lw=1) ax.axvline(R, c="k", lw=1) if T >= 0.0: ax.axvspan(S, R, color="y", alpha=0.1) ax.axvline(T, c="k", lw=1) ax.axvspan(-R, T, color="y", alpha=0.1) ax.axvline(-R, c="k", lw=1) elif T < 0.0: ax.axvline(-R, c="k", lw=1) ax.set_xlim(left=x[0], right=x[-1]) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$n(x)$", fontsize=fs["fsa"]) ax.grid() ax.legend(loc="upper right", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ##------------------------------------------------------------------------- if plotq: ## Force density plot ax = axs[1] ## Data ax.plot(etax, qx, label=r"Simulation $x$") ax.plot(etay, qy, label=r"Simulation $y$") ## Gaussian ax.plot(etax, gauss(etax, 0.0, 1 / a), "c-", label=r"$G\left(0, \frac{1}{\alpha}\right)$") ax.set_xlabel(r"$\eta$", fontsize=fs["fsa"]) ax.set_ylabel(r"$q(\eta)$", fontsize=fs["fsa"]) ax.grid() ax.legend(loc="upper right", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ##------------------------------------------------------------------------- fig.tight_layout() fig.subplots_adjust(top=0.95) title = r"PDFs in $r$ and $\eta$. $\alpha=%.1f, R=%.1f, S=%.1f$"%(a,R,S) if T<0.0\ else r"PDFs in $r$ and $\eta$. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f$"%(a,R,S,T) else: title = r"Spatial PDF. $\alpha=%.1f, R=%.1g, S=%.1g$"%(a,R,S) if T<0.0\ else r"Spatial PDF. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.f$"%(a,R,S,T) # fig.suptitle(title, fontsize=fs["fst"]) if not nosave: plotfile = os.path.dirname(histfile) + "/PDFxy1d" + os.path.basename( histfile)[4:-4] plotfile += "." + fs["saveext"] fig.savefig(plotfile, format=fs["saveext"]) if vb: print me + "Figure saved to", plotfile if vb: print me + "Execution time %.1f seconds." % (time.time() - t0) return
def plot_pdf3D(histfile, nosave, vb): """ Read in data for a single file and plot 3D PDF. """ me = me0+"plot_pdf3D: " psifile = "_psi" in histfile phifile = "_phi" in histfile ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") ## Space (for axes) bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") rbins = bins["rbins"] erbins = bins["erbins"] r = 0.5*(rbins[1:]+rbins[:-1]) etar = 0.5*(erbins[1:]+erbins[:-1]) ## Load histogram H = np.load(histfile) if (psifile or phifile): H = H.sum(axis=2) ## ------------------------------------------------------------------------ ## Normalise and convert to density H /= np.trapz(np.trapz(H,etar,axis=1),r,axis=0) rho = H / ( (2*np.pi)**2.0 * reduce(np.multiply, np.ix_(r,etar)) ) ## Resample to speed up nrpoints, nerpoints = 100, 100 x, y = np.linspace(r[0],r[-1],nrpoints), np.linspace(etar[0],etar[-1],nerpoints) X, Y = np.meshgrid(x, y) # Z = scipy.interpolate.RectBivariateSpline(r,etar,rho, s=0)(x,y,grid=True).T ## Slower Z = scipy.ndimage.interpolation.zoom(rho,[float(nrpoints)/r.size,float(nerpoints)/etar.size],order=1).T ## Smooth # Z = scipy.ndimage.gaussian_filter(Z, sigma=2.0, order=0, mode="nearest") ## To plot full, unsmoothed data # x, y = r, etar # X, Y = np.meshgrid(x, y) # Z = rho.T ## Marginalised PDFs Q = np.trapz(Z.T*2*np.pi*y,y,axis=1) ## p(r) E = np.trapz(Z*2*np.pi*x,x,axis=1) ## p(eta) ## Fit -- Gaussian fitfunc = lambda xx, B, b: B*b/(2*np.pi)*np.exp(-0.5*b*xx*xx) ## Fit p(eta) fitE = scipy.optimize.curve_fit(fitfunc, y, E, p0=[1.0,a])[0] ## Fit p(r) -- only when S=R fitR = scipy.optimize.curve_fit(fitfunc, (x-R), Q, p0=[(a+1),(a+1)])[0] # print [a,R],"\t",np.around([a+1,fitR[1]],2); return ## ------------------------------------------------------------------------ ## Plotting fig = plt.figure() ax = fig.gca(projection="3d") ## 3D contour plot ax.plot_surface(X, Y, Z, alpha=0.2, rstride=2, cstride=2, antialiased=True) ## 2D contours xoff, yoff, zoff = X.min()-0.1*X.max(), Y.min()-0.1*Y.max(), Z.min()-0.1*Z.max()## Offsets ax.contourf(X, Y, Z, zdir='x', offset=xoff, cmap=cm.coolwarm, antialiased=True) ## p(etar) ax.contourf(X, Y, Z, zdir='y', offset=yoff, cmap=cm.coolwarm, antialiased=True) ## p(r) ax.contourf(X, Y, Z, zdir='z', offset=zoff, cmap=cm.coolwarm, antialiased=True) ## 2D projection ## Plot p(r) and p(etar) envelopes ax.plot(x, yoff*np.ones(y.shape), Q/Q.max()*Z.max(), "r--",lw=3) ## p(r) ax.plot(xoff*np.ones(x.shape), y, E/E.max()*Z.max(), "g--",lw=3) ## p(etar) ## Plot Gaussian fit to p(etar) # ax.plot(xoff*np.ones(x.size), y, fitfunc(y,*fitE)*Z.max()/E.max(), "g--", lw=3, zorder=2) ## Indicate wall if S>0: ax.plot(S*np.ones(x.size), y, 0.8*zoff*np.ones(x.size), "g--", lw=3, zorder=2) if R>0: ax.plot(R*np.ones(x.size), y, 0.8*zoff*np.ones(x.size), "g--", lw=3, zorder=2) ## Accoutrements ax.set_xlim(xoff,ax.get_xlim()[1]) ax.set_ylim(yoff,ax.get_ylim()[1]) ax.set_zlim(zoff,ax.get_zlim()[1]) ax.elev = 30 ax.azim = 45 ax.set_xlabel(r"$r$", fontsize=18) ax.set_ylabel(r"$\eta_r$", fontsize=18) ax.set_zlabel(r"$\rho$", fontsize=18) fig.suptitle(r"PDF in $r$-$\eta_r$ space. $\alpha="+str(a)+"$, $R="+str(R)+"$, $S="+str(S)+"$", fontsize=16) if not nosave: plotfile = os.path.dirname(histfile)+"/PDF3D"+os.path.basename(histfile)[4:-4]+".jpg" fig.savefig(plotfile) if vb: print me+": Figure saved to",plotfile return
import numpy as np import scipy as sp from scipy.optimize import curve_fit from matplotlib import pyplot as plt from sys import argv import os from LE_Utils import filename_par """ Plot pdf of eta if given a file. pdf split into three regions. """ try: histfile = argv[1] a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") inner = False if S == 0.0 else True bulk = False if R == S else True ## Normalise each pdf individually (True) or have them all sum to 1 normalise = True ## To save, need argv2 try: nosave = not bool(argv[2]) except IndexError: nosave = True
def plot_current_2d(currfile, nosave, vb): """ """ me = me0+".plot_current_2d: " t0 = time.time() ##------------------------------------------------------------------------- ## Filename pars a = filename_par(currfile, "_a") R = filename_par(currfile, "_R") S = filename_par(currfile, "_S") T = filename_par(currfile, "_T") ##------------------------------------------------------------------------- ## Load data data = np.load(currfile) xbins = data["xbins"] ybins = data["ybins"] vxbins = data["vxbins"] vybins = data["vybins"] Hxy = data["Hxy"][:,::-1] Vx = data["Vx"][:,::-1] Vy = data["Vy"][:,::-1] del data x = 0.5*(xbins[:-1]+xbins[1:]) y = 0.5*(ybins[:-1]+ybins[1:]) vx = 0.5*(vxbins[:-1]+vxbins[1:]) vy = 0.5*(vybins[:-1]+vybins[1:]) ##------------------------------------------------------------------------- ## SMOOTHING # Vy = sp.ndimage.gaussian_filter(Vy, 1.0, order=0) zx, zy = 0.2, 1.0 Vx = sp.ndimage.interpolation.zoom(Vx, (zx,zy), mode="nearest", cval=0.0) Vy = sp.ndimage.interpolation.zoom(Vy, (zx,zy), mode="nearest", cval=0.0) Vy[:,0] = 0.0 Vy[:,-1] = 0.0 ##------------------------------------------------------------------------- ## PLOTTING plt.rcParams["image.cmap"] = "Greys" fig, ax = plt.subplots(1,1, figsize=fs["figsize"]) fig.canvas.set_window_title("Velocity in x-y") ##------------------------------------------------------------------------- ## Data ax.contourf(x, y, Hxy.T) ax.quiver(x[::int(1/zx)], y[::int(1/zy)], Vx.T, Vy.T) ## Indicate wall yfine = np.linspace(0,T,1000) ax.scatter(+R-S*np.sin(2*np.pi*yfine/T), yfine, c="k", s=1) ## Set number of ticks ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(4)) ax.set_xlim([xbins[0],xbins[-1]]) ax.set_ylim([ybins[0],ybins[-1]]) ax.set_xlabel(r"$x/T$", fontsize=fs["fsa"]) ax.set_ylabel(r"$y/T$", fontsize=fs["fsa"]) ax.grid() # ax.legend(loc="upper right", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ##------------------------------------------------------------------------- if not nosave: plotfile = os.path.dirname(currfile)+"/Jxy"+os.path.basename(currfile)[4:-4] plotfile += "."+fs["saveext"] fig.savefig(plotfile, format=fs["saveext"]) if vb: print me+"Figure saved to",plotfile if vb: print me+"Execution time %.1f seconds."%(time.time()-t0) return
def calc_pressure_dir(histdir, srchstr, noread, vb): """ Calculate the pressure for all files in directory matching string. The """ me = me0+".calc_pressure_dir: " t0 = time.time() ##------------------------------------------------------------------------- ## Dir pars assert "_CAR_" in histdir, me+"Functional only for Cartesian geometry." Casimir = "_DL_" not in histdir ## File discovery filelist = np.sort(glob.glob(histdir+"/BHIS_CAR_*"+srchstr+"*.npy")) numfiles = len(filelist) assert numfiles>1, me+"Check input directory." if vb: print me+"found",numfiles,"files" ##------------------------------------------------------------------------- A, R, S, T, PR, PS, PT, PU, PR_WN, PS_WN, PT_WN, PU_WN = np.zeros([12,numfiles]) ## Retrieve data for i, histfile in enumerate(filelist): ti = time.time() ## Assuming R, S, T are same for all files A[i] = filename_par(histfile, "_a") R[i] = filename_par(histfile, "_R") S[i] = filename_par(histfile, "_S") try: T[i] = filename_par(histfile, "_T") except ValueError: T[i] = -S[i] ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] x = 0.5*(xbins[1:]+xbins[:-1]) ## Wall indices Rind, Sind, Tind = np.abs(x-R[i]).argmin(), np.abs(x-S[i]).argmin()+1, np.abs(x-T[i]).argmin() STind = 0 if T[i]<0.0 else (Sind+Tind)/2 ## Adjust indices for pressure calculation if "_DC_" in histfile: STind = 0 elif "_DL_" in histfile: STind = 0 elif "_NL_" in histfile: STind = Sind Sind = Rind Tind = x.size-Rind ##------------------------------------------------------------------------- ## Histogram H = np.load(histfile) ## Spatial density Qx = H.sum(axis=2).sum(axis=1) / (H.sum()*(x[1]-x[0])) ##------------------------------------------------------------------------- ## Choose force if "_DC_" in histfile: fx = force_dcon([x,0],R[i],S[i])[0] elif "_DL_" in histfile: fx = force_dlin([x,0],R[i],S[i])[0] elif "_CL_" in histfile: fx = force_clin([x,0],R[i],S[i],T[i])[0] elif "_ML_" in histfile: fx = force_mlin([x,0],R[i],S[i],T[i])[0] elif "_NL_" in histfile: fx = force_nlin([x,0],R[i],S[i])[0] else: raise IOError, me+"Force not recognised." ## Calculate integral pressure PR[i] = -sp.integrate.trapz(fx[Rind:]*Qx[Rind:], x[Rind:]) PS[i] = +sp.integrate.trapz(fx[STind:Sind]*Qx[STind:Sind], x[STind:Sind]) PT[i] = -sp.integrate.trapz(fx[Tind:STind]*Qx[Tind:STind], x[Tind:STind]) if "_ML_" in histfile: mRind = x.size-Rind ## Index of wall at x=-R PU[i] = +sp.integrate.trapz(fx[:mRind]*Qx[:mRind], x[:mRind]) if vb: print me+"a=%.1f:\tPressure calculation %.2g seconds"%(A[i],time.time()-ti) ## Potential U = -sp.integrate.cumtrapz(fx, x, initial=0.0); U -= U.min() Qx_WN = np.exp(-U) / np.trapz(np.exp(-U), x) ## WN pressure PR_WN[i] = -sp.integrate.trapz(fx[Rind:]*Qx_WN[Rind:], x[Rind:]) PS_WN[i] = +sp.integrate.trapz(fx[STind:Sind]*Qx_WN[STind:Sind], x[STind:Sind]) if Casimir: PT_WN[i] = -sp.integrate.trapz(fx[Tind:STind]*Qx_WN[Tind:STind], x[Tind:STind]) if "_ML_" in histfile: PU_WN[i] = +sp.integrate.trapz(fx[:mRind]*Qx_WN[:mRind], x[:mRind]) ##------------------------------------------------------------------------- ## SORT BY ALPHA srtidx = A.argsort() A = A[srtidx] R, S, T = R[srtidx], S[srtidx], T[srtidx] PR, PS, PT, PU = PR[srtidx], PS[srtidx], PT[srtidx], PU[srtidx] PR_WN, PS_WN, PT_WN, PU_WN = PR_WN[srtidx], PS_WN[srtidx], PT_WN[srtidx], PU_WN[srtidx] ## Normalise PR /= PR_WN + (PR_WN==0) PS /= PS_WN + (PS_WN==0) if Casimir: PT /= PT_WN + (PT_WN==0) if "_ML_" in histdir: PU /= PU_WN + (PU_WN==0) ##------------------------------------------------------------------------- ## SAVING if not noread: pressfile = histdir+"/PRESS_"+srchstr+".npz" np.savez(pressfile, A=A, R=R, S=S, T=T, PR=PR, PS=PS, PT=PT, PU=PU, PR_WN=PR_WN, PS_WN=PS_WN, PT_WN=PT_WN, PU_WN=PU_WN) if vb: print me+"Calculations saved to",pressfile print me+"Calculation time %.1f seconds."%(time.time()-t0) return {"A":A,"R":R,"S":S,"T":T,"PR":PR,"PS":PS,"PT":PT,"PU":PU, "PR_WN":PR_WN,"PS_WN":PS_WN,"PT_WN":PT_WN,"PU_WN":PU_WN}
def plot_current_1d(histfile, nosave, vb): """ """ me = me0+".plot_current_1d: " t0 = time.time() ##------------------------------------------------------------------------- ## Filename pars a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") ##------------------------------------------------------------------------- ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] exbins = bins["exbins"] x = 0.5*(xbins[1:]+xbins[:-1]) ## Double space x = np.hstack([-x[::-1],x]) etax = 0.5*(exbins[1:]+exbins[:-1]) X, ETAX = np.meshgrid(x,etax, indexing="ij") ## Wall indices Rind, Sind = np.abs(x-R).argmin(), np.abs(x-S).argmin() ##------------------------------------------------------------------------- ## Force if "_DL_" in histfile: fx = force_dlin([x,0],R,S)[0] elif "_CL_" in histfile: fx = force_clin([x,0],R,S,T)[0] elif "_ML_" in histfile: fx = force_mlin([x,0],R,S,T)[0] else: raise IOError, me+"Force not recognised." F = fx.repeat(etax.size).reshape([x.size,etax.size]) ##------------------------------------------------------------------------- ## Histogram H = np.load(histfile) rho = H.sum(axis=2) / (H.sum() * (x[1]-x[0])*(etax[1]-etax[0])) ## Double space rho = np.vstack([rho[::-1,::-1],rho]) ## Currents Jx = (F + ETAX)*rho Jy = -1/a*ETAX*rho - 1/(a*a)*np.gradient(rho,etax[1]-etax[0])[1] Vx, Vy = Jx/rho, Jy/rho ##------------------------------------------------------------------------- ## SMOOTHING Vy = sp.ndimage.gaussian_filter(Vy, 2.0, order=0) ##------------------------------------------------------------------------- ## PLOTTING plt.rcParams["image.cmap"] = "Greys" fig, ax = plt.subplots(1,1, figsize=fs["figsize"]) fig.canvas.set_window_title("Current in x-eta") ##------------------------------------------------------------------------- ## Data ax.contourf(x, etax, rho.T) sx, se = 50, 5 # sx, se = 20, 2 ax.quiver(x[::sx], etax[::se], Vx.T[::se,::sx], Vy.T[::se,::sx] , scale=2, units='x', width=0.011*2) ## Indicate bulk if 0: ax.axvline(S,c="k",lw=1) ax.axvline(R,c="k",lw=1) ## Set number of ticks # ax.xaxis.set_major_locator(NullLocator()) #MaxNLocator(5) # ax.yaxis.set_major_locator(NullLocator()) #MaxNLocator(4) ax.set_xticks([-S,-0.5*(S+T),T,+0.5*(S+T),+S]) ax.set_xticklabels([""]*5) ax.set_yticks([-0.5*(S+T),0.0,+0.5*(S+T)]) ax.set_yticklabels([""]*3) # ax.set_xlim(left=x[0],right=x[-1]) ax.set_xlim(left=-S*2,right=S*2) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\eta$", fontsize=fs["fsa"]) ax.grid() # ax.legend(loc="upper right", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ##------------------------------------------------------------------------- ## Add force line if 1: ax.plot(x, -fx, "k-", label=r"$-f(x)$") ymax = min(3*fx.max(),etax.max()) ax.set_ylim(-ymax,ymax) ##------------------------------------------------------------------------- ## Add in BC line if 1: from LE_CBulkConst import bulk_const x, Q, BC = bulk_const(histfile) ## Double space x = np.hstack([-x[::-1],x]) Q = np.hstack([Q[::-1],Q]) BC = np.hstack([BC[::-1],BC]) ax.plot(x, (Q/Q.max())*0.5*ax.get_ylim()[1]+ax.get_ylim()[0], "b-", lw=4) ax.plot(x, (BC/BC.max())*0.5*ax.get_ylim()[1]+ax.get_ylim()[0], "r-", lw=4) ax2 = ax.twinx() ax2.yaxis.set_major_locator(NullLocator()) ax2.set_ylabel(r"$n$ \& $\left<\eta^2\right>n$ \hfill") ax2.yaxis.set_label_coords(-0.07,0.15) # ax.yaxis.set_label_coords(-0.07,0.5) ##------------------------------------------------------------------------- if not nosave: plotfile = os.path.dirname(histfile)+"/Jxeta"+os.path.basename(histfile)[4:-4] plotfile += "."+fs["saveext"] fig.savefig(plotfile, format=fs["saveext"]) if vb: print me+"Figure saved to",plotfile if vb: print me+"Execution time %.1f seconds."%(time.time()-t0) return
def plot_file(histfile, nosave, vb): """ """ me = me0 + ".plot_file: " ##------------------------------------------------------------------------- ## Dir pars assert "_CAR_" in histfile, me + "Functional only for Cartesian geometry." Casimir = "_CL_" in histfile or "_ML_" in histfile ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") if Casimir else -S ## Calculate quantities x, Q, BC = bulk_const(histfile)[:3] ex2 = BC / (Q + (Q == 0.0)) ##------------------------------------------------------------------------- ## Potential if "_DL_" in histfile: fx = force_dlin([x, 0], R, S)[0] elif "_CL_" in histfile: fx = force_clin([x, 0], R, S, T)[0] elif "_ML_" in histfile: fx = force_mlin([x, 0], R, S, T)[0] elif "_NL_" in histfile: fx = force_nlin([x, 0], R, S)[0] U = -sp.integrate.cumtrapz(fx, x, initial=0.0) U -= U.min() ##------------------------------------------------------------------------- ## Smooth sp.ndimage.gaussian_filter1d(Q, 1.0, order=0, output=Q) sp.ndimage.gaussian_filter1d(BC, 1.0, order=0, output=BC) sp.ndimage.gaussian_filter1d(ex2, 1.0, order=0, output=ex2) ##------------------------------------------------------------------------- ## PLOT fig, ax = plt.subplots(1, 1, figsize=fs["figsize"]) ## Data ax.plot(x, Q / Q.max(), label=r"$n(x)$", lw=2) ax.plot(x, ex2 / ex2.max(), label=r"$\langle\eta_x^2\rangle(x)$", lw=2) ax.plot(x, BC / BC.max(), label=r"$\langle\eta_x^2\rangle \cdot n$", lw=2) ax.plot(x, U / U.max() * ax.get_ylim()[1], "k--", label=r"$U(x)$") ## Indicate bulk region if "_DL_" in histfile: ax.axvspan(S, R, color="yellow", alpha=0.2) ax.axvline(S, c="k", lw=2) ax.axvline(R, c="k", lw=2) elif "_ML_" in histfile: ax.axvspan(S, R, color="yellow", alpha=0.2) ax.axvspan(-R, T, color="yellow", alpha=0.2) ax.axvline(S, c="k", lw=2) ax.axvline(R, c="k", lw=2) ax.axvline(T, c="k", lw=2) ax.axvline(-R, c="k", lw=2) elif "_CL_" in histfile: ax.axvspan(S, R, color="yellow", alpha=0.2) ax.axvspan(0, T, color="yellow", alpha=0.2) ax.axvline(S, c="k", lw=2) ax.axvline(R, c="k", lw=2) ax.axvline(T, c="k", lw=2) ax.axvline(-R, c="k", lw=2) ##------------------------------------------------------------------------- ## ATTRIBUTES ax.set_xlim(left=x[0], right=x[-1]) ax.xaxis.set_major_locator(NullLocator()) ax.yaxis.set_major_locator(NullLocator()) ax.set_xlabel("$x$", fontsize=fs["fsa"]) ax.set_ylabel("Rescaled variable", fontsize=fs["fsa"]) ax.grid() legloc = [0.35, 0.25] if "_ML_" in histfile else [0.32, 0.67] ax.legend(loc=legloc, fontsize=fs["fsl"]).get_frame().set_alpha(0.8) title = r"Bulk Constant. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f$."%(a,R,S,T) if T>=0.0\ else r"Bulk Constant. $\alpha=%.1f, R=%.1f, S=%.1f$."%(a,R,S) # fig.suptitle(title,fontsize=fs["fst"]) ## SAVE # ax.set_ylim(top=BC.max()) plotfile = os.path.dirname(histfile) + "/QEe2" + os.path.basename( histfile)[4:-4] + "." + fs["saveext"] if not nosave: fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile ##------------------------------------------------------------------------- return plotfile
def plot_pdf2d(histfile, nosave, vb): """ Read in data for a single file and plot 2D PDF projections. """ me = me0 + ".plot_pdf2D: " t0 = time.time() ##------------------------------------------------------------------------- ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") try: P = filename_par(histfile, "_P") except: P = 0.0 ##------------------------------------------------------------------------- ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] ybins = bins["ybins"] x = 0.5 * (xbins[1:] + xbins[:-1]) y = 0.5 * (ybins[1:] + ybins[:-1]) ## Wall indices Rind = np.abs(x - R).argmin() ##------------------------------------------------------------------------- ## Histogram / density H = np.load(histfile) rho = H / (H.sum() * (x[1] - x[0]) * (y[1] - y[0])) ## For comparison with Nik++16 rho = rho[:, ::-1] ## ------------------------------------------------------------------------ ## Plotting fig, ax = plt.subplots(1, 1, figsize=fs["figsize"]) fig.canvas.set_window_title("2D PDF") lvls = 20 plt.set_cmap("Greys") #Greys coolwarm ## Plot density cax = ax.contourf(x, y, rho.T, lvls) # cbar = fig.colorbar(cax,) # cbar.locator = MaxNLocator(nbins=5); cbar.update_ticks() ## Indicate bulk yfine = np.linspace(y[0], y[-1], 1000) ax.scatter(+R - S * np.sin(2 * np.pi * yfine / T), yfine, c="k", s=1) ax.set_xlim(xbins[0], xbins[-1]) ax.set_ylim(ybins[0], ybins[-1]) ax.set_xlabel(r"$x/\lambda$", fontsize=fs["fsa"]) ax.set_ylabel(r"$y/\lambda$", fontsize=fs["fsa"]) ax.xaxis.set_major_locator(MaxNLocator(5)) ax.grid() ## ------------------------------------------------------------------------ ## Potential inset ## Plot potential in 3D # left, bottom, width, height = [0.44, 0.16, 0.30, 0.30] ## For lower right # axin = fig.add_axes([left, bottom, width, height], projection="3d") # Rschem, Sschem, Tschem = (2.0,1.0,1.0) # plot_U3D_ulin(axin, Rschem, Sschem, Tschem) ## Plot potential in 2D try: cbar left, bottom, width, height = [0.47, 0.16, 0.25, 0.25] ## For lower right except: left, bottom, width, height = [0.57, 0.16, 0.30, 0.30] axin = fig.add_axes([left, bottom, width, height]) Rschem, Sschem, Tschem = (2.0, 1.0, 1.0) plot_U2D_ulin(axin, Rschem, Sschem, Tschem) axin.set_axis_bgcolor(plt.get_cmap()(0.00)) axin.patch.set_facecolor("None") ## ------------------------------------------------------------------------ title = r"PDF projections. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f, P=%.1f\pi$" % ( a, R, S, T, P) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname(histfile) + "/PDFxy2d" + os.path.basename( histfile)[4:-4] plotfile += "." + fs["saveext"] fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile if vb: print me + "Execution time %.1f seconds." % (time.time() - t0) return
def plot_pdfq1d(histfile, nosave, vb): """ Read in data for a single file and plot a quasi-1d 2D PDF projections. """ me = me0+".plot_pdfq1d: " t0 = time.time() ##------------------------------------------------------------------------- ## Get pars from filename assert "_CAR_" in histfile, me+"Functional only for Cartesian geometry." Casimir = "_CL_" in histfile a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") if Casimir else -S ##------------------------------------------------------------------------- ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] exbins = bins["exbins"] x = 0.5*(xbins[1:]+xbins[:-1]) etax = 0.5*(exbins[1:]+exbins[:-1]) ## Wall indices Rind, Sind = np.abs(x-R).argmin(), np.abs(x-S).argmin() ##------------------------------------------------------------------------- ## Histogram / density H = np.load(histfile).sum(axis=2) rhoxex = H / (H.sum() * (x[1]-x[0])*(etax[1]-etax[0])) ## ------------------------------------------------------------------------ ## Plotting fig, ax = plt.subplots(1,1, figsize=fs["figsize"]) fig.canvas.set_window_title("Quasi-1D PDF") ## Set number of ticks ax.xaxis.set_major_locator(NullLocator()) ax.yaxis.set_major_locator(NullLocator()) plt.rcParams["image.cmap"] = "Greys"#"coolwarm" ## ------------------------------------------------------------------------ ## x-etax ax.contourf(x,etax,rhoxex.T) ## Indicate bulk ax.axvline(S,c="k",lw=1) ax.axvline(R,c="k",lw=1) if T>=0.0: ax.axvline(T,c="k",lw=1) elif T<0.0 and ("_DL_" not in histfile and "_DC_" not in histfile): ax.axvline(-R,c="k",lw=1) # ax.axvspan(S,R,color="y",alpha=0.1) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\eta_x$", fontsize=fs["fsa"]) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname(histfile)+"/PDFxyq1d"+os.path.basename(histfile)[4:-4] plotfile += "."+fs["saveext"] fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile if vb: print me+"Execution time %.1f seconds."%(time.time()-t0) return
def plot_pdf1d(histfile, nosave, vb): """ Read in data for a single file and plot a few 1D PDF slices. """ me = me0 + ".plot_pdf1D: " t0 = time.time() ##------------------------------------------------------------------------- ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") try: P = filename_par(histfile, "_P") except: P = 0.0 ##------------------------------------------------------------------------- ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] ybins = bins["ybins"] x = 0.5 * (xbins[1:] + xbins[:-1]) y = 0.5 * (ybins[1:] + ybins[:-1]) ##------------------------------------------------------------------------- ## Histogram / density H = np.load(histfile) rho = H / (H.sum() * (x[1] - x[0]) * (y[1] - y[0])) ## For comparison with Nik++16 rho = rho[:, ::-1] ## ------------------------------------------------------------------------ ## Plotting fig, ax = plt.subplots(1, 1, figsize=fs["figsize"]) fig.canvas.set_window_title("1D PDF") ## Slices to plot idxs = np.linspace(y.size / 4, y.size * 3 / 4, 11) labs = [r"$%.2f$" % (float(i) / y.size) for i in idxs] ## Plot density and wall for i, idx in enumerate(idxs): sp.ndimage.gaussian_filter1d(rho[:, idx], 1.0, order=0, output=rho[:, idx]) off = 0.0 * S * np.sin(idxs[i] / y.size * T * 2 * np.pi) ax.plot(x + off, rho[:, idx], label=labs[i]) ax.axvline(+R - S * np.sin(2 * np.pi * y[idx] / T) + off, c=ax.lines[-1].get_color(), ls="--") ax.set_xlim(xbins[0], xbins[-1]) ax.set_xlabel(r"$x/\lambda$", fontsize=fs["fsa"]) ax.set_ylabel(r"$n(x,y^\ast)$", fontsize=fs["fsa"]) ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(7)) ax.grid() leg = ax.legend(loc="upper left", ncol=1) leg.set_title(r"$y^\ast/\lambda$", prop={"size": fs["fsl"]}) # leg.get_frame().set_alpha(0.7) ## ------------------------------------------------------------------------ title = r"PDF slices. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f, P=%.1f\pi$" % ( a, R, S, T, P) # fig.suptitle(title, fontsize=fs["fst"]) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname(histfile) + "/PDFxy1d" + os.path.basename( histfile)[4:-4] plotfile += "." + fs["saveext"] fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile if vb: print me + "Execution time %.1f seconds." % (time.time() - t0) return
def plot_dir(histdir, srchstr, logplot, nosave, vb): """ For each file in directory, calculate the pressure in both ways for all walls (where applicable) and plot against alpha. """ me = me0+".plot_dir: " filelist = np.sort(glob.glob(histdir+"/BHIS_CAR_*"+srchstr+"*.npy")) numfiles = filelist.size if vb: print me+"Found",numfiles,"files." ## Initialise arrays A, pR, pS, pT, PR, PS, PT = np.zeros([7,numfiles]) ## Retrieve data for i, histfile in enumerate(filelist): Casimir = "_CL_" in histfile or "_ML_" in histfile or "_NL_" in histfile ## Get pars from filename A[i] = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") if Casimir else -S ## Calculate BC x, Qx, BC = bulk_const(histfile)[:3] ## Wall indices Rind, Sind, Tind = np.abs(x-R).argmin(), np.abs(x-S).argmin(), np.abs(x-T).argmin() STind = 0 if "_DL_" in histfile else (Tind+Sind)/2 ##--------------------------------------------------------------------- ## Calculate pressure from BC if "_DL_" in histfile: BCsr = BC[Sind:Rind+1].mean() pR[i] = A[i] * BCsr pS[i] = A[i] * BCsr elif "_CL_" in histfile: BCsr = BC[Sind:Rind+1].mean() BCts = BC[STind] BC0t = BC[0:Tind+1].mean() pR[i] = A[i] * BCsr pS[i] = A[i] * (BCsr - BCts) pT[i] = A[i] * (BC0t - BCts) elif "_ML_" in histfile: BCsr = BC[Sind:Rind+1].mean() BCts = BC[STind] BCrt = BC[x.size-Rind:Tind+1].mean() pR[i] = A[i] * BCsr pS[i] = A[i] * (-BCsr + BCts) pT[i] = A[i] * (-BCrt + BCts) elif "_NL_" in histfile: BCr = BC[Rind] BCs = BC[Sind] BCmr = BC[x.size-Rind] pR[i] = A[i] * BCr pS[i] = A[i] * (BCs - BCr) pT[i] = A[i] * (BCs - BCmr) ##--------------------------------------------------------------------- ## Calculate pressure from integral ## Choose force if "_DL_" in histfile: fx = force_dlin([x,0],R,S)[0] elif "_CL_" in histfile: fx = force_clin([x,0],R,S,T)[0] elif "_ML_" in histfile: fx = force_mlin([x,0],R,S,T)[0] elif "_NL_" in histfile: fx = force_nlin([x,0],R,S)[0] ## Calculate integral pressure PR[i] = -sp.integrate.trapz(fx[Rind:]*Qx[Rind:], x[Rind:]) PS[i] = +sp.integrate.trapz(fx[STind:Sind]*Qx[STind:Sind], x[STind:Sind]) PT[i] = -sp.integrate.trapz(fx[Tind:STind]*Qx[Tind:STind], x[Tind:STind]) ##--------------------------------------------------------------------- ## SORT BY ALPHA srtidx = A.argsort() A = A[srtidx] pR, pS, pT = pR[srtidx], pS[srtidx], pT[srtidx] PR, PS, PT = PR[srtidx], PS[srtidx], PT[srtidx] ##------------------------------------------------------------------------- ## Calculate white noise PDF and pressure -- assuming alpha is only varying parameter U = -sp.integrate.cumtrapz(fx, x, initial=0.0); U -= U.min() Qx_WN = np.exp(-U) / np.trapz(np.exp(-U),x) PR_WN = -sp.integrate.trapz(fx[Rind:]*Qx_WN[Rind:], x[Rind:]) PS_WN = +sp.integrate.trapz(fx[STind:Sind]*Qx_WN[STind:Sind], x[STind:Sind]) PT_WN = -sp.integrate.trapz(fx[Tind:STind]*Qx_WN[Tind:STind], x[Tind:STind]) ## Normalise pR /= PR_WN; pS /= PS_WN; pT /= PT_WN PR /= PR_WN; PS /= PS_WN; PT /= PT_WN ##------------------------------------------------------------------------- ## Add a=0 point if 0.0 not in A: nlin = np.unique(S).size A = np.hstack([[0.0]*nlin,A]) pR = np.hstack([[1.0]*nlin,pR]) pS = np.hstack([[1.0]*nlin,pS]) PR = np.hstack([[1.0]*nlin,PR]) PS = np.hstack([[1.0]*nlin,PS]) ##------------------------------------------------------------------------- ## PLOT DATA fig, ax = plt.subplots(1,1, figsize=fs["figsize"]) sty = ["-","--",":"] A += int(logplot) """ lpR = ax.plot(A, pR, "o"+sty[0], label=r"BC pR") lpS = ax.plot(A, pS, "o"+sty[1], c=ax.lines[-1].get_color(), label=r"BC pS") if Casimir: lpT = ax.plot(A, pT, "o"+sty[2], c=ax.lines[-1].get_color(), label=r"BC pT") ax.plot(A, PR, "v"+sty[0], label=r"Int PR") ax.plot(A, PS, "v"+sty[1], c=ax.lines[-1].get_color(), label=r"Int PS") if Casimir: ax.plot(A, PT, "v"+sty[2], c=ax.lines[-1].get_color(), label=r"Int PT") """ lpR = ax.plot(A, 0.5*(pR+pS), "o--", label=r"$\alpha\left<\eta^2\right>n(x)|^{\rm bulk}$") ax.plot(A, 0.5*(PR+PS), "v--", label=r"$-\int f(x)n(x) {\rm d}x$") ##------------------------------------------------------------------------- ## ACCOUTREMENTS if logplot: ax.set_xscale("log"); ax.set_yscale("log") xlim = (ax.get_xlim()[0],A[-1]) xlabel = r"$1+\alpha$" else: xlim = (0.0,A[-1]) xlabel = r"$\alpha$" ax.set_xlim(xlim) ax.set_ylim(1e-1,1e+1) ax.set_xlabel(xlabel,fontsize=fs["fsa"]) ax.set_ylabel(r"$P(\alpha)/P^{\rm passive}$",fontsize=fs["fsa"]) ax.grid() ax.legend(loc="best", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) title = "Pressure normalised by WN result. $R=%.1f, S=%.1f, T=%.1f.$"%(R,S,T) if T>=0.0\ else "Pressure normalised by WN result. $R=%.1f, S=%.1f.$"%(R,S) # fig.suptitle(title,fontsize=fs["fst"]) ## SAVING plotfile = histdir+"/QEe2_Pa_R%.1f_S%.1f_T%.1f"%(R,S,T) if T>=0.0\ else histdir+"/QEe2_Pa_R%.1f_S%.1f"%(R,S) plotfile += "_loglog"*logplot+"."+fs["saveext"] if not nosave: fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile return plotfile
def plot_pdf1d_intx(histfile, nosave, vb): """ Read in data for a single file and plot the density integrated from the wall to infinity as a function of y. """ me = me0 + ".plot_pdf1D_intx: " t0 = time.time() ##------------------------------------------------------------------------- ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") try: P = filename_par(histfile, "_P") except: P = 0.0 ##------------------------------------------------------------------------- ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] ybins = bins["ybins"] x = 0.5 * (xbins[1:] + xbins[:-1]) y = 0.5 * (ybins[1:] + ybins[:-1]) ##------------------------------------------------------------------------- ## Histogram / density H = np.load(histfile) rho = H / (H.sum() * (x[1] - x[0]) * (y[1] - y[0])) ## For comparison with Nik++16 rho = rho[:, ::-1] ## Integrate rho over x IN WALL REGION Qy = np.zeros(y.size) wind = +R - S * np.sin(2 * np.pi * y / T) ### HARD CODED for i, yi in enumerate(y): Qy[i] = np.trapz(rho[wind[i]:, i], x[wind[i]:], axis=0) ## ------------------------------------------------------------------------ ## Plotting fig, ax = plt.subplots(1, 1, figsize=fs["figsize"]) fig.canvas.set_window_title("1D PDF integrated along x") ## Plot density and wall ax.plot(y, Qy) ## Indicate inflexion point ax.axvspan(y[0], 0.5 * T, color="g", alpha=0.2) ax.set_xlabel(r"$y$", fontsize=fs["fsa"]) ax.set_ylabel(r"$Q_x(y)$", fontsize=fs["fsa"]) ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(7)) ax.grid() ax.legend(loc="upper left") ## ------------------------------------------------------------------------ title = r"PDF slice integrated over x in wall region. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f, P=%.1f\pi$" % ( a, R, S, T, P) fig.suptitle(title, fontsize=fs["fst"]) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname( histfile) + "/PDFxy1dintx" + os.path.basename(histfile)[4:-4] plotfile += "." + fs["saveext"] fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile if vb: print me + "Execution time %.1f seconds." % (time.time() - t0) return
def plot_peta_CL(histfile, fig, ax, nosave=True): """ """ me = me0 + ".plot_peta_CL: " assert ("_CL_" in histfile) or ("_ML_" in histfile), me + "Designed for Casmir geometry." a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") ## Space (for axes) bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] xmax = xbins[-1] x = 0.5 * (xbins[1:] + xbins[:-1]) exbins = bins["exbins"] ex = 0.5 * (exbins[1:] + exbins[:-1]) ## Wall indices Rind = np.abs(x - R).argmin() Sind = np.abs(x - S).argmin() Tind = np.abs(x - T).argmin() cuspind = np.abs(x - 0.5 * (S + T)).argmin() ## Load histogram; normalise H = np.load(histfile) try: H = H.sum(axis=2) except ValueError: pass H /= np.trapz(np.trapz(H, ex, axis=1), x, axis=0) ## Distribution on either side of the wall: inner, outer xin = x[:cuspind] Hin = H[:cuspind, :] xout = x[cuspind:] Hout = H[cuspind:, :] ## q is probability density in eta. r is no longer relevant. ## if "_CL_" in histfile: qin = H[Tind] qout = np.trapz(H[Sind:Rind + 1], x[Sind:Rind + 1], axis=0) labels = ["Interior", "Bulk"] colour = ["g", "b"] elif "_ML_" in histfile: ## in is now right region and out is left region qin = np.trapz(H[Sind:Rind + 1], x[Sind:Rind + 1], axis=0) if Sind != Rind else H[Sind] qout = np.trapz(H[x.size - Rind:Tind], x[x.size - Rind:Tind], axis=0) labels = ["Small bulk", "Large bulk"] colour = ["b", "g"] ## Normalise each individually so we can see just distrbution qin /= np.trapz(qin, ex) qout /= np.trapz(qout, ex) ##--------------------------------------------------------------- ## PDF PLOT ax.plot(ex, qout, colour[0] + "-", label=labels[1]) ax.fill_between(ex, 0, qout, facecolor=colour[0], alpha=0.1) ax.plot(ex, qin, colour[1] + "-", label=labels[0]) ax.fill_between(ex, 0, qin, facecolor=colour[1], alpha=0.1) ## ##--------------------------------------------------------------- ## ## Entire in/out region ## qIN = np.trapz(H[0:cuspind], x[0:cuspind], axis=0) ## qOUT = np.trapz(H[cuspind:], x[cuspind:], axis=0) ## ## Normalise pdf ### qIN /= np.trapz(qIN, ex) ### qOUT /= np.trapz(qOUT, ex) ## ## Normalise by size of region ### qIN /= x[cuspind]-x[0] ### qOUT /= x[-1]-x[cuspind] ## ## Plot ### ax.plot(ex, qIN, "b-", label=labels[0]) ### ax.fill_between(ex,0,qIN,facecolor="blue",alpha=0.1) ### ax.plot(ex, qOUT, "g-", label=labels[1]) ### ax.fill_between(ex,0,qOUT,facecolor="green",alpha=0.1) # ## Lots of intermediate # colours = ["r","k","b","k","grey","orange","grey","k","b"] # linesty = ["-"]*6+["--"]*3 # for i,idx in enumerate([0,cuspind/2,cuspind,3*cuspind/2,Sind,(Sind+Rind)/2,Rind,Rind+cuspind/2,Rind+cuspind]): # ax.plot(ex, H[idx], c=colours[i], ls=linesty[i], label="%.2f"%(x[idx])) # ax.set_ylim(0,1.5*H[Sind].max()) ## ## ## ##--------------------------------------------------------------- ## Accoutrements ax.yaxis.set_major_locator(MaxNLocator(7)) ax.set_xlabel(r"$\eta$") ax.set_ylabel(r"$p(\eta)$") ax.grid() ## Make legend if standalone if not nosave: ax.legend() ##--------------------------------------------------------------- ## Plot inset if not nosave: if "_ML_" in histfile: ## Plot potential as inset x = np.linspace(-R - 1.5, +R + 1.5, x.size) fx = force_mlin([x, 0], R, S, T)[0] U = -sp.integrate.cumtrapz(fx, x, initial=0.0) U -= U.min() left, bottom, width, height = [0.18, 0.63, 0.25, 0.25] axin = fig.add_axes([left, bottom, width, height]) axin.plot(x, U, "k-") # axin.axvspan(x[0],x[cuspind], color=lL[0].get_color(),alpha=0.2) # axin.axvspan(x[cuspind],x[-1], color=lR[0].get_color(),alpha=0.2) axin.set_xlim(-R - 1.5, R + 1.5) # axin.set_ylim(top=2*U[cuspind]) axin.xaxis.set_major_locator(NullLocator()) axin.yaxis.set_major_locator(NullLocator()) axin.set_xlabel(r"$x$", fontsize=fs["fsa"] - 5) axin.set_ylabel(r"$U$", fontsize=fs["fsa"] - 5) ##--------------------------------------------------------------- # fig.suptitle(r"PDF of $\eta$, divided into regions. $\alpha="+str(a)+"$, $R="+str(R)+"$, $S="+str(S)+"$") if not nosave: plotfile = os.path.dirname(histfile) + "/PDFeta" + os.path.basename( histfile)[4:-4] + ".pdf" fig.savefig(plotfile) print me + "Figure saved to", plotfile return
def calc_energy_dir(histdir, srchstr, noread, vb): """ Calculate the steady state energy for all files in directory matching string. The """ me = me0+".calc_energy_dir: " t0 = time.time() ##------------------------------------------------------------------------- ## Dir pars assert ("_POL_" in histdir or "_CIR_" in histdir), me+"Functional only for polar geometry." ## File discovery filelist = np.sort(glob.glob(histdir+"/BHIS_*"+srchstr+"*.npy")) numfiles = len(filelist) assert numfiles>1, me+"Check input directory." if vb: print me+"found",numfiles,"files" ##------------------------------------------------------------------------- A, R, S, E, E_WN = np.zeros([5,numfiles]) ## Retrieve data for i, histfile in enumerate(filelist): ti = time.time() ## Assuming R, S, T are same for all files A[i] = filename_par(histfile, "_a") R[i] = filename_par(histfile, "_R") S[i] = filename_par(histfile, "_S") ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") rbins = bins["rbins"] r = 0.5*(rbins[1:]+rbins[:-1]) erbins = bins["erbins"] er = 0.5*(erbins[1:]+erbins[:-1]) ## Wall indices Rind, Sind = np.abs(r-R[i]).argmin(), np.abs(r-S[i]).argmin() ##------------------------------------------------------------------------- ## Load histogram, normalise H = np.load(histfile) try: H = H.sum(axis=2) except ValueError: pass H = np.trapz(H, er, axis=1) ## Noise dimension irrelevant here; convert to *pdf* rho = H/(2*np.pi*r) / np.trapz(H, x=r, axis=0) ##------------------------------------------------------------------------- ## Choose force f = force_dlin(r,r,R[i],S[i]) U = -sp.integrate.cumtrapz(f, r, initial=0.0); U -= U.min() ## Calculate energy E[i] = sp.integrate.trapz(U*rho*2*np.pi*r, r) if vb: print me+"a=%.1f:\tEnergy calculation %.2g seconds"%(A[i],time.time()-ti) ## Potential rho_WN = np.exp(-U) / np.trapz(np.exp(-U), r) ## WN energy E_WN[i] = sp.integrate.trapz(U*rho_WN, r) ##------------------------------------------------------------------------- ## SORT BY ALPHA srtidx = A.argsort() A = A[srtidx] R, S = R[srtidx], S[srtidx] E, E_WN = E[srtidx], E_WN[srtidx] ##------------------------------------------------------------------------- ## SAVING if not noread: pressfile = histdir+"/E_"+srchstr+".npz" np.savez(pressfile, A=A, R=R, S=S, E=E, E_WN=E_WN) if vb: print me+"Calculations saved to",pressfile print me+"Calculation time %.1f seconds."%(time.time()-t0) return {"A":A,"R":R,"S":S,"E":E,"E_WN":E_WN}
def calc_energy_dir(histdir, srchstr, noread, vb): """ Calculate the steady state energy for all files in directory matching string. The """ me = me0 + ".calc_energy_dir: " t0 = time.time() ##------------------------------------------------------------------------- ## Dir pars assert ("_POL_" in histdir or "_CIR_" in histdir), me + "Functional only for polar geometry." ## File discovery filelist = np.sort(glob.glob(histdir + "/BHIS_*" + srchstr + "*.npy")) numfiles = len(filelist) assert numfiles > 1, me + "Check input directory." if vb: print me + "found", numfiles, "files" ##------------------------------------------------------------------------- A, R, S, E, E_WN = np.zeros([5, numfiles]) ## Retrieve data for i, histfile in enumerate(filelist): ti = time.time() ## Assuming R, S, T are same for all files A[i] = filename_par(histfile, "_a") R[i] = filename_par(histfile, "_R") S[i] = filename_par(histfile, "_S") ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") rbins = bins["rbins"] r = 0.5 * (rbins[1:] + rbins[:-1]) erbins = bins["erbins"] er = 0.5 * (erbins[1:] + erbins[:-1]) ## Wall indices Rind, Sind = np.abs(r - R[i]).argmin(), np.abs(r - S[i]).argmin() ##------------------------------------------------------------------------- ## Load histogram, normalise H = np.load(histfile) try: H = H.sum(axis=2) except ValueError: pass H = np.trapz(H, er, axis=1) ## Noise dimension irrelevant here; convert to *pdf* rho = H / (2 * np.pi * r) / np.trapz(H, x=r, axis=0) ##------------------------------------------------------------------------- ## Choose force f = force_dlin(r, r, R[i], S[i]) U = -sp.integrate.cumtrapz(f, r, initial=0.0) U -= U.min() ## Calculate energy E[i] = sp.integrate.trapz(U * rho * 2 * np.pi * r, r) if vb: print me + "a=%.1f:\tEnergy calculation %.2g seconds" % ( A[i], time.time() - ti) ## Potential rho_WN = np.exp(-U) / np.trapz(np.exp(-U), r) ## WN energy E_WN[i] = sp.integrate.trapz(U * rho_WN, r) ##------------------------------------------------------------------------- ## SORT BY ALPHA srtidx = A.argsort() A = A[srtidx] R, S = R[srtidx], S[srtidx] E, E_WN = E[srtidx], E_WN[srtidx] ##------------------------------------------------------------------------- ## SAVING if not noread: pressfile = histdir + "/E_" + srchstr + ".npz" np.savez(pressfile, A=A, R=R, S=S, E=E, E_WN=E_WN) if vb: print me + "Calculations saved to", pressfile print me + "Calculation time %.1f seconds." % (time.time() - t0) return {"A": A, "R": R, "S": S, "E": E, "E_WN": E_WN}
def pressure_pdf_file(histfile, plotpress, verbose): """ Make plot for a single file """ me = "LE_inSPressure.pressure_pdf_file: " t0 = time() ## Filename plotfile = os.path.dirname(histfile)+"/PDF"+os.path.basename(histfile)[4:-4]+".jpg" ## Get pars from filename a = filename_par(histfile, "_a") S = filename_par(histfile, "_S") R,lam,nu = None, None, None ftype = "linin" if verbose: print me+"alpha =",a,"and S =",S ## 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 = rmax ## Start point for computing pressures rinid = -1#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, x=r, axis=0) rho /= rho[-1] ## 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,[R,S,lam,nu],ftype,verbose) ##--------------------------------------------------------------- ## 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)+"$, $S = "+str(S)+"$" # xlim = [S-2*lam,R+2*lam] if (ftype[-3:]=="tan" or ftype[-2:]=="nu") else [S-4.0,R+4.0] ##--------------------------------------------------------------- ## PDF PLOT ## Wall plot_wall(ax, ftype, [R,S,lam,nu], r) ## PDF and WN PDF ax.plot(r,rho, "b-", label="CN simulation") ax.plot(r_WN,rho_WN,"r-", label="WN theory") ## Accoutrements # ax.set_xlim(xlim) # ax.set_ylim(bottom=0.0, top=min(20,round(max(rho.max(),rho_WN.max())+0.05,1))) 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=fsa) ax.set_ylabel("$\\rho(r,\\phi)$", fontsize=fsa) ax.grid() ##--------------------------------------------------------------- ## 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,S],"\t",np.around([p[:20].mean()],6) ##----------------------------------------------------------- ## PRESSURE PLOT ax = axs[1] ## Wall plot_wall(ax, ftype, [R,S,lam,nu], r) ## Pressure and WN pressure ax.plot(r,p,"b-",label="CN simulation") ax.plot(r_WN,p_WN,"r-",label="WN theory") ## 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=fsa) ax.set_ylabel("$P(r)$", fontsize=fsa) ax.grid() ##--------------------------------------------------------------- ## Tidy figure fig.suptitle(figtit,fontsize=fst) fig.tight_layout(); plt.subplots_adjust(top=0.9) fig.savefig(plotfile) if verbose: print me+"plot saved to",plotfile return
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_peta_CL(histfile, fig, ax, nosave=True): """ """ me = me0+".plot_peta_CL: " assert ("_CL_" in histfile) or ("_ML_" in histfile), me+"Designed for Casmir geometry." a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") ## Space (for axes) bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] xmax = xbins[-1] x = 0.5*(xbins[1:]+xbins[:-1]) exbins = bins["exbins"] ex = 0.5*(exbins[1:]+exbins[:-1]) ## Wall indices Rind = np.abs(x-R).argmin() Sind = np.abs(x-S).argmin() Tind = np.abs(x-T).argmin() cuspind = np.abs(x-0.5*(S+T)).argmin() ## Load histogram; normalise H = np.load(histfile) try: H = H.sum(axis=2) except ValueError: pass H /= np.trapz(np.trapz(H,ex,axis=1),x,axis=0) ## Distribution on either side of the wall: inner, outer xin = x[:cuspind] Hin = H[:cuspind,:] xout = x[cuspind:] Hout = H[cuspind:,:] ## q is probability density in eta. r is no longer relevant. ## if "_CL_" in histfile: qin = H[Tind] qout = np.trapz(H[Sind:Rind+1], x[Sind:Rind+1], axis=0) labels = ["Interior","Bulk"] colour = ["g","b"] elif "_ML_" in histfile: ## in is now right region and out is left region qin = np.trapz(H[Sind:Rind+1], x[Sind:Rind+1], axis=0) if Sind!=Rind else H[Sind] qout = np.trapz(H[x.size-Rind:Tind], x[x.size-Rind:Tind], axis=0) labels = ["Small bulk","Large bulk"] colour = ["b","g"] ## Normalise each individually so we can see just distrbution qin /= np.trapz(qin, ex) qout /= np.trapz(qout, ex) ##--------------------------------------------------------------- ## PDF PLOT ax.plot(ex, qout, colour[0]+"-", label=labels[1]) ax.fill_between(ex,0,qout,facecolor=colour[0],alpha=0.1) ax.plot(ex, qin, colour[1]+"-", label=labels[0]) ax.fill_between(ex,0,qin,facecolor=colour[1],alpha=0.1) ## ##--------------------------------------------------------------- ## ## Entire in/out region ## qIN = np.trapz(H[0:cuspind], x[0:cuspind], axis=0) ## qOUT = np.trapz(H[cuspind:], x[cuspind:], axis=0) ## ## Normalise pdf ### qIN /= np.trapz(qIN, ex) ### qOUT /= np.trapz(qOUT, ex) ## ## Normalise by size of region ### qIN /= x[cuspind]-x[0] ### qOUT /= x[-1]-x[cuspind] ## ## Plot ### ax.plot(ex, qIN, "b-", label=labels[0]) ### ax.fill_between(ex,0,qIN,facecolor="blue",alpha=0.1) ### ax.plot(ex, qOUT, "g-", label=labels[1]) ### ax.fill_between(ex,0,qOUT,facecolor="green",alpha=0.1) # ## Lots of intermediate # colours = ["r","k","b","k","grey","orange","grey","k","b"] # linesty = ["-"]*6+["--"]*3 # for i,idx in enumerate([0,cuspind/2,cuspind,3*cuspind/2,Sind,(Sind+Rind)/2,Rind,Rind+cuspind/2,Rind+cuspind]): # ax.plot(ex, H[idx], c=colours[i], ls=linesty[i], label="%.2f"%(x[idx])) # ax.set_ylim(0,1.5*H[Sind].max()) ## ## ## ##--------------------------------------------------------------- ## Accoutrements ax.yaxis.set_major_locator(MaxNLocator(7)) ax.set_xlabel(r"$\eta$") ax.set_ylabel(r"$p(\eta)$") ax.grid() ## Make legend if standalone if not nosave: ax.legend() ##--------------------------------------------------------------- ## Plot inset if not nosave: if "_ML_" in histfile: ## Plot potential as inset x = np.linspace(-R-1.5,+R+1.5,x.size) fx = force_mlin([x,0],R,S,T)[0] U = -sp.integrate.cumtrapz(fx, x, initial=0.0); U -= U.min() left, bottom, width, height = [0.18, 0.63, 0.25, 0.25] axin = fig.add_axes([left, bottom, width, height]) axin.plot(x, U, "k-") # axin.axvspan(x[0],x[cuspind], color=lL[0].get_color(),alpha=0.2) # axin.axvspan(x[cuspind],x[-1], color=lR[0].get_color(),alpha=0.2) axin.set_xlim(-R-1.5, R+1.5) # axin.set_ylim(top=2*U[cuspind]) axin.xaxis.set_major_locator(NullLocator()) axin.yaxis.set_major_locator(NullLocator()) axin.set_xlabel(r"$x$", fontsize = fs["fsa"]-5) axin.set_ylabel(r"$U$", fontsize = fs["fsa"]-5) ##--------------------------------------------------------------- # fig.suptitle(r"PDF of $\eta$, divided into regions. $\alpha="+str(a)+"$, $R="+str(R)+"$, $S="+str(S)+"$") if not nosave: plotfile = os.path.dirname(histfile)+"/PDFeta"+os.path.basename(histfile)[4:-4]+".pdf" fig.savefig(plotfile) print me+"Figure saved to",plotfile return
def plot_pdfq1d(histfile, nosave, vb): """ Read in data for a single file and plot a quasi-1d 2D PDF projections. """ me = me0 + ".plot_pdfq1d: " t0 = time.time() ##------------------------------------------------------------------------- ## Get pars from filename assert "_CAR_" in histfile, me + "Functional only for Cartesian geometry." Casimir = "_CL_" in histfile a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") if Casimir else -S ##------------------------------------------------------------------------- ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] exbins = bins["exbins"] x = 0.5 * (xbins[1:] + xbins[:-1]) etax = 0.5 * (exbins[1:] + exbins[:-1]) ## Wall indices Rind, Sind = np.abs(x - R).argmin(), np.abs(x - S).argmin() ##------------------------------------------------------------------------- ## Histogram / density H = np.load(histfile).sum(axis=2) rhoxex = H / (H.sum() * (x[1] - x[0]) * (etax[1] - etax[0])) ## ------------------------------------------------------------------------ ## Plotting fig, ax = plt.subplots(1, 1, figsize=fs["figsize"]) fig.canvas.set_window_title("Quasi-1D PDF") ## Set number of ticks ax.xaxis.set_major_locator(NullLocator()) ax.yaxis.set_major_locator(NullLocator()) plt.rcParams["image.cmap"] = "Greys" #"coolwarm" ## ------------------------------------------------------------------------ ## x-etax ax.contourf(x, etax, rhoxex.T) ## Indicate bulk ax.axvline(S, c="k", lw=1) ax.axvline(R, c="k", lw=1) if T >= 0.0: ax.axvline(T, c="k", lw=1) elif T < 0.0 and ("_DL_" not in histfile and "_DC_" not in histfile): ax.axvline(-R, c="k", lw=1) # ax.axvspan(S,R,color="y",alpha=0.1) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\eta_x$", fontsize=fs["fsa"]) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname(histfile) + "/PDFxyq1d" + os.path.basename( histfile)[4:-4] plotfile += "." + fs["saveext"] fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile if vb: print me + "Execution time %.1f seconds." % (time.time() - t0) return
def plot_FPEres(histfile, nosave, vb): """ Read in data for a single file density, run it through FP operator, and plot. """ me = me0+".plot_FPEres: " ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") psifile = "_psi" in histfile phifile = "_phi" in histfile ## ------------------------------------------------------------------------ ## Space (for axes) bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") rbins = bins["rbins"] erbins = bins["erbins"] r = 0.5*(rbins[1:]+rbins[:-1]) etar = 0.5*(erbins[1:]+erbins[:-1]) if psifile: epbins = bins["epbins"] etap = 0.5*(epbins[1:]+epbins[:-1]) ## Force assert histfile.find("_DL_") ftype = "dlin" f = force_dlin(r,r,R,S) ## Spatial arrays with dimensions commensurate to rho if psifile: ff = f[:,np.newaxis,np.newaxis] 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 else: ff = f[:,np.newaxis] rr = r[:,np.newaxis] ee = etar[np.newaxis,:] dV = (r[1]-r[0])*(etar[1]-etar[0]) ## Assumes regular grid ## ------------------------------------------------------------------------ ## Load histogram H = np.load(histfile) if phifile: H = H.sum(axis=2) ## If old _phi file ## Normalise and convert to density H /= H.sum()*dV rho = H / ( (2*np.pi)**2.0 * rr*ee ) ## ------------------------------------------------------------------------ ## Derivative function D = lambda arr, x, order, **kwargs: \ scipy.ndimage.gaussian_filter1d(arr, 1.0, order=order, axis=kwargs["axis"]) / (x[1]-x[0]) ## FPE operator -- caluclate residue (res should be 0) t0 = time.time() if psifile: res = -D((ee*np.cos(pp)+ff)*rho, r, 1, axis=0) -1/rr*(ee*np.cos(pp)+ff)*rho + 1/rr*D(ee*np.sin(pp)*rho, etap, 1, axis=2) +\ + 1/a*D(ee*rho, etar, 1, axis=1) + 1/a*rho +\ + 1/a**2*1/ee*D(rho, etar, 1, axis=1) + 1/a**2*D(rho, etar, 2, axis=1) + 1/a**2*1/(ee*ee)*D(rho, etap, 2, axis=2) else: ## If radial (r,eta) only, or (r,eta,eta_phi) converted to (r,eta) res = -D((ee+ff)*rho, r, 1, axis=0) -1/rr*(ee+ff)*rho + 1/a*D(ee*rho, etar, 1, axis=1) +\ + 1/a*rho + 1/a**2*1/ee*D(rho, etar, 1, axis=1) +\ + 1/a**2*D(rho, etar, 2, axis=1) if vb: print me+"Residue calculation %.2g seconds."%(time.time()-t0) ## ------------------------------------------------------------------------ ## Plotting fig, axs = plt.subplots(2,1, sharex=True) X, Y = np.meshgrid(r, etar) ## ------------------------------------------------------------------------ ## Plot density ax = axs[0] if psifile: Z = np.trapz(rho, etap, axis=2).T else: Z = rho.T clim = [0.0,float("%.1g"%(Z.mean()+5*np.sqrt(a)*Z.std()))] # clim = [0.0,float("%.1g"%(Z.max()))] im = ax.contourf(X, Y, Z, levels=np.linspace(clim[0],clim[1],11), vmin=0.0, antialiased=True) cax = mplmal(ax).append_axes("right", size="5%", pad=0.05) fig.colorbar(im, cax=cax) axs[0].set_ylabel(r"$\eta_r$", fontsize=fsa) ax.set_title(r"2D Radial Density. $\alpha=%.1f$, $R=%.1f$, $S=%.1f$."%(a,R,S), fontsize=fst) ## ------------------------------------------------------------------------ ## Plot residue ax = axs[1] # res = scipy.ndimage.gaussian_filter(res,sigma=2.0,order=0) if psifile: Z = np.trapz(res, etap, axis=2).T else: Z = res.T p = 1.0 clim = [float("%.1g"%(Z.mean()-p*Z.std())),float("%.1g"%(Z.mean()+p*Z.std()))] ## std dominated by choppy r=0. im = ax.contourf(X, Y, Z, levels=np.linspace(clim[0],clim[1],11), cmap=cm.BrBG, antialiased=True) cax = mplmal(ax).append_axes("right", size="5%", pad=0.05) fig.colorbar(im, cax=cax) axs[1].set_xlabel(r"$r$", fontsize=fsa) axs[1].set_ylabel(r"$\eta_r$", fontsize=fsa) ax.set_title("Radially Symmetric FP Residual", fontsize=fst) ## ------------------------------------------------------------------------ ## Indicate wall for ax in axs: ax.axvline(S, c="k", lw=2) ax.axvline(R, c="k", lw=2) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname(histfile)+"/FPEres"+os.path.basename(histfile)[4:-4]+"_psi"*psifile+".jpg" fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile return
def calc_pressure_dir(histdir, srchstr, noread, vb): """ Calculate the pressure for all files in directory matching string. """ me = me0 + ".calc_pressure_dir: " t0 = time.time() ##------------------------------------------------------------------------- ## File discovery filelist = np.sort( glob.glob(histdir + "/BHIS_CAR_UL_*" + srchstr + "*.npy")) numfiles = len(filelist) assert numfiles > 1, me + "Check input directory." if vb: print me + "found", numfiles, "files" ##------------------------------------------------------------------------- ## Arrays for parameters and pressure calculations ## P is phase array. Pt is total pressure. Py is pressure as a function of y. A, R, S, T, P, Pt, Pt_WN = np.zeros([7, numfiles]) Y, Py, Py_WN = [], [], [] ## Retrieve data for i, histfile in enumerate(filelist): ti = time.time() ## Assuming R, S, T are same for all files A[i] = filename_par(histfile, "_a") R[i] = filename_par(histfile, "_R") S[i] = filename_par(histfile, "_S") T[i] = filename_par(histfile, "_T") try: P[i] = filename_par(histfile, "_P") except ValueError: P[i] = 0.0 ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] ybins = bins["ybins"] x = 0.5 * (xbins[1:] + xbins[:-1]) y = 0.5 * (ybins[1:] + ybins[:-1]) ## Wall indices ##------------------------------------------------------------------------- ## Histogram H = np.load(histfile) ## Spatial density Qxy = H / (H.sum() * (x[1] - x[0]) * (y[1] - y[0])) ##------------------------------------------------------------------------- ## Force array fxy = np.array([ force_ulin([xi, yi], R[i], S[i], T[i]) for xi in x for yi in y ]).reshape((x.size, y.size, 2)) fxy = np.rollaxis(fxy, 2, 0) ## Calculate integral pressure in the x direction as function of y ## First index is file; second index is y position ## Flip in y for comparison with Nikola etal 2016 Py += [-np.trapz(fxy[0] * Qxy, x, axis=0)[::-1]] ## Calculate integral pressure for full period in y Pt[i] = np.trapz(Py[i], y) if vb: print me + "a=%.1f:\tPressure calculation %.2g seconds" % ( A[i], time.time() - ti) ## Potential U = potential_ulin(x, y, R[i], S[i], T[i]) Qxy_WN = np.exp(-U) Qxy_WN /= np.trapz(np.trapz(Qxy_WN, y, axis=1), x, axis=0) ## WN pressure in the x direction as function of y ## Flip in y for comparison with Nikola etal 2016 Py_WN += [-np.trapz(fxy[0] * Qxy_WN, x, axis=0)[::-1]] ## WN pressure for full period of y Pt_WN[i] = np.trapz(Py_WN[i], y) Y += [y] ##------------------------------------------------------------------------- Y = np.array(Y) Py = np.array(Py) Py_WN = np.array(Py_WN) ## SORT BY ALPHA srtidx = A.argsort() A = A[srtidx] R, S, T = R[srtidx], S[srtidx], T[srtidx] y = y[srtidx] Py = Py[srtidx] Py_WN = Py_WN[srtidx] Pt = Pt[srtidx] Pt_WN = Pt_WN[srtidx] ## Normalise Py /= Py_WN + (Py_WN == 0) Pt /= Pt_WN + (Pt_WN == 0) ##------------------------------------------------------------------------- ## SAVING if not noread: pressfile = histdir + "/PRESS_" + srchstr + ".npz" np.savez(pressfile, A=A, R=R, S=S, T=T, P=P, Y=Y, Py=Py, Py_WN=Py_WN, Pt=Pt, Pt_WN=Pt_WN) if vb: print me + "Calculations saved to", pressfile print me + "Calculation time %.1f seconds." % (time.time() - t0) return { "A": A, "R": R, "S": S, "T": T, "P": P, "Y": Y, "Py": Py, "Py_WN": Py_WN, "Pt": Pt, "Pt_WN": Pt_WN }
def plot_pressure_file(histfile, nosave, vb): """ Plot spatial PDF Q(x) and spatially-varying pressure P(x). """ me = me0 + ".plot_pressure_file: " ##------------------------------------------------------------------------- ## Dir pars assert "_CAR_" in histfile, me + "Functional only for Cartesian geometry." Casimir = "_CL_" in histfile or "_ML_" in histfile or "_NL_" in histfile ##------------------------------------------------------------------------- ## Filename parameters a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") try: T = filename_par(histfile, "_T") except ValueError: T = -S ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] x = 0.5 * (xbins[1:] + xbins[:-1]) ## Wall indices Rind, Sind, Tind = np.abs(x - R).argmin(), np.abs(x - S).argmin(), np.abs( x - T).argmin() STind = (Sind + Tind) / 2 ## Adjust indices for pressure calculation if "_DC_" in histfile: STind = 0 elif "_DL_" in histfile: STind = 0 elif "_NL_" in histfile: STind = Sind Sind = Rind Tind = x.size - Rind ##------------------------------------------------------------------------- ## Histogram H = np.load(histfile) ## Spatial density Qx = H.sum(axis=2).sum(axis=1) / (H.sum() * (x[1] - x[0])) ##------------------------------------------------------------------------- ## Choose force if "_DC_" in histfile: fx = force_dcon([x, 0], R, S)[0] elif "_DL_" in histfile: fx = force_dlin([x, 0], R[i], S[i])[0] elif "_CL_" in histfile: fx = force_clin([x, 0], R, S, T)[0] elif "_ML_" in histfile: fx = force_mlin([x, 0], R, S, T)[0] elif "_NL_" in histfile: fx = force_nlin([x, 0], R, S)[0] else: raise IOError, me + "Force not recognised." ## Calculate integral pressure PR = -sp.integrate.cumtrapz(fx[Rind:] * Qx[Rind:], x[Rind:], initial=0.0) PS = -sp.integrate.cumtrapz(fx[STind:Sind + 1] * Qx[STind:Sind + 1], x[STind:Sind + 1], initial=0.0) PS -= PS[-1] if Casimir: PT = -sp.integrate.cumtrapz(fx[Tind:STind + 1] * Qx[Tind:STind + 1], x[Tind:STind + 1], initial=0.0) if x[0] < 0: R2ind = x.size - Rind PR2 = -sp.integrate.cumtrapz( fx[:R2ind] * Qx[:R2ind], x[:R2ind], initial=0.0) PR2 -= PR2[-1] ##------------------------------------------------------------------------- ## Potential and WN U = -sp.integrate.cumtrapz(fx, x, initial=0.0) U -= U.min() Qx_WN = np.exp(-U) / np.trapz(np.exp(-U), x) ## WN pressure PR_WN = -sp.integrate.cumtrapz( fx[Rind:] * Qx_WN[Rind:], x[Rind:], initial=0.0) PS_WN = -sp.integrate.cumtrapz(fx[STind:Sind + 1] * Qx_WN[STind:Sind + 1], x[STind:Sind + 1], initial=0.0) PS_WN -= PS_WN[-1] if Casimir: PT_WN = -sp.integrate.cumtrapz( fx[Tind:STind + 1] * Qx_WN[Tind:STind + 1], x[Tind:STind + 1], initial=0.0) ##------------------------------------------------------------------------- ## PLOTTING fig, axs = plt.subplots(2, 1, sharex=True, figsize=fs["figsize"]) if "_DL_" in histfile: legloc = "upper right" elif "_CL_" in histfile: legloc = "upper right" elif "_ML_" in histfile: legloc = "upper left" elif "_NL_" in histfile: legloc = "lower left" else: legloc = "best" ## Plot PDF ax = axs[0] lQ = ax.plot(x, Qx, lw=2, label=r"CN") ax.plot(x, Qx_WN, lQ[0].get_color() + ":", lw=2, label="WN") ## Potential ax.plot(x, U / U.max() * ax.get_ylim()[1], "k--", lw=2, label=r"$U(x)$") ax.set_xlim((x[0], x[-1])) ax.set_ylim(bottom=0.0) ax.set_ylabel(r"$Q(x)$", fontsize=fs["fsa"]) ax.grid() ax.legend(loc=legloc, fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ## Plot pressure ax = axs[1] lPR = ax.plot(x[Rind:], PR, lw=2, label=r"$P_R$") lPS = ax.plot(x[STind:Sind + 1], PS, lw=2, label=r"$P_S$") if Casimir: lPT = ax.plot(x[Tind:STind + 1], PT, lw=2, label=r"$P_T$") if x[0] < 0: ax.plot(x[:R2ind], PR2, lPR[0].get_color() + "-", lw=2) ## WN result ax.plot(x[Rind:], PR_WN, lPR[0].get_color() + ":", lw=2) ax.plot(x[STind:Sind + 1], PS_WN, lPS[0].get_color() + ":", lw=2) if Casimir: ax.plot(x[Tind:STind + 1], PT_WN, lPT[0].get_color() + ":", lw=2) if x[0] < 0: ax.plot(x[:R2ind], PR_WN[::-1], lPR[0].get_color() + ":", lw=2) ## Potential ax.plot(x, U / U.max() * ax.get_ylim()[1], "k--", lw=2) #, label=r"$U(x)$") ax.set_xlim((x[0], x[-1])) ax.set_ylim(bottom=0.0) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$P(x)$", fontsize=fs["fsa"]) ax.grid() if Casimir: ax.legend(loc=legloc, fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ##------------------------------------------------------------------------- fig.tight_layout() fig.subplots_adjust(top=0.90) title = r"Spatial PDF and Pressure. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f$"%(a,R,S,T) if T>=0.0\ else r"Spatial PDF and Pressure. $\alpha=%.1f, R=%.1f, S=%.1f$"%(a,R,S) fig.suptitle(title, fontsize=fs["fst"]) if not nosave: plotfile = os.path.dirname(histfile) + "/PDFP" + os.path.basename( histfile)[4:-4] + ".jpg" fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile return
def plot_pdf3D(histfile, nosave, vb): """ Read in data for a single file and plot 3D PDF. """ me = me0 + "plot_pdf3D: " psifile = "_psi" in histfile phifile = "_phi" in histfile ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") ## Space (for axes) bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") rbins = bins["rbins"] erbins = bins["erbins"] r = 0.5 * (rbins[1:] + rbins[:-1]) etar = 0.5 * (erbins[1:] + erbins[:-1]) ## Load histogram H = np.load(histfile) if (psifile or phifile): H = H.sum(axis=2) ## ------------------------------------------------------------------------ ## Normalise and convert to density H /= np.trapz(np.trapz(H, etar, axis=1), r, axis=0) rho = H / ((2 * np.pi)**2.0 * reduce(np.multiply, np.ix_(r, etar))) ## Resample to speed up nrpoints, nerpoints = 100, 100 x, y = np.linspace(r[0], r[-1], nrpoints), np.linspace(etar[0], etar[-1], nerpoints) X, Y = np.meshgrid(x, y) # Z = scipy.interpolate.RectBivariateSpline(r,etar,rho, s=0)(x,y,grid=True).T ## Slower Z = scipy.ndimage.interpolation.zoom( rho, [float(nrpoints) / r.size, float(nerpoints) / etar.size], order=1).T ## Smooth # Z = scipy.ndimage.gaussian_filter(Z, sigma=2.0, order=0, mode="nearest") ## To plot full, unsmoothed data # x, y = r, etar # X, Y = np.meshgrid(x, y) # Z = rho.T ## Marginalised PDFs Q = np.trapz(Z.T * 2 * np.pi * y, y, axis=1) ## p(r) E = np.trapz(Z * 2 * np.pi * x, x, axis=1) ## p(eta) ## Fit -- Gaussian fitfunc = lambda xx, B, b: B * b / (2 * np.pi) * np.exp(-0.5 * b * xx * xx) ## Fit p(eta) fitE = scipy.optimize.curve_fit(fitfunc, y, E, p0=[1.0, a])[0] ## Fit p(r) -- only when S=R fitR = scipy.optimize.curve_fit(fitfunc, (x - R), Q, p0=[(a + 1), (a + 1)])[0] # print [a,R],"\t",np.around([a+1,fitR[1]],2); return ## ------------------------------------------------------------------------ ## Plotting fig = plt.figure() ax = fig.gca(projection="3d") ## 3D contour plot ax.plot_surface(X, Y, Z, alpha=0.2, rstride=2, cstride=2, antialiased=True) ## 2D contours xoff, yoff, zoff = X.min() - 0.1 * X.max(), Y.min() - 0.1 * Y.max(), Z.min( ) - 0.1 * Z.max() ## Offsets ax.contourf(X, Y, Z, zdir='x', offset=xoff, cmap=cm.coolwarm, antialiased=True) ## p(etar) ax.contourf(X, Y, Z, zdir='y', offset=yoff, cmap=cm.coolwarm, antialiased=True) ## p(r) ax.contourf(X, Y, Z, zdir='z', offset=zoff, cmap=cm.coolwarm, antialiased=True) ## 2D projection ## Plot p(r) and p(etar) envelopes ax.plot(x, yoff * np.ones(y.shape), Q / Q.max() * Z.max(), "r--", lw=3) ## p(r) ax.plot(xoff * np.ones(x.shape), y, E / E.max() * Z.max(), "g--", lw=3) ## p(etar) ## Plot Gaussian fit to p(etar) # ax.plot(xoff*np.ones(x.size), y, fitfunc(y,*fitE)*Z.max()/E.max(), "g--", lw=3, zorder=2) ## Indicate wall if S > 0: ax.plot(S * np.ones(x.size), y, 0.8 * zoff * np.ones(x.size), "g--", lw=3, zorder=2) if R > 0: ax.plot(R * np.ones(x.size), y, 0.8 * zoff * np.ones(x.size), "g--", lw=3, zorder=2) ## Accoutrements ax.set_xlim(xoff, ax.get_xlim()[1]) ax.set_ylim(yoff, ax.get_ylim()[1]) ax.set_zlim(zoff, ax.get_zlim()[1]) ax.elev = 30 ax.azim = 45 ax.set_xlabel(r"$r$", fontsize=18) ax.set_ylabel(r"$\eta_r$", fontsize=18) ax.set_zlabel(r"$\rho$", fontsize=18) fig.suptitle(r"PDF in $r$-$\eta_r$ space. $\alpha=" + str(a) + "$, $R=" + str(R) + "$, $S=" + str(S) + "$", fontsize=16) if not nosave: plotfile = os.path.dirname(histfile) + "/PDF3D" + os.path.basename( histfile)[4:-4] + ".jpg" fig.savefig(plotfile) if vb: print me + ": Figure saved to", plotfile return
def plot_pdf2d(histfile, nosave, vb): """ Read in data for a single file and plot 3D PDF. """ me = me0 + ".plot_pdf2D: " t0 = time.time() ##------------------------------------------------------------------------- ## Get pars from filename assert ("_POL_" in histfile or "_CIR_" in histfile), me + "Functional only for Cartesian geometry." a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") ##------------------------------------------------------------------------- ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") rbins = bins["rbins"] ebins = bins["erbins"] pbins = bins["epbins"] r = 0.5 * (rbins[1:] + rbins[:-1]) eta = 0.5 * (ebins[1:] + ebins[:-1]) psi = 0.5 * (pbins[1:] + pbins[:-1]) ## Wall indices Rind, Sind = np.abs(r - R).argmin(), np.abs(r - S).argmin() ##------------------------------------------------------------------------- ## Histogram / density H = np.load(histfile) rho = H / (H.sum() * (r[1] - r[0]) * (eta[1] - eta[0]) * (psi[1] - psi[0])) ## ------------------------------------------------------------------------ ## Projections rhore = rho.sum(axis=2) rhorp = rho.sum(axis=1) rhoep = rho.sum(axis=0) ## ------------------------------------------------------------------------ ## Plotting fig, axs = plt.subplots(3, 1, sharey=True, figsize=(10, 10)) fig.canvas.set_window_title("2D PDFs") plt.rcParams["image.cmap"] = "Greys" #"coolwarm" ## ------------------------------------------------------------------------ ## r-eta ax = axs[0] ax.contourf(r, eta, rhore.T) ax.axvline(R, c="k") ax.axvline(S, c="k") ax.set_xlabel(r"$r$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\eta$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(r,\eta)$ data", fontsize=fs["fsa"]) ## r-psi ax = axs[1] ax.contourf(r, psi, rhorp.T) ax.axvline(R, c="k") ax.axvline(S, c="k") ax.set_xlabel(r"$r$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\psi$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(r,\psi)$ data", fontsize=fs["fsa"]) ## etax-etay ax = axs[2] ax.contourf(eta, psi, rhoep.T) ax.set_xlabel(r"$\eta$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\psi$", fontsize=fs["fsa"]) ax.set_title(r"$\rho(\eta,\psi)$ data", fontsize=fs["fsa"]) ## ------------------------------------------------------------------------ title = r"PDF projections. $\alpha=%.1f, R=%.1f, S=%.1f$" % (a, R, S) fig.suptitle(title, fontsize=fs["fst"]) fig.tight_layout() fig.subplots_adjust(top=0.9) ## ------------------------------------------------------------------------ if not nosave: plotfile = os.path.dirname(histfile) + "/PDFre2d" + os.path.basename( histfile)[4:-4] + ".jpg" fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile if vb: print me + "Execution time %.1f seconds." % (time.time() - t0) return
def calc_mass_ratio(histdir, srchstr, noread, vb): """ Read in directory of files with inner and outer regions. Compute mass in each region, take ratio. Compare with integrated and calculated white noise result. """ me = me0 + ".calc_mass_ratio: " t0 = time.time() ##------------------------------------------------------------------------- ## Dir pars assert "_CAR_" in histdir, me + "Functional only for Cartesian geometry." assert "_DL_" not in histdir, me + "Must have interior region." ## File discovery filelist = np.sort(glob.glob(histdir + "/BHIS_CAR_*" + srchstr + "*.npy")) numfiles = len(filelist) assert numfiles > 1, me + "Check input directory." if vb: print me + "found", numfiles, "files" ##------------------------------------------------------------------------- A, ML, MR = np.zeros([3, numfiles]) ## Retrieve data for i, histfile in enumerate(filelist): ## Assume R, S, T are same for all files A[i] = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") try: T = filename_par(histfile, "_T") except ValueError: T = -S ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] x = 0.5 * (xbins[1:] + xbins[:-1]) ##------------------------------------------------------------------------- ## Histogram H = np.load(histfile) ## Spatial density Qx = H.sum(axis=2).sum(axis=1) / (H.sum() * (x[1] - x[0])) ## Mass on either side of cusp: data. Left, right. if "_CL_" in histfile: cuspind = np.abs(0.5 * (T + S) - x).argmin() ## Half-domain elif "_ML_" in histfile: cuspind = np.abs(0.5 * (T + S) - x).argmin() elif "_NL_" in histfile: cuspind = np.abs(S - x).argmin() ML[i] = np.trapz(Qx[:cuspind], x[:cuspind]) MR[i] = np.trapz(Qx[cuspind:], x[cuspind:]) ## SORT BY ALPHA srtidx = A.argsort() A = A[srtidx] ML = ML[srtidx] MR = MR[srtidx] ##------------------------------------------------------------------------- ## WN result from density solution if "_DL_" in histfile: fx = force_dlin([x, 0], R, S)[0] elif "_CL_" in histfile: fx = force_clin([x, 0], R, S, T)[0] elif "_ML_" in histfile: fx = force_mlin([x, 0], R, S, T)[0] elif "_NL_" in histfile: fx = force_nlin([x, 0], R, S)[0] else: raise IOError, me + "Force not recognised." U = -sp.integrate.cumtrapz(fx, x, initial=0.0) U -= U.min() Qx_WN = np.exp(-U) / np.trapz(np.exp(-U), x) MLwn = np.trapz(Qx_WN[:cuspind], x[:cuspind]) MRwn = np.trapz(Qx_WN[cuspind:], x[cuspind:]) ##------------------------------------------------------------------------- ## Add a=0 point if 0.0 not in A: A = np.hstack([0.0, A]) ML = np.hstack([MLwn, ML]) MR = np.hstack([MRwn, MR]) ##------------------------------------------------------------------------- ### This might not be the cleanest thing to save... ## SAVING if not noread: massfile = histdir + "/MASS_" + srchstr + ".npz" np.savez(massfile, A=A, ML=ML, MR=MR, MLwn=MLwn, MRwn=MRwn, x=x, Qx_WN=Qx_WN, R=R, S=S, T=T, cuspind=cuspind) if vb: print me + "Calculations saved to", massfile print me + "Calculation time %.1f seconds." % (time.time() - t0) return { "A": A, "ML": ML, "MR": MR, "MLwn": MLwn, "MRwn": MRwn, "x": x, "Qx_WN": Qx_WN, "R": R, "S": S, "T": T, "cuspind": cuspind }
def plot_fitpars(histdir, searchstr, nosave, vb): """ For each file in directory, plot offset of Q(r) peak from R. """ me = me0 + ".plot_fitpars: " ##------------------------------------------------------------------------- ## Fit function gauss = lambda x, m, s2:\ 1/(2*np.pi*(s2*np.exp(-0.5*m**2/s2)+\ +m*np.sqrt(np.pi*s2/2)*(1+sp.special.erf(m/(np.sqrt(2*s2))))))*\ np.exp(-0.5*(x-m)**2/s2) ##------------------------------------------------------------------------- filelist = np.sort(glob.glob(histdir + "/BHIS_*" + searchstr + "*.npy")) numfiles = filelist.size assert numfiles > 1, me + "Check directory." if vb: print me + "Found", numfiles, "files." A, M, S2 = np.zeros((3, numfiles)) for i, histfile in enumerate(filelist): ## Get pars from filename A[i] = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") assert R == S, me + "Functionality only for zero bulk." ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") rbins = bins["rbins"] ebins = bins["erbins"] r = 0.5 * (rbins[1:] + rbins[:-1]) eta = 0.5 * (ebins[1:] + ebins[:-1]) ## Histogram H = np.load(histfile) try: H = H.sum(axis=2) except ValueError: pass ## Spatial density Q = H.sum(axis=1) * (eta[1] - eta[0]) / (2 * np.pi * r) / np.trapz( np.trapz(H, eta, axis=1), r, axis=0) M[i], S2[i] = sp.optimize.curve_fit(gauss, r, Q, p0=[R, 1 / (1 + A[i])])[0] srtidx = A.argsort() A = A[srtidx] M = M[srtidx] S2 = S2[srtidx] S1 = np.sqrt(S2) ##------------------------------------------------------------------------- ## Fit linear = lambda x, m, c: m * x + c fitS = sp.optimize.curve_fit(linear, np.log(1 + A), np.log(S1), p0=[-0.5, 0.0])[0] ##------------------------------------------------------------------------- fig, ax = plt.subplots(1, 1) ## Plot data -- sigma lineS = ax.plot(1 + A, S1, "o", label=r"$\sigma$ (data)") ## Plot fit ax.plot(1+A, np.exp(linear(np.log(1+A), *fitS)), lineS[0].get_color()+"--",\ label=r"$%.1g(1+\alpha)^{%.2g}$"%(np.exp(fitS[1]),fitS[0])) ## Plot prediction # ax.plot(1+A, np.exp(linear(np.log(1+A), -0.5, 0.0)), lineS[0].get_color()+":", label=r"$(1+\alpha)^{-1/2}$") ## Plot data -- mean lineM = ax.plot(1 + A, M - R, "o-", label=r"$\mu-R$ (data)") ax.set_xlim(1.0, 1.0 + A[-1]) ax.set_xscale("log") ax.set_yscale("log") ax.set_xlabel(r"$1+\alpha$", fontsize=fs["fsa"]) ax.set_ylabel(r"Parameter", fontsize=fs["fsa"]) ax.set_title(r"Gaussian fit parameters. $R=%.1f, S=%.1f$" % (R, S), fontsize=fs["fst"]) ax.grid() ax.legend(loc="best", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) if not nosave: plotfile = histdir + "/PDFparsa_R%.1f_S%.1f.jpg" % (R, S) fig.savefig(plotfile) fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile ##------------------------------------------------------------------------- return
def calc_mass_ratio(histdir, srchstr, noread, vb): """ Read in directory of files with inner and outer regions. Compute mass in each region, take ratio. Compare with integrated and calculated white noise result. """ me = me0+".calc_mass_ratio: " t0 = time.time() ##------------------------------------------------------------------------- ## Dir pars assert "_CAR_" in histdir, me+"Functional only for Cartesian geometry." assert "_DL_" not in histdir, me+"Must have interior region." ## File discovery filelist = np.sort(glob.glob(histdir+"/BHIS_CAR_*"+srchstr+"*.npy")) numfiles = len(filelist) assert numfiles>1, me+"Check input directory." if vb: print me+"found",numfiles,"files" ##------------------------------------------------------------------------- A, ML, MR = np.zeros([3,numfiles]) ## Retrieve data for i, histfile in enumerate(filelist): ## Assume R, S, T are same for all files A[i] = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") try: T = filename_par(histfile, "_T") except ValueError: T = -S ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] x = 0.5*(xbins[1:]+xbins[:-1]) ##------------------------------------------------------------------------- ## Histogram H = np.load(histfile) ## Spatial density Qx = H.sum(axis=2).sum(axis=1) / (H.sum()*(x[1]-x[0])) ## Mass on either side of cusp: data. Left, right. if "_CL_" in histfile: cuspind = np.abs(0.5*(T+S)-x).argmin() ## Half-domain elif "_ML_" in histfile: cuspind = np.abs(0.5*(T+S)-x).argmin() elif "_NL_" in histfile: cuspind = np.abs(S-x).argmin() ML[i] = np.trapz(Qx[:cuspind],x[:cuspind]) MR[i] = np.trapz(Qx[cuspind:],x[cuspind:]) ## SORT BY ALPHA srtidx = A.argsort() A = A[srtidx] ML = ML[srtidx]; MR = MR[srtidx] ##------------------------------------------------------------------------- ## WN result from density solution if "_DL_" in histfile: fx = force_dlin([x,0],R,S)[0] elif "_CL_" in histfile: fx = force_clin([x,0],R,S,T)[0] elif "_ML_" in histfile: fx = force_mlin([x,0],R,S,T)[0] elif "_NL_" in histfile: fx = force_nlin([x,0],R,S)[0] else: raise IOError, me+"Force not recognised." U = -sp.integrate.cumtrapz(fx, x, initial=0.0); U -= U.min() Qx_WN = np.exp(-U) / np.trapz(np.exp(-U), x) MLwn = np.trapz(Qx_WN[:cuspind],x[:cuspind]) MRwn = np.trapz(Qx_WN[cuspind:],x[cuspind:]) ##------------------------------------------------------------------------- ## Add a=0 point if 0.0 not in A: A = np.hstack([0.0,A]) ML = np.hstack([MLwn,ML]) MR = np.hstack([MRwn,MR]) ##------------------------------------------------------------------------- ### This might not be the cleanest thing to save... ## SAVING if not noread: massfile = histdir+"/MASS_"+srchstr+".npz" np.savez(massfile, A=A, ML=ML, MR=MR, MLwn=MLwn, MRwn=MRwn, x=x, Qx_WN=Qx_WN, R=R, S=S, T=T, cuspind=cuspind) if vb: print me+"Calculations saved to",massfile print me+"Calculation time %.1f seconds."%(time.time()-t0) return {"A":A, "ML":ML, "MR":MR, "MLwn":MLwn, "MRwn":MRwn, "x":x, "Qx_WN":Qx_WN, "R":R, "S":S, "T":T, "cuspind":cuspind}
def plot_pdf1d(histfile, nosave, vb): """ Calculate Q(r) and q(eta) from file and plot. """ me = me0 + ".plot_pdf1d: " ## Get pars from filename a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") rbins = bins["rbins"] ebins = bins["erbins"] r = 0.5 * (rbins[1:] + rbins[:-1]) eta = 0.5 * (ebins[1:] + ebins[:-1]) ## Wall indices Rind, Sind = np.abs(r - R).argmin(), np.abs(r - S).argmin() ##------------------------------------------------------------------------- ## Histogram H = np.load(histfile) try: H = H.sum(axis=2) except ValueError: pass H /= np.trapz(np.trapz(H, eta, axis=1), r, axis=0) ## Spatial density Q = H.sum(axis=1) * (eta[1] - eta[0]) / (2 * np.pi * r) ## Force density q = H.sum(axis=0) * (r[1] - r[0]) / (2 * np.pi * eta) ##------------------------------------------------------------------------- ## Fit gauss = lambda x, m, s2:\ 1/(2*np.pi*(s2*np.exp(-0.5*m**2/s2)+\ +np.abs(m)*np.sqrt(np.pi*s2/2)*(1+sp.special.erf(np.abs(m)/(np.sqrt(2*s2))))))*\ np.exp(-0.5*(x-m)**2/s2) if R == S: fitQ = sp.optimize.curve_fit(gauss, r, Q, p0=[R, 1 / np.sqrt(1 + a)])[0] fitq = sp.optimize.curve_fit(gauss, eta, q, p0=[0, 1 / a])[0] ##------------------------------------------------------------------------- fig, axs = plt.subplots(2, 1) fig.canvas.set_window_title("1D PDFs") ## Spatial density plot ax = axs[0] ## Data ax.plot(r, Q, label=r"Simulation") ## Gaussian if R == S: ax.plot(r, gauss(r, fitQ[0], 1 / (1 + a)), label=r"$G\left(\mu, \frac{1}{\alpha+1}\right)$") ## Potential if "_DL_" in histfile: ax.plot(r, (r - R)**2 * Q.max() / ((r - R)**2).max(), "k--", label=r"$U(r)$") ax.set_xlabel(r"$r$", fontsize=fs["fsa"]) ax.set_ylabel(r"$Q(r)$", fontsize=fs["fsa"]) ax.grid() ax.legend(loc="upper right", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ##------------------------------------------------------------------------- ## Force density plot ax = axs[1] ## Data ax.plot(eta, q, label=r"Simulation") ## Gaussian ax.plot(eta, gauss(eta, 0, 1 / a), label=r"$G\left(0, \frac{1}{\alpha}\right)$") ax.set_xlabel(r"$\eta$", fontsize=fs["fsa"]) ax.set_ylabel(r"$q(\eta)$", fontsize=fs["fsa"]) ax.grid() ax.legend(loc="upper right", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ##------------------------------------------------------------------------- fig.tight_layout() fig.subplots_adjust(top=0.9) fig.suptitle(r"PDFs in $r$ and $\eta$. $\alpha=%.1f, R=%.1f, S=%.1f$" % (a, R, S), fontsize=fs["fst"]) if not nosave: plotfile = os.path.dirname(histfile) + "/PDFre1d" + os.path.basename( histfile)[4:-4] + ".jpg" fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile return
def plot_current_1d(histfile, nosave, vb): """ """ me = me0 + ".plot_current_1d: " t0 = time.time() ##------------------------------------------------------------------------- ## Filename pars a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") ##------------------------------------------------------------------------- ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] exbins = bins["exbins"] x = 0.5 * (xbins[1:] + xbins[:-1]) ## Double space x = np.hstack([-x[::-1], x]) etax = 0.5 * (exbins[1:] + exbins[:-1]) X, ETAX = np.meshgrid(x, etax, indexing="ij") ## Wall indices Rind, Sind = np.abs(x - R).argmin(), np.abs(x - S).argmin() ##------------------------------------------------------------------------- ## Force if "_DL_" in histfile: fx = force_dlin([x, 0], R, S)[0] elif "_CL_" in histfile: fx = force_clin([x, 0], R, S, T)[0] elif "_ML_" in histfile: fx = force_mlin([x, 0], R, S, T)[0] else: raise IOError, me + "Force not recognised." F = fx.repeat(etax.size).reshape([x.size, etax.size]) ##------------------------------------------------------------------------- ## Histogram H = np.load(histfile) rho = H.sum(axis=2) / (H.sum() * (x[1] - x[0]) * (etax[1] - etax[0])) ## Double space rho = np.vstack([rho[::-1, ::-1], rho]) ## Currents Jx = (F + ETAX) * rho Jy = -1 / a * ETAX * rho - 1 / (a * a) * np.gradient( rho, etax[1] - etax[0])[1] Vx, Vy = Jx / rho, Jy / rho ##------------------------------------------------------------------------- ## SMOOTHING Vy = sp.ndimage.gaussian_filter(Vy, 2.0, order=0) ##------------------------------------------------------------------------- ## PLOTTING plt.rcParams["image.cmap"] = "Greys" fig, ax = plt.subplots(1, 1, figsize=fs["figsize"]) fig.canvas.set_window_title("Current in x-eta") ##------------------------------------------------------------------------- ## Data ax.contourf(x, etax, rho.T) sx, se = 50, 5 # sx, se = 20, 2 ax.quiver(x[::sx], etax[::se], Vx.T[::se, ::sx], Vy.T[::se, ::sx], scale=2, units='x', width=0.011 * 2) ## Indicate bulk if 0: ax.axvline(S, c="k", lw=1) ax.axvline(R, c="k", lw=1) ## Set number of ticks # ax.xaxis.set_major_locator(NullLocator()) #MaxNLocator(5) # ax.yaxis.set_major_locator(NullLocator()) #MaxNLocator(4) ax.set_xticks([-S, -0.5 * (S + T), T, +0.5 * (S + T), +S]) ax.set_xticklabels([""] * 5) ax.set_yticks([-0.5 * (S + T), 0.0, +0.5 * (S + T)]) ax.set_yticklabels([""] * 3) # ax.set_xlim(left=x[0],right=x[-1]) ax.set_xlim(left=-S * 2, right=S * 2) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$\eta$", fontsize=fs["fsa"]) ax.grid() # ax.legend(loc="upper right", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ##------------------------------------------------------------------------- ## Add force line if 1: ax.plot(x, -fx, "k-", label=r"$-f(x)$") ymax = min(3 * fx.max(), etax.max()) ax.set_ylim(-ymax, ymax) ##------------------------------------------------------------------------- ## Add in BC line if 1: from LE_CBulkConst import bulk_const x, Q, BC = bulk_const(histfile) ## Double space x = np.hstack([-x[::-1], x]) Q = np.hstack([Q[::-1], Q]) BC = np.hstack([BC[::-1], BC]) ax.plot(x, (Q / Q.max()) * 0.5 * ax.get_ylim()[1] + ax.get_ylim()[0], "b-", lw=4) ax.plot(x, (BC / BC.max()) * 0.5 * ax.get_ylim()[1] + ax.get_ylim()[0], "r-", lw=4) ax2 = ax.twinx() ax2.yaxis.set_major_locator(NullLocator()) ax2.set_ylabel(r"$n$ \& $\left<\eta^2\right>n$ \hfill") ax2.yaxis.set_label_coords(-0.07, 0.15) # ax.yaxis.set_label_coords(-0.07,0.5) ##------------------------------------------------------------------------- if not nosave: plotfile = os.path.dirname(histfile) + "/Jxeta" + os.path.basename( histfile)[4:-4] plotfile += "." + fs["saveext"] fig.savefig(plotfile, format=fs["saveext"]) if vb: print me + "Figure saved to", plotfile if vb: print me + "Execution time %.1f seconds." % (time.time() - t0) return
def plot_dir(histdir, srchstr, logplot, nosave, vb): """ For each file in directory, calculate the pressure in both ways for all walls (where applicable) and plot against alpha. """ me = me0 + ".plot_dir: " filelist = np.sort(glob.glob(histdir + "/BHIS_CAR_*" + srchstr + "*.npy")) numfiles = filelist.size if vb: print me + "Found", numfiles, "files." ## Initialise arrays A, pR, pS, pT, PR, PS, PT = np.zeros([7, numfiles]) ## Retrieve data for i, histfile in enumerate(filelist): Casimir = "_CL_" in histfile or "_ML_" in histfile or "_NL_" in histfile ## Get pars from filename A[i] = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") T = filename_par(histfile, "_T") if Casimir else -S ## Calculate BC x, Qx, BC = bulk_const(histfile)[:3] ## Wall indices Rind, Sind, Tind = np.abs(x - R).argmin(), np.abs( x - S).argmin(), np.abs(x - T).argmin() STind = 0 if "_DL_" in histfile else (Tind + Sind) / 2 ##--------------------------------------------------------------------- ## Calculate pressure from BC if "_DL_" in histfile: BCsr = BC[Sind:Rind + 1].mean() pR[i] = A[i] * BCsr pS[i] = A[i] * BCsr elif "_CL_" in histfile: BCsr = BC[Sind:Rind + 1].mean() BCts = BC[STind] BC0t = BC[0:Tind + 1].mean() pR[i] = A[i] * BCsr pS[i] = A[i] * (BCsr - BCts) pT[i] = A[i] * (BC0t - BCts) elif "_ML_" in histfile: BCsr = BC[Sind:Rind + 1].mean() BCts = BC[STind] BCrt = BC[x.size - Rind:Tind + 1].mean() pR[i] = A[i] * BCsr pS[i] = A[i] * (-BCsr + BCts) pT[i] = A[i] * (-BCrt + BCts) elif "_NL_" in histfile: BCr = BC[Rind] BCs = BC[Sind] BCmr = BC[x.size - Rind] pR[i] = A[i] * BCr pS[i] = A[i] * (BCs - BCr) pT[i] = A[i] * (BCs - BCmr) ##--------------------------------------------------------------------- ## Calculate pressure from integral ## Choose force if "_DL_" in histfile: fx = force_dlin([x, 0], R, S)[0] elif "_CL_" in histfile: fx = force_clin([x, 0], R, S, T)[0] elif "_ML_" in histfile: fx = force_mlin([x, 0], R, S, T)[0] elif "_NL_" in histfile: fx = force_nlin([x, 0], R, S)[0] ## Calculate integral pressure PR[i] = -sp.integrate.trapz(fx[Rind:] * Qx[Rind:], x[Rind:]) PS[i] = +sp.integrate.trapz(fx[STind:Sind] * Qx[STind:Sind], x[STind:Sind]) PT[i] = -sp.integrate.trapz(fx[Tind:STind] * Qx[Tind:STind], x[Tind:STind]) ##--------------------------------------------------------------------- ## SORT BY ALPHA srtidx = A.argsort() A = A[srtidx] pR, pS, pT = pR[srtidx], pS[srtidx], pT[srtidx] PR, PS, PT = PR[srtidx], PS[srtidx], PT[srtidx] ##------------------------------------------------------------------------- ## Calculate white noise PDF and pressure -- assuming alpha is only varying parameter U = -sp.integrate.cumtrapz(fx, x, initial=0.0) U -= U.min() Qx_WN = np.exp(-U) / np.trapz(np.exp(-U), x) PR_WN = -sp.integrate.trapz(fx[Rind:] * Qx_WN[Rind:], x[Rind:]) PS_WN = +sp.integrate.trapz(fx[STind:Sind] * Qx_WN[STind:Sind], x[STind:Sind]) PT_WN = -sp.integrate.trapz(fx[Tind:STind] * Qx_WN[Tind:STind], x[Tind:STind]) ## Normalise pR /= PR_WN pS /= PS_WN pT /= PT_WN PR /= PR_WN PS /= PS_WN PT /= PT_WN ##------------------------------------------------------------------------- ## Add a=0 point if 0.0 not in A: nlin = np.unique(S).size A = np.hstack([[0.0] * nlin, A]) pR = np.hstack([[1.0] * nlin, pR]) pS = np.hstack([[1.0] * nlin, pS]) PR = np.hstack([[1.0] * nlin, PR]) PS = np.hstack([[1.0] * nlin, PS]) ##------------------------------------------------------------------------- ## PLOT DATA fig, ax = plt.subplots(1, 1, figsize=fs["figsize"]) sty = ["-", "--", ":"] A += int(logplot) """ lpR = ax.plot(A, pR, "o"+sty[0], label=r"BC pR") lpS = ax.plot(A, pS, "o"+sty[1], c=ax.lines[-1].get_color(), label=r"BC pS") if Casimir: lpT = ax.plot(A, pT, "o"+sty[2], c=ax.lines[-1].get_color(), label=r"BC pT") ax.plot(A, PR, "v"+sty[0], label=r"Int PR") ax.plot(A, PS, "v"+sty[1], c=ax.lines[-1].get_color(), label=r"Int PS") if Casimir: ax.plot(A, PT, "v"+sty[2], c=ax.lines[-1].get_color(), label=r"Int PT") """ lpR = ax.plot(A, 0.5 * (pR + pS), "o--", label=r"$\alpha\left<\eta^2\right>n(x)|^{\rm bulk}$") ax.plot(A, 0.5 * (PR + PS), "v--", label=r"$-\int f(x)n(x) {\rm d}x$") ##------------------------------------------------------------------------- ## ACCOUTREMENTS if logplot: ax.set_xscale("log") ax.set_yscale("log") xlim = (ax.get_xlim()[0], A[-1]) xlabel = r"$1+\alpha$" else: xlim = (0.0, A[-1]) xlabel = r"$\alpha$" ax.set_xlim(xlim) ax.set_ylim(1e-1, 1e+1) ax.set_xlabel(xlabel, fontsize=fs["fsa"]) ax.set_ylabel(r"$P(\alpha)/P^{\rm passive}$", fontsize=fs["fsa"]) ax.grid() ax.legend(loc="best", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) title = "Pressure normalised by WN result. $R=%.1f, S=%.1f, T=%.1f.$"%(R,S,T) if T>=0.0\ else "Pressure normalised by WN result. $R=%.1f, S=%.1f.$"%(R,S) # fig.suptitle(title,fontsize=fs["fst"]) ## SAVING plotfile = histdir+"/QEe2_Pa_R%.1f_S%.1f_T%.1f"%(R,S,T) if T>=0.0\ else histdir+"/QEe2_Pa_R%.1f_S%.1f"%(R,S) plotfile += "_loglog" * logplot + "." + fs["saveext"] if not nosave: fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile return plotfile
def plot_pressure_file(histfile, nosave, vb): """ Plot spatial PDF Q(x) and spatially-varying pressure P(x). """ me = me0+".plot_pressure_file: " ##------------------------------------------------------------------------- ## Dir pars assert "_CAR_" in histfile, me+"Functional only for Cartesian geometry." Casimir = "_CL_" in histfile or "_ML_" in histfile or "_NL_" in histfile ##------------------------------------------------------------------------- ## Filename parameters a = filename_par(histfile, "_a") R = filename_par(histfile, "_R") S = filename_par(histfile, "_S") try: T = filename_par(histfile, "_T") except ValueError: T = -S ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] x = 0.5*(xbins[1:]+xbins[:-1]) ## Wall indices Rind, Sind, Tind = np.abs(x-R).argmin(), np.abs(x-S).argmin(), np.abs(x-T).argmin() STind = (Sind+Tind)/2 ## Adjust indices for pressure calculation if "_DC_" in histfile: STind = 0 elif "_DL_" in histfile: STind = 0 elif "_NL_" in histfile: STind = Sind Sind = Rind Tind = x.size-Rind ##------------------------------------------------------------------------- ## Histogram H = np.load(histfile) ## Spatial density Qx = H.sum(axis=2).sum(axis=1) / (H.sum()*(x[1]-x[0])) ##------------------------------------------------------------------------- ## Choose force if "_DC_" in histfile: fx = force_dcon([x,0],R,S)[0] elif "_DL_" in histfile: fx = force_dlin([x,0],R[i],S[i])[0] elif "_CL_" in histfile: fx = force_clin([x,0],R,S,T)[0] elif "_ML_" in histfile: fx = force_mlin([x,0],R,S,T)[0] elif "_NL_" in histfile: fx = force_nlin([x,0],R,S)[0] else: raise IOError, me+"Force not recognised." ## Calculate integral pressure PR = -sp.integrate.cumtrapz(fx[Rind:]*Qx[Rind:], x[Rind:], initial=0.0) PS = -sp.integrate.cumtrapz(fx[STind:Sind+1]*Qx[STind:Sind+1], x[STind:Sind+1], initial=0.0); PS -= PS[-1] if Casimir: PT = -sp.integrate.cumtrapz(fx[Tind:STind+1]*Qx[Tind:STind+1], x[Tind:STind+1], initial=0.0) if x[0]<0: R2ind = x.size-Rind PR2 = -sp.integrate.cumtrapz(fx[:R2ind]*Qx[:R2ind], x[:R2ind], initial=0.0); PR2 -= PR2[-1] ##------------------------------------------------------------------------- ## Potential and WN U = -sp.integrate.cumtrapz(fx, x, initial=0.0); U -= U.min() Qx_WN = np.exp(-U) / np.trapz(np.exp(-U), x) ## WN pressure PR_WN = -sp.integrate.cumtrapz(fx[Rind:]*Qx_WN[Rind:], x[Rind:], initial=0.0) PS_WN = -sp.integrate.cumtrapz(fx[STind:Sind+1]*Qx_WN[STind:Sind+1], x[STind:Sind+1], initial=0.0); PS_WN -= PS_WN[-1] if Casimir: PT_WN = -sp.integrate.cumtrapz(fx[Tind:STind+1]*Qx_WN[Tind:STind+1], x[Tind:STind+1], initial=0.0) ##------------------------------------------------------------------------- ## PLOTTING fig, axs = plt.subplots(2,1, sharex=True, figsize=fs["figsize"]) if "_DL_" in histfile: legloc = "upper right" elif "_CL_" in histfile: legloc = "upper right" elif "_ML_" in histfile: legloc = "upper left" elif "_NL_" in histfile: legloc = "lower left" else: legloc = "best" ## Plot PDF ax = axs[0] lQ = ax.plot(x, Qx, lw=2, label=r"CN") ax.plot(x, Qx_WN, lQ[0].get_color()+":", lw=2, label="WN") ## Potential ax.plot(x, U/U.max()*ax.get_ylim()[1], "k--", lw=2, label=r"$U(x)$") ax.set_xlim((x[0],x[-1])) ax.set_ylim(bottom=0.0) ax.set_ylabel(r"$Q(x)$", fontsize=fs["fsa"]) ax.grid() ax.legend(loc=legloc, fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ## Plot pressure ax = axs[1] lPR = ax.plot(x[Rind:], PR, lw=2, label=r"$P_R$") lPS = ax.plot(x[STind:Sind+1], PS, lw=2, label=r"$P_S$") if Casimir: lPT = ax.plot(x[Tind:STind+1], PT, lw=2, label=r"$P_T$") if x[0]<0: ax.plot(x[:R2ind], PR2, lPR[0].get_color()+"-", lw=2) ## WN result ax.plot(x[Rind:], PR_WN, lPR[0].get_color()+":", lw=2) ax.plot(x[STind:Sind+1], PS_WN, lPS[0].get_color()+":", lw=2) if Casimir: ax.plot(x[Tind:STind+1], PT_WN, lPT[0].get_color()+":", lw=2) if x[0]<0: ax.plot(x[:R2ind], PR_WN[::-1], lPR[0].get_color()+":", lw=2) ## Potential ax.plot(x, U/U.max()*ax.get_ylim()[1], "k--", lw=2)#, label=r"$U(x)$") ax.set_xlim((x[0],x[-1])) ax.set_ylim(bottom=0.0) ax.set_xlabel(r"$x$", fontsize=fs["fsa"]) ax.set_ylabel(r"$P(x)$", fontsize=fs["fsa"]) ax.grid() if Casimir: ax.legend(loc=legloc, fontsize=fs["fsl"]).get_frame().set_alpha(0.5) ##------------------------------------------------------------------------- fig.tight_layout() fig.subplots_adjust(top=0.90) title = r"Spatial PDF and Pressure. $\alpha=%.1f, R=%.1f, S=%.1f, T=%.1f$"%(a,R,S,T) if T>=0.0\ else r"Spatial PDF and Pressure. $\alpha=%.1f, R=%.1f, S=%.1f$"%(a,R,S) fig.suptitle(title, fontsize=fs["fst"]) if not nosave: plotfile = os.path.dirname(histfile)+"/PDFP"+os.path.basename(histfile)[4:-4]+".jpg" fig.savefig(plotfile) if vb: print me+"Figure saved to",plotfile return
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