def test_edge_cons(out,semiinf=True,lhs=True):
    # test LHS edge conditions (semi-infinite)
    print('Test edge conditions:')

    th_vec = out['angles']
    print(len(th_vec))

    if semiinf:
        figname = 'fig_scripts/figs/SSboltzmann-EdgeCons-semiinf.png'
        edge    = out['edge_lhs']
    elif lhs:
        figname = 'fig_scripts/figs/SSboltzmann-EdgeCons-lhs.png'
        edge    = out['edge_lhs']
    else:
        figname = 'fig_scripts/figs/SSboltzmann-EdgeCons-rhs.png'
        edge    = out['edge_rhs']

    if 1:
        print('angles (deg)')
        print(th_vec[:10]*180/np.pi)
        print('cosines')
        print(np.cos(th_vec)[:10])
        print('Im(E_edge),x=0')
        print(edge['E_edge'].imag[:10])
        print('Re(E_edge),x=0')
        print(edge['E_edge'].real[:10])
        print('Incident spectrum')
        print(edge['dirspec_inc'][:10])

    if 0:
        plt.plot(th_vec*180/np.pi,edge['E_edge'].real)
        plt.plot(th_vec*180/np.pi,edge['dirspec_inc'],'--r')
        plt.show()
    elif 1:
        pobj  = Fplt.plot_1d(th_vec*180/np.pi,edge['E_edge'].imag,
                    labs=['Angle,  degrees','$E$'],linestyle='-',color='b')
        Fplt.plot_1d(th_vec*180/np.pi,edge['E_edge'].real,
                    labs=None,pobj=pobj,linestyle='-',color='k')
        Fplt.plot_1d(th_vec*180/np.pi,edge['dirspec_inc'].real,
                    labs=None,pobj=pobj,linestyle='--',color='r')

        fig,ax,line = pobj
        fig.savefig(figname,bbox_inches='tight',pad_inches=0.05)
        ax.cla()
        plt.close(fig)
        print(' ')
        print('Saving to file : '+figname)
        print(' ')
    return
Example #2
0
def plot_diagnostics(Tp_vec, Wmiz, taux_max):
    # plot MIZ width and taux max

    figdir = "out_io/figs_diag"

    # MIZ width:
    fig = figdir + "/Wmiz.png"
    f = Fplt.plot_1d(Tp_vec, Wmiz, ["$T_p$, s", "$W_{MIZ}$, km"])
    plt.savefig(fig, bbox_inches="tight", pad_inches=0.05)
    plt.close()
    f.clf()

    # tau_x
    fig = figdir + "/taux.png"
    f = Fplt.plot_1d(Tp_vec, taux_max, ["$T_p$, s", "stress ($x$ dir), Pa"])
    plt.savefig(fig, bbox_inches="tight", pad_inches=0.05)
    plt.close()
    f.clf()
Example #3
0
def plot_diagnostics(Tp_vec,Wmiz,taux_max):
    # plot MIZ width and taux max

    figdir = 'out_io/figs_diag'

    # MIZ width:
    fig = figdir+'/Wmiz.png'
    f   = Fplt.plot_1d(Tp_vec,Wmiz,['$T_p$, s','$W_{MIZ}$, km'])
    plt.savefig(fig,bbox_inches='tight',pad_inches=0.05)
    plt.close()
    f.clf()

    # tau_x
    fig = figdir+'/taux.png'
    f   = Fplt.plot_1d(Tp_vec,taux_max,['$T_p$, s','stress ($x$ dir), Pa'])
    plt.savefig(fig,bbox_inches='tight',pad_inches=0.05)
    plt.close()
    f.clf()
def plot_energy(out,width=None,n_test=0,Hs=1.,f_inc=None):
    # n_test is the Fourier component to plot:
    # (0 is the energy)
    # NB odd n are zero

    fdir  = 'fig_scripts/figs/profiles/'
    fdir2 = 'fig_scripts/figs/profiles/IsoFrac/'
    if not os.path.exists(fdir):
        os.mkdir(fdir)
    if not os.path.exists(fdir2):
        os.mkdir(fdir2)

    if width is None:
        semiinf   = True
        L         = 500.0e3 # plotting limit
        figname   = fdir+'SSboltzmann_E'+str(n_test)+'_profile-semiinf.png'
        figname2  = fdir2+'SSboltzmann_IsoFrac_profile-semiinf.png'
        edge_keys = ['lhs']
    else:
        semiinf   = False
        L         = width
        figname   = fdir+'SSboltzmann_E'+str(n_test)+'_profile-L'+str(width)+'.png'
        figname2  = fdir2+'SSboltzmann_IsoFrac_profile-L'+str(width)+'.png'
        edge_keys = ['lhs','rhs']

    # plot energy vs x:
    npts = 5000
    xx   = np.linspace(0.0,L,npts)
    E_n  = 0.0j*xx
    #
    cn      = out['eig_coeffs']
    M_c2th  = out['edge_lhs']['M_c2th']
    alp     = out['inputs'][0]
    alp_dis = out['inputs'][2]
    th_vec  = out['angles']

    if 'M_E2En' in out.keys():
        # have eigenvectors in position space;
        # transform n=0 into Fourier space
        inp0    = {}
        inp_all = {}
        for key in out.keys():
            if type(out[key])==type([]):
                print(key+' (list)')
                inp0.update({key      : list(out[key])})
                inp_all.update({key  : list(out[key])})
            else:
                print(key+' (np array)')
                inp0.update({key:out[key].copy()})
                inp_all.update({key:out[key].copy()})

        Mt   = out['M_E2En']
        soln = out['solution']
        for key in soln.keys():
            if 'evecs' in key:
                print('Taking FT of: '+key)
                print(Mt.shape,inp_all['solution'][key].shape,inp0['solution'][key].shape)
                EV = soln[key]
                inp0['solution'][key] = np.array([Mt[n_test,:].dot(EV)]) # convert back to rank 2
                print(Mt.shape,inp_all['solution'][key].shape,inp0['solution'][key].shape)
                inp_all['solution'][key] = Mt.dot(EV)
    else:
        inp0    = out.copy()
        inp_all = out
        for key in out['solution'].keys():
            if 'evecs' in key:
                print('Taking '+str(n_test)+'-th row of: '+key)
                inp0['solution'][key] = np.array([inp0['solution'][key][n_test,:]]) # convert back to rank 2

    # calc Fourier coefficients at x:
    if semiinf:
        # semi-infinite
        E_n   = calc_expansion(out,xx,L=None,n_test=[n_test])
        No2   = len(cn) # N/2
        N     = 2*No2
        En_si = E_n

        En_all   = calc_expansion(out,xx,L=None)
        E_coh    = 0*xx # coherent energy: E going to right
        iso_frac = 0*xx # amount of isotropy measure
        dth      = th_vec[1]-th_vec[0]
        for n in range(npts):
            E_th     = out['M_En2E'].dot(En_all[n,:])
            E_f      = E_th[abs(th_vec)<dth].real # two closest intervals around 0
            E_coh[n] = dth*(E_f.sum()) # integrate over these intervals
            #
            e0          = abs(E_n[n])*abs(E_n[n])
            ea          = abs(En_all[n,:])*abs(En_all[n,:])
            iso_frac[n] = e0/np.sum(ea)
    else:
        # finite width
        E_n = calc_expansion(inp0,xx,L=L)
        N   = len(cn)
        No2 = int(N/2.)
        if 0:
            comp_si= 1
            cg     = out['inputs'][3]
            Hs     = out['inputs'][4]
            f_inc  = out['inputs'][5]
            out_si = solve_boltzmann_ft_semiinf(alp=alp,N=N,alp_dis=alp_dis,cg=cg,Hs=Hs,f_inc=f_inc)
            En_si  = calc_expansion(out_si,xx,L=None,n_test=[n_test]) # semi-infinite profile
        #
        En_all   = calc_expansion(inp_all,xx,L)
        E_coh    = 0*xx # coherent energy: E going to right
        iso_frac = 0*xx # amount of isotropy measure
        dth      = th_vec[1]-th_vec[0]
        M_ift    = calc_M_En2E(th_vec)

        for n in range(npts):
            E_th     = M_ift.dot(En_all[n,:])
            E_f      = E_th[abs(th_vec)<dth].real # two closest intervals around 0
            E_coh[n] = dth*(E_f.sum()) # integrate over these intervals
            #
            e0 = abs(E_n[n])*abs(E_n[n])
            ea = abs(En_all[n,:])*abs(En_all[n,:])
            iso_frac[n] = e0/np.sum(ea)

    th_vec = out['angles']
    dth    = 2*np.pi/float(N)
    fwd_mask = np.zeros(N)
    fwd_mask[np.cos(th_vec)>0] = 1.0
    if 1:
        if f_inc is None:
            #dirspec_plane or analytical delta function
            A      = Hs/2./np.sqrt(2.)
            Ec_tst = A*A/2.
        else:
            #dirspec_spreading
            Ec_tst = 1./np.pi*(dth+.5*np.sin(2*dth))*pow(Hs/4.,2)

        print('\n')
        print('Check coherent energy (converted to Hs)')
        print('(analytic integration at x=0)')
        print(4*np.sqrt(E_coh[0]),4*np.sqrt(Ec_tst))
        print('\n')
    #
    if 0:
        for key in edge_keys:
            print('************************************************')
            print('check edge E')
            edge   = out['edge_'+key]
            E_edge = edge['E_edge']
            E0_p   = dth*(fwd_mask*E_edge).sum()
            E0_m   = dth*((1-fwd_mask)*E_edge).sum()

            if n_test==0:
                print('E0 at edge: '+edge['which_edge'])
                print('E0 fwd    = '+str(E0_p))
                print('E0 back   = '+str(E0_m))
                # print('E0 total    = '+str(edge['En_edge'][0]))
                print('E0 total 1 = '+str(E0_p+E0_m))

                if edge['which_edge']=='lhs':
                    print('E0 total 2 = '+str(E_n[0]))
                    print('x          = '+str(xx[0]))
                else:
                    print('E0 total 2 = '+str(E_n[-1]))
                    print('x          = '+str(xx[-1]))

            print('************************************************')
            print('\n')

    if 0:
        fig = plt.figure()
        ax  = fig.add_subplot(1,1,1)
        ax.plot(xx,E_n.real)
        ax.set_yscale('log')
        plt.show()
    elif 0:#n_test==0:
        fig  = plt.figure()
        ax   = fig.add_subplot(1,1,1)
        pobj = [fig,ax]
        if (not semiinf) and (comp_si==1):
            Fplt.plot_1d(xx/1.0e3,4*np.sqrt(En_si.real),pobj=pobj,
                    plot_steps=False,linestyle='-',color='g')
        Fplt.plot_1d(xx/1.0e3,4*np.sqrt(E_n.real),pobj=pobj,
                    plot_steps=False,labs=['$x$, km','$H_s$, m'],linestyle='-',color='k')
        Fplt.plot_1d(xx/1.0e3,4*np.sqrt(E_coh),pobj=pobj,
                    plot_steps=False,linestyle='--',color='r')

        # check vs exponential decay
        Fplt.plot_1d(xx/1.0e3,Hs*np.exp(-alp/2.*xx),pobj=pobj,
                    plot_steps=False,linestyle='--',color='b')

        # check vs equi-partition of energy
        E_eq  = En_si[-1].real/float(N)
        Fplt.plot_1d(xx/1.0e3,4*np.sqrt(E_eq)+0*xx,pobj=pobj,
                    plot_steps=False,linestyle='--',color='g')

        if lam[0]>0.0:
            # dissipation so plot y with log scale (exponential decay)
            ax.set_yscale('log')

        plt.savefig(figname,bbox_inches='tight',pad_inches=0.05)
        ax.cla()
        plt.close(fig)
        print(' ')
        print('Saving to file : '+figname)
        print(' ')

        # plot amount of isotropy:
        fig = plt.figure()
        Fplt.plot_1d(xx/1.0e3,iso_frac,pobj=pobj,
                    plot_steps=False,labs=['$x$, km','Isotropic fraction'],linestyle='-',color='k')
        Fplt.plot_1d(xx/1.0e3,1-np.exp(-alp*xx),pobj=pobj,
                    plot_steps=False,linestyle='--',color='r')
        plt.savefig(figname2,bbox_inches='tight',pad_inches=0.05)
        plt.close()
        fig.clf()
        print(' ')
        print('Saving to file : '+figname2)
        print(' ')
    elif 1:
        # simple plot
        fig = plt.figure()
        ax  = fig.add_subplot(1,1,1)
        if 0:
            # of E
            Fplt.plot_1d(xx/1.0e3,E_n.real,pobj=[fig,ax],
                    plot_steps=False,labs=['$x$, km','$E$, m$^2$'],linestyle='-',color='k')
        else:
            # of Hs
            Fplt.plot_1d(xx/1.0e3,4*np.sqrt(E_n.real),pobj=[fig,ax],
                    plot_steps=False,labs=['$x$, km','$H_s$, m'],linestyle='-',color='k')

        if alp_dis>0.0:
            ax.set_yscale('log')

        fig.savefig(figname,bbox_inches='tight',pad_inches=0.05)
        ax.cla()
        plt.close(fig)
        print(' ')
        print('Saving to file : '+figname)
        print(' ')

    out = {'E_n':E_n,'x':xx,'n':n_test,'E_coh':E_coh}

    # save data to file
    if n_test==0:
        Hs   = 4*np.sqrt(E_n.real)
        Hs_f = 4*np.sqrt(E_coh)

        ddir = 'fig_scripts/figs/profiles/datfiles'
        if not os.path.exists(ddir):
            os.mkdir(ddir)

        if width is None:
            out_file = ddir+'/steady_semiinf.dat'
        else:
            out_file = ddir+'/steady_L'+str(width)+'.dat'

        print('\n')
        print('Saving data points to '+out_file)
        of1    = open(out_file,'w')
        of1.write('x, m         Hs, m         Hs (coherent), m\n')
        for n in range(len(xx)):
            of1.write('%f    %f     %f\n'%(xx[n],Hs[n],Hs_f[n]))

        of1.close()

    return out
Example #5
0
   E_n         = Fbs.calc_energy(out,x_ice,L=ice_width,n_test=[0])
   Hs_steady   = 4*np.sqrt(E_n[:,0].real)

   # print(x_ice)
   # print(Hs_steady)
   # fig      = Fplt.plot_1d(1.e-3*(xe+x_ice),Hs_steady,labs=labs,color='y',linewidth=3)
   #out_fields  = Fdat.fn_check_prog(outdir,nstep) # load ice/wave conditions from binaries
   #Hs_n        = out_fields['Hs'][:,0]
   #
   if loop_c==Nc-1:
      loop_c   = 0
      loop_s   = loop_s+1
   else:
      loop_c   = loop_c+1

   fig      = Fplt.plot_1d(1.e-3*(xe+x_ice),Hs_steady,labs=labs,f=fig,color=cols[loop_c],linestyle=lstil[loop_s])
#
figdir   = 'fig_scripts/figs'
figname  = figdir+'/test_steady.png'
print('saving to '+figname+'...')
plt.savefig(figname,bbox_inches='tight',pad_inches=0.05)
plt.close()
fig.clf()
# 
# if 1:
#    # print to dat-file
#    dfil  = figdir+'/test_steady1.dat'
#    fid   = open(dfil,'w')
#    blk   = 4*' '
#    for loop_x in range(len(xx)):
#       lin   =           ('%f' % (1.e3*xx[loop_x])  )
Example #6
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()
Example #7
0
   lstil    = ['-','--','-.',':']
   Nc       = len(cols)
   loop_c   = -1
   loop_s   = 0

   figdir3     = figdir+'/prog'
   prog_files  = os.listdir(bindir+'/prog')
   steps       = []
   for pf in prog_files:
      if '.a'==pf[-2:]:
         stepno   = pf.strip('wim_prog').strip('.a')
         steps.append(stepno)

   for step in steps:
      out_fields  = Fdat.fn_check_prog(outdir,step) # 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()
Example #8
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
Example #9
0
            alp=alp,N=N,alp_dis=alp_dis,cg=cg,f_inc=Fbs.dirspec_inc_spreading,Hs=Hs_in)
   #
   E_th        = Fbs.calc_expansion(out,x_ice,L=ice_width)
   dtheta      = 2*np.pi/float(N)
   E0          = dtheta*E_th.sum(1)                      # integral over directions (freq spec)
   Hs_steady   = 4*np.sqrt(E0.real)
   #
   S_th        = E_th.dot(out['solution']['Rmat'].transpose())
   S_cos       = S_th.dot(dtheta*np.cos(out['angles']))  # integral with cos over directions
   rhow        = 1025 # kg/m^3
   gravity     = 9.81 # m/s^2
   tx_steady   = -(rhow*gravity/cp)*S_cos.real
   #############################################################

   # plot Hs
   pobj  = Fplt.plot_1d(1.e-3*(xe+x_ice),Hs_steady,pobj=[fig,ax1],plot_steps=False,\
            labs=labs1,color='y',linewidth=3)
   lines_h.append(pobj[-1])
   
   # plot taux
   pobj  = Fplt.plot_1d(1.e-3*(xe+x_ice),tx_steady,pobj=[fig,ax2],plot_steps=False,\
            labs=labs1,color='y',linewidth=3)
   lines_t.append(pobj[-1])
   text_leg.append('Steady')

   if cmp_steady_num:
      # compare to numerical scheme from matlab
      # NB needs to be run for the same parameters
      w2d   = os.getenv('WIM2D_PATH')
      tdir  = w2d+'/matlab/boltzmann/out/'
      tfil  = tdir+'boltzmann_steady_numeric.dat'
      #
Example #10
0
    ax = fig.add_subplot(1, 1, 1)
    lines = []
    legs = []

    for pf in prog_files:
        if ".a" == pf[-2:]:
            stepno = pf.strip("wim_prog").strip(".a")
            afile = pdir + "/" + pf
            print(afile)
            #
            out_fields, info = Fdat.fn_read_general_binary(afile)  # load ice/wave conditions from binaries
            Hs_n = out_fields[vname][:, 0]
            t_prog = info["t_out"] / 3600.0  # time in h
            leg = "%5.1fh" % (t_prog)
            #
            loop_c = np.mod(loop_c + 1, Nc)
            if loop_c == 0:
                loop_s = np.mod(loop_s + 1, Ns)

            fig, ax, line = Fplt.plot_1d(
                xx, Hs_n, labs=labs, pobj=[fig, ax], color=cols[loop_c], linestyle=lstil[loop_s]
            )
            lines.append(line)
            legs.append(leg)
    #
    ax.legend(lines, legs)
    figname = figdir + "/time_dep_" + vname + ".png"
    print("Saving to " + figname + "...")
    fig.savefig(figname, bbox_inches="tight", pad_inches=0.05)
    plt.close(fig)