def setup(): #Import CPL library from cplpy import CPL #initialise MPI from mpi4py import MPI comm = MPI.COMM_WORLD #Check run as part of a coupled run comm.rank # Parameters of the cpu topology (cartesian grid) npxyz = np.array([1, 1, 1], order='F', dtype=np.int32) xyzL = np.array([1., 1., 1.], order='F', dtype=np.float64) xyz_orig = np.array([0.0, 0.0, 0.0], order='F', dtype=np.float64) #initialise CPL CPL = CPL() MD_COMM = CPL.init(CPL.MD_REALM) CPL.setup_md(MD_COMM.Create_cart([npxyz[0], npxyz[1], npxyz[2]]), xyzL, xyz_orig) recvbuf, sendbuf = CPL.get_arrays(recv_size=9, send_size=8) #Analytical solution dt = 0.05 U = 1.0 nu = 1.004e-2 Re = xyzL[1]/nu #Note Reynolds in independent of velocity in analytical fn ncx = CPL.get("ncx") ncy = CPL.get("ncy") ncz = CPL.get("ncz") CAObj = CA(Re=Re, U=U, Lmin=0., Lmax=xyzL[1], npoints=2*ncy+1, nmodes=100*ncy) #Yield statement delineates end of setup and start of teardown yield [CPL, MD_COMM, recvbuf, sendbuf, CAObj, dt, U, nu] CPL.finalize() MPI.Finalize()
#Get values from CPL library ncy = CPL.get("ncy") yL_md = CPL.get("yl_md") yL_cfd = CPL.get("yl_cfd") dy = CPL.get("dy") jcmax_olap = CPL.get("jcmax_olap") #Setup Coupled domain details yL_cpl = yL_md + yL_cfd - dy * jcmax_olap ncy_cpl = int(yL_cpl / dy) #Create analytical solution object nu = 1.7 Re = yL_cpl / nu CAObj = CA(Re=Re, U=1., Lmin=0.0, Lmax=yL_cpl, npoints=2 * ncy_cpl + 2) #Setup send and recv buffers recv_array, send_array = CPL.get_arrays(recv_size=3, send_size=4) #Set velocity U = 0.5 N = 10 n = 0 for time in range(-2, 199): # recv data recv_array, ierr = CPL.recv(recv_array) # send data
def check_OpenFOAM_vs_Analytical(fdir, plotstuff=False): OpenFOAMfdir = fdir + "/cfd_data/openfoam_ico/" print("Openfoam dir = ", OpenFOAMfdir) OpenFOAMuObj = ppl.OpenFOAM_vField(OpenFOAMfdir, parallel_run=True) dt = float(OpenFOAMuObj.Raw.delta_t) tplot = float( OpenFOAMuObj.Raw.header.headerDict['controlDict']['writeInterval']) endtime = float( OpenFOAMuObj.Raw.header.headerDict['controlDict']['endTime']) enditer = int(endtime / dt) OpenFOAMwriteinterval = int(tplot / dt) # Parameters of the cpu topology (cartesian grid) xyzL = [OpenFOAMuObj.Raw.xL, OpenFOAMuObj.Raw.yL, OpenFOAMuObj.Raw.zL] dx = OpenFOAMuObj.Raw.dx dy = OpenFOAMuObj.Raw.dy dz = OpenFOAMuObj.Raw.dz ncx = OpenFOAMuObj.Raw.ncx ncy = OpenFOAMuObj.Raw.ncy ncz = OpenFOAMuObj.Raw.ncz #Analytical solution scriptdir = fdir + "/md_data/python_dummy/" with open(scriptdir + "MD_sendrecv.py", 'r') as f: for l in f: if "U =" in l: d = l.split("=") U = float(d[1].replace("\n", "").replace(" ", "")) nu = OpenFOAMuObj.Raw.nu[0] Re = (xyzL[1] + dy / 2.) / nu CAObj = CA(Re=Re, U=U, Lmin=0. - dy / 2., Lmax=xyzL[1], npoints=2 * ncy + 2) if plotstuff: import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) if "dynamic" in plotstuff or plotstuff == True: plotstuff = "dynamic" recds = range(enditer) elif "summary" in plotstuff: recds = [5, int(0.1 * enditer), int(0.25 * enditer), enditer - 1] else: plotstuff = "False" n = 0 for time in range(enditer): #Plot data if time % OpenFOAMwriteinterval == 0: rec = int(time / float(OpenFOAMwriteinterval)) try: OpenFOAMuObj = ppl.OpenFOAM_vField(OpenFOAMfdir, parallel_run=True) y, u = OpenFOAMuObj.profile(1, startrec=rec, endrec=rec) halou = OpenFOAMuObj.read_halo(startrec=rec, endrec=rec, haloname="CPLReceiveMD") print(halou.shape, halou[..., 0].min(), halou[..., 0].max()) halout = OpenFOAMuObj.read_halo(startrec=rec, endrec=rec, haloname="movingWall") y_anal, u_anal = CAObj.get_vprofile(time * dt, flip=True) error = (u_anal[2:-1:2] - u[:, 0]) / U #/u_anal[2:-1:2] #error[u_anal[2:-1:2] < 0.005] = 0. if plotstuff != "False": if time in recds: l, = ax.plot(u[:, 0], y, 'ro-', label="OpenFOAM domain from file") ax.plot(np.mean(halou[:, :, :, :, 0], (0, 2)), y[0] - 0.5 * dy, 'bs', ms=10, label="OpenFOAM halo from file") ax.plot(np.mean(halout[:, :, :, :, 0], (0, 2)), y[-1] + 0.5 * dy, 'bs', ms=10, label="OpenFOAM halo fixed") ax.plot(u_anal, y_anal, 'k.-', label="Analytical Solution") ax.plot(-error, y_anal[2:-1:2], 'g--', label="Analytical Solution") #ax.plot(10.*(u[:,0]-u_anal[-2:0:-2]),y,'y--') if "dynamic" in plotstuff: ax.set_xlim([-0.1, U * 1.1]) ax.set_xlabel("$u$", fontsize=24) ax.set_ylabel("$y$", fontsize=24) plt.legend(loc=1) plt.pause(0.001) plt.savefig('out{:05}.png'.format(n)) n += 1 ax.cla() l2 = np.sqrt(np.sum(error[1:]**2)) if not np.isnan(l2): print(time, "L2 norm error =", l2) test_error(l2, time) except AssertionError as e: print("AssertionError ", e) raise except ppl.field.OutsideRecRange: print("Error result missing", time, OpenFOAMuObj.maxrec, rec) raise if "summary" in plotstuff: ax.set_xlim([-0.1, U * 1.1]) ax.set_xlabel("$u$", fontsize=24) ax.set_ylabel("$y$", fontsize=24) #plt.legend(loc=1) plt.savefig('summary.png')
order='F', dtype=np.int32) BC_portion = CPL.my_proc_portion(BC_limits) [BC_ncxl, BC_ncyl, BC_nczl] = CPL.get_no_cells(BC_portion) #Plot output fig, ax = plt.subplots(1, 1) plt.ion() plt.show() #Analytical solution U = 1. nu = 1e-02 Re = U / nu ncy = CPL.get("ncy") CAObj = CA(Re=Re, U=U, Lmin=0., Lmax=xyzL[1], npoints=ncy) #Porous region solution pcell = 7 dy = CPL.get("dy") yl_cfd = CPL.get("yl_cfd") CApObj = CA(Re=Re, U=U, Lmin=yl_cfd - (pcell + 2.5) * dy, Lmax=xyzL[1], npoints=ncy) #y_p = np.linspace(yl_cfd-(pcell+2)*dy,yl_cfd, ncy) # Coupling parameters eps = 0.0001
MD_COMM = CPL.init(CPL.MD_REALM) CPL.setup_md(MD_COMM.Create_cart([npxyz[0], npxyz[1], npxyz[2]]), xyzL, xyz_orig) recvbuf, sendbuf = CPL.get_arrays(recv_size=9, send_size=8) #Analytical solution dt = 0.05 U = 1. nu = 1e-02 Re = xyzL[1] * U / nu ncx = CPL.get("ncx") ncy = CPL.get("ncy") ncz = CPL.get("ncz") CAObj = CA(Re=Re, U=U, Lmin=0., Lmax=xyzL[1], npoints=2 * ncy + 1, nmodes=100 * ncy) dx = xyzL[0] / float(ncx) dy = xyzL[1] / float(ncy) dz = xyzL[2] / float(ncz) dV = dx * dy * dz y = np.linspace(dy / 2., xyzL[1] - dy / 2., num=ncy) #Main time loop pcount = 0 for time in range(10000): print(time, recvbuf.shape) # Recv data: # [Ux, Uy, Uz, gradPx, gradPy, gradPz, divTaux, divTauy, divTauz]
ymin = yMD[3] # ax.plot(uMD[:-12,0], yMD[:-12]-4.33021, 'ro') # ax.plot(uCFD[:,0], yCFD-9.296, 'bx') # CAObj = CA(Re=Re, U=U, Lmin=0.0, Lmax=yCFD[-1]-9.296+5.66/2., npoints=2*nxyz[1]+2) # y_anal, u_anal = CAObj.get_vprofile(rec*rec_dt) # ax.plot(u_anal, y_anal, 'k-') #yMD = np.linspace(-4, 50, uMD.shape[0]) ax.plot(uMD[:,0], yMD[:], 'bo') ax.plot(uCFD[:,0], yCFD, 'gx') haloCFD = CFDObj.read_halo(startrec=rec,endrec=rec, haloname="movingWall") haloCPL = CFDObj.read_halo(startrec=rec, endrec=rec, haloname="CPLReceiveMD") ax.plot(np.mean(haloCPL[...,0],(0,2,3)), yCFD[0 ]-dy/2., 'gs') ax.plot(np.mean(haloCFD[...,0],(0,2,3)), yCFD[-1]+dy/2., 'gs') #Get analytical solns CAObj = CA(Re=Re, U=U, Lmin=ymin, Lmax=yCFD[-1]+dy/2., npoints=2*nxyz[1]+2) y_anal, u_anal = CAObj.get_vprofile(rec*rec_dt) ax.plot(u_anal, y_anal, 'k-') #plt.pause(0.001) #plt.cla() plt.show()
#Get values from CPL library ncy = CPL.get("ncy") yL_md = CPL.get("yl_md") yL_cfd = CPL.get("yl_cfd") dy = CPL.get("dy") jcmax_olap = CPL.get("jcmax_olap") #Setup Coupled domain details yL_cpl = yL_md + yL_cfd - dy*jcmax_olap ncy_cpl = int(yL_cpl/dy) #Create analytical solution object Uwall = 1.0 nu = 1.7 Re = yL_cpl/nu CAObj = CA(Re=Re, U=Uwall, Lmin=0.0, Lmax=yL_cpl, npoints=ncy_cpl+2) for time in range(500): y_anal, u_anal = CAObj.get_vprofile(time) # send data to update send_array[...] = 0.0 send_array[0,:,:,:] = Uwall # u_anal[-ncy] CPL.send(send_array) # recv data and plot recv_array, ierr = CPL.recv(recv_array) Ux = np.mean(recv_array[0,:,:,:])/np.mean(recv_array[3,:,:,:])
def check_OpenFOAM_vs_Analytical(fdir, plotstuff=False): OpenFOAMfdir = fdir + "/cfd_data/openfoam/" print("Openfoam dir = ", OpenFOAMfdir) OpenFOAMuObj = ppl.OpenFOAM_vField(OpenFOAMfdir, parallel_run=True) dt = float(OpenFOAMuObj.Raw.delta_t) tplot = float( OpenFOAMuObj.Raw.header.headerDict['controlDict']['writeInterval']) endtime = float( OpenFOAMuObj.Raw.header.headerDict['controlDict']['endTime']) enditer = int(endtime / dt) OpenFOAMwriteinterval = int(tplot / dt) # Parameters of the cpu topology (cartesian grid) xyzL = [OpenFOAMuObj.Raw.xL, OpenFOAMuObj.Raw.yL, OpenFOAMuObj.Raw.zL] dx = OpenFOAMuObj.Raw.dx dy = OpenFOAMuObj.Raw.dy dz = OpenFOAMuObj.Raw.dz ncx = OpenFOAMuObj.Raw.ncx ncy = OpenFOAMuObj.Raw.ncy ncz = OpenFOAMuObj.Raw.ncz #Analytical solution scriptdir = fdir + "/md_data/python_dummy/" with open(scriptdir + "test_vs_couette_analytical.py", 'r') as f: for l in f: if "U =" in l: d = l.split("=") U = float(d[1].replace("\n", "").replace(" ", "")) nu = OpenFOAMuObj.Raw.nu[0] Re = (xyzL[1] + dy / 2.) / nu CAObj = CA(Re=Re, U=U, Lmin=0., Lmax=xyzL[1], npoints=2 * ncy + 1) if plotstuff: import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) n = 0 for time in range(enditer): #Plot data if time % OpenFOAMwriteinterval == 0: rec = int(time / float(OpenFOAMwriteinterval)) try: OpenFOAMpp = ppl.OpenFOAM_PostProc(OpenFOAMfdir) OpenFOAMuObj = OpenFOAMpp.plotlist[ 'Ub'] #ppl.OpenFOAM_vField(OpenFOAMfdir, parallel_run=True) y, u = OpenFOAMuObj.profile(1, startrec=rec, endrec=rec) y_anal, u_anal = CAObj.get_vprofile(time * dt, flip=False) error = (u_anal[1:-1:2] - u[:, 0]) / u_anal[1:-1:2] if plotstuff: l, = ax.plot(u[:, 0], y, 'ro-', label="OpenFOAM domain from file") ax.plot(u_anal[1:-1:2], y_anal[1:-1:2], 'k.-', label="Analytical Solution") #ax.plot(10.*(u[:,0]-u_anal[-2:0:-2]),y,'y--') ax.set_xlim([-0.1, U * 1.1]) ax.set_xlabel("$u$", fontsize=24) ax.set_ylabel("$y$", fontsize=24) plt.legend(loc=1) plt.pause(0.001) plt.savefig('out{:05}.png'.format(n)) n += 1 ax.cla() l2 = np.sqrt(np.sum(error[1:]**2)) if not np.isnan(l2): print("Time = ", time, "Error= ", l2) test_error(l2, time) except AssertionError as e: print("AssertionError ", e) raise except: # ppl.field.OutsideRecRange: print("Error result missing", time, OpenFOAMuObj.maxrec, rec) raise
def check_LAMMPS_vs_Analytical(fdir, uwall=1., plotevolve=False): with open(fdir + "/profile.wall.2d", "r") as f: filestr = f.read() header = filestr.split("\n")[:3] body = filestr.split("\n")[3:] u = read_rec(body, 0) y = u[:,1] nsteps = 25 dt = 0.005 nu = 1.7 Ly = 40.3103 liquidstart = 0.13*Ly liquidend = 0.82*Ly liquidregion = liquidend-liquidstart liquidbins = y.shape[0] Re = liquidregion/nu CAObj = CA(Re=Re, U=uwall, Lmin=liquidstart, Lmax=liquidend, npoints=10*liquidbins, nmodes=100*liquidbins) if "dynamic" is plotevolve or plotevolve == True: plotevolve = "dynamic" import matplotlib.pyplot as plt fig, ax = plt.subplots(1,1) plt.ion() plt.show() recds = range(nsteps) elif "summary" is plotevolve: import matplotlib.pyplot as plt fig, ax = plt.subplots(1,1) recds = [1, 3, 7, 24] elif plotevolve == False or plotevolve == None: plotevolve = "False" else: raise IOError("plotevolve="+str(plotevolve)+ " which is unknown, should be dynamic or summary") ft = True timeerror = [] for rec in range(nsteps): try: u = read_rec(body, rec) except IndexError: print("Last value read, exiting loop") break if plotevolve != "False": # 0=Chunk 1=Coord1 2=Ncount 3=density/mass # 4=vx 5=vy 6=vz 7=temperature if rec in recds: ax.plot(u[:,4], u[:,1]*Ly, 'o', label="vx") y_anal, u_anal = CAObj.get_vprofile(1000*(rec+0.5)*dt) indxs = [] mn = 1 mx = -2 for i in range(mn, u.shape[0]+mx): indxs.append(find_nearest_indx(y_anal, u[i,1]*Ly)) if plotevolve != "False": if rec in recds: ax.plot(u_anal[indxs], y_anal[indxs], 'k-x', label="vx Analytical") error = (u_anal[indxs] - u[mn:mx,4])/uwall if "dynamic" is plotevolve: ax.plot(error, y_anal[indxs], 'r-', label="Error") assert np.max(np.abs(error[:-1])) < 0.2 timeerror.append(error) #print("Error = ", np.sum(error)) if "dynamic" is plotevolve: if ft: plt.legend() ft = False #plt.xlim([-0.1, 1.2]) plt.pause(.2) plt.cla() elif "summary" in plotevolve: pass timeerror = np.array(timeerror) if "dynamic" is plotevolve: plt.ioff() plt.pcolormesh(timeerror[:,:-1].T, cmap=plt.cm.RdYlBu_r) plt.colorbar() plt.show() elif "summary" is plotevolve: ax.set_xlabel("$u$") ax.set_ylabel("$y$") plt.savefig("LAMMPS_Validation_uwall" + str(uwall) + ".png", bbox_inches="tight") #Check average error less than 4% #print(np.mean(np.abs(timeerror),0)) assert np.all(np.mean(np.abs(timeerror[:,:-1]),0) < 0.04)