#         sys.path.append(dd2)

import WIM2d_f2py                 as Mwim
import run_WIM2d                  as Rwim
import fns_get_data              as Fdat
import fns_plot_data             as Fplt
import fns_boltzmann_steady    as Fbs

# linear algebra
from scipy import linalg as LA
#eig    = LA.eig             # 
#solve = np.linalg.solve # x=solve(A,b) -> solves A*x=b

# get grid
gdir       = 'inputs'
grid_prams = Fdat.fn_check_grid(gdir)
nx         = grid_prams['nx']
ny         = grid_prams['ny']
dx         = grid_prams['dx']
dy         = grid_prams['dy']
X          = grid_prams['X']
Y          = grid_prams['Y']
LANDMASK   = grid_prams['LANDMASK']
xmin       = X.min()
xmax       = X.max()

N       = 2**5
h       = 2.   # thickness [m]
period  = 12.  # period [s]
youngs  = 5.e9 # period [s]
visc_rp = 0.   # R-P damping parameter [m^s/s]
Beispiel #2
0
# interface to fortran code
# - compile with single frequency
import run_WIM2d     as Rwim

# other python modules
import WIM2d_f2py    as Mwim
import fns_get_data  as Fdat
import fns_plot_data as Fplt

# steady state results to compare to:
import fns_boltzmann_steady   as Fbs

RUN_OPT  = 2 # rerun then plot
# RUN_OPT  = 3 # plot saved results

gf          = Fdat.fn_check_grid('inputs')
gfl         = gf['LANDMASK']
ICEMASK     = 1.-gfl
WAVEMASK    = 1.-gfl
grid_prams  = gf

###########################################################################
# set inputs: (icec,iceh,dfloe), (Hs,Tp,mwd)
if 1:

   # ice band of finite width
   xe                   = -220.e3
   ICEMASK              = 1+0*gf['X']
   ICEMASK[gf['X']<xe]  = 0.
   ICEMASK[gfl>0]       = 0.
Beispiel #3
0
##
dd = os.path.abspath("..")
dirs = [dd + "/bin", dd + "/run", dd + "/misc_py"]
for n in range(0, len(dirs)):
    dd2 = dirs[n]
    print("adding path : " + dd2)
    sys.path.append(dd2)

import WIM2d_f2py as Mwim
import run_WIM2d as Rwim
import fns_get_data as Fdat
import fns_plot_data as Fplt

# get grid
gdir = "inputs"
grid_prams = Fdat.fn_check_grid(gdir)
nx = grid_prams["nx"]
ny = grid_prams["ny"]
dx = grid_prams["dx"]
dy = grid_prams["dy"]
X = grid_prams["X"]
Y = grid_prams["Y"]
LANDMASK = grid_prams["LANDMASK"]
xmin = X.min()
xmax = X.max()

#########################################################
v = np.arange(0, ny) / float(ny - 1)  # ny points between 0,1

if 1:
    # do a new calculation:
Beispiel #4
0
def plot_simulation(outdir=".", infile_grid=None, PLOT_INIT=0, PLOT_PROG_OPT=0):
    import numpy as np
    import os
    import sys
    import shutil
    import struct

    # import matplotlib.rcsetup as rc

    ##
    ## NB run from 'run' directory !!
    ##
    w2d = os.getenv("WIM2D_PATH")
    dd = w2d + "/fortran"
    sys.path.append(dd + "/bin")
    sys.path.append(dd + "/py_funs")

    import fns_get_data as Fdat
    import fns_plot_data as Fplt

    # Make plots
    bindir = outdir + "/binaries"  # wim_init.[ab],wim_out.[ab],"prog" directory with wim_prog???.[ab]
    figdir = outdir + "/figs"  # where to save files

    if infile_grid is None:
        grid_prams = Fdat.fn_check_grid(bindir)  # load grid from binaries
        # dictionary with X,Y,...
    else:
        import fns_grid_setup as gs

        # TODO read in infile_grid.txt
        x0 = 0.0
        y0 = 0.0
        nx = 150
        ny = 4
        dx = 4.0e3
        dy = 40.0e3
        LAND_OPT = 0  # no land
        grid_arrays, grid_prams = gs.get_grid_arrays(x0=x0, y0=y0, nx=nx, ny=ny, dx=dx, dy=dy, LAND_OPT=LAND_OPT)

    ##########################################################################
    if PLOT_INIT == 1:
        # Look at initial fields:
        print("Plotting initial conditions...")
        ice_fields, wave_fields = Fdat.fn_check_init(bindir)  # load initial conditions from binaries
        #
        figdir1 = figdir + "/init/"
        Fplt.fn_plot_init(grid_prams, ice_fields, wave_fields, figdir1)  # plot initial conditions
        print("Plots in " + figdir + "/init")
        print(" ")
    ##########################################################################

    ################################################################
    # Look at end results:
    out_fields = Fdat.fn_check_out_bin(bindir)

    print("Plotting results...")
    figdir2 = figdir + "/final/"
    Fplt.fn_plot_final(grid_prams, out_fields, figdir2)
    print("Plots in " + figdir2 + "\n")
    print(" ")
    ################################################################

    if PLOT_PROG_OPT == 1:
        ################################################################
        # Plot progress files (if they exist)
        # - as colormaps
        figdir3 = figdir + "/prog"
        prog_files = os.listdir(bindir + "/prog")
        steps = []
        for pf in prog_files:
            if ".a" == pf[-2:]:
                stepno = pf[-5:-2]
                steps.append(stepno)

        # make dir for progress plots
        if (not os.path.exists(figdir3)) and len(steps) > 0:
            os.mkdir(figdir3)

        # clear old progress plots
        old_dirs = os.listdir(figdir3)
        for od in old_dirs:
            # need this for macs
            if od != ".DS_Store":
                # os.rmdir(figdir3+'/'+od)
                shutil.rmtree(figdir3 + "/" + od)

        for stepno in steps:
            print("Plotting results at time step " + stepno + " ...")
            prog_fields = Fdat.fn_check_prog(outdir, int(stepno))
            figdir3_0 = figdir3 + "/" + stepno
            Fplt.fn_plot_final(grid_prams, prog_fields, figdir3_0)
            print("Plots in " + figdir3_0 + "\n")
        ################################################################

        print(" ")
        print("To make a movie of progress images:")
        print("cd " + figdir + "/prog")
        print(dd + "/tools/prog2mp4.sh Hs (or Dmax,taux,tauy)")

    elif PLOT_PROG_OPT == 2:
        ################################################################
        # Plot progress files (if they exist)
        # - as profiles
        steps2plot = range(0, 600, 40)
        # steps2plot  = range(0,140,40)
        cols = ["k", "b", "r", "g", "m", "c"]
        lstil = ["-", "--", "-.", ":"]
        Nc = len(cols)
        loop_c = -1
        loop_s = 0

        for nstep in steps2plot:
            out_fields = Fdat.fn_check_prog(outdir, nstep)  # load ice/wave conditions from binaries
            Hs_n = out_fields["Hs"]
            #
            if loop_c == Nc - 1:
                loop_c = 0
                loop_s = loop_s + 1
            else:
                loop_c = loop_c + 1

            fig = Fplt.plot_1d(xx, Hs_n, labs=labs, f=fig, color=cols[loop_c], linestyle=lstil[loop_s])
        #
        figname = figdir + "/convergence2steady.png"
        print("saving to " + figname + "...")
        plt.savefig(figname, bbox_inches="tight", pad_inches=0.05)
        plt.close()
        fig.clf()
Beispiel #5
0
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
Beispiel #6
0
import os,sys
import shutil
import struct
from matplotlib import pyplot as plt

w2d   = os.getenv('WIM2D_PATH')
sys.path.append("bin")

import run_WIM2d     as Rwim
import fns_get_data  as Fdat
import fns_plot_data as Fplt

TEST_MESH   = 1
DO_PLOTTING = 1

gf          = Fdat.fn_check_grid('grid')
gfl         = gf['LANDMASK']
ICEMASK     = 1.-gfl
WAVEMASK    = 1.-gfl
grid_prams  = gf

###########################################################################
# set inputs: (icec,iceh,dfloe), (Hs,Tp,mwd)
if 1:
   # ice edge
   xe       = .5*(gf['X'].min()+gf['X'].max())\
               -.7*.5*(-gf['X'].min()+gf['X'].max())
   ICEMASK  = 1+0*gf['X']
   #
   ICEMASK[gf['X']<xe]  = 0.
   ICEMASK[gfl>0]       = 0.
Beispiel #7
0
import fns_plot_data as Fplt
import fns_grid_setup as gs

def plot_simulation(outdir='.',infile_grid=None,PLOT_INIT=0,PLOT_PROG_OPT=0):

    ##
    ## NB run from 'run' directory !!
    ##

    # Make plots
    # bindir: where wim_init.[ab],wim_out.[ab],"prog" directory with wim_prog???.[ab] are saved
    bindir = os.path.join(outdir,'binaries')
    figdir = os.path.join(outdir,'figs') # where to save figs

    if infile_grid is None:
        grid_prams  = Fdat.fn_check_grid(bindir) # load grid from binaries
        # dictionary with X,Y,...
    else:
        #TODO read in infile_grid.txt
        x0 = 0.
        y0 = 0.
        nx = 150
        ny = 4
        dx = 4.0e3
        dy = 40.e3
        LAND_OPT = 0# no land
        grid_arrays,grid_prams = gs.get_grid_arrays(\
            x0=x0,y0=y0,nx=nx,ny=ny,dx=dx,dy=dy,LAND_OPT=LAND_OPT)

    if PLOT_INIT==1:
        # Look at initial fields:
Beispiel #8
0
import WIM2d_f2py    as Mwim
import fns_get_data  as Fdat
import fns_plot_data as Fplt

# steady state results to compare to:
import fns_boltzmann_steady as Fbs

# RUN_OPT  = 1 # plot from saved dir (not in default location)
# RUN_OPT  = 2 # rerun then plot
RUN_OPT  = 3 # plot saved results (from default location)

do_legend       = 1 # show times as legends
cmp_steady      = 1 # compare to steady state solution
cmp_steady_num  = 0 # compare to steady state Galerkin solution from matlab

gf          = Fdat.fn_check_grid('inputs')
gfl         = gf['LANDMASK']
ICEMASK     = 1.-gfl
WAVEMASK    = 1.-gfl
grid_prams  = gf

###########################################################################
# set inputs: (icec,iceh,dfloe), (Hs,Tp,mwd)
if 1:

   # ice band of finite width
   xe                   = 50.e3
   ICEMASK              = 1+0*gf['X']
   ICEMASK[gf['X']<xe]  = 0.
   ICEMASK[gfl>0]       = 0.
Beispiel #9
0
import os,sys
import matplotlib.pyplot as plt

w2d = os.getenv('WIM2D_PATH')
sys.path.append(w2d+'/fortran/py_funs')
import fns_get_data as Fdat
import fns_plot_data as Fplt

gdir   = '.'
gf     = Fdat.fn_check_grid(gdir)
fields = {'LANDMASK':gf['LANDMASK']}
Fplt.fn_plot_gen(gf,fields,'out/')

figname = 'land_mask.png'
print('Saved to '+figname)
Beispiel #10
0
   out_fields,outdir = Rwim.do_run(RUN_OPT)
   sys.exit()

##########################################################################
elif testing is 2:

   RUN_OPT  = 2
   # check passing in of 'in_fields'
   # - read in inputs from saved files:
   # (need to run without I/O first)
   if 1:
      in_dir   = 'out_py/binaries'
   else:
      in_dir   = 'out_py_io/binaries'

   gf                      = Fdat.fn_check_grid(in_dir)
   grid_prams              = gf
   ice_fields,wave_fields  = Fdat.fn_check_init(in_dir)

   # merge ice and wave fields:
   ice_fields.update(wave_fields)
   in_fields   = ice_fields

   # other inputs:
   int_prams   = None # default parameters
   real_prams  = None # default parameters

   if 1:
      # check passing in of integer parameters:
      SCATMOD      = 0
      ADV_DIM     = 2
dd = os.path.abspath(wim2d_path + "/fortran")
sys.path.append(dd + "/bin")
sys.path.append(dd + "/py_funs")

import fns_get_data as Fdat
import fns_plot_data as Fplt

# run from root results directory eg out, out_io
outdir = os.getcwd()
bindir = outdir + "/binaries"
figdir = outdir + "/figs"

if not os.path.exists(bindir):
    raise ValueError("No binaries folder in current directory")
else:
    grid_prams = Fdat.fn_check_grid(bindir)

##########################################################################
# Make plots
if not os.path.exists(figdir):
    os.mkdir(figdir)

PROG_OPT = 1
##########################################################################

################################################################
# Plot progress files (if they exist)
pdir = bindir + "/prog"
prog_files = os.listdir(pdir)
figdir3 = figdir + "/prog_profiles"
if not os.path.exists(figdir3):
Beispiel #12
0
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
Beispiel #13
0
def do_run(in_fields=None,params_in={}):

    if in_fields is not None:
        RUN_OPT  = 1
    else:
        RUN_OPT  = 0
        if len(params_in)>0:
            warnings.warn('params_in input being ignored - no input arrays')

    run_dict = {0: 'old version (no in/out)',
                1: 'in/out'}

    print("###################################################")
    print("Run option:")
    print(" "+str(RUN_OPT)+' : '+run_dict[RUN_OPT])
    print("###################################################")

    # check directories for outputs exist
    if (RUN_OPT == 0):
        outdir = 'out_py'
    else:
        outdir = 'out_py_io_1'

    dirs = [outdir,
            outdir+'/diagnostics',
            outdir+'/diagnostics/local',
            outdir+'/diagnostics/global',
            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 dirj in dirs:
        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)

    if RUN_OPT == 0:
        # run the non-IO WIM 
        # (can still specify parameters in infile_nonIO.txt)
        print(" ")
        print("Running WIM without input/output")
        print("###################################################")
        print(" ")

        Fwim.py_wim2d_run()
        os.remove(ifd_name)

        print(" ")
        print("###################################################")
        print("Finished call to wim2d_run:")
        print("###################################################")
        print(" ")

        # load results from binary files
        return Fdat.wim_results(outdir)
        # out_fields  = Fdat.fn_check_out_bin(outdir+'/binaries')

    else:
        # 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)
        if 0:
            print(params_in)
            print(param_dict)
            print(param_vec)
            sys.exit()


        if in_fields is not None:
            # 'in_fields' is given as input
            # - put data into 'in_arrays':
            keys  = ['icec','iceh','dfloe','Hs','Tp','mwd']

            nx,ny     = in_fields[keys[0]].shape
            in_arrays = np.zeros((nx,ny,6))

            n  = 0
            for key in keys:
                in_arrays[:,:,n] = in_fields[key]
                n                = n+1

            del in_fields

        elif 0:
            # 'in_fields' not given as input
            # - read in inputs from saved files:
            in_dir                 = 'out_py/binaries'
            grid_prams             = Fdat.fn_check_grid(in_dir)
            ice_fields,wave_fields = Fdat.fn_check_init(in_dir)

            # merge ice and wave fields:
            ice_fields.update(wave_fields)
            in_fields = ice_fields
            del wave_fields

            # put data into 'in_arrays':
            keys  = ['icec','iceh','dfloe','Hs','Tp','mwd']

            nx,ny     = in_fields[keys[0]].shape
            in_arrays = np.zeros((nx,ny,6))

            n  = 0
            for key in keys:
                in_arrays[:,:,n] = in_fields[key]
                n                = n+1

            del in_fields,ice_fields

        elif 1:
            # 'in_fields' not given as input
            # - specify 'in_arrays' manually

            in_dir     = 'out/binaries'
            grid_prams = Fdat.fn_check_grid(in_dir)

            n        = grid_prams['nx']
            ny       = grid_prams['ny']
            X        = grid_prams['X']
            Y        = grid_prams['Y']
            LANDMASK = grid_prams['LANDMASK']
            xmin     = X.min()
            xmax     = X.max()

            # set ice conc/thickness
            ICE_MASK = np.zeros((nx,ny))
            ICE_MASK[np.logical_and(X>0.7*xmin,LANDMASK<1)] = 1 # i>=24
            icec  = 0.75*ICE_MASK
            iceh  = 2.0*ICE_MASK
            dfloe = 250*ICE_MASK

            # set wave fields
            WAVE_MASK = np.zeros((nx,ny))
            WAVE_MASK[X<xmin*0.8] = 1 # i<=15
            Hs  = 2.0*WAVE_MASK
            Tp  = 12.0*WAVE_MASK
            mwd = -90.0*WAVE_MASK

            in_arrays[:,:,0] = icec
            in_arrays[:,:,1] = iceh
            in_arrays[:,:,2] = dfloe
            in_arrays[:,:,3] = Hs
            in_arrays[:,:,4] = Tp
            in_arrays[:,:,5] = mwd

        # run the WIM
        print(" ")
        print("###################################################")
        print("Running WIM with input/output")
        print("###################################################")
        print(" ")

        out_arrays  = Fwim.py_wim2d_run_io(in_arrays,param_vec)
        os.remove(ifd_name)

        print(" ")
        print("###################################################")
        print("Finished call to wim2d_run_io:")
        print("###################################################")
        print(" ")

        # 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[:,:,4]

        # convert out_arrays to dictionary
        out_fields = Fdat.fn_check_out_arr(out_arrays)
        del out_arrays

    return out_fields,Fdat.wim_results(outdir)