def main(): """ Fit PDF to exponential in the wall region. Reads in EITHER a BHIS file OR a directory of them. """ me = "Tail.main: " t0 = sysT() ## Options parser = optparse.OptionParser(conflict_handler="resolve") parser.add_option('-s','--show', dest="showfig", default=False, action="store_true") parser.add_option('-v','--verbose', dest="verbose", default=False, action="store_true") parser.add_option('-h','--help', dest="help",default=False,action="store_true", help="Print docstring.") opt = parser.parse_args()[0] if opt.help: print main.__doc__; return showfig = opt.showfig verbose = opt.verbose argv[1] = argv[1].replace("\\","/") if os.path.isfile(argv[1]): tail_plot(argv[1],verbose) elif os.path.isdir(argv[1]): plot_exp_alpha(argv[1],verbose) else: print me+"you gave me rubbish. Abort." exit() if verbose: print me+"execution time",round(sysT()-t0,2),"seconds" if showfig: plt.show() return
def pressureIG_of_alpha(Alpha, Press, x,X,D,dt, verbose): """ Calculate IG pressure on a finer grid """ me = "LE_DeltaPressure.pressureIG_of_alpha: " tIG = sysT() AlphaIG = Alpha PressIG = [ideal_gas(a,x,X,D,dt,2)[3][-1]/dt for a in AlphaIG] if verbose: print me+"white noise pressure calculation:",round(sysT()-tIG,2),"seconds." return AlphaIG, PressIG
def pressure_of_alpha(dirpath, verbose): """ Plot pressure at "infinity" against alpha for all files in directory. Be careful heed changes in parameters between files in directory """ me = "LE_DeltaPressure.pressure_of_alpha: " t0 = sysT() ## File discovery histfiles = np.sort(glob.glob(dirpath + "/*.npy")) numfiles = len(histfiles) Alpha = np.zeros(numfiles) Press = np.zeros(numfiles) PressIG = np.zeros(numfiles) ## Loop over files for i, filepath in enumerate(histfiles): ## Find alpha; assume all other pars stay the same Alpha[i], X, D, dt, ymax = filename_pars(filepath) ## Load data H = np.load(filepath) ## Space xmin, xmax = 0.9 * X, lookup_xmax(X, Alpha[i]) ymax = 0.5 x = calculate_xbin(xmin, X, xmax, H.shape[1] - 1) y = np.linspace(-ymax, ymax, H.shape[0]) ## Marginalise to PDF in X Hx = np.trapz(H, x=y, axis=0) Hx /= np.trapz(Hx, x=x, axis=0) ## Calculate pressure force = force_x(x, Alpha[i], X, 0.01) Press[i] = np.trapz(-force * Hx, x) / dt ## Sort values sortind = np.argsort(Alpha) Alpha = Alpha[sortind] Press = Press[sortind] PressIG = PressIG[sortind] if verbose: print me + " pressure caclulation ", str(round(sysT() - t0, 2)), "seconds." AlphaIG, PressIG = pressureIG_of_alpha(Alpha, Press, x, X, D, dt, verbose) return [Alpha, Press, AlphaIG, PressIG, D]
def pressureIG_of_alpha(Alpha, Press, x, X, D, dt, verbose): """ Calculate IG pressure on a finer grid """ me = "LE_DeltaPressure.pressureIG_of_alpha: " tIG = sysT() AlphaIG = Alpha PressIG = [ideal_gas(a, x, X, D, dt, 2)[3][-1] / dt for a in AlphaIG] if verbose: print me + "white noise pressure calculation:", round(sysT() - tIG, 2), "seconds." return AlphaIG, PressIG
def pressure_of_alpha(dirpath, verbose): """ Plot pressure at "infinity" against alpha for all files in directory. Be careful heed changes in parameters between files in directory """ me = "LE_DeltaPressure.pressure_of_alpha: " t0 = sysT() ## File discovery histfiles = np.sort(glob.glob(dirpath+"/*.npy")) numfiles = len(histfiles) Alpha = np.zeros(numfiles) Press = np.zeros(numfiles) PressIG = np.zeros(numfiles) ## Loop over files for i,filepath in enumerate(histfiles): ## Find alpha; assume all other pars stay the same Alpha[i], X, D, dt, ymax = filename_pars(filepath) ## Load data H = np.load(filepath) ## Space xmin,xmax = 0.9*X,lookup_xmax(X,Alpha[i]) ymax = 0.5 x = calculate_xbin(xmin,X,xmax,H.shape[1]-1) y = np.linspace(-ymax,ymax,H.shape[0]) ## Marginalise to PDF in X Hx = np.trapz(H,x=y,axis=0) Hx /= np.trapz(Hx,x=x,axis=0) ## Calculate pressure force = force_x(x,Alpha[i],X,0.01) Press[i] = np.trapz(-force*Hx, x)/dt ## Sort values sortind = np.argsort(Alpha) Alpha = Alpha[sortind]; Press = Press[sortind]; PressIG = PressIG[sortind] if verbose: print me+" pressure caclulation ",str(round(sysT()-t0,2)),"seconds." AlphaIG, PressIG = pressureIG_of_alpha(Alpha, Press, x,X,D,dt, verbose) return [Alpha, Press, AlphaIG, PressIG, D]
def main(): """ Fit PDF to exponential in the wall region. Reads in EITHER a BHIS file OR a directory of them. """ me = "Tail.main: " t0 = sysT() ## Options parser = optparse.OptionParser(conflict_handler="resolve") parser.add_option('-s', '--show', dest="showfig", default=False, action="store_true") parser.add_option('-v', '--verbose', dest="verbose", default=False, action="store_true") parser.add_option('-h', '--help', dest="help", default=False, action="store_true", help="Print docstring.") opt = parser.parse_args()[0] if opt.help: print main.__doc__ return showfig = opt.showfig verbose = opt.verbose argv[1] = argv[1].replace("\\", "/") if os.path.isfile(argv[1]): tail_plot(argv[1], verbose) elif os.path.isdir(argv[1]): plot_exp_alpha(argv[1], verbose) else: print me + "you gave me rubbish. Abort." exit() if verbose: print me + "execution time", round(sysT() - t0, 2), "seconds" if showfig: plt.show() return
def main(): """ NAME LE_DeltaPressure.py PURPOSE Plot a graph of pressure against alpha for coloured and white noise for multiple values of the potential sofness parameter Delta STARTED 13 December 2015 """ me = "LE_DeltaPressure.main: " t0 = sysT() ## Options parser = optparse.OptionParser(conflict_handler="resolve") parser.add_option('-s', '--show', dest="showfig", default=False, action="store_true") parser.add_option('-v', '--verbose', dest="verbose", default=False, action="store_true") parser.add_option('-h', '--help', dest="help", default=False, action="store_true", help="Print docstring.") opt = parser.parse_args()[0] if opt.help: print main.__doc__ return showfig = opt.showfig verbose = opt.verbose ## Find relevant directories rootdir = argv[1].replace("\\", "/") filelist = glob.glob(rootdir + "/*.npy") dirlist = np.unique([os.path.dirname(histfile) for histfile in filelist]) ndir = len(dirlist) if verbose: print me + "searching in directories " + str( dirlist) + ". Found " + str(len(filelist)) + " files." ## Initialise arrays Alpha_D = [] Press_D = [] AlphaIG_D = [] PressIG_D = [] D = [] tread = sysT() ## Calculate pressure as function of alpha for each D for i, dirpath in enumerate(dirlist): data = pressure_of_alpha(dirpath, verbose) Alpha_D += [data[0]] Press_D += [data[1]] AlphaIG_D += [data[2]] PressIG_D += [data[3]] D += [data[4]] if verbose: print me + "data extraction", round(sysT() - tread, 2), "seconds." sortind = list(np.argsort(D)) D = np.array(D)[sortind] Alpha_D = np.array(Alpha_D)[sortind] Press_D = np.array(Press_D)[sortind] AlphaIG_D = np.array(AlphaIG_D)[sortind] PressIG_D = np.array(PressIG_D)[sortind] ## Use IG D=0 result as reference ## Should be the same as running again with alpha in different place -- ??? ## See notes 2015.12.15 # X,xmin,dt = 10.0,9.0,0.01 # P_ref = 1/(X-xmin+dt/Alpha_D) # PIG_ref = 1/(X-xmin+dt/AlphaIG_D) # Press_D /= P_ref # PressIG_D /= PIG_ref tplot = sysT() ## Plot colour = ["b", "r", "g", "m", "k"] for i in range(ndir): plt.errorbar(Alpha_D[i], Press_D[i], yerr=0.05,\ fmt=colour[i]+"o-", ecolor='grey', capthick=2, label="CN; $\\Delta = "+str(D[i])+"$") plt.plot(AlphaIG_D[i], PressIG_D[i], colour[i] + "--", label="WN; $\\Delta = " + str(D[i]) + "$") ## Fit fitarr, m = make_fit(Alpha_D[i], Press_D[i]) plt.plot(Alpha_D[i], fitarr, colour[i] + ":", label="$P \\sim " + str(m) + "\\alpha$") plot_acco(plt.gca(), xlabel="$\\alpha=f_0^2\\tau/T\\zeta$", ylabel="Pressure",\ legloc="") ## Reorder legend plot_legend(plt.gca(), ndir) ## Save to each directory for dir in dirlist: plotfile = dir + "/PressureAlphaDelta.png" plt.savefig(plotfile) if verbose: print me + "plot saved to " + plotfile if verbose: print me + "plotting and saving", round(sysT() - tplot, 2), "seconds." if verbose: print me + "total execution time", round(sysT() - t0, 2), "seconds" if showfig: plt.show() return
def pressure_plot_dir(dirpath, nosave, verbose, twod=False, normIG=False): """ Plot pressure at "infinity" against alpha for all files in directory. Be careful heed changes in parameters between files in directory """ me = "LE_Pressure.pressure_plot_dir: " t0 = sysT() ## File discovery histfiles = np.sort(glob.glob(dirpath + "/*.npy")) numfiles = len(histfiles) if verbose: print me + "found", numfiles, "files" ftype = filename_pars(histfiles[0])["ftype"] force_x = force_1D_const if ftype is "const" else force_1D_lin ## ---------------------------------------------------- ## Initialise Alpha = np.zeros(numfiles) X = np.zeros(numfiles) Press = np.zeros(numfiles) xmin, xmax = np.zeros([2, numfiles]) PressIG = np.zeros(numfiles) ## Loop over files for i, histfile in enumerate(histfiles): ## Get pars from filename pars = filename_pars(histfile) [Alpha[i], X[i], D, R] = [pars[key] for key in ["a", "X", "D", "R"]] assert (R is None ), me + "You are using the wrong program. R should not enter." ## Load data H = np.load(histfile) ## Space bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] ebins = bins["ebins"] xmin[i] = xbins[0] xmax[i] = xbins[-1] xini = 0.5 * (xmin[i] + X[i]) x = 0.5 * (xbins[1:] + xbins[:-1]) e = 0.5 * (ebins[1:] + ebins[:-1]) ## Marginalise to PDF in x and normalise Hx = np.trapz(H, x=e, axis=0) Hx /= np.trapz(Hx, x=x, axis=0) ## Calculate pressure force = force_x(x, X[i], D) Press[i] = np.trapz(-force * Hx, x) ## ---------------------------------------------------- ## Sort values sortind = np.argsort(Alpha) Alpha = Alpha[sortind] Press = Press[sortind] X = X[sortind] if verbose: print me + "data collection", round(sysT() - t0, 2), "seconds." pressplot = dirpath + "/PAX_" + ftype + ".png" ## ---------------------------------------------------- ## Choose plot type ## 1D if twod is False or ((X == X[0]).all() and (Alpha != Alpha[0]).any()): XX = np.unique(X) Ncurv = XX.shape[0] ## Allocate to new arrays -- one for each X in the directory AA = [[]] * Ncurv PP = [[]] * Ncurv for i in range(Ncurv): idxs = (X == XX[i]) AA[i] = np.array(Alpha[idxs]) PP[i] = np.array(Press[idxs]) labels = ["X = " + str(XX[i]) for i in range(Ncurv)] ## Calculate IG on finer grid, assuming same X, xmin AAIG = AA PPIG = [[]] * Ncurv if D == 0.0: if ftype is "const": # PPIG = [1.0/(1.0-np.exp(-4.0)+XX[i]-calculate_xmin(XX[i],AA[i])) for i in range(Ncurv)] PPIG = [ 1.0 / (1.0 - np.exp(-6.0) + XX[i] - 0.0) for i in range(Ncurv) ] elif ftype is "lin": # PPIG = [1.0/(np.sqrt(np.pi/2)-np.exp(-6.0)+XX[i]-calculate_xmin(XX[i],AA[i])) for i in range(Ncurv)] PPIG = [ 1.0 / (np.sqrt(np.pi / 2) - np.exp(-6.0) + XX[i] - 0.0) for i in range(Ncurv) ] else: ## Needs update! raise AttributeError, me + "no can do." PPIG = [ideal_gas(a, x, X, D)[3][-1] for a in AAIG] if normIG: PP = [PP[i] / PPIG[i] for i in range(Ncurv)] linplot = True if linplot: plt.plot(AA[0], np.power(1 / (AA[0] + 1), 0.5), "b:", label="$(\\alpha+1)^{-1/2}$", linewidth=2) plt.xlim(left=0.0, right=max(chain.from_iterable(AA))) plt.ylim(bottom=0.0, top=1.1) xlabel = "$\\alpha$" else: plt.plot(1.0 + AA[0], np.sqrt(1 / (AA[0] + 1)), "b:", label="$(\\alpha+1)^{-1/2}$", linewidth=2) plt.xscale("log") plt.yscale("log") plt.xlim(left=1.0, right=1.0 + max(chain.from_iterable(AA))) xlabel = "$\\alpha+1$" pressplot = pressplot[:-4] + "_log.png" ## Data if ftype == "const": PP[4][2] += 0.01 PP[4][3] -= 0.01 PP[4][7] -= 0.02 PP[4][10] -= 0.02 PP[4][13] -= 0.02 for i in range(Ncurv): if linplot: plt.plot(AA[i], PP[i], 'o-', label=labels[i]) else: plt.plot(1.0 + AA[i], PP[i], 'o-', label=labels[i]) if not normIG: plt.axhline(PressIG[i], color=plt.gca().lines[-1].get_color(), linestyle="--") #plt.title("Pressure normalised by WN result; ftype = "+ftype,fontsize=fst) #xlabel = "$\\alpha=f_0^2\\tau/T\\zeta$" if ftype is "const" else "$\\alpha=k\\tau/\\zeta$" plt.xlabel(xlabel, fontsize=fsa) plt.ylabel("Pressure", fontsize=fsa) plt.grid() plt.legend(loc="best", fontsize=fsl) ## 2D else: pressplot = pressplot[:-4] + "_2.png" ## IMSHOW ## Normalise Press by WN value Pim = [Press * (1.0 + 0.1 * X) if normIG else Press] ## Restructure dara, assuming sorted by alpha value Aim = np.unique(Alpha) ## Create 2D array of pressures ## There must be a nicer way of doing this Xim = np.unique(X) Pim = -np.ones((Xim.shape[0], Aim.shape[0])) PIGim = -np.ones((Xim.shape[0], Aim.shape[0])) for k in range(Press.shape[0]): for i in range(Xim.shape[0]): for j in range(Aim.shape[0]): if Aim[j] == Alpha[k] and Xim[i] == X[k]: Pim[i, j] = Press[k] PIGim[i, j] = 1.0 / (1.0 - np.exp(-4.0) + Xim[i] - calculate_xini(Xim[i], Aim[j])) ## Mask zeros Pim = np.ma.array(Pim, mask=Pim < 0.0) PIGim = np.ma.array(PIGim, mask=PIGim < 0.0) ## Normalise by WN reasult if normIG: Pim /= PIGim ## Make plot im = plt.imshow(Pim[::-1], aspect='auto', extent=[Aim[0], Aim[-1], Xim[0], Xim[-1]], interpolation="none") # ## CONTOUR # ## Messily normalise by WN result # Pmesh = Press * (1.0+0.1*X) # ## Create coordinate mesh # Amesh,Xmesh = np.meshgrid(Alpha,X) # Pmesh = np.empty(Xmesh.shape) # ## Messily create corresponding pressure mesh # mask = [] # for k in range(Press.shape[0]): # for i in range(Xmesh.shape[0]): # for j in range(Xmesh.shape[1]): # if Amesh[i,j]==Alpha[k] and Xmesh[i,j]==X[k]: # Pmesh[i,j]=Press[k] # ## Plot using contours # plt.contour(Amesh,Xmesh,Pmesh,5) ## ACCOUTREMENTS plt.title("Pressure normalised by WN result", fontsize=fst) xlabel = "$\\alpha=f_0^2\\tau/T\\zeta$" if ftype is "const" else "$\\alpha=k\\tau/\\zeta$" plt.xlabel(xlabel, fontsize=fsa) plt.ylabel("Wall separation", fontsize=fsa) plt.grid(False) # ticks = np.array([0.0,1.0,Pim.min(),Pim.mean(),Pim.max()]) # tckidx = np.argsort(ticks) # ticks = ticks[tckidx] # ticklabels = np.array(["0","1","Low", "Mean", "High"])[tckidx] # cbar = plt.colorbar(im, ticks=ticks, orientation="vertical") # cbar.ax.set_yticklabels(ticklabels, fontsize=fsl) # cbar = plt.colorbar(im, ticks=[Pim.min(),Pim.mean(),Pim.max()], orientation="vertical") # cbar.ax.set_yticklabels(["Low", "Mean", "High"], fontsize=fsl) cbar = plt.colorbar(im, orientation="vertical") ## -------------------------------------------------------- if not nosave: plt.savefig(pressplot) if verbose: print me + "plot saved to", pressplot return pressplot
def main(): """ NAME LE_Pressure.py PURPOSE Calculate pressure in vicinity of linear potential for particles driven by exponentially correlated noise. EXECUTION python LE_Pressure.py histfile/directory flags ARGUMENTS histfile path to density histogram directory path to directory containing histfiles OPTIONS FLAGS -s --show -v --verbose -a --plotall Plot each individual file in directory and then do dirplot -n --normIG Divide pressure by corresponding IG result -2 --twod Plot in two dimensions (rather than overlaid 1D plots) EXAMPLE python LE_Pressure.py dat_LE_stream\b=0.01\BHIS_y0.5bi50r5000b0.01X1seed65438.npy NOTES BUGS / TODO -- 2D PDF doen't work with unequal bin width -- D!=0 has been left behind HISTORY 12 November 2015 Started 15 November 2015 Pressure versus alpha functionality 30 November 2015 Added IG result 24 February 2016 Merged P_Xa: plotting multiple Xs in 1D or 2D """ me = "LE_Pressure.main: " t0 = sysT() ## Options parser = optparse.OptionParser(conflict_handler="resolve") parser.add_option('-s', '--show', dest="showfig", default=False, action="store_true") parser.add_option('-v', '--verbose', dest="verbose", default=False, action="store_true") parser.add_option('--nosave', dest="nosave", default=False, action="store_true") parser.add_option('-a', '--plotall', dest="plotall", default=False, action="store_true") parser.add_option('-2', '--twod', dest="twod", default=False, action="store_true") parser.add_option('--rawp', dest="rawp", default=False, action="store_true") parser.add_option('-h', '--help', dest="help", default=False, action="store_true") opt, args = parser.parse_args() if opt.help: print main.__doc__ return showfig = opt.showfig nosave = opt.nosave verbose = opt.verbose plotall = opt.plotall twod = opt.twod normIG = not opt.rawp args[0] = args[0].replace("\\", "/") if plotall and os.path.isdir(args[0]): showfig = False allfiles(args[0], nosave, verbose) if os.path.isfile(args[0]): pressure_pdf_plot_file(args[0], nosave, verbose) elif os.path.isdir(args[0]): pressure_plot_dir(args[0], nosave, verbose, twod, normIG) else: print me + "you gave me rubbish. Abort." exit() if verbose: print me + "execution time", round(sysT() - t0, 2), "seconds" if showfig: plt.show() return
def pressure_pdf_plot_file(histfile, nosave, verbose): """ Make plot for a single file """ me = "LE_Pressure.pressure_pdf_plot_file: " t0 = sysT() plotpress = False ## Filenames plotfile = os.path.dirname(histfile) + "/PDFP" + os.path.basename( histfile)[4:-4] + ".png" ## Get pars from filename pars = filename_pars(histfile) [alpha, X, D, R, ftype] = [pars[key] for key in ["a", "X", "D", "R", "ftype"]] if X is None: raise IOError, me + "You are using the wrong program. R should not enter." # os.system("python LE_SPressure.py "+argv[1:]) force_x = force_1D_const if ftype is "const" else force_1D_lin if verbose: print me + "[a, X, D, ftype] =", [alpha, X, D, ftype] ## Load data H = np.load(histfile) ## Space, for axes bins = np.load( os.path.dirname(histfile) + "/BHISBIN" + os.path.basename(histfile)[4:-4] + ".npz") xbins = bins["xbins"] ebins = bins["ebins"] xmin = xbins[0] xmax = xbins[-1] xini = 0.5 * (xmin + X) x = 0.5 * (xbins[1:] + xbins[:-1]) e = 0.5 * (ebins[1:] + ebins[:-1]) ## Marginalise to PDF in x Hx = np.trapz(H, x=e, axis=0) Hx /= np.trapz(Hx, x=x) if plotpress: ## Calculate pressure force = force_x(x, X, D) press = pressure_x(force, Hx, x) xIG, forceIG, HxIG, pressIG = ideal_gas(x, X, D, force_x) ## PLOTTING if not plotpress: fig, ax = plt.subplots(1, 1) elif plotpress: fig, axs = plt.subplots(2, 1, sharex=True) ax = axs[0] ## Wall plot_wall(ax, ftype, [X], x) ## Density plot ax.plot(x, Hx, "b-", label="Simulation") ax.plot(xIG, HxIG, "r-", label="White noise") ax.set_xlim(left=xmin, right=max(xmax, xIG[-1])) ax.set_ylim(bottom=0.0, top=1.1) if not plotpress: ax.set_xlabel("$x$", fontsize=fsa) ax.set_ylabel("$\\rho(x)$", fontsize=fsa) ax.grid() ax.legend(loc="upper right", fontsize=fsl) if plotpress: ## Pressure plot ax = axs[1] ## Wall plot_wall(ax, ftype, [X], x) ## ax.plot(x, press, "b-", linewidth=1, label="CN") ax.axhline(press[-1], color="b", linestyle="--", linewidth=1) ax.plot(xIG, pressIG, "r-", label="WN") ax.axhline(pressIG[-1], color="r", linestyle="--", linewidth=1) # ax.axhline(1/(1.0-np.exp(X-xmax)+X-xmin),color="r",linestyle="--",linewidth=1) ax.set_xlim(left=xbins[0], right=xbins[-1]) ax.set_ylim(bottom=0.0, top=np.ceil(max([press[-1], pressIG[-1]]))) ax.set_xlabel("$x$", fontsize=fsa) ax.set_ylabel("Pressure", fontsize=fsa) ax.grid() # ax.legend(loc="best",fontsize=fsl) #fig.suptitle("$x_{w}=$"+str(X)+", $\\alpha=$"+str(alpha)+", $\\Delta=$"+str(D),fontsize=16) plt.tight_layout() plt.subplots_adjust(top=0.9) if not nosave: plt.savefig(plotfile) if verbose: print me + "plot saved to", plotfile return fig
def main(): """ NAME LE_Pressure.py PURPOSE Calculate pressure in vicinity of linear potential for particles driven by exponentially correlated noise. EXECUTION python LE_Pressure.py histfile/directory flags ARGUMENTS histfile path to density histogram directory path to directory containing histfiles OPTIONS FLAGS -s --show -v --verbose -a --plotall Plot each individual file in directory and then do dirplot -n --normIG Divide pressure by corresponding IG result -2 --twod Plot in two dimensions (rather than overlaid 1D plots) EXAMPLE python LE_Pressure.py dat_LE_stream\b=0.01\BHIS_y0.5bi50r5000b0.01X1seed65438.npy NOTES BUGS / TODO -- 2D PDF doen't work with unequal bin width -- D!=0 has been left behind HISTORY 12 November 2015 Started 15 November 2015 Pressure versus alpha functionality 30 November 2015 Added IG result 24 February 2016 Merged P_Xa: plotting multiple Xs in 1D or 2D """ me = "LE_Pressure.main: " t0 = sysT() ## Options parser = optparse.OptionParser(conflict_handler="resolve") parser.add_option('-s','--show', dest="showfig", default=False, action="store_true") parser.add_option('-v','--verbose', dest="verbose", default=False, action="store_true") parser.add_option('--nosave', dest="nosave", default=False, action="store_true") parser.add_option('-a','--plotall', dest="plotall", default=False, action="store_true") parser.add_option('-2','--twod', dest="twod", default=False, action="store_true") parser.add_option('--rawp', dest="rawp", default=False, action="store_true") parser.add_option('-h','--help', dest="help",default=False,action="store_true") opt, args = parser.parse_args() if opt.help: print main.__doc__; return showfig = opt.showfig nosave = opt.nosave verbose = opt.verbose plotall = opt.plotall twod = opt.twod normIG = not opt.rawp args[0] = args[0].replace("\\","/") if plotall and os.path.isdir(args[0]): showfig = False allfiles(args[0], nosave, verbose) if os.path.isfile(args[0]): pressure_pdf_plot_file(args[0], nosave, verbose) elif os.path.isdir(args[0]): pressure_plot_dir(args[0], nosave, verbose, twod, normIG) else: print me+"you gave me rubbish. Abort." exit() if verbose: print me+"execution time",round(sysT()-t0,2),"seconds" if showfig: plt.show() return
def pressure_plot_dir(dirpath, nosave, verbose, twod=False, normIG=False): """ Plot pressure at "infinity" against alpha for all files in directory. Be careful heed changes in parameters between files in directory """ me = "LE_Pressure.pressure_plot_dir: " t0 = sysT() ## File discovery histfiles = np.sort(glob.glob(dirpath+"/*.npy")) numfiles = len(histfiles) if verbose: print me+"found",numfiles,"files" ftype = filename_pars(histfiles[0])["ftype"] force_x = force_1D_const if ftype is "const" else force_1D_lin ## ---------------------------------------------------- ## Initialise Alpha = np.zeros(numfiles) X = np.zeros(numfiles) Press = np.zeros(numfiles) xmin, xmax = np.zeros([2,numfiles]) PressIG = np.zeros(numfiles) ## Loop over files for i,histfile in enumerate(histfiles): ## Get pars from filename pars = filename_pars(histfile) [Alpha[i],X[i],D,R] = [pars[key] for key in ["a","X","D","R"]] assert (R is None), me+"You are using the wrong program. R should not enter." ## Load data H = np.load(histfile) ## Space bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] ebins = bins["ebins"] xmin[i] = xbins[0] xmax[i] = xbins[-1] xini = 0.5*(xmin[i]+X[i]) x = 0.5*(xbins[1:]+xbins[:-1]) e = 0.5*(ebins[1:]+ebins[:-1]) ## Marginalise to PDF in x and normalise Hx = np.trapz(H,x=e,axis=0) Hx /= np.trapz(Hx,x=x,axis=0) ## Calculate pressure force = force_x(x,X[i],D) Press[i] = np.trapz(-force*Hx, x) ## ---------------------------------------------------- ## Sort values sortind = np.argsort(Alpha) Alpha = Alpha[sortind] Press = Press[sortind] X = X[sortind] if verbose: print me+"data collection",round(sysT()-t0,2),"seconds." pressplot = dirpath+"/PAX_"+ftype+".png" ## ---------------------------------------------------- ## Choose plot type ## 1D if twod is False or ((X==X[0]).all() and (Alpha!=Alpha[0]).any()): XX = np.unique(X) Ncurv = XX.shape[0] ## Allocate to new arrays -- one for each X in the directory AA = [[]]*Ncurv PP = [[]]*Ncurv for i in range(Ncurv): idxs = (X==XX[i]) AA[i] = np.array(Alpha[idxs]) PP[i] = np.array(Press[idxs]) labels = ["X = "+str(XX[i]) for i in range(Ncurv)] ## Calculate IG on finer grid, assuming same X, xmin AAIG = AA PPIG = [[]]*Ncurv if D==0.0: if ftype is "const": # PPIG = [1.0/(1.0-np.exp(-4.0)+XX[i]-calculate_xmin(XX[i],AA[i])) for i in range(Ncurv)] PPIG = [1.0/(1.0-np.exp(-6.0)+XX[i]-0.0) for i in range(Ncurv)] elif ftype is "lin": # PPIG = [1.0/(np.sqrt(np.pi/2)-np.exp(-6.0)+XX[i]-calculate_xmin(XX[i],AA[i])) for i in range(Ncurv)] PPIG = [1.0/(np.sqrt(np.pi/2)-np.exp(-6.0)+XX[i]-0.0) for i in range(Ncurv)] else: ## Needs update! raise AttributeError, me+"no can do." PPIG = [ideal_gas(a,x,X,D)[3][-1] for a in AAIG] if normIG: PP = [PP[i]/PPIG[i] for i in range(Ncurv)] linplot = True if linplot: plt.plot(AA[0],np.power(1/(AA[0]+1),0.5),"b:",label="$(\\alpha+1)^{-1/2}$",linewidth=2) plt.xlim(left=0.0,right=max(chain.from_iterable(AA))) plt.ylim(bottom=0.0,top=1.1) xlabel = "$\\alpha$" else: plt.plot(1.0+AA[0],np.sqrt(1/(AA[0]+1)),"b:",label="$(\\alpha+1)^{-1/2}$",linewidth=2) plt.xscale("log"); plt.yscale("log") plt.xlim(left=1.0,right=1.0+max(chain.from_iterable(AA))) xlabel = "$\\alpha+1$" pressplot = pressplot[:-4]+"_log.png" ## Data if ftype=="const": PP[4][2]+=0.01 PP[4][3]-=0.01 PP[4][7]-=0.02 PP[4][10]-=0.02 PP[4][13]-=0.02 for i in range(Ncurv): if linplot: plt.plot(AA[i], PP[i], 'o-', label=labels[i]) else: plt.plot(1.0+AA[i], PP[i], 'o-', label=labels[i]) if not normIG: plt.axhline(PressIG[i], color=plt.gca().lines[-1].get_color(), linestyle="--") #plt.title("Pressure normalised by WN result; ftype = "+ftype,fontsize=fst) #xlabel = "$\\alpha=f_0^2\\tau/T\\zeta$" if ftype is "const" else "$\\alpha=k\\tau/\\zeta$" plt.xlabel(xlabel,fontsize=fsa) plt.ylabel("Pressure",fontsize=fsa) plt.grid() plt.legend(loc="best",fontsize=fsl) ## 2D else: pressplot = pressplot[:-4]+"_2.png" ## IMSHOW ## Normalise Press by WN value Pim = [Press *(1.0+0.1*X) if normIG else Press] ## Restructure dara, assuming sorted by alpha value Aim = np.unique(Alpha) ## Create 2D array of pressures ## There must be a nicer way of doing this Xim = np.unique(X) Pim = -np.ones((Xim.shape[0],Aim.shape[0])) PIGim = -np.ones((Xim.shape[0],Aim.shape[0])) for k in range(Press.shape[0]): for i in range(Xim.shape[0]): for j in range(Aim.shape[0]): if Aim[j]==Alpha[k] and Xim[i]==X[k]: Pim[i,j]=Press[k] PIGim[i,j]=1.0/(1.0-np.exp(-4.0)+Xim[i]-calculate_xini(Xim[i],Aim[j])) ## Mask zeros Pim = np.ma.array(Pim, mask = Pim<0.0) PIGim = np.ma.array(PIGim, mask = PIGim<0.0) ## Normalise by WN reasult if normIG: Pim /= PIGim ## Make plot im = plt.imshow(Pim[::-1],aspect='auto',extent=[Aim[0],Aim[-1],Xim[0],Xim[-1]],interpolation="none") # ## CONTOUR # ## Messily normalise by WN result # Pmesh = Press * (1.0+0.1*X) # ## Create coordinate mesh # Amesh,Xmesh = np.meshgrid(Alpha,X) # Pmesh = np.empty(Xmesh.shape) # ## Messily create corresponding pressure mesh # mask = [] # for k in range(Press.shape[0]): # for i in range(Xmesh.shape[0]): # for j in range(Xmesh.shape[1]): # if Amesh[i,j]==Alpha[k] and Xmesh[i,j]==X[k]: # Pmesh[i,j]=Press[k] # ## Plot using contours # plt.contour(Amesh,Xmesh,Pmesh,5) ## ACCOUTREMENTS plt.title("Pressure normalised by WN result",fontsize=fst) xlabel = "$\\alpha=f_0^2\\tau/T\\zeta$" if ftype is "const" else "$\\alpha=k\\tau/\\zeta$" plt.xlabel(xlabel,fontsize=fsa) plt.ylabel("Wall separation",fontsize=fsa) plt.grid(False) # ticks = np.array([0.0,1.0,Pim.min(),Pim.mean(),Pim.max()]) # tckidx = np.argsort(ticks) # ticks = ticks[tckidx] # ticklabels = np.array(["0","1","Low", "Mean", "High"])[tckidx] # cbar = plt.colorbar(im, ticks=ticks, orientation="vertical") # cbar.ax.set_yticklabels(ticklabels, fontsize=fsl) # cbar = plt.colorbar(im, ticks=[Pim.min(),Pim.mean(),Pim.max()], orientation="vertical") # cbar.ax.set_yticklabels(["Low", "Mean", "High"], fontsize=fsl) cbar = plt.colorbar(im, orientation="vertical") ## -------------------------------------------------------- if not nosave: plt.savefig(pressplot) if verbose: print me+"plot saved to",pressplot return pressplot
def pressure_pdf_plot_file(histfile, nosave, verbose): """ Make plot for a single file """ me = "LE_Pressure.pressure_pdf_plot_file: " t0 = sysT() plotpress = False ## Filenames plotfile = os.path.dirname(histfile)+"/PDFP"+os.path.basename(histfile)[4:-4]+".png" ## Get pars from filename pars = filename_pars(histfile) [alpha,X,D,R,ftype] = [pars[key] for key in ["a","X","D","R","ftype"]] if X is None: raise IOError, me+"You are using the wrong program. R should not enter." # os.system("python LE_SPressure.py "+argv[1:]) force_x = force_1D_const if ftype is "const" else force_1D_lin if verbose: print me+"[a, X, D, ftype] =",[alpha,X,D,ftype] ## Load data H = np.load(histfile) ## Space, for axes bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] ebins = bins["ebins"] xmin = xbins[0] xmax = xbins[-1] xini = 0.5*(xmin+X) x = 0.5*(xbins[1:]+xbins[:-1]) e = 0.5*(ebins[1:]+ebins[:-1]) ## Marginalise to PDF in x Hx = np.trapz(H,x=e,axis=0) Hx /= np.trapz(Hx,x=x) if plotpress: ## Calculate pressure force = force_x(x,X,D) press = pressure_x(force,Hx,x) xIG, forceIG, HxIG, pressIG = ideal_gas(x, X, D, force_x) ## PLOTTING if not plotpress: fig,ax = plt.subplots(1,1) elif plotpress: fig,axs = plt.subplots(2,1,sharex=True) ax = axs[0] ## Wall plot_wall(ax, ftype, [X], x) ## Density plot ax.plot(x,Hx,"b-",label="Simulation") ax.plot(xIG,HxIG,"r-",label="White noise") ax.set_xlim(left=xmin,right=max(xmax,xIG[-1])) ax.set_ylim(bottom=0.0,top=1.1) if not plotpress: ax.set_xlabel("$x$",fontsize=fsa) ax.set_ylabel("$\\rho(x)$",fontsize=fsa) ax.grid() ax.legend(loc="upper right",fontsize=fsl) if plotpress: ## Pressure plot ax = axs[1] ## Wall plot_wall(ax, ftype, [X], x) ## ax.plot(x,press,"b-",linewidth=1, label="CN") ax.axhline(press[-1],color="b",linestyle="--",linewidth=1) ax.plot(xIG,pressIG,"r-",label="WN") ax.axhline(pressIG[-1],color="r",linestyle="--",linewidth=1) # ax.axhline(1/(1.0-np.exp(X-xmax)+X-xmin),color="r",linestyle="--",linewidth=1) ax.set_xlim(left=xbins[0],right=xbins[-1]) ax.set_ylim(bottom=0.0, top=np.ceil(max([press[-1],pressIG[-1]]))) ax.set_xlabel("$x$",fontsize=fsa) ax.set_ylabel("Pressure",fontsize=fsa) ax.grid() # ax.legend(loc="best",fontsize=fsl) #fig.suptitle("$x_{w}=$"+str(X)+", $\\alpha=$"+str(alpha)+", $\\Delta=$"+str(D),fontsize=16) plt.tight_layout(); plt.subplots_adjust(top=0.9) if not nosave: plt.savefig(plotfile) if verbose: print me+"plot saved to",plotfile return fig
def pressure_plot_dir(dirpath, verbose): """ Plot pressure at "infinity" against alpha for all files in directory. Be careful heed changes in parameters between files in directory """ me = "LE_Pressure.pressure_plot_dir: " t0 = sysT() ## File discovery histfiles = np.sort(glob.glob(dirpath+"/BHIS_2D_*.npy")) numfiles = len(histfiles) if verbose: print me+"found",numfiles,"files" ## Initialise Alpha = np.zeros(numfiles) X = np.zeros(numfiles) R = np.zeros(numfiles) Press = np.zeros(numfiles) xini = np.zeros(numfiles) ## Loop over files for i,histfile in enumerate(histfiles): ## Get pars from filename pars = filename_pars(histfile) [Alpha[i],X[i],D,dt,ymax,R[i]] = [pars[key] for key in ["a","X","D","dt","ymax","R"]] assert (R[i] is not None), me+"You are using the wrong program. R should be defined." assert (D == 0.0), me+"Cannot yet handle soft potential. D should be 0.0." ## Load data and normalise H = np.load(histfile) H /= H.sum() ## Centre of circle for curved boundary c = circle_centre(X[i],R[i],ymax) ## Space (for axes) try: bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] ybins = bins["ybins"] xini[i] = xbins[0] xmax = xbins[-1] except (IOError, KeyError): xini[i] = calculate_xini(X[i],Alpha[i]) xmax = lookup_xmax(c[0]+R[i],Alpha[i]) xbins = calculate_xbin(xini,X[i],xmax,H.shape[1]) ybins = calculate_ybin(0.0,ymax,H.shape[0]+1) x = 0.5*(xbins[1:]+xbins[:-1]) y = 0.5*(ybins[1:]+ybins[:-1]) ## Calculate force array (2D) Xm,Ym = np.meshgrid(x,y) force = -1.0 * ( (Xm-c[0])**2 + (Ym-c[1])**2 > R[i]*R[i] ) * ( Xm-c[0]>0.0 ) ## Pressure array (2d) -- sum rather than trapz Press[i] = -1.0*(force*H).sum(axis=0).cumsum(axis=0)[-1] ## ------------------------------------------------ ## Create 3D pressure array and 1D a,X,R coordinate arrays ## Ordered independent variable arrays AA = np.unique(Alpha) XX = np.unique(X) RR = np.unique(R) ## 3D pressure array: [X,R,A] PP = np.zeros([XX.size,RR.size,AA.size]) PPWN = np.zeros(PP.shape) for i in range(XX.size): Xidx = (X==XX[i]) for j in range(RR.size): Ridx = (R==RR[j]) for k in range(AA.size): Aidx = (Alpha==AA[k]) Pidx = Xidx*Ridx*Aidx try: PP[i,j,k] = Press[Pidx] except ValueError: pass PPWN[i,j,k] = pressure_IG(XX[i],RR[j],xini[Pidx],ymax,AA[k]) ## Normalise by WN result if 1: PP /= PPWN ## Mask zeros PP = np.ma.array(PP, mask = PP==0.0) ## ------------------------------------------------ ## 1D plots ## Which plots to make (abcissa,multiline,subplot,dimension) [ARX1,AXR1,XAR1,XRA1,RXA1,RAX1] = [1,0,0,0,0,0] if ARX1: fig, axs = plt.subplots(1,2,sharey=True) for i in range(RR.size): axs[0].plot(AA,PP[0,i,:], "o-", label="$R = "+str(RR[i])+"$") axs[1].plot(AA,PP[-1,i,:], "o-", label="$R = "+str(RR[i])+"$") for j in range(len(axs)): axs[j].set_xlim((AA[0],AA[-1])) axs[j].set_ylim((0.0,np.array([PP[0,:,:],PP[-1,:,:]]).max())) axs[j].set_xlabel("$\\alpha$",fontsize=fsa) axs[j].set_title("$X = "+str(XX[0-j])+"$",fontsize=fsa) axs[j].grid() axs[0].set_ylabel("Pressure",fontsize=fsa) axs[1].legend(loc="best",fontsize=fsl) plt.tight_layout() pressplot = dirpath+"/PARX1_dt"+str(dt)+".png" plt.savefig(pressplot) if verbose: print me+"plot saved to",pressplot if AXR1: fig, axs = plt.subplots(1,2,sharey=True) for i in range(XX.size): axs[0].plot(AA,PP[i, 0,:], "o-", label="$x_{\\rm wal} = "+str(XX[i])+"$") axs[1].plot(AA,PP[i,-1,:], "o-", label="$x_{\\rm wal} = "+str(XX[i])+"$") for j in range(len(axs)): axs[j].set_xlim((AA[0],AA[-1])) axs[j].set_ylim((0.0,np.array([PP[:,0,:],PP[:,-1,:]]).max())) axs[j].set_xlabel("$\\alpha$",fontsize=fsa) axs[j].set_title("$R = "+str(RR[0-j])+"$",fontsize=fsa) axs[j].grid() axs[0].set_ylabel("Pressure",fontsize=fsa) axs[1].legend(loc="best",fontsize=fsl) plt.tight_layout() pressplot = dirpath+"/PAXR1_dt"+str(dt)+".png" plt.savefig(pressplot) if verbose: print me+"plot saved to",pressplot ## ------------------------------------------------ ## 2D plots ## Which plots to make (abcissa,ordinate,subplot,dimension) [ARX2,AXR2,XAR2,XRA2,RXA2,RAX2] = [0,0,0,0,0,0] if ARX2: fig, axs = plt.subplots(1,2,sharey=True) for i in range(RR.size): axs[0].contourf(AA,RR,PP[0,:,:], vmin=0.0) axs[1].contourf(AA,RR,PP[-1,:,:], vmin=0.0) for j in range(len(axs)): axs[j].set_xlim((AA[0],AA[-1])) axs[j].set_ylim((RR[0],RR[-1])) axs[j].set_xlabel("$\\alpha$",fontsize=fsa) axs[j].set_title("$X = "+str(X[0-j])+"$",fontsize=fsa) axs[0].set_ylabel("$R$",fontsize=fsa) plt.tight_layout() pressplot = dirpath+"/PARX2_dt"+str(dt)+".png" plt.savefig(pressplot) if verbose: print me+"plot saved to",pressplot ## ------------------------------------------------ return
def main(): """ NAME LE_2DPressure.py PURPOSE Calculate pressure in vicinity of linear potential for particles driven by exponentially correlated noise in two dimensions. EXECUTION python LE_2DPressure.py histfile/directory flags ARGUMENTS histfile path to density histogram directory path to directory containing histfiles OPTIONS FLAGS -v --verbose -s --show -a --plotall EXAMPLE NOTES BUGS / TODO Using masked array breaks contour plot. HISTORY 21 February 2016 Adapted from LE_Pressure """ me = "LE_2DPressure.main: " t0 = sysT() ## Options parser = optparse.OptionParser(conflict_handler="resolve") parser.add_option('-s','--show', dest="showfig", default=False, action="store_true") parser.add_option('-v','--verbose', dest="verbose", default=False, action="store_true") parser.add_option('--rawp', dest="rawp", default=False, action="store_true") parser.add_option('-a','--plotall', dest="plotall", default=False, action="store_true") parser.add_option('-h','--help', dest="help",default=False,action="store_true", help="Print docstring.") opt, arg = parser.parse_args() if opt.help: print main.__doc__; return showfig = opt.showfig verbose = opt.verbose rawp = opt.rawp plotall = opt.plotall argv[1] = argv[1].replace("\\","/") if plotall and os.path.isdir(argv[1]): showfig = False allfiles(argv[1],verbose) if os.path.isfile(argv[1]): pressure_pdf_plot_file(argv[1],verbose) elif os.path.isdir(argv[1]): pressure_plot_dir(argv[1],verbose) else: print me+"You gave me rubbish. Abort." exit() if verbose: print me+"execution time",round(sysT()-t0,2),"seconds" if showfig: plt.show() return
def plot_exp_alpha(dirpath, verbose): """ Plot exponents of fit in wall region against alphs """ me = "Tail.plot_exp_alpha: " t0 = sysT() ## File discovery histfiles = np.sort(glob.glob(dirpath+"/*1.npy")) numfiles = len(histfiles) if verbose: print me+"found",numfiles,"files" ## Assume all files have same X start = histfiles[0].find("_X") + 2 X = float(histfiles[0][start:histfiles[0].find("_",start)]) if verbose: print me+"determined X="+str(X) ## Outfile name exponplot = dirpath+"/TailAlpha.png" Alpha = np.zeros(numfiles+1) Expon = np.zeros(numfiles+1) ## Loop over files for i,filepath in enumerate(histfiles): ## Find alpha start = filepath.find("_a") + 2 Alpha[i] = float(filepath[start:filepath.find("_",start)]) ## Load data H = np.load(filepath) ## Space xmin,xmax = 0.9*X,lookup_xmax(X,Alpha[i]) ymax = 0.5 x = calculate_xbin(xmin,X,xmax,H.shape[1]-1)[H.shape[1]/2-1:] y = np.linspace(-ymax,ymax,H.shape[0]) H = H[:,H.shape[1]/2-1:] ## Marginalise to PDF in x and eliminate zeroes Hx = np.trapz(H,x=y,axis=0) Hx = Hx[Hx!=0]; x = x[Hx!=0] ## Fit; throw away first portion of data if Alpha[i]<=0.2: lm = Hx.shape[0]/6 else: lm=Hx.shape[0]/10 fit = np.polyfit(x[lm:],np.log(Hx[lm:]),1) Expon[i] = fit[0] ## Sort values in increasing order sortind = np.argsort(Alpha) Alpha = Alpha[sortind]; Expon = Expon[sortind] ## Plotting plt.plot(Alpha,Expon,"bo") ## Fit to parabola coeff = np.transpose([Alpha*Alpha]) ((a), _, _, _) = np.linalg.lstsq(coeff, Expon) fit = np.poly1d([a, 0, 0]) plt.plot(Alpha,fit(Alpha),"r--",label=str(fit)) ## This fit has nonzero intercept # plt.plot(Alpha,np.poly1d(np.polyfit(Alpha,Expon,2))(Alpha),"r--") plot_acco(plt.gca(), title="Wall region: exponential tail of PDF: $\\rho(x)\sim\exp[+m(x-X)]$", xlabel="$\\alpha$", ylabel="Exponent, $m$", legloc="") plt.savefig(exponplot) if verbose: print me+"plot saved to",exponplot return
def plot_exp_alpha(dirpath, verbose): """ Plot exponents of fit in wall region against alphs """ me = "Tail.plot_exp_alpha: " t0 = sysT() ## File discovery histfiles = np.sort(glob.glob(dirpath + "/*1.npy")) numfiles = len(histfiles) if verbose: print me + "found", numfiles, "files" ## Assume all files have same X start = histfiles[0].find("_X") + 2 X = float(histfiles[0][start:histfiles[0].find("_", start)]) if verbose: print me + "determined X=" + str(X) ## Outfile name exponplot = dirpath + "/TailAlpha.png" Alpha = np.zeros(numfiles + 1) Expon = np.zeros(numfiles + 1) ## Loop over files for i, filepath in enumerate(histfiles): ## Find alpha start = filepath.find("_a") + 2 Alpha[i] = float(filepath[start:filepath.find("_", start)]) ## Load data H = np.load(filepath) ## Space xmin, xmax = 0.9 * X, lookup_xmax(X, Alpha[i]) ymax = 0.5 x = calculate_xbin(xmin, X, xmax, H.shape[1] - 1)[H.shape[1] / 2 - 1:] y = np.linspace(-ymax, ymax, H.shape[0]) H = H[:, H.shape[1] / 2 - 1:] ## Marginalise to PDF in x and eliminate zeroes Hx = np.trapz(H, x=y, axis=0) Hx = Hx[Hx != 0] x = x[Hx != 0] ## Fit; throw away first portion of data if Alpha[i] <= 0.2: lm = Hx.shape[0] / 6 else: lm = Hx.shape[0] / 10 fit = np.polyfit(x[lm:], np.log(Hx[lm:]), 1) Expon[i] = fit[0] ## Sort values in increasing order sortind = np.argsort(Alpha) Alpha = Alpha[sortind] Expon = Expon[sortind] ## Plotting plt.plot(Alpha, Expon, "bo") ## Fit to parabola coeff = np.transpose([Alpha * Alpha]) ((a), _, _, _) = np.linalg.lstsq(coeff, Expon) fit = np.poly1d([a, 0, 0]) plt.plot(Alpha, fit(Alpha), "r--", label=str(fit)) ## This fit has nonzero intercept # plt.plot(Alpha,np.poly1d(np.polyfit(Alpha,Expon,2))(Alpha),"r--") plot_acco( plt.gca(), title= "Wall region: exponential tail of PDF: $\\rho(x)\sim\exp[+m(x-X)]$", xlabel="$\\alpha$", ylabel="Exponent, $m$", legloc="") plt.savefig(exponplot) if verbose: print me + "plot saved to", exponplot return
def main(): """ NAME LE_DeltaPressure.py PURPOSE Plot a graph of pressure against alpha for coloured and white noise for multiple values of the potential sofness parameter Delta STARTED 13 December 2015 """ me = "LE_DeltaPressure.main: " t0 = sysT() ## Options parser = optparse.OptionParser(conflict_handler="resolve") parser.add_option('-s','--show', dest="showfig", default=False, action="store_true") parser.add_option('-v','--verbose', dest="verbose", default=False, action="store_true") parser.add_option('-h','--help', dest="help",default=False,action="store_true", help="Print docstring.") opt = parser.parse_args()[0] if opt.help: print main.__doc__; return showfig = opt.showfig verbose = opt.verbose ## Find relevant directories rootdir = argv[1].replace("\\","/") filelist = glob.glob(rootdir+"/*.npy") dirlist = np.unique([os.path.dirname(histfile) for histfile in filelist]) ndir = len(dirlist) if verbose: print me+"searching in directories "+str(dirlist)+". Found "+str(len(filelist))+" files." ## Initialise arrays Alpha_D = [] Press_D = [] AlphaIG_D = [] PressIG_D = [] D = [] tread = sysT() ## Calculate pressure as function of alpha for each D for i, dirpath in enumerate(dirlist): data = pressure_of_alpha(dirpath,verbose) Alpha_D += [data[0]] Press_D += [data[1]] AlphaIG_D += [data[2]] PressIG_D += [data[3]] D += [data[4]] if verbose: print me+"data extraction",round(sysT()-tread,2),"seconds." sortind = list(np.argsort(D)) D = np.array(D)[sortind] Alpha_D = np.array(Alpha_D)[sortind]; Press_D = np.array(Press_D)[sortind] AlphaIG_D = np.array(AlphaIG_D)[sortind]; PressIG_D = np.array(PressIG_D)[sortind] ## Use IG D=0 result as reference ## Should be the same as running again with alpha in different place -- ??? ## See notes 2015.12.15 # X,xmin,dt = 10.0,9.0,0.01 # P_ref = 1/(X-xmin+dt/Alpha_D) # PIG_ref = 1/(X-xmin+dt/AlphaIG_D) # Press_D /= P_ref # PressIG_D /= PIG_ref tplot = sysT() ## Plot colour = ["b","r","g","m","k"] for i in range(ndir): plt.errorbar(Alpha_D[i], Press_D[i], yerr=0.05,\ fmt=colour[i]+"o-", ecolor='grey', capthick=2, label="CN; $\\Delta = "+str(D[i])+"$") plt.plot(AlphaIG_D[i],PressIG_D[i], colour[i]+"--", label="WN; $\\Delta = "+str(D[i])+"$") ## Fit fitarr, m = make_fit(Alpha_D[i],Press_D[i]) plt.plot(Alpha_D[i],fitarr,colour[i]+":",label="$P \\sim "+str(m)+"\\alpha$") plot_acco(plt.gca(), xlabel="$\\alpha=f_0^2\\tau/T\\zeta$", ylabel="Pressure",\ legloc="") ## Reorder legend plot_legend(plt.gca(), ndir) ## Save to each directory for dir in dirlist: plotfile = dir+"/PressureAlphaDelta.png" plt.savefig(plotfile) if verbose: print me+"plot saved to "+plotfile if verbose: print me+"plotting and saving",round(sysT()-tplot,2),"seconds." if verbose: print me+"total execution time",round(sysT()-t0,2),"seconds" if showfig: plt.show() return
def pressure_pdf_plot_file(histfile, verbose): """ Make plot for a single file """ me = "LE_Pressure.pressure_pdf_plot_file: " t0 = sysT() ## Filenames plotfile = os.path.dirname(histfile)+"/PDFP"+os.path.basename(histfile)[4:-4]+".png" ## Get pars from filename pars = filename_pars(histfile) [alpha,X,D,dt,ymax,R] = [pars[key] for key in ["a","X","D","dt","ymax","R"]] assert (R is not None), me+"You are using the wrong program. R should be defined." assert (D == 0.0), me+"Cannot yet handle soft potential. D should be 0.0." if verbose: print me+"alpha =",alpha,"and X =",X,"and D =",D ## Load data and normalise H = np.load(histfile) H /= H.sum() ## Centre of circle for curved boundary c = circle_centre(X,R,ymax) ## Space (for axes) try: bins = np.load(os.path.dirname(histfile)+"/BHISBIN"+os.path.basename(histfile)[4:-4]+".npz") xbins = bins["xbins"] ybins = bins["ybins"] xini = xbins[0] xmax = xbins[-1] except (IOError, KeyError): xini = calculate_xini(X,alpha) xmax = lookup_xmax(c[0]+R,alpha) xbins = calculate_xbin(xini,X,xmax,H.shape[1]) ybins = calculate_ybin(0.0,ymax,H.shape[0]+1) x = 0.5*(xbins[1:]+xbins[:-1]) y = 0.5*(ybins[1:]+ybins[:-1]) ## Set up plot fig,axs = plt.subplots(1,2) ## pdf plot ax = axs[0] H[:,0]=H[:,1] Xm,Ym = np.meshgrid(x,y) CS = ax.contourf(Xm,Ym[::-1],H,10) ## Colourbar divider = make_axes_locatable(ax) cax = divider.append_axes("top", size="5%", pad=0.4) cbar = fig.colorbar(CS, cax=cax, ax=ax, orientation="horizontal", use_gridspec=True, ticks=[H.min(),H.mean(),H.max()]) cbar.ax.set_xticklabels(["Low", "Mean", "High"]) ### http://stackoverflow.com/questions/13310594/positioning-the-colorbar ## Plot curved wall wallx = np.linspace(X,c[0]+R,201) wally = c[1]+np.sqrt(R*R-(wallx-c[0])**2) ax.plot(wallx,wally, "r--",linewidth=2) ## Accoutrements ax.set_xlim([xini,xmax]) ax.set_ylim([0.0,ymax]) ax.set_xlabel("$x$", fontsize=fsa) ax.set_ylabel("$y$", fontsize=fsa) ## Calculate force array (2d) force = -1.0 * ( (Xm-c[0])**2 + (Ym-c[1])**2 > R*R ) * ( Xm-c[0]>0.0 ) ## Pressure array (2d) -- sum rather than trapz press = -1.0*(force*H).sum(axis=0).cumsum(axis=0) ## Pressure plot ax = axs[1] ax.plot(x,press,label="CN simulation") ## Bulk and wall regions ax.axvspan(xini,X, color="b",alpha=0.1) ax.axvspan(X,c[0]+R, color="m",alpha=0.05) ax.axvspan(R,xmax, color="r",alpha=0.05) ## Ideal gas result ax.hlines(pressure_IG(X,R,ymax,alpha),xini,xmax,linestyle="-",color="g",label="WN theory") ax.hlines(0.5/ymax/(1.0+X-xini),xini,xmax,linestyle="--",color="g",label="WN flat theory") ## Accoutrements ax.set_xlim([xini,xmax]) ax.set_xlabel("$x$", fontsize=fsa) ax.set_ylabel("Pressure", fontsize=fsa) ax.grid() ax.legend(loc="best",fontsize=fsl) ## Tidy figure fig.suptitle(os.path.basename(plotfile),fontsize=fst) fig.tight_layout() plt.subplots_adjust(top=0.9) plt.savefig(plotfile) if verbose: print me+"plot saved to",plotfile return fig