def DownldData_pyJHTDB(self,dataset_name,time,lx,ly,lz,nproc,my_id,auth_token,getFunction='Velocity'): chkSz=32 #This is the maximum possible. May be increased in future depending on network bandwidth slabs=lx//chkSz lJHTDB=libJHTDB(auth_token) lJHTDB.initialize()#NOTE: datbase returns Velcocity as [lz,ly,lx,3] for k in range(slabs): start=np.array([my_id*lx+k*chkSz,0,0],dtype=np.int) width=np.array([chkSz,ly,lz],dtype=np.int) uAll=lJHTDB.getRawData(time,start,width,data_set=dataset_name,getFunction=getFunction) if(k==0): vx=uAll[:,:,:,0] vy=uAll[:,:,:,1] vz=uAll[:,:,:,2] else: vx=np.concatenate((vx,uAll[:,:,:,0]),axis=2) #axis=2=> the index of lx vy=np.concatenate((vy,uAll[:,:,:,1]),axis=2) vz=np.concatenate((vz,uAll[:,:,:,2]),axis=2) lJHTDB.finalize() u=ft.zeros_aligned((lx,ly,lz),dtype='float32') v=ft.zeros_aligned((lx,ly,lz),dtype='float32') w=ft.zeros_aligned((lx,ly,lz),dtype='float32') u[:,:,:]=np.transpose(vx) v[:,:,:]=np.transpose(vy) w[:,:,:]=np.transpose(vz) return u,v,w
def get_data(point_coords, time): """ Get velocity and velocity gradient at specified spatial points and a specified time in channel flow database. :param point_coords: Spatial coordinates of the data points of interest. Must be in single precision. :param time: Time of interest. :return: Velocity and velocity gradient arrays. """ # Create library object lJHTDB = pyJHTDB.libJHTDB() # Initialize library object lJHTDB.initialize() # Get velocity u = lJHTDB.getData(time, point_coords, sinterp='NoSInt', data_set='channel', getFunction='getVelocity') # Get velocity gradient grad_u = lJHTDB.getData(time, point_coords, sinterp='FD4NoInt', data_set='channel', getFunction='getVelocityGradient') # Finalize library object lJHTDB.finalize() return u, grad_u
def __init__(self, token_file="token"): with open(token_file, 'r') as f: auth_token = f.read().strip(" \n") self.lJHTDB = pyJHTDB.libJHTDB() self.lJHTDB.initialize() self.lJHTDB.add_token(auth_token)
def test_misc(): # load shared library lJHTDB = pyJHTDB.libJHTDB() #initialize webservices lJHTDB.initialize() spectra_check(lJHTDB=lJHTDB) contour_check(lJHTDB=lJHTDB, info=pyJHTDB.dbinfo.channel) #finalize webservices lJHTDB.finalize() return None
def test_misc(): # load shared library lJHTDB = pyJHTDB.libJHTDB() #initialize webservices lJHTDB.initialize() spectra_check(lJHTDB = lJHTDB) contour_check(lJHTDB = lJHTDB, info = pyJHTDB.dbinfo.channel) #finalize webservices lJHTDB.finalize() return None
def evolve(Prandtl, tind, t, x, HT, LB, LT, disp, savewhich='no history', evolve_backward=True): nu = 5e-5 kappa = nu / Prandtl dt = abs(t[0] - t[1]) if savewhich == 'history': npoints = x.shape[1] nparticles = x.shape[2] else: npoints = x.shape[0] nparticles = x.shape[1] lJHTDB = libJHTDB() lJHTDB.initialize() T0 = time.time() for tindex in range(tind, t.shape[0]): t0 = time.time() print( 'Channel step {0} of {1} for npoints {2}, nparticles {3} annd Prandtl Number = {4}' .format(tindex, t.shape[0], npoints, nparticles, Prandtl)) if savewhich == 'history': x[tindex + 1], HT, LB[tindex + 1], LT[tindex + 1] = evolve_one_step( lJHTDB, t[tindex], dt, x[tindex], HT, LB[tindex], LT[tindex], kappa, evolve_backward) disp[tindex] = get_dispersion(x[tindex], npoints, nparticles) else: x, HT, LB, LT = evolve_one_step(lJHTDB, t[tindex], dt, x, HT, LB, LT, kappa, evolve_backward) disp[tindex] = get_dispersion(x, npoints, nparticles) if tindex % 100 == 0: save_data(npoints, nparticles, Prandtl, tindex, t, x, LT, LB, HT, disp, savewhich) t1 = time.time() print_progress(t, tindex, t0, t1) T1 = time.time() print('FINISHED: Prandtl {0} took {1} hours total'.format( Prandtl, ((T1 - T0) / 60.) / 60.)) lJHTDB.finalize() save_data(npoints, nparticles, Prandtl, tindex, t, x, LT, LB, HT, disp, savewhich)
def test_interp(nbatches=4, npoints=2**5, isotropic1024coarse=False, mhd1024=False, channel=False, nmax=7, mmax=2): # load shared library lJHTDB = pyJHTDB.libJHTDB() #initialize webservices lJHTDB.initialize() if isotropic1024coarse: estimate_interpolation_error(lJHTDB, pyJHTDB.dbinfo.isotropic1024coarse, npoints=npoints, randseeds=range(nbatches), nmax=nmax, mmax=mmax) if mhd1024: estimate_interpolation_error(lJHTDB, pyJHTDB.dbinfo.mhd1024, npoints=npoints, randseeds=range(nbatches), nmax=nmax, mmax=mmax) if channel: estimate_interpolation_error(lJHTDB, pyJHTDB.dbinfo.channel, npoints=npoints, randseeds=range(nbatches), dir_name='random', nmax=nmax, mmax=mmax) for ynode in [0, 64, 128, 192, 256]: yval = pyJHTDB.dbinfo.channel['ynodes'][ ynode] + pyJHTDB.dbinfo.channel['dy'][ynode] / 2 estimate_interpolation_error( lJHTDB, pyJHTDB.dbinfo.channel, npoints=npoints, randseeds=range(nbatches), dir_name='ynode_{0:0>3x}'.format(ynode), yfixed=yval, nmax=nmax, mmax=mmax) #finalize webservices lJHTDB.finalize() return None
def evolve(Prandtl, tind, t, x, HT, LB, LT, disp, savewhich = 'no history', evolve_backward = True): nu = 5e-5 kappa = nu/Prandtl dt = abs(t[0] - t[1]) if savewhich == 'history': npoints = x.shape[1] nparticles = x.shape[2] else: npoints = x.shape[0] nparticles = x.shape[1] lJHTDB = libJHTDB() lJHTDB.initialize() T0 = time.time() for tindex in range(tind, t.shape[0]): t0 = time.time() print('Channel step {0} of {1} for npoints {2}, nparticles {3} annd Prandtl Number = {4}'.format(tindex, t.shape[0], npoints, nparticles, Prandtl)) if savewhich == 'history': x[tindex + 1], HT, LB[tindex + 1], LT[tindex + 1] = evolve_one_step(lJHTDB, t[tindex], dt, x[tindex], HT, LB[tindex], LT[tindex], kappa, evolve_backward) disp[tindex] = get_dispersion(x[tindex], npoints, nparticles) else: x, HT, LB, LT = evolve_one_step(lJHTDB, t[tindex], dt, x, HT, LB, LT, kappa, evolve_backward) disp[tindex] = get_dispersion(x, npoints, nparticles) if tindex%100 == 0: save_data(npoints, nparticles, Prandtl, tindex, t, x, LT, LB, HT, disp, savewhich) t1 = time.time() print_progress(t, tindex, t0, t1) T1 = time.time() print('FINISHED: Prandtl {0} took {1} hours total'.format(Prandtl, ((T1-T0)/60.)/60.)) lJHTDB.finalize() save_data(npoints, nparticles, Prandtl, tindex, t, x, LT, LB, HT, disp, savewhich)
def test_rawData( info = pyJHTDB.dbinfo.channel, npoints = 256): start = numpy.array([0, 0, 0], dtype = numpy.int) width = numpy.array([npoints, npoints, 1], dtype = numpy.int) xg = info['xnodes'][0:width[0]] yg = info['ynodes'][0:width[1]] zg = info['znodes'][0:width[2]] x = numpy.zeros((npoints, npoints, 3), numpy.float32) x[:, :, 0] = xg[None, :] x[:, :, 1] = yg[:, None] x[:, :, 2] = zg[0] lJHTDB = pyJHTDB.libJHTDB() lJHTDB.initialize() res4 = lJHTDB.getData( 0, x, sinterp = 4, tinterp = 0, data_set = info['name'], getFunction = 'Velocity') res0 = lJHTDB.getRawData( 0, start = start, size = width, data_set = info['name'], getFunction = 'Velocity') lJHTDB.finalize() fig = plt.figure(figsize=(12,6)) ax = fig.add_subplot(121) c = ax.contour(res4[:, :, 0]) ax.clabel(c) ax.set_title('Lag4 result from database') ax = fig.add_subplot(122) c = ax.contour(res0[:, :, 0, 0]) ax.clabel(c) ax.set_title('rawData result from database') fig.savefig('tst.pdf', format = 'pdf') return None
def loadData(x, time): # load shared library lTDB = pyJHTDB.libJHTDB() #initialize webservices lTDB.initialize() for t in np.arange(time.size): temp = lTDB.getData(time[t], x, data_set='channel', sinterp=4, getFunction='getVelocity') if t == 0: u = temp[:, :, 0] else: u = np.dstack((u, temp[:, :, 0])) lTDB.finalize() return u
def DownldData4Pressure(self, dataset_name, time, lx, ly, lz, my_id, auth_token): chkSz = 32 #This is the maximum possible. May be increased in future depending on network bandwidth slabs = lx // chkSz lJHTDB = libJHTDB(auth_token) lJHTDB.initialize() #NOTE: datbase returns Pressure as [lz,ly,lx] for k in range(slabs): start = np.array([my_id * lx + k * chkSz, 0, 0], dtype=np.int) width = np.array([chkSz, ly, lz], dtype=np.int) pSlab = lJHTDB.getRawData(time, start, width, data_set=dataset_name, getFunction='Pressure') if (k == 0): pAll = pSlab[:, :, :] else: pAll = np.concatenate((pAll, pSlab[:, :, :]), axis=2) #axis=2=> the index of lx lJHTDB.finalize() p = ft.zeros_aligned((lx, ly, lz), dtype='float32') p[:, :, :] = np.transpose(pAll) return p
def testchannel(numpts): ltdb = pyJHTDB.libJHTDB() ltdb.initialize() ltdb.authToken = "edu.jhu.ssh-c11eeb58" #Channel flow sanity check #points = numpy.empty((12, 3), dtype = 'float32') #points = numpy.array([[1.0, .5, 1.0],[7.1, -.5, 1.0],[1.0, .5, 4.2],[7.2,.5,4.1],[13.0,.5,2.1],[20.1,.5,1.2],[14.3,-.5,4.9],[22.1,.5,5.2],[5.1,.5,7.44],[7.45,.7,7.54],[16.1,.3,8.6],[23.1,-.3,8.94]], dtype= 'float32') #for time in range(1,25,1): #print("Velocity basic testing time %s" % time) #print ltdb.getData(time, points, sinterp=208, data_set='channel', getFunction='getVelocity') #print("Velocity Gradient testing") #ltdb.getData(0.364, points, sinterp=208, data_set='channel', getFunction='getVelocityGradient', sinterp='FD4NoInt') #print("querying %s random points from each server" % numpts) #time = 1.4100 time = 0 #print(" at time %s" % time) start = timeit.default_timer() #print("Channeldb 01:") x = numpy.random.random_sample(size=(numpts,1))[:,:]*2*math.pi y = numpy.random.random_sample(size=(numpts,1))[:,:]* 2-1 z = numpy.random.random_sample(size=(numpts,1))[:,:]*math.pi points = numpy.hstack((x,y,z)) print points try: ltdb.getData(time, points.astype(numpy.float32), sinterp=208, data_set='channel', getFunction='getVelocity') except: print ("fail") endtime = timeit.default_timer() channel1 = endtime-start #print("Total time: %s" % (endtime-start)) start = timeit.default_timer() #print("Channeldb 02:") x = numpy.random.random_sample(size=(numpts,1))[:,:]*2*math.pi + 2*math.pi y = numpy.random.random_sample(size=(numpts,1))[:,:]* 2-1 z = numpy.random.random_sample(size=(numpts,1))[:,:]*math.pi points = numpy.hstack((x,y,z)) #print points try: ltdb.getData(time, points.astype(numpy.float32), sinterp=208, data_set='channel', getFunction='getVelocity') except: pass print ("fail") endtime = timeit.default_timer() channel2 = endtime-start #print("Total time: %s" % (endtime-start)) start = timeit.default_timer() print("Channeldb 03:") x = numpy.random.random_sample(size=(numpts,1))[:,:]*2*math.pi y = numpy.random.random_sample(size=(numpts,1))[:,:]* 2-1 z = numpy.random.random_sample(size=(numpts,1))[:,:]*math.pi + math.pi points = numpy.hstack((x,y,z)) #print points try: ltdb.getData(time, points.astype(numpy.float32), sinterp=208, data_set='channel', getFunction='getVelocity') except: print ("fail") endtime = timeit.default_timer() channel3 = endtime-start print("Total time: %s" % (endtime-start)) start = timeit.default_timer() print("Channeldb 04:") x = numpy.random.random_sample(size=(numpts,1))[:,:]*2*math.pi + 2*math.pi y = numpy.random.random_sample(size=(numpts,1))[:,:]* 2-1 z = numpy.random.random_sample(size=(numpts,1))[:,:]*math.pi + math.pi points = numpy.hstack((x,y,z)) #print points try: ltdb.getData(time, points.astype(numpy.float32), sinterp=208, data_set='channel', getFunction='getVelocity') except: print ("fail") endtime = timeit.default_timer() channel4 = endtime-start #print("Total time: %s" % (endtime-start)) start = timeit.default_timer() #print("Channeldb 05:") x = (numpy.random.random_sample(size=(numpts,1))[:,:]*2*math.pi + 4*math.pi) #-.5 #to avoid a boundary y = numpy.random.random_sample(size=(numpts,1))[:,:]* 2-1 z = numpy.random.random_sample(size=(numpts,1))[:,:]*math.pi - .01 points = numpy.hstack((x,y,z)) print points try: ltdb.getData(time, points.astype(numpy.float32), sinterp=208, data_set='channel', getFunction='getVelocity') except: print ("fail") endtime = timeit.default_timer() channel5 = endtime-start #print("Total time: %s" % (endtime-start)) start = timeit.default_timer() #print("Channeldb 06:") x = numpy.random.random_sample(size=(numpts,1))[:,:]*2*math.pi + 6*math.pi y = numpy.random.random_sample(size=(numpts,1))[:,:]* 2-1 z = numpy.random.random_sample(size=(numpts,1))[:,:]*math.pi points = numpy.hstack((x,y,z)) #print points try: ltdb.getData(time, points.astype(numpy.float32), sinterp=208, data_set='channel', getFunction='getVelocity') except: print ("fail") endtime = timeit.default_timer() channel6 = endtime-start #print("Total time: %s" % (endtime-start)) start = timeit.default_timer() #print("Channeldb 07:") x = numpy.random.random_sample(size=(numpts,1))[:,:]*2*math.pi + 4*math.pi y = numpy.random.random_sample(size=(numpts,1))[:,:]* 2-1 z = numpy.random.random_sample(size=(numpts,1))[:,:]*math.pi + math.pi points = numpy.hstack((x,y,z)) #print points try: ltdb.getData(time, points.astype(numpy.float32), sinterp=208, data_set='channel', getFunction='getVelocity') except: print ("fail") endtime = timeit.default_timer() channel7 = endtime-start #print("Total time: %s" % (endtime-start)) start = timeit.default_timer() print("Channeldb 08:") x = numpy.random.random_sample(size=(numpts,1))[:,:]*2*math.pi + 6*math.pi y = numpy.random.random_sample(size=(numpts,1))[:,:]* 2-1 z = numpy.random.random_sample(size=(numpts,1))[:,:]*math.pi + math.pi points = numpy.hstack((x,y,z)) #print points try: ltdb.getData(time, points.astype(numpy.float32), sinterp=208, data_set='channel', getFunction='getVelocity') except: print ("fail") endtime = timeit.default_timer() channel8 = endtime-start #print("Total time: %s" % (endtime-start)) start = timeit.default_timer() print("Channeldb 09:") x = numpy.random.random_sample(size=(numpts,1))[:,:]*2*math.pi y = numpy.random.random_sample(size=(numpts,1))[:,:]* 2-1 z = numpy.random.random_sample(size=(numpts,1))[:,:]*math.pi + 2*math.pi points = numpy.hstack((x,y,z)) #print points try: ltdb.getData(time, points.astype(numpy.float32), sinterp=208, data_set='channel', getFunction='getVelocity') except: print ("fail") endtime = timeit.default_timer() channel9 = endtime-start #print("Total time: %s" % (endtime-start)) start = timeit.default_timer() print("Channeldb 10:") x = numpy.random.random_sample(size=(numpts,1))[:,:]*2*math.pi + 2*math.pi y = numpy.random.random_sample(size=(numpts,1))[:,:]* 2-1 z = numpy.random.random_sample(size=(numpts,1))[:,:]*math.pi + 2*math.pi points = numpy.hstack((x,y,z)) #print points try: ltdb.getData(time, points.astype(numpy.float32), sinterp=208, data_set='channel', getFunction='getVelocity') except: print ("fail") endtime = timeit.default_timer() channel10 = endtime-start #print("Total time: %s" % (endtime-start)) start = timeit.default_timer() print("Channeldb 11:") x = numpy.random.random_sample(size=(numpts,1))[:,:]*2*math.pi + 4*math.pi y = numpy.random.random_sample(size=(numpts,1))[:,:]* 2-1 z = numpy.random.random_sample(size=(numpts,1))[:,:]*math.pi + 2*math.pi points = numpy.hstack((x,y,z)) #print points try: ltdb.getData(time, points.astype(numpy.float32), sinterp=208, data_set='channel', getFunction='getVelocity') except: print ("fail") endtime = timeit.default_timer() channel11 = endtime-start #print("Total time: %s" % (endtime-start)) start = timeit.default_timer() print("Channeldb 12:") x = numpy.random.random_sample(size=(numpts,1))[:,:]*2*math.pi + 6*math.pi y = numpy.random.random_sample(size=(numpts,1))[:,:]* 2-1 z = numpy.random.random_sample(size=(numpts,1))[:,:]*math.pi + 2*math.pi points = numpy.hstack((x,y,z)) #print points try: ltdb.getData(time, points.astype(numpy.float32), sinterp=208, data_set='channel', getFunction='getVelocity') except: print ("fail") endtime = timeit.default_timer() channel12 = endtime-start #print("Total time: %s" % (endtime-start)) #print ("Time summary") #print ("1: %s" % channel1) #print ("2: %s" % channel2) #print ("3: %s" % channel3) #print ("4: %s" % channel4) #print ("5: %s" % channel5) #print ("6: %s" % channel6) #print ("7: %s" % channel7) #print ("8: %s" % channel8) #print ("9: %s" % channel9) #print ("10: %s" % channel10) #print ("11: %s" % channel11) #print ("12: %s" % channel12) channeltimes = [channel1, channel2, channel3, channel4, channel5, channel6, channel7, channel8, channel9, channel10, channel11, channel12] return channeltimes
# The filtered velocity fields saved are wider than the stresses because the # boundaries are needed in the nonlocal integration. The stresses have the same # horizontal dimensions as those that will be calculated nonlocally. # import modules import numpy as np import pyJHTDB import scipy.signal import spherical import models import sys # Initialize and add token auth_token = "edu.jhu.pato-ca56ca00" lJHTDB = pyJHTDB.libJHTDB() lJHTDB.initialize() lJHTDB.add_token(auth_token) # Dimensions dims = 3 visc_length = 1.0006e-3 dx = 8*np.pi/2048 dz = 3*np.pi/1536 dx_plus = dx/visc_length dz_plus = dz/visc_length y_points = np.loadtxt('y_points.txt') y_plus = y_points/visc_length + 1/visc_length y0 = 0 # 125 for TOP, 0 for not x_domain = np.arange(spherical.Nx)*dx y_domain = y_points[y0:y0+spherical.Ny]
############################################################################## ############################################################################## ############################################################################## ############################################################################## PrandtlNumbers = np.array([1e1, 1e0, 1e-1]) for m in range(PrandtlNumbers.shape[0]): x = x0.copy() r = np.zeros(shape = (npoints, nparticles, nparticles), dtype = np.float32) disp = np.zeros(shape = (subdivisions*nsteps + 1, npoints), dtype = np.float32) Prandtl = np.float(PrandtlNumbers[m]) kappa = nu/Prandtl noiseamplitude = (2*kappa)**.5 lJHTDB = libJHTDB() lJHTDB.initialize() for tindex in range(subdivisions*nsteps): t0 = time.time() print('step {0} of {1} for Pr = {2}'.format(tindex, subdivisions*nsteps, Prandtl)) for tryT in trytimes: try: u = lJHTDB.getData( t[tindex], x, sinterp = interpolation_code['M2Q8'], tinterp = interpolation_code['NoTInt'], data_set = info['name'], getFunction = 'getVelocity') break
def test_local_vs_db_interp(info=pyJHTDB.dbinfo.channel, time=0.0, m=1, q=4, npoints=256, dbinterp=[8, 44], start=numpy.array([0, 0, 0], dtype=numpy.int), width=numpy.array([91, 67, 31], dtype=numpy.int), messages_on=False, token="edu.jhu.pha.turbulence.testing-201311"): i = pyJHTDB.interpolator.spline_interpolator(info=info, n=(q - 2) / 2, m=m) i.generate_clib() # build point array xg = [ info['xnodes'][start[0] + i.n + 1], info['xnodes'][start[0] + width[0] - i.n - 1] ] if info['yperiodic']: yg = [ info['ynodes'][start[1] + i.n + 1], info['ynodes'][start[1] + width[1] - i.n - 1] ] else: yg = [ info['ynodes'][start[1]], info['ynodes'][start[1] + width[1] - i.n - 1] ] zg = [ info['znodes'][start[2] + i.n + 1], info['znodes'][start[2] + width[2] - i.n - 1] ] x = numpy.random.random(size=(npoints, 3)).astype(numpy.float32) x[:, 0] = xg[0] + x[:, 0] * (xg[1] - xg[0]) x[:, 1] = yg[0] + x[:, 1] * (yg[1] - yg[0]) x[:, 2] = zg[0] + x[:, 2] * (zg[1] - zg[0]) lJHTDB = pyJHTDB.libJHTDB() lJHTDB.initialize() lJHTDB.add_token(token) # get raw data to interpolate test_field = lJHTDB.getRawData(time, start=start, size=width, data_set=info['name'], getFunction='Velocity') # get DB field res0 = lJHTDB.getData(time, x, sinterp=dbinterp[0], tinterp=0, data_set=info['name'], getFunction='getVelocity') # get DB gradient resd0 = lJHTDB.getData(time, x, sinterp=dbinterp[1], tinterp=0, data_set=info['name'], getFunction='getVelocityGradient') # get locally interpolated field res1 = i.cinterpolate(x, test_field, diff=[0, 0, 0], field_offset=start) # get locally interpolated gradient resdx1 = i.cinterpolate(x, test_field, diff=[1, 0, 0], field_offset=start) resdy1 = i.cinterpolate(x, test_field, diff=[0, 1, 0], field_offset=start) resdz1 = i.cinterpolate(x, test_field, diff=[0, 0, 1], field_offset=start) resd1 = resd0.copy() resd1[..., 0] = resdx1[..., 0] resd1[..., 1] = resdy1[..., 0] resd1[..., 2] = resdz1[..., 0] resd1[..., 3] = resdx1[..., 1] resd1[..., 4] = resdy1[..., 1] resd1[..., 5] = resdz1[..., 1] resd1[..., 6] = resdx1[..., 2] resd1[..., 7] = resdy1[..., 2] resd1[..., 8] = resdz1[..., 2] del resdx1, resdy1, resdz1 lJHTDB.finalize() if messages_on: comp0 = ['ux', 'uy', 'uz'] comp1 = [ 'dxux', 'dyux', 'dzux', 'dxuy', 'dyuy', 'dzuy', 'dxuz', 'dyuz', 'dzuz' ] print('printing average relative distance between DB and local') print('example point is {0}'.format(x[0])) print('for direct interpolation using (DB) {0} and (local) M{1}Q{2}'. format(dbinterp[0], m, q)) print( 'printing average((DB) - (local)) / average(DB), (DB) at example point, abs((DB) - (local)) at example point ' ) for i in range(3): magnitude = numpy.average(numpy.abs(res0[:, i])) distance = numpy.average( numpy.abs(res0[:, i] - res1[:, i])) / magnitude print(comp0[i] + ' ' + '{0}, {1:+}, {2}'.format( distance, res0[0, i], numpy.abs(res0[0, i] - res1[0, i]))) print('for gradient interpolation using (DB) {0} and (local) M{1}Q{2}'. format(dbinterp[1], m, q)) for i in range(9): magnitude = numpy.average(numpy.abs(resd0[:, i])) distance = numpy.average( numpy.abs(resd0[:, i] - resd1[:, i])) / magnitude print(comp1[i] + ' ' + '{0}, {1:+}, {2}'.format( distance, resd0[0, i], numpy.abs(resd0[0, i] - resd1[0, i]))) return res0, res1, resd0, resd1
def test_interp_2D(info=pyJHTDB.dbinfo.channel, m=1, q=4, npoints=256): start = numpy.array([0, 0, 0], dtype=numpy.int) width = numpy.array([91, 67, 11], dtype=numpy.int) i = pyJHTDB.interpolator.spline_interpolator(info=info, n=(q - 2) / 2, m=m) i.generate_clib() xg = numpy.linspace(info['xnodes'][i.n + 1], info['xnodes'][width[0] - i.n - 1], npoints) if info['yperiodic']: yg = numpy.linspace(info['ynodes'][i.n + 1], info['ynodes'][width[1] - i.n - 1], npoints) else: yg = numpy.linspace(info['ynodes'][0], info['ynodes'][width[1] - i.n - 1], npoints) zg = numpy.linspace(info['znodes'][i.n + 1], info['znodes'][width[2] - i.n - 1], npoints) x = numpy.zeros((npoints, npoints, 3), numpy.float32) x[:, :, 0] = xg[0] #None, :] x[:, :, 1] = yg[:, None] x[:, :, 2] = zg[0] #zg[:, None] lJHTDB = pyJHTDB.libJHTDB() lJHTDB.initialize() # get raw data to interpolate test_field = lJHTDB.getRawData(0, start=start, size=width, data_set=info['name'], getFunction='Velocity') # get Lag8 velocity res0 = lJHTDB.getData(0, x, sinterp=8, tinterp=0, data_set=info['name'], getFunction='getVelocity') # get locally interpolated values res1 = i.cinterpolate(x, test_field) # get Lag4 gradient resd0 = lJHTDB.getData(0, x, sinterp=44, tinterp=0, data_set=info['name'], getFunction='getVelocityGradient') # get locally interpolated gradient resdx1 = i.cinterpolate(x, test_field, diff=[1, 0, 0]) resdy1 = i.cinterpolate(x, test_field, diff=[0, 1, 0]) resdz1 = i.cinterpolate(x, test_field, diff=[0, 0, 1]) resd1 = resd0.copy() resd1[..., 0] = resdx1[..., 0] resd1[..., 1] = resdy1[..., 0] resd1[..., 2] = resdz1[..., 0] resd1[..., 3] = resdx1[..., 1] resd1[..., 4] = resdy1[..., 1] resd1[..., 5] = resdz1[..., 1] resd1[..., 6] = resdx1[..., 2] resd1[..., 7] = resdy1[..., 2] resd1[..., 8] = resdz1[..., 2] del resdx1, resdy1, resdz1 lJHTDB.finalize() def compare_results(fld0, fld1, figname='tst'): fig = plt.figure(figsize=(12, 6)) ax = fig.add_subplot(121) c = ax.contour( #x[:, :, 0], #x[:, :, 1], fld0) ax.clabel(c) ax.set_title('result from database') ax = fig.add_subplot(122) c = ax.contour( #x[:, :, 0], #x[:, :, 1], fld1, c.levels) ax.clabel(c) ax.set_title('local M{0}Q{1:0>2} result'.format(i.m, i.n * 2 + 2)) fig.savefig(figname + '.pdf', format='pdf') fig = plt.figure() ax = fig.add_subplot(111) ax.plot(fld0[:, 0], color='blue') ax.plot(fld1[:, 0], color='red') fig.savefig(figname + '_1D.pdf', format='pdf') compare_results(res0[:, :, 1], res1[:, :, 1], figname='tst') compare_results(resd0[:, :, 1], resd1[:, :, 1], figname='dtst') ddist = (numpy.average(numpy.sqrt(numpy.sum((resd0 - resd1)**2, axis=1))) / numpy.average(numpy.sqrt(numpy.sum((resd0)**2, axis=1)))) print(ddist) return res0, res1, resd0, resd1
def test_interp_2D( info = pyJHTDB.dbinfo.channel, m = 1, q = 4, npoints = 256): start = numpy.array([0, 0, 0], dtype = numpy.int) width = numpy.array([91, 67, 11], dtype = numpy.int) i = pyJHTDB.interpolator.spline_interpolator( info = info, n = (q - 2)/2, m = m) i.generate_clib() xg = numpy.linspace(info['xnodes'][i.n+1], info['xnodes'][width[0] - i.n - 1], npoints) if info['yperiodic']: yg = numpy.linspace(info['ynodes'][i.n+1], info['ynodes'][width[1] - i.n - 1], npoints) else: yg = numpy.linspace(info['ynodes'][0], info['ynodes'][width[1] - i.n - 1], npoints) zg = numpy.linspace(info['znodes'][i.n+1], info['znodes'][width[2] - i.n - 1], npoints) x = numpy.zeros((npoints, npoints, 3), numpy.float32) x[:, :, 0] = xg[0] #None, :] x[:, :, 1] = yg[:, None] x[:, :, 2] = zg[0] #zg[:, None] lJHTDB = pyJHTDB.libJHTDB() lJHTDB.initialize() # get raw data to interpolate test_field = lJHTDB.getRawData( 0, start = start, size = width, data_set = info['name'], getFunction = 'Velocity') # get Lag8 velocity res0 = lJHTDB.getData( 0, x, sinterp = 8, tinterp = 0, data_set = info['name'], getFunction = 'getVelocity') # get locally interpolated values res1 = i.cinterpolate( x, test_field) # get Lag4 gradient resd0 = lJHTDB.getData( 0, x, sinterp = 44, tinterp = 0, data_set = info['name'], getFunction = 'getVelocityGradient') # get locally interpolated gradient resdx1 = i.cinterpolate( x, test_field, diff = [1, 0, 0]) resdy1 = i.cinterpolate( x, test_field, diff = [0, 1, 0]) resdz1 = i.cinterpolate( x, test_field, diff = [0, 0, 1]) resd1 = resd0.copy() resd1[..., 0] = resdx1[..., 0] resd1[..., 1] = resdy1[..., 0] resd1[..., 2] = resdz1[..., 0] resd1[..., 3] = resdx1[..., 1] resd1[..., 4] = resdy1[..., 1] resd1[..., 5] = resdz1[..., 1] resd1[..., 6] = resdx1[..., 2] resd1[..., 7] = resdy1[..., 2] resd1[..., 8] = resdz1[..., 2] del resdx1, resdy1, resdz1 lJHTDB.finalize() def compare_results( fld0, fld1, figname = 'tst'): fig = plt.figure(figsize=(12,6)) ax = fig.add_subplot(121) c = ax.contour( #x[:, :, 0], #x[:, :, 1], fld0) ax.clabel(c) ax.set_title('result from database') ax = fig.add_subplot(122) c = ax.contour( #x[:, :, 0], #x[:, :, 1], fld1, c.levels) ax.clabel(c) ax.set_title('local M{0}Q{1:0>2} result'.format(i.m, i.n*2+2)) fig.savefig(figname + '.pdf', format = 'pdf') fig = plt.figure() ax = fig.add_subplot(111) ax.plot(fld0[:, 0], color = 'blue') ax.plot(fld1[:, 0], color = 'red') fig.savefig(figname + '_1D.pdf', format = 'pdf') compare_results( res0[:, :, 1], res1[:, :, 1], figname = 'tst') compare_results( resd0[:, :, 1], resd1[:, :, 1], figname = 'dtst') ddist = (numpy.average(numpy.sqrt(numpy.sum((resd0 - resd1)**2, axis = 1))) / numpy.average(numpy.sqrt(numpy.sum((resd0)**2, axis = 1)))) print (ddist) return res0, res1, resd0, resd1
def test_plain(N=10): #time = 0.364 #turbc.c has a fixed time, but it makes more sense to have a random one time = 0.002 * numpy.random.randint(1024) # points must be created with the single precision data type points = numpy.empty((N, 3), dtype = 'float32') # [:,:] is there to force the conversion from the return type of random_sample to single precision points[:,:] = 2*math.pi*numpy.random.random_sample(size = (N, 3))[:,:] spatialInterp = 6 # 6 point Lagrange temporalInterp = 0 # no time interpolation FD4Lag4 = 40 # 4 point Lagrange interp for derivatives # mhdc has starttime .364 and endtime .376 startTime = 0.002 * numpy.random.randint(1024) endTime = startTime + 0.012 lag_dt = 0.0004 print('Coordinates of {0} points where variables are requested:'.format(N)) for p in range(N): print('{0}: {1}'.format(p, points[p])) print('Data is requested at time {0}'.format(time)) # load shared library lTDB = pyJHTDB.libJHTDB() #initialize webservices lTDB.initialize() print('Requesting velocity at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp = spatialInterp, tinterp = temporalInterp, getFunction = 'getVelocity') for p in range(N): print('{0}: {1}'.format(p, result[p])) print('Requesting forcing at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp = spatialInterp, tinterp = temporalInterp, getFunction = 'getForce') for p in range(N): print('{0}: {1}'.format(p, result[p])) print('Requesting velocity and pressure at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp = spatialInterp, tinterp = temporalInterp, getFunction = 'getVelocityAndPressure') for p in range(N): print('{0}: v = {1}, p = {2:+}'.format(p, result[p][0:3], result[p][3])) print('Requesting velocity gradient at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp = FD4Lag4, tinterp = temporalInterp, getFunction = 'getVelocityGradient') for p in range(N): print('{0}: '.format(p) + 'duxdx = {0:+e}, duxdy = {1:+e}, duxdz = {2:+e}\n '.format(result[p][0], result[p][1], result[p][2]) + 'duydx = {0:+e}, duydy = {1:+e}, duydz = {2:+e}\n '.format(result[p][3], result[p][4], result[p][5]) + 'duzdx = {0:+e}, duzdy = {1:+e}, duzdz = {2:+e}'.format(result[p][6], result[p][7], result[p][8])) print('Requesting velocity hessian at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp = FD4Lag4, tinterp = temporalInterp, getFunction = 'getVelocityHessian') for p in range(N): print('{0}: '.format(p) + 'd2uxdxdx = {0:+e}, d2uxdxdy = {1:+e}, d2uxdxdz = {2:+e}\n '.format(result[p][ 0], result[p][ 1], result[p][ 2]) + 'd2uxdydy = {0:+e}, d2uxdydz = {1:+e}, d2uxdzdz = {2:+e}\n '.format(result[p][ 3], result[p][ 4], result[p][ 5]) + 'd2uydxdx = {0:+e}, d2uydxdy = {1:+e}, d2uydxdz = {2:+e}\n '.format(result[p][ 6], result[p][ 7], result[p][ 8]) + 'd2uydydy = {0:+e}, d2uydydz = {1:+e}, d2uydzdz = {2:+e}\n '.format(result[p][ 9], result[p][10], result[p][11]) + 'd2uzdxdx = {0:+e}, d2uzdxdy = {1:+e}, d2uzdxdz = {2:+e}\n '.format(result[p][12], result[p][13], result[p][14]) + 'd2uzdydy = {0:+e}, d2uzdydz = {1:+e}, d2uzdzdz = {2:+e}'.format(result[p][15], result[p][16], result[p][17])) print('Requesting velocity laplacian at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp = FD4Lag4, tinterp = temporalInterp, getFunction = 'getVelocityLaplacian') for p in range(N): print('{0}: '.format(p) + 'grad2ux = {0:+e}, grad2uy = {1:+e}, grad2uz = {2:+e}, '.format(result[p][0], result[p][1], result[p][2])) print('Requesting pressure gradient at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp = FD4Lag4, tinterp = temporalInterp, getFunction = 'getPressureGradient') for p in range(N): print('{0}: '.format(p) + 'dpdx = {0:+e}, dpdy = {1:+e}, dpdz = {2:+e}, '.format(result[p][0], result[p][1], result[p][2])) print('Requesting pressure hessian at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp = FD4Lag4, tinterp = temporalInterp, getFunction = 'getVelocityHessian') for p in range(N): print('{0}: '.format(p) + 'd2pdxdx = {0:+e}, d2pdxdy = {1:+e}, d2pdxdz = {2:+e}\n '.format(result[p][0], result[p][1], result[p][2]) + 'd2pdydy = {0:+e}, d2pdydz = {1:+e}, d2pdzdz = {2:+e}'.format(result[p][3], result[p][4], result[p][5])) # print 'Requesting position at {0} points, starting at time {1} and ending at time {2}...'.format(N, startTime, endTime) # result = pyJHTDB.getPosition(startTime, endTime, lag_dt, points, sinterp = spatialInterp) # print 'Coordinates of {0} points at startTime:'.format(N) # for p in range(N): # print p, points[p] # print 'Coordinates of {0} points at endTime:'.format(N) # for p in range(N): # print p, result[p] ## only if matplotlib is present if pyJHTDB.found_matplotlib: ken_contours( 'kin_en_contours', lTDB, spatialInterp = spatialInterp, temporalInterp = temporalInterp, time = 0.002 * numpy.random.randint(1024), spacing = 2 * math.pi * 2.**(-10), nx = 64, ny = 64, xoff = 2*math.pi * numpy.random.rand(), yoff = 2*math.pi * numpy.random.rand(), zoff = 2*math.pi * numpy.random.rand()) #finalize webservices lTDB.finalize() return None
def test_interp_1D( info = pyJHTDB.dbinfo.channel, m = 1, q = 4, npoints = 256): start = numpy.array([0, 0, 0], dtype = numpy.int) width = numpy.array([51+q, 37+q, 17+q], dtype = numpy.int) i = pyJHTDB.interpolator.spline_interpolator( info = info, n = (q - 2)/2, m = m) i.generate_clib() xg = numpy.linspace(info['xnodes'][i.nx+1], info['xnodes'][width[0] - i.nx - 1], npoints) if info['yperiodic']: yg = numpy.linspace(info['ynodes'][i.ny+1], info['ynodes'][width[1] - i.ny - 1], npoints) else: yg = numpy.linspace(info['ynodes'][0], info['ynodes'][width[1] - i.ny - 1], npoints) zg = numpy.linspace(info['znodes'][i.nz+1], info['znodes'][width[2] - i.nz - 1], npoints) x = numpy.zeros((npoints, 3), numpy.float32) x[:, 0] = xg[0] x[:, 1] = yg[:] x[:, 2] = zg[0] lJHTDB = pyJHTDB.libJHTDB() lJHTDB.initialize() # get raw data to interpolate test_field = lJHTDB.getRawData( 0, start = start, size = width, data_set = info['name'], getFunction = 'Velocity') # get Lag8 velocity res0 = lJHTDB.getData( 0, x, sinterp = 8, tinterp = 0, data_set = info['name'], getFunction = 'getVelocity') # get locally interpolated values res1 = i.cinterpolate( x, test_field) # get Lag4 gradient resd0 = lJHTDB.getData( 0, x, sinterp = 44, tinterp = 0, data_set = info['name'], getFunction = 'getVelocityGradient') # get locally interpolated gradient resdx1 = i.cinterpolate( x, test_field, diff = [1, 0, 0]) resdy1 = i.cinterpolate( x, test_field, diff = [0, 1, 0]) resdz1 = i.cinterpolate( x, test_field, diff = [0, 0, 1]) resd1 = resd0.copy() resd1[..., 0] = resdx1[..., 0] resd1[..., 1] = resdy1[..., 0] resd1[..., 2] = resdz1[..., 0] resd1[..., 3] = resdx1[..., 1] resd1[..., 4] = resdy1[..., 1] resd1[..., 5] = resdz1[..., 1] resd1[..., 6] = resdx1[..., 2] resd1[..., 7] = resdy1[..., 2] resd1[..., 8] = resdz1[..., 2] del resdx1, resdy1, resdz1 lJHTDB.finalize() if pyJHTDB.found_matplotlib: def compare_results( fld0, fld1, figname = 'tst'): fig = plt.figure(figsize=(6,6)) ax = fig.add_subplot(111) ax.plot(fld0, color = 'blue') ax.plot(fld1, color = 'red') fig.savefig(figname + '.pdf', format = 'pdf') compare_results( res0, res1, figname = 'tst') compare_results( resd0, resd1, figname = 'dtst') dist = (numpy.average(numpy.sqrt(numpy.sum((res0 - res1)**2, axis = 1))) / numpy.average(numpy.sqrt(numpy.sum((res0)**2, axis = 1)))) print ('average distance for result {0}'.format(dist)) ddist = (numpy.average(numpy.sqrt(numpy.sum((resd0 - resd1)**2, axis = 1))) / numpy.average(numpy.sqrt(numpy.sum((resd0)**2, axis = 1)))) print ('average distance for dresult {0}'.format(ddist)) return res0, res1, resd0, resd1
def test_interp_1D(info=pyJHTDB.dbinfo.channel, m=1, q=4, npoints=256): start = numpy.array([0, 0, 0], dtype=numpy.int) width = numpy.array([51 + q, 37 + q, 17 + q], dtype=numpy.int) i = pyJHTDB.interpolator.spline_interpolator(info=info, n=(q - 2) / 2, m=m) i.generate_clib() xg = numpy.linspace(info['xnodes'][i.nx + 1], info['xnodes'][width[0] - i.nx - 1], npoints) if info['yperiodic']: yg = numpy.linspace(info['ynodes'][i.ny + 1], info['ynodes'][width[1] - i.ny - 1], npoints) else: yg = numpy.linspace(info['ynodes'][0], info['ynodes'][width[1] - i.ny - 1], npoints) zg = numpy.linspace(info['znodes'][i.nz + 1], info['znodes'][width[2] - i.nz - 1], npoints) x = numpy.zeros((npoints, 3), numpy.float32) x[:, 0] = xg[0] x[:, 1] = yg[:] x[:, 2] = zg[0] lJHTDB = pyJHTDB.libJHTDB() lJHTDB.initialize() # get raw data to interpolate test_field = lJHTDB.getRawData(0, start=start, size=width, data_set=info['name'], getFunction='Velocity') # get Lag8 velocity res0 = lJHTDB.getData(0, x, sinterp=8, tinterp=0, data_set=info['name'], getFunction='getVelocity') # get locally interpolated values res1 = i.cinterpolate(x, test_field) # get Lag4 gradient resd0 = lJHTDB.getData(0, x, sinterp=44, tinterp=0, data_set=info['name'], getFunction='getVelocityGradient') # get locally interpolated gradient resdx1 = i.cinterpolate(x, test_field, diff=[1, 0, 0]) resdy1 = i.cinterpolate(x, test_field, diff=[0, 1, 0]) resdz1 = i.cinterpolate(x, test_field, diff=[0, 0, 1]) resd1 = resd0.copy() resd1[..., 0] = resdx1[..., 0] resd1[..., 1] = resdy1[..., 0] resd1[..., 2] = resdz1[..., 0] resd1[..., 3] = resdx1[..., 1] resd1[..., 4] = resdy1[..., 1] resd1[..., 5] = resdz1[..., 1] resd1[..., 6] = resdx1[..., 2] resd1[..., 7] = resdy1[..., 2] resd1[..., 8] = resdz1[..., 2] del resdx1, resdy1, resdz1 lJHTDB.finalize() if pyJHTDB.found_matplotlib: def compare_results(fld0, fld1, figname='tst'): fig = plt.figure(figsize=(6, 6)) ax = fig.add_subplot(111) ax.plot(fld0, color='blue') ax.plot(fld1, color='red') fig.savefig(figname + '.pdf', format='pdf') compare_results(res0, res1, figname='tst') compare_results(resd0, resd1, figname='dtst') dist = (numpy.average(numpy.sqrt(numpy.sum((res0 - res1)**2, axis=1))) / numpy.average(numpy.sqrt(numpy.sum((res0)**2, axis=1)))) print('average distance for result {0}'.format(dist)) ddist = (numpy.average(numpy.sqrt(numpy.sum((resd0 - resd1)**2, axis=1))) / numpy.average(numpy.sqrt(numpy.sum((resd0)**2, axis=1)))) print('average distance for dresult {0}'.format(ddist)) return res0, res1, resd0, resd1
def test_local_vs_db_interp( info = pyJHTDB.dbinfo.channel, time = 0.0, m = 1, q = 4, npoints = 256, dbinterp = [8, 44], start = numpy.array([0, 0, 0], dtype = numpy.int), width = numpy.array([91, 67, 31], dtype = numpy.int), messages_on = False): i = pyJHTDB.interpolator.spline_interpolator( info = info, n = (q - 2)/2, m = m) i.generate_clib() # build point array xg = [info['xnodes'][start[0] + i.n+1], info['xnodes'][start[0] + width[0] - i.n - 1]] if info['yperiodic']: yg = [info['ynodes'][start[1] + i.n+1], info['ynodes'][start[1] + width[1] - i.n - 1]] else: yg = [info['ynodes'][start[1] ], info['ynodes'][start[1] + width[1] - i.n - 1]] zg = [info['znodes'][start[2] + i.n+1], info['znodes'][start[2] + width[2] - i.n - 1]] x = numpy.random.random(size = (npoints, 3)).astype(numpy.float32) x[:, 0] = xg[0] + x[:, 0]*(xg[1] - xg[0]) x[:, 1] = yg[0] + x[:, 1]*(yg[1] - yg[0]) x[:, 2] = zg[0] + x[:, 2]*(zg[1] - zg[0]) lJHTDB = pyJHTDB.libJHTDB() lJHTDB.initialize() # get raw data to interpolate test_field = lJHTDB.getRawData( time, start = start, size = width, data_set = info['name'], getFunction = 'Velocity') # get DB field res0 = lJHTDB.getData( time, x, sinterp = dbinterp[0], tinterp = 0, data_set = info['name'], getFunction = 'getVelocity') # get DB gradient resd0 = lJHTDB.getData( time, x, sinterp = dbinterp[1], tinterp = 0, data_set = info['name'], getFunction = 'getVelocityGradient') # get locally interpolated field res1 = i.cinterpolate( x, test_field, diff = [0, 0, 0], field_offset = start) # get locally interpolated gradient resdx1 = i.cinterpolate( x, test_field, diff = [1, 0, 0], field_offset = start) resdy1 = i.cinterpolate( x, test_field, diff = [0, 1, 0], field_offset = start) resdz1 = i.cinterpolate( x, test_field, diff = [0, 0, 1], field_offset = start) resd1 = resd0.copy() resd1[..., 0] = resdx1[..., 0] resd1[..., 1] = resdy1[..., 0] resd1[..., 2] = resdz1[..., 0] resd1[..., 3] = resdx1[..., 1] resd1[..., 4] = resdy1[..., 1] resd1[..., 5] = resdz1[..., 1] resd1[..., 6] = resdx1[..., 2] resd1[..., 7] = resdy1[..., 2] resd1[..., 8] = resdz1[..., 2] del resdx1, resdy1, resdz1 lJHTDB.finalize() if messages_on: comp0 = ['ux', 'uy', 'uz'] comp1 = ['dxux', 'dyux', 'dzux', 'dxuy', 'dyuy', 'dzuy', 'dxuz', 'dyuz', 'dzuz'] print ('printing average relative distance between DB and local') print ('example point is {0}'.format(x[0])) print ('for direct interpolation using (DB) {0} and (local) M{1}Q{2}'.format(dbinterp[0], m, q)) print ('printing average((DB) - (local)) / average(DB), (DB) at example point, abs((DB) - (local)) at example point ') for i in range(3): magnitude = numpy.average(numpy.abs(res0[:, i])) distance = numpy.average(numpy.abs(res0[:, i] - res1[:, i])) / magnitude print (comp0[i] + ' ' + '{0}, {1:+}, {2}'.format(distance, res0[0, i], numpy.abs(res0[0, i] - res1[0, i]))) print ('for gradient interpolation using (DB) {0} and (local) M{1}Q{2}'.format(dbinterp[1], m, q)) for i in range(9): magnitude = numpy.average(numpy.abs(resd0[:, i])) distance = numpy.average(numpy.abs(resd0[:, i] - resd1[:, i])) / magnitude print (comp1[i] + ' ' + '{0}, {1:+}, {2}'.format(distance, resd0[0, i], numpy.abs(resd0[0, i] - resd1[0, i]))) return res0, res1, resd0, resd1
def test_plain(N=10): #time = 0.364 #turbc.c has a fixed time, but it makes more sense to have a random one time = 0.002 * numpy.random.randint(1024) # points must be created with the single precision data type points = numpy.empty((N, 3), dtype='float32') # [:,:] is there to force the conversion from the return type of random_sample to single precision points[:, :] = 2 * math.pi * numpy.random.random_sample(size=(N, 3))[:, :] spatialInterp = 6 # 6 point Lagrange temporalInterp = 0 # no time interpolation FD4Lag4 = 40 # 4 point Lagrange interp for derivatives # mhdc has starttime .364 and endtime .376 startTime = 0.002 * numpy.random.randint(1024) endTime = startTime + 0.012 lag_dt = 0.0004 print('Coordinates of {0} points where variables are requested:'.format(N)) for p in range(N): print('{0}: {1}'.format(p, points[p])) print('Data is requested at time {0}'.format(time)) # load shared library lTDB = pyJHTDB.libJHTDB() #initialize webservices lTDB.initialize() print('Requesting velocity at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp=spatialInterp, tinterp=temporalInterp, getFunction='getVelocity') for p in range(N): print('{0}: {1}'.format(p, result[p])) print('Requesting forcing at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp=spatialInterp, tinterp=temporalInterp, getFunction='getForce') for p in range(N): print('{0}: {1}'.format(p, result[p])) print('Requesting velocity and pressure at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp=spatialInterp, tinterp=temporalInterp, getFunction='getVelocityAndPressure') for p in range(N): print('{0}: v = {1}, p = {2:+}'.format(p, result[p][0:3], result[p][3])) print('Requesting velocity gradient at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp=FD4Lag4, tinterp=temporalInterp, getFunction='getVelocityGradient') for p in range(N): print('{0}: '.format(p) + 'duxdx = {0:+e}, duxdy = {1:+e}, duxdz = {2:+e}\n '.format( result[p][0], result[p][1], result[p][2]) + 'duydx = {0:+e}, duydy = {1:+e}, duydz = {2:+e}\n '.format( result[p][3], result[p][4], result[p][5]) + 'duzdx = {0:+e}, duzdy = {1:+e}, duzdz = {2:+e}'.format( result[p][6], result[p][7], result[p][8])) print('Requesting velocity hessian at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp=FD4Lag4, tinterp=temporalInterp, getFunction='getVelocityHessian') for p in range(N): print('{0}: '.format(p) + 'd2uxdxdx = {0:+e}, d2uxdxdy = {1:+e}, d2uxdxdz = {2:+e}\n '. format(result[p][0], result[p][1], result[p][2]) + 'd2uxdydy = {0:+e}, d2uxdydz = {1:+e}, d2uxdzdz = {2:+e}\n '. format(result[p][3], result[p][4], result[p][5]) + 'd2uydxdx = {0:+e}, d2uydxdy = {1:+e}, d2uydxdz = {2:+e}\n '. format(result[p][6], result[p][7], result[p][8]) + 'd2uydydy = {0:+e}, d2uydydz = {1:+e}, d2uydzdz = {2:+e}\n '. format(result[p][9], result[p][10], result[p][11]) + 'd2uzdxdx = {0:+e}, d2uzdxdy = {1:+e}, d2uzdxdz = {2:+e}\n '. format(result[p][12], result[p][13], result[p][14]) + 'd2uzdydy = {0:+e}, d2uzdydz = {1:+e}, d2uzdzdz = {2:+e}'.format( result[p][15], result[p][16], result[p][17])) print('Requesting velocity laplacian at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp=FD4Lag4, tinterp=temporalInterp, getFunction='getVelocityLaplacian') for p in range(N): print('{0}: '.format(p) + 'grad2ux = {0:+e}, grad2uy = {1:+e}, grad2uz = {2:+e}, '.format( result[p][0], result[p][1], result[p][2])) print('Requesting pressure gradient at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp=FD4Lag4, tinterp=temporalInterp, getFunction='getPressureGradient') for p in range(N): print('{0}: '.format(p) + 'dpdx = {0:+e}, dpdy = {1:+e}, dpdz = {2:+e}, '.format( result[p][0], result[p][1], result[p][2])) print('Requesting pressure hessian at {0} points...'.format(N)) result = lTDB.getData(time, points, sinterp=FD4Lag4, tinterp=temporalInterp, getFunction='getVelocityHessian') for p in range(N): print('{0}: '.format(p) + 'd2pdxdx = {0:+e}, d2pdxdy = {1:+e}, d2pdxdz = {2:+e}\n '. format(result[p][0], result[p][1], result[p][2]) + 'd2pdydy = {0:+e}, d2pdydz = {1:+e}, d2pdzdz = {2:+e}'.format( result[p][3], result[p][4], result[p][5])) # print 'Requesting position at {0} points, starting at time {1} and ending at time {2}...'.format(N, startTime, endTime) # result = pyJHTDB.getPosition(startTime, endTime, lag_dt, points, sinterp = spatialInterp) # print 'Coordinates of {0} points at startTime:'.format(N) # for p in range(N): # print p, points[p] # print 'Coordinates of {0} points at endTime:'.format(N) # for p in range(N): # print p, result[p] ## only if matplotlib is present if pyJHTDB.found_matplotlib: ken_contours('kin_en_contours', lTDB, spatialInterp=spatialInterp, temporalInterp=temporalInterp, time=0.002 * numpy.random.randint(1024), spacing=2 * math.pi * 2.**(-10), nx=64, ny=64, xoff=2 * math.pi * numpy.random.rand(), yoff=2 * math.pi * numpy.random.rand(), zoff=2 * math.pi * numpy.random.rand()) #finalize webservices lTDB.finalize() return None
def main(): ''' This code will obtain a time history over a plane of filtered Homogeneous isotropic turbulence data from the JHU data base ''' ## From the database ## pi = np.float32(np.pi) # total time tot_t = 2.048 # The time at which to sample from the database t = tot_t / 2 # Size of the plain in grid points nx, ny, nz = 32, 32, 32 #~ nx, ny, nz = 64, 64, 64 #~ nx, ny, nz = 15, 12, 16 #~ nx, ny, nz = 1024, 192, 384 #~ nx, ny, nz = 64, 64, 128 # Domain Length from the HIT database Lx = Ly = Lz = 2. * pi # LES Filter width (depends on ny spectral direction) fw = Ly / ny # Define the size of the domain to be used x1 = np.linspace(0, Lx, nx) y1 = np.linspace(0, Ly, ny) z1 = np.linspace(0, Lz, nz) # Generate mesh x, y, z = np.meshgrid(x1, y1, z1, indexing='ij') # Generate the points #~ points = np.array((x, y, z), dtype = 'float32').reshape(-1, 3, order='F') points = np.zeros((nx, ny, nz, 3), dtype='float32', order='F') # Generate the velocity fields u = np.zeros((nx, ny, nz), dtype='float32', order='F') v = np.zeros((nx, ny, nz), dtype='float32', order='F') w = np.zeros((nx, ny, nz), dtype='float32', order='F') print 'shape points', np.shape(points) print 'shape x', np.shape(x) print 'shape y', np.shape(y) print 'shape z', np.shape(z) # Asign values to points for i in xrange(len(x1)): for j in xrange(len(y1)): for k in xrange(len(z1)): points[i, j, k, 0] = x1[i] points[i, j, k, 1] = y1[j] points[i, j, k, 2] = z1[k] # Name of the filtered file fname = 'Filtered' + '_nx_' + str(nx) + '_ny_' + str(ny) + '_nz_' + str(nz) # Read the files from current directory if available if os.path.isfile('./u' + fname + '.npy'): #~ u = np.fromfile('./u'+fname, dtype=np.float32).swapaxes(0,2) #~ v = np.fromfile('./v'+fname, dtype=np.float32).swapaxes(0,2) #~ w = np.fromfile('./w'+fname, dtype=np.float32).swapaxes(0,2) # Save data into numpy format # Load the numpy data u = np.load('./u' + fname + '.npy') v = np.load('./v' + fname + '.npy') w = np.load('./w' + fname + '.npy') # If not available extract the data from HIT database (JHU) else: # load shared library lTDB = pyJHTDB.libJHTDB(auth_token='com.gmail.tonyinme-7a6d4581') #initialize webservices lTDB.initialize() print "Error NOT Here 1" for k in xrange(len(z1)): # Get filtered Data uvw = lTDB.getBoxFilter(t, points[:, :, k, :].reshape(-1, 3), field='velocity', filter_width=fw) #~ uvw = lTDB.getData( #~ t, #~ points[:,:,k,:].reshape(-1, 3), #~ sinterp = 4, #~ getFunction='getVelocity') # Asign the components of velocity u[:, :, k] = uvw[:, 0].reshape(nx, ny) v[:, :, k] = uvw[:, 1].reshape(nx, ny) w[:, :, k] = uvw[:, 2].reshape(nx, ny) print 'Filtered Velocity obtained for k=', k # Save data into numpy format np.save('./u' + fname, u) np.save('./v' + fname, v) np.save('./w' + fname, w) # Write the data to a file fortran binary write_binary('./binary_u' + fname, u.swapaxes(0, 2)) write_binary('./binary_v' + fname, v.swapaxes(0, 2)) write_binary('./binary_w' + fname, w.swapaxes(0, 2)) # Save figures plt.pcolormesh(y[0, :, :], z[0, :, :], u[0, :, :], shading='gouraud', cmap=cmaps.inferno) plt.colorbar() # Set the colorscale plt.gca().set_aspect('equal', adjustable='box') # Axis limits plt.xlim([0., 2 * np.pi]) plt.ylim([0., 2 * np.pi]) plt.savefig('u.jpg', dpi=500) plt.clf() plt.pcolormesh(x[:, 3, :], z[:, 3, :], u[:, 3, :], shading='gouraud', cmap=cmaps.inferno) plt.colorbar() # Set the colorscale plt.gca().set_aspect('equal', adjustable='box') # Axis limits plt.xlim([0., 2 * np.pi]) plt.ylim([0., 2 * np.pi]) plt.savefig('v.jpg', dpi=500) plt.clf() plt.pcolormesh(x[:, :, 1], y[:, :, 1], u[:, :, 1], shading='gouraud', cmap=cmaps.inferno) plt.colorbar() # Set the colorscale plt.gca().set_aspect('equal', adjustable='box') # Axis limits plt.xlim([0., 2 * np.pi]) plt.ylim([0., 2 * np.pi]) plt.savefig('w.jpg', dpi=500)
def test_divfree(info=pyJHTDB.dbinfo.channel, m=1, q=4, npoints=256, dbinterp=44): start = numpy.array([0, 0, 0], dtype=numpy.int) width = numpy.array([91, 67, 31], dtype=numpy.int) i = pyJHTDB.interpolator.spline_interpolator(info=info, n=(q - 2) / 2, m=m) i.generate_clib() xg = [info['xnodes'][i.n + 1], info['xnodes'][width[0] - i.n - 1]] if info['yperiodic']: yg = [info['ynodes'][i.n + 1], info['ynodes'][width[1] - i.n - 1]] else: yg = [info['ynodes'][0], info['ynodes'][width[1] - i.n - 1]] zg = [info['znodes'][i.n + 1], info['znodes'][width[2] - i.n - 1]] x = numpy.random.random(size=(npoints, 3)).astype(numpy.float32) x[:, 0] = xg[0] + x[:, 0] * (xg[1] - xg[0]) x[:, 1] = yg[0] + x[:, 1] * (yg[1] - yg[0]) x[:, 2] = zg[0] + x[:, 2] * (zg[1] - zg[0]) lJHTDB = pyJHTDB.libJHTDB() lJHTDB.initialize() # get raw data to interpolate test_field = lJHTDB.getRawData(0, start=start, size=width, data_set=info['name'], getFunction='Velocity') # get Lag4 gradient resd0 = lJHTDB.getData(0, x, sinterp=dbinterp, tinterp=0, data_set=info['name'], getFunction='getVelocityGradient') # get locally interpolated gradient resdx1 = i.cinterpolate(x, test_field, diff=[1, 0, 0]) resdy1 = i.cinterpolate(x, test_field, diff=[0, 1, 0]) resdz1 = i.cinterpolate(x, test_field, diff=[0, 0, 1]) resd1 = resd0.copy() resd1[..., 0] = resdx1[..., 0] resd1[..., 1] = resdy1[..., 0] resd1[..., 2] = resdz1[..., 0] resd1[..., 3] = resdx1[..., 1] resd1[..., 4] = resdy1[..., 1] resd1[..., 5] = resdz1[..., 1] resd1[..., 6] = resdx1[..., 2] resd1[..., 7] = resdy1[..., 2] resd1[..., 8] = resdz1[..., 2] del resdx1, resdy1, resdz1 lJHTDB.finalize() dmagnitude = numpy.average(numpy.sqrt(numpy.sum((resd0)**2, axis=1))) ddist = numpy.average(numpy.sqrt(numpy.sum( (resd0 - resd1)**2, axis=1))) / dmagnitude print('average relative distance between dbinterp and M{0}Q{1} is {2}'. format(m, q, ddist)) div0 = resd0[:, 0] + resd0[:, 4] + resd0[:, 8] div1 = resd1[:, 0] + resd1[:, 4] + resd1[:, 8] print('average divergence for dbinterp is {0}'.format( numpy.average(div0**2) / dmagnitude)) print('average divergence for M{0}Q{1} is {2}'.format( m, q, numpy.average(div1**2) / dmagnitude)) return None
## modified version of lorenz_ui.py taken from ## http://docs.enthought.com/mayavi/mayavi/auto/example_lorenz_ui.html#example-lorenz-ui import numpy as np from traits.api import HasTraits, Range, Instance, on_trait_change, Array, Tuple, Str, Button from traitsui.api import View, Item, HSplit, Group from mayavi import mlab from mayavi.core.ui.api import MayaviScene, MlabSceneModel, SceneEditor import pyJHTDB import pyJHTDB.dbinfo info = pyJHTDB.dbinfo.isotropic1024coarse lTDB = pyJHTDB.libJHTDB() ################################################################################ # `plotter` class. ################################################################################ class plotter(HasTraits): # The parameters for the point. ox = Range( 0, 1023, 0, desc='first corner x', enter_set=True, auto_set=False) oy = Range( 0, 1023, 0, desc='first corner y',
def test_divfree( info = pyJHTDB.dbinfo.channel, m = 1, q = 4, npoints = 256, dbinterp = 44): start = numpy.array([0, 0, 0], dtype = numpy.int) width = numpy.array([91, 67, 31], dtype = numpy.int) i = pyJHTDB.interpolator.spline_interpolator( info = info, n = (q - 2)/2, m = m) i.generate_clib() xg = [info['xnodes'][i.n+1], info['xnodes'][width[0] - i.n - 1]] if info['yperiodic']: yg = [info['ynodes'][i.n+1], info['ynodes'][width[1] - i.n - 1]] else: yg = [info['ynodes'][0], info['ynodes'][width[1] - i.n - 1]] zg = [info['znodes'][i.n+1], info['znodes'][width[2] - i.n - 1]] x = numpy.random.random(size = (npoints, 3)).astype(numpy.float32) x[:, 0] = xg[0] + x[:, 0]*(xg[1] - xg[0]) x[:, 1] = yg[0] + x[:, 1]*(yg[1] - yg[0]) x[:, 2] = zg[0] + x[:, 2]*(zg[1] - zg[0]) lJHTDB = pyJHTDB.libJHTDB() lJHTDB.initialize() # get raw data to interpolate test_field = lJHTDB.getRawData( 0, start = start, size = width, data_set = info['name'], getFunction = 'Velocity') # get Lag4 gradient resd0 = lJHTDB.getData( 0, x, sinterp = dbinterp, tinterp = 0, data_set = info['name'], getFunction = 'getVelocityGradient') # get locally interpolated gradient resdx1 = i.cinterpolate( x, test_field, diff = [1, 0, 0]) resdy1 = i.cinterpolate( x, test_field, diff = [0, 1, 0]) resdz1 = i.cinterpolate( x, test_field, diff = [0, 0, 1]) resd1 = resd0.copy() resd1[..., 0] = resdx1[..., 0] resd1[..., 1] = resdy1[..., 0] resd1[..., 2] = resdz1[..., 0] resd1[..., 3] = resdx1[..., 1] resd1[..., 4] = resdy1[..., 1] resd1[..., 5] = resdz1[..., 1] resd1[..., 6] = resdx1[..., 2] resd1[..., 7] = resdy1[..., 2] resd1[..., 8] = resdz1[..., 2] del resdx1, resdy1, resdz1 lJHTDB.finalize() dmagnitude = numpy.average(numpy.sqrt(numpy.sum((resd0)**2, axis = 1))) ddist = numpy.average(numpy.sqrt(numpy.sum((resd0 - resd1)**2, axis = 1))) / dmagnitude print ('average relative distance between dbinterp and M{0}Q{1} is {2}'.format(m, q, ddist)) div0 = resd0[:, 0] + resd0[:, 4] + resd0[:, 8] div1 = resd1[:, 0] + resd1[:, 4] + resd1[:, 8] print('average divergence for dbinterp is {0}'.format(numpy.average(div0**2) / dmagnitude)) print('average divergence for M{0}Q{1} is {2}'.format(m, q, numpy.average(div1**2) / dmagnitude)) return None
def main(): ''' This code will obtain a time history over a plane of filtered Homogeneous isotropic turbulence data from the JHU data base You need certain input parameters to be able to reach a desired turbulence intensity inflow. First, you need to specify a turbulence intensity TI = this is the desired turbulence intensity as u'/U Then, you need to specify a time series. The code will sweep through the database at a sweeping velocity corresponding to the turbulence intensity You need to specity the initial and final times for sweeping t0 = initial time in the database tf = final time on the database The widht of the domain is specified as: Ly = spanwise direction (database width=2pi) Lz = spanwise direction (database width=2pi) Lx = Streamwise direction (computed according to the time sweeping) Grid points ny, nz = this is the number of grid points Filter width fw = the size of the filter width, by default it is the grid spacing ''' # Desired turbulence intensity TI = 0.1 # Make working directory and switch to it dir = 'DataTI10' if not os.path.exists(dir): os.makedirs(dir) os.chdir(dir) ## From the database ## pi = np.float32(np.pi) # Fluctuations in the database (u'_DB) up = 0.686 # The sweeping velocity (u'_DB / [u'_LES/U_LES]) Usweeping = up / TI # Total time sample #~ t0 = 0. #~ tf = 10.056 t0 = 2. tf = 4. # Domain Length from the HIT database Lx = np.float32((tf - t0) * Usweeping) Ly = Lz = 2. * pi # Size of the plain in grid points ny, nz = 32, 32 nx = int(Lx * ny / Ly) #~ nx, ny, nz = 5, 5, 5 # Time sampling time = np.linspace(t0, tf, nx) # LES Filter width (depends on ny spectral direction) fw = Ly / ny # Open file simulation details (fsd) fsd = open('simulationdetails.txt', 'w') fsd.write('Simulation Details' + '\n') fsd.write('up=' + str(up) + '\n') fsd.write('TI=' + str(TI) + '\n') fsd.write('Usweeping=' + str(Usweeping) + '\n') fsd.write('Lx=' + str(Lx) + '\n') fsd.write('Ly=' + str(Ly) + '\n') fsd.write('Lz=' + str(Lz) + '\n') fsd.write('Nx=' + str(nx) + '\n') fsd.write('Ny=' + str(ny) + '\n') fsd.write('Nz=' + str(nz) + '\n') fsd.write('Time start=' + str(t0) + '\n') fsd.write('Time final=' + str(tf) + '\n') fsd.close() # Define the size of the domain to be used x1 = Usweeping * time y1 = np.linspace(0, Ly, ny) z1 = np.linspace(0, Lz, nz) # Generate mesh x, y, z = np.meshgrid(x1, y1, z1, indexing='ij') # Generate the points points = np.zeros((nx, ny, nz, 3), dtype='float32', order='F') # Generate the velocity fields u = np.zeros((nx, ny, nz), dtype='float32', order='F') v = np.zeros((nx, ny, nz), dtype='float32', order='F') w = np.zeros((nx, ny, nz), dtype='float32', order='F') print 'shape points', np.shape(points) print 'shape x', np.shape(x) print 'shape y', np.shape(y) print 'shape z', np.shape(z) # Asign values to points for i in xrange(len(x1)): for j in xrange(len(y1)): for k in xrange(len(z1)): points[i, j, k, 0] = x1[i] points[i, j, k, 1] = y1[j] points[i, j, k, 2] = z1[k] # Name of the filtered file fname = 'Filtered' + '_nx_' + str(nx) + '_ny_' + str(ny) + '_nz_' + str(nz) # Read the files from current directory if available if os.path.isfile('./u' + fname + '.npy'): print 'Reading Data' # Load the numpy data u = np.load('./u' + fname + '.npy') v = np.load('./v' + fname + '.npy') w = np.load('./w' + fname + '.npy') # If not available extract the data from HIT database (JHU) else: print 'Initializing Database' # load shared library lTDB = pyJHTDB.libJHTDB(auth_token='com.gmail.tonyinme-7a6d4581') #initialize webservices lTDB.initialize() for i in xrange(len(x1)): print 'Calling Database for i=', i # Get filtered Data uvw = lTDB.getBoxFilter(time[i], points[i, :, :, :].reshape(-1, 3), field='velocity', filter_width=fw) #~ uvw = lTDB.getData( #~ t, #~ points[:,:,k,:].reshape(-1, 3), #~ sinterp = 4, #~ getFunction='getVelocity') # Asign the components of velocity u[i, :, :] = uvw[:, 0].reshape(ny, nz) v[i, :, :] = uvw[:, 1].reshape(ny, nz) w[i, :, :] = uvw[:, 2].reshape(ny, nz) print 'Filtered Velocity obtained for i=', i # Save data into numpy format np.save('./u' + fname, u) np.save('./v' + fname, v) np.save('./w' + fname, w) # Write the data to a file fortran binary write_binary('./binary_u' + fname, u.swapaxes(0, 2)) write_binary('./binary_v' + fname, v.swapaxes(0, 2)) write_binary('./binary_w' + fname, w.swapaxes(0, 2)) write_lesgo_data('./lesgo_u' + fname, u.swapaxes(0, 2)) write_lesgo_data('./lesgo_v' + fname, v.swapaxes(0, 2)) write_lesgo_data('./lesgo_w' + fname, w.swapaxes(0, 2)) # Save figures plt.pcolormesh(y[0, :, :], z[0, :, :], u[0, :, :], shading='gouraud', cmap=cmaps.inferno) plt.colorbar() # Set the colorscale plt.gca().set_aspect('equal', adjustable='box') # Axis limits #~ plt.xlim([0., 2*np.pi]) #~ plt.ylim([0., 2*np.pi]) plt.savefig('u.jpg', dpi=500) plt.clf() plt.pcolormesh(x[:, 3, :], z[:, 3, :], u[:, 3, :], shading='gouraud', cmap=cmaps.inferno) plt.colorbar() # Set the colorscale plt.gca().set_aspect('equal', adjustable='box') # Axis limits #~ plt.xlim([0., 2*np.pi]) #~ plt.ylim([0., 2*np.pi]) plt.savefig('v.jpg', dpi=500) plt.clf() plt.pcolormesh(x[:, :, 1], y[:, :, 1], u[:, :, 1], shading='gouraud', cmap=cmaps.inferno) plt.colorbar() # Set the colorscale plt.gca().set_aspect('equal', adjustable='box') # Axis limits #~ plt.xlim([0., 2*np.pi]) #~ plt.ylim([0., 2*np.pi]) plt.savefig('w.jpg', dpi=500)