ny = int(lin.split()[0]) lin = bf.readline() # OPT OPT = int(lin.split()[0]) bf.close() # open .a file to get data: basename = bfil[:-2] afil = odir+'/'+basename+'.a' aid = open(afil,'rb') X = Fdat.get_array(aid,nx,ny) Y = Fdat.get_array(aid,nx,ny) h = Fdat.get_array(aid,nx,ny) # advected quantity aid.close() # plot and save figure fig = Fplt.cmap_3d(X/1.e3,Y/1.e3,h,['$x$, km','$y$, km','h']) ############################################################# # plot test curves on top # - get some parameters from X,Y dx = X[1,0]-X[0,0] dy = Y[0,1]-Y[0,0] x0 = X.min() y0 = Y.min() xm = .5*(X.max()-x0) ym = .5*(Y.max()-y0) xx = X[:,0] yy = Y[0,:] n = int(basename[-3:]) #############################################################
def grid_setup(GRID_OPT=1,LAND_OPT=0): outdir = '.' # wim_grid.[a,b] saved here outdir2 = '.' # wave_info.h,grid_info.h saved here dd = os.path.abspath(".") dd2 = dd+'/'+outdir print('\n') print("Saving grid files to:") print(dd2) print('\n') if not (os.path.exists(dd2)): os.makedirs(dd2) ########################################################### ########################################################### # set grid configurations if type(GRID_OPT)==type('string'): # read in parameters from infile infile = GRID_OPT print('using infile '+infile+' for parameters\n') fid = open(infile) lines = fid.readlines() fid.close() # check version number Vno = 1 vno = int(lines[0].split()[0]) if vno!=Vno: s1 = '\nWrong version of '+infile s2 = '\nCurrent version number is '+str(vno) s3 = '\nVersion number should be '+str(Vno)+'\n' raise ValueError(s1+s2+s3) # get values as floats 1st, then convert some to integers params = [] for lin in lines[1:]: lin2 = lin.split() params.append(float(lin2[0])) nx,ny,dx,dy,x0,y0,LAND_OPT = params # convert some parameters to integers nx = int(nx) ny = int(ny) LAND_OPT = int(LAND_OPT) # grid_arrays,grid_fields = get_grid_arrays(x0=x0,y0=y0,nx=nx,ny=ny,\ dx=dx,dy=dy,LAND_OPT=LAND_OPT) elif GRID_OPT is 0: # standard 1d setup: nx = 150 ny = 4 dx = 4.0e3 dy = 10*dx # to make plots clearer x0 = 0. y0 = 0. # grid_arrays,grid_fields = get_grid_arrays(x0=x0,y0=y0,nx=nx,ny=ny,\ dx=dx,dy=dy,LAND_OPT=LAND_OPT) elif GRID_OPT is 1: # standard 2d setup: nx = 150 ny = 50 dx = 4.0e3 dy = 4.0e3 x0 = 0. y0 = 0. # grid_arrays,grid_fields = get_grid_arrays(x0=x0,y0=y0,nx=nx,ny=ny,\ dx=dx,dy=dy,LAND_OPT=LAND_OPT) elif GRID_OPT is 2: # to use with Philipp's "small-square" grid diag_length = 96e3 # m resolution = 0.75e3 # m # this gives a rotated (x',y') grid to align with the sides of the square grid_arrays,grid_fields = _get_grid_arrays_SmallSquare(diag_length,resolution) # nx = grid_fields['nx'] ny = grid_fields['ny'] dx = grid_fields['dx'] dy = grid_fields['dy'] print('nx = '+str(nx)) print('ny = '+str(ny)) print('dx = '+str(dx/1.e3)+'km') print('dy = '+str(dy/1.e3)+'km') ########################################################### ########################################################### print(' ') print(60*'*') gs.save_grid_info_hdr_f2py(outdir2,nx,ny,dx,dy) gs.save_grid_f2py(outdir,grid_arrays) print(60*'*') print(' ') ########################################################### ########################################################### if 0: # check difference between binaries # saved by pure fortran and f2py: outdir1 = 'test/out' # fortran binaries here # run grid_setup.sh with # testing=1 in p_save_grid.F (recompile) gf1 = Fdat.fn_check_grid(outdir1) gf2 = Fdat.fn_check_grid(outdir) keys = ['X','Y','scuy','scvx','scp2','scp2i','LANDMASK'] print('Comparing fortran to python:\n') for key in keys: diff = np.abs(gf1[key]-gf2[key]) diff_max = diff.max() diff_min = diff.min() print('max difference in : '+key+' = '+str(diff_max)) print('min difference in : '+key+' = '+str(diff_min)+'\n') elif 1: # check difference between binaries # saved by f2py and the input fields: gf = grid_fields gf2 = Fdat.fn_check_grid(outdir) keys = ['X','Y','scuy','scvx','scp2','scp2i','LANDMASK'] print('Comparing python in to python out:\n') for key in keys: diff = np.abs(gf[key]-gf2[key]) diff_max = diff.max() diff_min = diff.min() print('max difference in : '+key+' = '+str(diff_max)) print('min difference in : '+key+' = '+str(diff_min)+'\n') ########################################################### ########################################################### SV_FIG = 1 if SV_FIG: from matplotlib import pyplot as plt # save test figure: if not os.path.exists('out_py'): os.mkdir('out_py') fig = 'out_py/land.png' # gf = grid_fields nx = gf['nx'] ny = gf['ny'] dx = gf['dx'] dy = gf['dy'] x = gf['X'][:,0]+dx/2. x = np.concatenate([[x[0]-dx],x])/1.e3 y = gf['Y'][0,:]+dy/2. y = np.concatenate([[y[0]-dy],y])/1.e3 if gf['ny']>1: # 2d grid => make colormap of LANDMASK z = gf['LANDMASK'].transpose() f,ax = Fplt.cmap_3d(x,y,z,['$x$, km','$y$, km','LANDMASK']) else: # 1d grid => make 1d plot of LANDMASK f,ax,line = Fplt.plot_1d(gf['X'][:,0]/1.0e3,gf['LANDMASK'][:,0],\ labs=['$x$, km','LANDMASK']) print('Saving test figure : '+fig) f.savefig(fig,bbox_inches='tight',pad_inches=0.05) plt.close(f) ########################################################### ########################################################### # print(' ') # print(60*'*') # print("Now compile WIM code in .Build") # print("Run in ..") # print(60*'*') # print(' ') ########################################################### return grid_fields,grid_arrays
def do_run_vSdir(sdf_dir=None, wave_fields=None,ice_fields=None, params_in={},mesh_e=None): dd = os.path.abspath("..") sys.path.append(dd+"/bin") sys.path.append(dd+"/py_funs") RUN_OPT = 0 run_dict = { 0: 'run "vSdir", passing directional spectrum in/out'} print("###################################################") print("Run option:") print(" "+str(RUN_OPT)+' : '+run_dict[RUN_OPT]) print("###################################################") TEST_IN_SPEC = 0 # check Hs,Tp,mwd calc'd from input spec TEST_OUT_SPEC = 0 # check Hs,Tp calc'd from output spec # check directories for outputs exist if mesh_e is None: outdir = 'out_py_io_2' else: outdir = 'out_py_io_3' dirs = [outdir, outdir+'/diagnostics', outdir+'/diagnostics/global', outdir+'/diagnostics/local', outdir+'/binaries', outdir+'/binaries/prog'] # tell fortran where to save the outputs ifd_name = 'infile_dirs.txt' fid = open(ifd_name,'w') fid.write('grid\n') fid.write(outdir+'\n') fid.close() for j in range(0,len(dirs)): dirj = dirs[j] if not os.path.exists(dirj): os.makedirs(dirj) # clear out old progress files dd = os.path.abspath(outdir+"/binaries/prog") files = os.listdir(dd) for f in files: os.remove(dd+"/"+f) # run wim2d with inputs and outputs param_dict = default_params() for key in params_in: if key not in param_dict: raise ValueError('Parameter '+key+'invalid') else: param_dict[key] = params_in[key] param_vec = param_dict2vec(param_dict) # dimensions of grid nx,ny,nfreq,ndir = Fwim.wim2d_dimensions() freq_vec = Fwim.wim2d_freq_vec(nfreq) if ice_fields is not None: # 'ice_fields' is given as input # - put data into 'ice_arrays': keys = ['icec','iceh','dfloe'] ice_arrays = np.zeros((nx,ny,len(keys))) n = 0 for key in keys: ice_arrays[:,:,n] = ice_fields[key] n = n+1 del ice_fields else: raise ValueError("No 'ice_fields' input") if sdf_dir is None: if wave_fields is not None: # 'wave_fields' is given as input # instead of sdf_dir Hs = wave_fields['Hs'] Tp = wave_fields['Tp'] mwd = wave_fields['mwd'] # Tmean = np.mean(Tp [Hs>0]) dir_mean = np.mean(mwd[Hs>0]) if nfreq==1: # check only 1 freq stdev = np.std( Tp[Hs>0]) if stdev/Tmean>1.e-3: print('Expected one frequency, but') print('std dev (Tp) = '+str(stdev)+'s') print('mean (Tp) = '+str(Tmean) +'s') raise ValueError('Tp array not consistent with 1 frequency') if ndir==1: # check only 1 dir stdev = np.std (mwd[Hs>0]) if stdev/dir_mean>1.e-3: print('Expected one direction, but') print('std dev (mwd) = '+str(stdev)+'degrees') print('mean (mwd) = '+str(dir_mean) +'degrees') raise ValueError('mwd array not consistent with 1 direction') sdf_dir = np.zeros((nx,ny,ndir,nfreq)) PI = np.pi for i in range(nx): for j in range(ny): if Hs[i,j]>0: if nfreq==1: # use single freq formula: S=A^2/2 sdf_dir[i,j,:,:] = pow(Hs[i,j]/4.0,2) else: # use Bretschneider for w in range(nfreq): om = 2*PI*freq_vec[w] sdf_dir[i,j,:,w] = Fmisc.SDF_Bretschneider(om) if ndir>1: theta_max = 90.0 theta_min = -270.0 dtheta = (theta_min-theta_max)/float(ndir) #<0 wavdir = theta_max+np.arange(ndir)*dtheta # modify spectrum depending on direction D2R = np.pi/180. # test_sum = 0. # test_sum_ = 0. for wth in range(ndir): theta_fac_ = Fmisc.theta_dirfrac(wavdir[wth]-.5*abs(dtheta),abs(dtheta),mwd[i,j])/abs(D2R*dtheta) # chi = PI/180.0*(wavdir[wth]-mwd[i,j]) # if (np.cos(chi)>0.0): # theta_fac = 2.0/PI*pow(np.cos(chi),2) # else: # theta_fac = 0.0 sdf_dir[i,j,wth,:] = sdf_dir[i,j,wth,:]*theta_fac_ # test_sum += theta_fac_ # test_sum_ += theta_fac_ # print(wavdir[wth],wavdir[wth]-.5*abs(dtheta),dtheta,mwd[i,j],theta_fac,theta_fac_) # print(test_sum*abs(dtheta),test_sum_*abs(dtheta)) # sys.exit() if 0: # test spectrum is defined OK sq = np.squeeze(sdf_dir[i,j,:,0]) m0 = np.sum(sq)*abs((PI/180.)*dtheta) print(i,j) print(4*np.sqrt(m0),Hs[i,j]) # plt.plot(wavdir/180.,sq) plt.show() # sys.exit() if TEST_IN_SPEC: # test integrals of spectrum are the same as intended: print('Testing input spectrum...') wave_fields2 = {'Hs':0,'Tp':0,'mwd':0} if nfreq==1: freq_vec_ = np.array([1./Tp_single_freq]) else: freq_vec_ = freq_vec if ndir==1: wavdir_ = np.array([mwd_single_dir]) else: wavdir_ = wavdir (wave_fields2['Hs'], wave_fields2['Tp'], wave_fields2['mwd'] ) = Fmisc.spectrum_integrals( sdf_dir,freq_vec_,wavdir_) arrays = [wave_fields2,wave_fields] keys = arrays[0].keys() for key in keys: print('Comparing field: '+key) diff = abs(arrays[0][key]-arrays[1][key]) print('Maximum difference = '+str(np.max(diff))+'\n') sys.exit() del wave_fields # finished setting sdf_dir from wave_fields else: raise ValueError("No wave inputs (need 'sdf_dir' or 'wave_fields')") # now run the WIM print(" ") print("###################################################") print("Running WIM with sdf_dir inputted") print("###################################################") print(" ") sdf_dir = sdf_dir.reshape(sdf_dir.size,order='fortran') sdf_dir = np.array(sdf_dir,dtype='float32') print(param_vec) if mesh_e is None: sdf_dir2,out_arrays = Fwim.py_wim2d_run_vsdir( sdf_dir,ice_arrays,param_vec,ndir,nfreq) os.remove(ifd_name) print(" ") print("###################################################") print("Finished call to wim2d_vSdir:") print("###################################################") print(" ") else: # mesh_e=dictionary with keys ['x','y','conc','thick','Nfloes','broken'] # > convert this to array nmesh_vars = len(mesh_e) mesh_arr = mesh_dict2arr(mesh_e,inverse=False) nmesh_e = len(mesh_arr[:,0]) # print(mesh_arr.transpose()) # sys.exit() # reshape array to a vector mesh_arr = mesh_arr.reshape( (nmesh_e*nmesh_vars,),order='fortran') # run WIM, with interpolation of Nfloes onto the mesh out = Fwim.py_wim2d_run_vsdir_mesh( sdf_dir,ice_arrays,mesh_arr, param_vec,ndir,nfreq,nmesh_e) sdf_dir2,out_arrays,mesh_arr = out os.remove(ifd_name) print(" ") print("###################################################") print("Finished call to wim2d_vSdir_mesh:") print("###################################################") print(" ") mesh_arr = mesh_arr.reshape((nmesh_e,nmesh_vars),order='fortran') mesh_e = mesh_dict2arr(mesh_arr,inverse=True) # print(mesh_arr.transpose()) sdf_dir2 = sdf_dir2.reshape((nx,ny,ndir,nfreq),order='fortran') # Dmax = out_arrays[:,:,0] # Hs = out_arrays[:,:,1] # Tp = out_arrays[:,:,2] # tau_x = out_arrays[:,:,3] # tau_y = out_arrays[:,:,4] # mwd = out_arrays[:,:,5] # convert out_arrays to dictionary out_fields = Fdat.fn_check_out_arr(out_arrays) del out_arrays if TEST_OUT_SPEC: # test integrals of spectrum are the same as intended: print('Testing integrals of output spectrum...') wave_fields2 = {'Hs':0,'Tp':0,'mwd':0} if nfreq==1: Tp_single_freq = param_dict['T_init'] freq_vec_ = np.array([1./Tp_single_freq]) else: freq_vec_ = freq_vec if ndir==1: mwd_single_dir = param_dict['mwd_init'] wavdir_ = np.array([mwd_single_dir]) else: wavdir_ = wavdir (wave_fields2['Hs'], wave_fields2['Tp'], wave_fields2['mwd'] ) = Fmisc.spectrum_integrals( sdf_dir2,freq_vec_,wavdir_) arrays = [wave_fields2,out_fields] keys = ['Hs','Tp'] # keys = arrays[0].keys() for key in keys: print('Comparing field: '+key) diff = abs(arrays[0][key]-arrays[1][key]) print('Maximum difference = '+str(np.max(diff))+'\n') if 1: # plot Tp for visual comparison # - small differences? gf = Fdat.fn_check_grid('inputs') labs = ['$x$, km','$y$, km', '$T_p$, s'] # f = Fplt.cmap_3d( gf['X']/1.e3, gf['Y']/1.e3, wave_fields2['Tp'], labs) f.show() # f = Fplt.cmap_3d( gf['X']/1.e3, gf['Y']/1.e3, out_fields['Tp'], labs) f.show() if 0: # plot Hs for visual comparison gf = Fdat.fn_check_grid('inputs') labs = ['$x$, km','$y$, km', '$H_s$, m'] # f = Fplt.cmap_3d( gf['X']/1.e3, gf['Y']/1.e3, wave_fields2['Hs'], labs) f.show() # f = Fplt.cmap_3d( gf['X']/1.e3, gf['Y']/1.e3, out_fields['Hs'], labs) f.show() sys.exit() elif 0: # test out_fields are the same as in the binary files print('Testing output fields against binary files...') arrays = 2*[1] arrays[0] = out_fields arrays[1] = Fdat.fn_check_out_bin('out_2/binaries') keys = arrays[0].keys() for key in keys: print('Comparing field: '+key) diff = abs(arrays[0][key]-arrays[1][key]) print('Maximum difference = '+str(np.max(diff))+'\n') sys.exit() return out_fields,Fdat.wim_results(outdir),mesh_e