Ejemplo n.º 1
0
def tail_plot(histfile, verbose):
    """
	Plot tail PDF on log scale and make exponential fit
	"""
    me = "Tail.tail_plot: "

    plotfile = os.path.splitext(histfile)[0] + "_t.png"

    ## Get alpha and X from filename
    alpha, X, dt, ymax = filename_pars(histfile)
    if verbose: print me + "alpha =", alpha, "and X =", X

    ## 2D histogram
    H = np.load(histfile)

    ## Space -- bin edges and centres
    ybins = np.linspace(-0.5, 0.5, H.shape[0] + 1)
    y = 0.5 * (ybins[1:] + ybins[:-1])
    xmin, xmax = 0.9 * X, lookup_xmax(X, alpha)
    xbins = calculate_xbin(xmin, X, xmax, H.shape[1])[H.shape[1] / 2 - 1:]
    x = 0.5 * (xbins[1:] + xbins[:-1])

    ## Interested in wall region
    H = H[:, H.shape[1] / 2 - 1:]

    ## Marginalise
    Hx = np.trapz(H, x=y, axis=0)
    # Hx = H.sum(axis=0) * (y[1]-y[0])	## Should be dot product with diffy
    Hx = Hx[Hx != 0]
    x = x[Hx != 0]

    ## Fit; throw away first portion of data
    lm = Hx.shape[0] / 10
    fit = np.polyfit(x[lm:], np.log(Hx[lm:]), 1)
    fit_fn = np.poly1d(fit)

    ## White noise result
    HxIG = np.exp(fit[1]) * np.exp(-alpha / dt * (x - X))

    ## Plot (x-X distance into wall)
    plt.semilogy(x - X, Hx, label="Data")
    plt.semilogy(x-X,np.exp(fit_fn(x)),"r--",\
       label="$\exp["+str(round(fit[0]*dt/(alpha),1))+"\\frac{\\alpha}{dt}x]$")
    ## Plot IG result
    plt.semilogy(x - X, HxIG, label="White noise")
    plt.xlim(left=0.0)
    plot_acco(plt.gca(),
              title="Wall region, $\\alpha=" + str(alpha) + "$",
              xlabel="Distance into wall region",
              ylabel="PDF $p(x)$")

    plt.savefig(plotfile)
    if verbose: print me + "figure saved to", plotfile

    return
Ejemplo n.º 2
0
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]
Ejemplo n.º 3
0
def tail_plot(histfile, verbose):	
	"""
	Plot tail PDF on log scale and make exponential fit
	"""
	me = "Tail.tail_plot: "
	
	plotfile = os.path.splitext(histfile)[0]+"_t.png"

	## Get alpha and X from filename
	alpha, X, dt, ymax = filename_pars(histfile)
	if verbose: print me+"alpha =",alpha,"and X =",X
	
	## 2D histogram
	H = np.load(histfile)
	
	## Space -- bin edges and centres
	ybins = np.linspace(-0.5,0.5,H.shape[0]+1)
	y = 0.5*(ybins[1:]+ybins[:-1])
	xmin, xmax = 0.9*X, lookup_xmax(X,alpha)
	xbins = calculate_xbin(xmin,X,xmax,H.shape[1])[H.shape[1]/2-1:]
	x = 0.5*(xbins[1:]+xbins[:-1])
	
	## Interested in wall region
	H = H[:,H.shape[1]/2-1:]
	
	## Marginalise
	Hx = np.trapz(H,x=y,axis=0)
	# Hx = H.sum(axis=0) * (y[1]-y[0])	## Should be dot product with diffy
	Hx = Hx[Hx!=0]; x = x[Hx!=0]

	## Fit; throw away first portion of data
	lm=Hx.shape[0]/10
	fit = np.polyfit(x[lm:],np.log(Hx[lm:]),1)
	fit_fn = np.poly1d(fit)
	
	## White noise result
	HxIG = np.exp(fit[1])*np.exp(-alpha/dt*(x-X))

	## Plot (x-X distance into wall)
	plt.semilogy(x-X,Hx,label="Data")
	plt.semilogy(x-X,np.exp(fit_fn(x)),"r--",\
				label="$\exp["+str(round(fit[0]*dt/(alpha),1))+"\\frac{\\alpha}{dt}x]$")
	## Plot IG result
	plt.semilogy(x-X,HxIG,label="White noise")
	plt.xlim(left=0.0)
	plot_acco(plt.gca(),title="Wall region, $\\alpha="+str(alpha)+"$",
		xlabel="Distance into wall region",ylabel="PDF $p(x)$")
	
	plt.savefig(plotfile)
	if verbose:	print me+"figure saved to",plotfile
	
	return
Ejemplo n.º 4
0
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]
Ejemplo n.º 5
0
def main():
    """
	NAME
		LE_2DLBS.py
	
	PURPOSE
		Simulate coloured noise trajectories in 2D.
	
	EXECUTION
		
	FLAGS
		-a --alpha		0.1		Slope of the potential
		-X --wallpos	10.0	Position of wall
		-D --Delta		0.0		Width of wall onset in units of X
		-r --nruns		100		Number of runs for each (x0,y0)
		-t --timefac	1.0		Multiply t_max by factor
		-v --verbose	False	Print useful information to screen
		-h --help		False	Print docstring and exit
		-R --radius	1.0	Radius of wall curvature
		   --BC-impenetrable	Change BC to impenetrable rather then periodic
		   --schematic		Plot a schematic of the simulation space
		   --trajectory		Output some trajectory plots
	
	EXAMPLE
	
	NOTES
	
	BUGS
	
	HISTORY
		20 February 2016	Adapted from LE_LightBoundarySim.py
	"""
    me = "LE_2DLBS.main: "
    t0 = time.time()

    ## ----------------------------------------------------------------
    ## INPUT OPTIONS

    parser = optparse.OptionParser(conflict_handler="resolve")
    parser.add_option('-a',
                      '--alpha',
                      dest="a",
                      default=0.1,
                      type="float",
                      help="The steepness of the potential.")
    parser.add_option('-X', '--wallpos', dest="X", default=10.0, type="float")
    parser.add_option('-D', '--Delta', dest="Delta", default=0.0, type="float")
    parser.add_option('-r', '--nrun', dest="Nrun", default=100, type="int")
    parser.add_option('--dt', dest="dt", default=0.01, type="float")
    parser.add_option('-t',
                      '--timefac',
                      dest="timefac",
                      default=1.0,
                      type="float")
    parser.add_option('-v',
                      '--verbose',
                      dest="vb",
                      default=False,
                      action="store_true",
                      help="Print useful information to screen.")
    parser.add_option('-R', '--radius', dest="R", default=1.0, type="float")
    parser.add_option('--BC-impenetrable',
                      dest="PBC",
                      default=True,
                      action="store_false")
    parser.add_option('--schematic',
                      dest="schematic",
                      default=False,
                      action="store_true")
    parser.add_option('--trajectory',
                      dest="traj",
                      default=False,
                      action="store_true")
    parser.add_option('-v',
                      '--verbose',
                      dest="vb",
                      default=False,
                      action="store_true",
                      help="Print useful information to screen.")
    parser.add_option('-h',
                      '--help',
                      dest="help",
                      default=False,
                      action="store_true",
                      help="Print docstring.")
    opts, argv = parser.parse_args()
    if opts.help:
        print main.__doc__
        return
    a = opts.a
    X = opts.X
    Delta = opts.Delta
    Nrun = opts.Nrun
    global dt
    dt = opts.dt
    timefac = opts.timefac
    vb = opts.vb
    R = opts.R
    schematic = opts.schematic
    traj = opts.traj
    PBC = opts.PBC

    if Delta != 0.0:
        print me + "WARNING: Resetting Delta = 0.0."
        Delta = 0.0

    if vb: print "\n==\n" + me + "Input parameters:\n\t", opts

    ## ----------------------------------------------------------------
    ## SETUP CALCULATIONS

    ## Simulation time
    tmax = 5e2 * timefac

    ## Space: y, circle, x
    ymax = 0.5
    assert (R >= ymax), me + "The wall must enclose the volume."
    if (vb and ymax <= 2 * a):
        print me + "Warning: the width of the space is comparable to or smaller than the memory length-scale."
    ## Centre of circle for curved boundary
    R2 = R * R
    c = [X - np.sqrt(R2 - ymax * ymax), 0.0]
    ## Simulation limits
    xmax = lookup_xmax(c[0] + R, a)
    xmin = calculate_xmin(X, a)  ## Simulation cutoff
    ## Injection x coordinate
    xini = calculate_xini(X, a)

    ## Histogramming; bin edges
    Nxbin = 200
    Nybin = 50
    xbins = calculate_xbin(xini, X, xmax, Nxbin)
    ybins = calculate_ybin(0.0, ymax, Nybin + 1)

    ## Particles
    Nparticles = 1 * len(ybins) * Nrun

    ## Initial noise drawn from Gaussian
    eIC = np.random.normal(
        0.0, 1.0 /
        a, [Nparticles, 2
            ]) if a > 0.0 else 100 * (np.random.random([Nparticles, 2]) - 0.5)

    ## Centre of circle for curved boundary
    R2 = R * R
    c = [X - np.sqrt(R2 - ymax * ymax), 0.0]

    ## Filename; directory and file existence; readme
    BCstr = "PBC" if PBC else "IBC"
    hisdir = "Pressure/"+str(datetime.now().strftime("%y%m%d"))+\
      "_2D_"+BCstr+"_r"+str(Nrun)+"_dt"+str(dt)+"/"
    hisfile = "BHIS_2D_" + BCstr + "_a" + str(a) + "_X" + str(X) + "_R" + str(
        R) + "_r" + str(Nrun) + "_dt" + str(dt)
    binfile = "BHISBIN" + hisfile[4:]
    filepath = hisdir + hisfile
    check_path(filepath, vb)
    create_readme(filepath, vb)

    ## Save bins
    np.savez(hisdir + binfile, xbins=xbins, ybins=ybins)

    ## ----------------------------------------------------------------
    ## SCHEMATIC IMAGE

    if schematic:
        draw_schematic(xmin, xbins, ybins, c, R,
                       hisdir + "SCHM" + hisfile[4:] + ".png", True)
        return

    ## ----------------------------------------------------------------
    ## SIMULATION

    if vb: print me + "Computing", Nparticles, "trajectories."

    ## Precompute exp(-t/a^2)
    expmt = np.exp(-np.arange(0, tmax, dt) /
                   (a * a)) if a > 0 else np.array([1.] + [0.] *
                                                   (int(tmax / dt) - 1))
    ## Initialise histogram in space
    H = np.zeros((Nxbin, Nybin))
    ## Counter for noise initial conditions
    i = 0

    ## Loop over initial coordinates
    for yini in ybins:
        ## Perform several runs
        for run in xrange(Nrun):
            ## x, y are coordinates as a function of time
            x, y = boundary_sim((xini, yini), eIC[i], a, X, Delta, xmin, ymax,
                                R2, c, tmax, expmt, PBC,
                                (vb and run % 50 == 0))
            if traj and run == 0:
                plot_traj(x, y, xmin, X, xmax, ymax,
                          hisdir + "TRAJ" + str(i) + hisfile[4:] + ".png")
            H += np.histogram2d(x, y, bins=[xbins, ybins], normed=False)[0]
            i += 1
    H = (H.T)[::-1]
    ## When normed=False, need to divide by the bin area
    H /= np.outer(np.diff(ybins), np.diff(xbins))
    ## Normalise by number of particles
    H /= Nparticles
    save_data(filepath, H, vb)

    if vb: print me + "execution time", round(time.time() - t0, 2), "seconds"

    return filepath
Ejemplo n.º 6
0
def main():
	"""
	NAME
		LE_2DLBS.py
	
	PURPOSE
		Simulate coloured noise trajectories in 2D.
	
	EXECUTION
		
	FLAGS
		-a --alpha		0.1		Slope of the potential
		-X --wallpos	10.0	Position of wall
		-D --Delta		0.0		Width of wall onset in units of X
		-r --nruns		100		Number of runs for each (x0,y0)
		-t --timefac	1.0		Multiply t_max by factor
		-v --verbose	False	Print useful information to screen
		-h --help		False	Print docstring and exit
		-R --radius	1.0	Radius of wall curvature
		   --BC-impenetrable	Change BC to impenetrable rather then periodic
		   --schematic		Plot a schematic of the simulation space
		   --trajectory		Output some trajectory plots
	
	EXAMPLE
	
	NOTES
	
	BUGS
	
	HISTORY
		20 February 2016	Adapted from LE_LightBoundarySim.py
	"""	
	me = "LE_2DLBS.main: "
	t0 = time.time()
	
	## ----------------------------------------------------------------
	## INPUT OPTIONS
	
	parser = optparse.OptionParser(conflict_handler="resolve")	
	parser.add_option('-a','--alpha',
                  dest="a",default=0.1,type="float",
				  help="The steepness of the potential.")
	parser.add_option('-X','--wallpos',
                  dest="X",default=10.0,type="float")
	parser.add_option('-D','--Delta',
                  dest="Delta",default=0.0,type="float")		
	parser.add_option('-r','--nrun',
                  dest="Nrun",default=100,type="int")
	parser.add_option('--dt',
                  dest="dt",default=0.01,type="float")		
	parser.add_option('-t','--timefac',
                  dest="timefac",default=1.0,type="float")	 
	parser.add_option('-v','--verbose',
                  dest="vb",default=False,action="store_true",
				  help="Print useful information to screen.")	
	parser.add_option('-R','--radius',
                  dest="R",default=1.0,type="float")
	parser.add_option('--BC-impenetrable',
                  dest="PBC",default=True,action="store_false")
	parser.add_option('--schematic',
                  dest="schematic",default=False,action="store_true")
	parser.add_option('--trajectory',
                  dest="traj",default=False,action="store_true")
	parser.add_option('-v','--verbose',
                  dest="vb",default=False,action="store_true",
				  help="Print useful information to screen.")
	parser.add_option('-h','--help',
                  dest="help",default=False,action="store_true",
				  help="Print docstring.")					  
	opts, argv = parser.parse_args()
	if opts.help: print main.__doc__; return
	a		= opts.a
	X		= opts.X
	Delta	= opts.Delta
	Nrun	= opts.Nrun
	global dt; dt = opts.dt
	timefac = opts.timefac
	vb		= opts.vb
	R = opts.R
	schematic = opts.schematic
	traj = opts.traj
	PBC = opts.PBC
	
	if Delta!=0.0:
		print me+"WARNING: Resetting Delta = 0.0."
		Delta = 0.0
	
	if vb: print "\n==\n"+me+"Input parameters:\n\t",opts

	## ----------------------------------------------------------------
	## SETUP CALCULATIONS
	
	## Simulation time
	tmax = 5e2*timefac
	
	## Space: y, circle, x
	ymax = 0.5
	assert (R>=ymax), me+"The wall must enclose the volume."
	if (vb and ymax<=2*a):
		print me+"Warning: the width of the space is comparable to or smaller than the memory length-scale."
	## Centre of circle for curved boundary
	R2 = R*R
	c = [X-np.sqrt(R2-ymax*ymax),0.0]
	## Simulation limits
	xmax = lookup_xmax(c[0]+R,a)
	xmin = calculate_xmin(X,a)	## Simulation cutoff
	## Injection x coordinate
	xini = calculate_xini(X,a)
		
	## Histogramming; bin edges
	Nxbin = 200
	Nybin = 50
	xbins = calculate_xbin(xini,X,xmax,Nxbin)
	ybins = calculate_ybin(0.0,ymax,Nybin+1)
	
	## Particles	
	Nparticles = 1*len(ybins)*Nrun

	## Initial noise drawn from Gaussian 
	eIC = np.random.normal(0.0,1.0/a,[Nparticles,2]) if a>0.0 else 100*(np.random.random([Nparticles,2])-0.5)
	
	## Centre of circle for curved boundary
	R2 = R*R
	c = [X-np.sqrt(R2-ymax*ymax),0.0]
	
	
	## Filename; directory and file existence; readme
	BCstr = "PBC" if PBC else "IBC"
	hisdir = "Pressure/"+str(datetime.now().strftime("%y%m%d"))+\
			"_2D_"+BCstr+"_r"+str(Nrun)+"_dt"+str(dt)+"/"
	hisfile = "BHIS_2D_"+BCstr+"_a"+str(a)+"_X"+str(X)+"_R"+str(R)+"_r"+str(Nrun)+"_dt"+str(dt)
	binfile = "BHISBIN"+hisfile[4:]
	filepath = hisdir+hisfile
	check_path(filepath, vb)
	create_readme(filepath, vb)
	
	## Save bins
	np.savez(hisdir+binfile,xbins=xbins,ybins=ybins)
		
	## ----------------------------------------------------------------
	## SCHEMATIC IMAGE

	if schematic:
		draw_schematic(xmin,xbins,ybins,c,R, hisdir+"SCHM"+hisfile[4:]+".png",True)
		return
	
	## ----------------------------------------------------------------
	## SIMULATION
	
	if vb: print me+"Computing",Nparticles,"trajectories."
	
	## Precompute exp(-t/a^2)
	expmt = np.exp(-np.arange(0,tmax,dt)/(a*a)) if a>0 else np.array([1.]+[0.]*(int(tmax/dt)-1))
	## Initialise histogram in space
	H = np.zeros((Nxbin,Nybin))
	## Counter for noise initial conditions
	i = 0
	
	## Loop over initial coordinates
	for yini in ybins:
		## Perform several runs
		for run in xrange(Nrun):
			## x, y are coordinates as a function of time
			x, y = boundary_sim((xini,yini), eIC[i], a, X,Delta, xmin,ymax,
				R2,c, tmax,expmt, PBC, (vb and run%50==0))
			if traj and run==0: plot_traj(x,y,xmin,X,xmax,ymax, hisdir+"TRAJ"+str(i)+hisfile[4:]+".png")
			H += np.histogram2d(x,y,bins=[xbins,ybins],normed=False)[0]
			i += 1
	H = (H.T)[::-1]
	## When normed=False, need to divide by the bin area
	H /= np.outer(np.diff(ybins),np.diff(xbins))
	## Normalise by number of particles
	H /= Nparticles
	save_data(filepath, H, vb)
	
	if vb: print me+"execution time",round(time.time()-t0,2),"seconds"
	
	return filepath
Ejemplo n.º 7
0
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
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
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
Ejemplo n.º 10
0
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