Example #1
0
arrays    = 2*[0]
for j in range(2):
    outdir    = odir[j]
    bindir    = outdir+'/binaries'

    if OPT==1:

        # Look at initial fields:
        ice_fields,wave_fields  = Fdat.fn_check_init(bindir) # load initial conditions from binaries
        arrays[j]                    = ice_fields
        arrays[j].update(wave_fields)

    elif OPT==2:

        # Look at end results:
        out_fields  = Fdat.fn_check_out_bin(bindir)
        arrays[j]    = out_fields

    elif OPT==3:

        # Plot progress files (if they exist)
        # - as colormaps
        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)

        print('Available time steps:')
        print(steps)
Example #2
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 #3
0
         diff_max = diff.max()
         diff_min = diff.min()
         #
         ss = ' max/min |difference|: %f %f' % (diff_max,diff_min)
         print(' '+key+Key[len(key):]+ss)

      for key in wf1.keys():
         diff     = np.abs(wf1[key]-wf2[key])
         diff_max = diff.max()
         diff_min = diff.min()
         #
         ss = ' max/min |difference|: %f %f' % (diff_max,diff_min)
         print(' '+key+Key[len(key):]+ss)

   elif 1:
      # check out fields are the same
      print('Checking final fields are the same...')
      ##
      of1   = Fdat.fn_check_out_bin(bindir1)
      of2   = Fdat.fn_check_out_bin(bindir2)

      Key   = '         '
      for key in of1.keys():
         diff     = np.abs(of1[key]-of2[key])
         diff_max = diff.max()
         diff_min = diff.min()
         #
         ss = ' max/min |difference|: %f %f' % (diff_max,diff_min)
         print(' '+key+Key[len(key):]+ss)
##########################################################################
Example #4
0
    print("Getting inputs/outputs from binaries...")
    print(" ")

    ## look at initial fields:
    print("Plotting initial conditions...")
    grid_prams = Fdat.fn_check_grid(outdir)  # load grid from binaries
    ice_fields, wave_fields = Fdat.fn_check_init(outdir)  # load initial conditions from binaries
    ##
    figdir = outdir + "/figs/"
    Fplt.fn_plot_init(grid_prams, ice_fields, wave_fields, figdir)  # plot initial conditions
    print("Plots in " + figdir + "/init")
    print(" ")

    ## look at results:
    print("Plotting results...")
    out_fields = Fdat.fn_check_out_bin(outdir)
    # Fplt.fn_plot_final(grid_prams,out_fields,figdir)
    Fplt.fn_plot_final_V1d(grid_prams, Tp_vec, out_fields, figdir)
    print("Plots in " + figdir + "/final")
elif 0:
    # plot results from outputs:

    ## look at initial fields:
    print("Plotting initial conditions...")
    figdir = outdir + "/figs/"
    Fplt.fn_plot_init(grid_prams, ice_fields, wave_fields, figdir)  # plot initial conditions
    print("Plots in " + figdir + "/init")
    print(" ")

    ## look at results:
    print("Plotting results...")
Example #5
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