Ejemplo n.º 1
0
def station_bound(varname, srcfile, srcgrd, dst_grd, \
              rotate_uv=False, trange=None, srange=None, \
              dstdir='./' ,zlevel=None, dmax=0, cdepth=0, kk=0, \
              uvar='u', vvar='v', rotate_part=False):
    '''
    A function to extract boundary conditions from a ROMS station file.
    It will optionally rotating u and v variables (maybe later), but
    would need to be called separately for each u/v pair (such as u/v,
    uice/vice).
    '''

    # get input and output grid
    if type(srcgrd).__name__ == 'Stations_Grid':
        srcgrd = srcgrd
    else:
        srcgrd = pyroms.sta_grid.get_Stations_grid(srcgrd, sta_file=srcfile)
    if type(dst_grd).__name__ == 'ROMS_Grid':
        dst_grd = dst_grd
    else:
        dst_grd = pyroms.grid.get_ROMS_grid(dst_grd)

#    pyroms.sta_grid.write_Stations_grid(srcgrd, filename='sta_test.nc')

    # build intermediaire zgrid
    if zlevel is None:
# for deep water
#        zlevel = np.array([-7500.,-7000.,-6500.,-6000.,-5500.,-5000.,\
#                   -4500.,-4000.,-3500.,-3000.,-2500.,-2000.,-1750.,\
#                   -1500.,-1250.,-1000.,-900.,-800.,-700.,-600.,-500.,\
#                   -400.,-300.,-250.,-200.,-175.,-150.,-125.,-100.,-90.,\
#                   -80.,-70.,-60.,-50.,-45.,-40.,-35.,-30.,-25.,-20.,-17.5,\
#                   -15.,-12.5,-10.,-7.5,-5.,-2.5,0.])
# for Glacier bay
        zlevel = np.array([-100.,-95.,-90.,-85.,-80.,-75.,-70.,-65., \
                   -60.,-55.,-50.,-45.,-40.,-35.,-32.5,-30.,-27.5,-25.,-22.5,\
                   -20.,-19.,-18.,-17.,-16.,-15.,-14.,-13.,\
                   -12.,-11.,-10.,-9.,-8.,-7.,-6.,-5.,-4.,-3.,-2.,-1.,0.])
    else:
        zlevel = np.sort(-abs(zlevel))
    nzlevel = len(zlevel)
    dzlevel = np.zeros(nzlevel)
    for k in range(1,nzlevel-1):
        dzlevel[k] = 0.5*(zlevel[k+1]-zlevel[k-1])
    dzlevel[0] = 0.5*(zlevel[1]-zlevel[0])
    dzlevel[-1] = 0.5*(zlevel[-1]-zlevel[-2])

    src_zcoord = pyroms.vgrid.z_coordinate(srcgrd.vgrid.h, zlevel, nzlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
#    print "name = ", srcgrd.name
#    srcgrdz = pyroms.sta_grid.Stations_Grid(srcgrd.name+'_Z', srcgrd.hgrid, src_zcoord)
    srcgrdz = pyroms.sta_grid.Stations_Grid('stations_Z', srcgrd.hgrid, src_zcoord)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)

    # varname argument
    if type(varname).__name__ == 'list':
        nvar = len(varname)
    elif type(varname).__name__ == 'str':
        varname = [varname]
        nvar = len(varname)
    else:
        raise ValueError, 'varname must be a str or a list of str'

    # if we're working on u and v, we'll compute ubar,vbar afterwards
    compute_ubar = False
    if (varname.__contains__('u') == 1 and varname.__contains__('v') == 1) or \
       (varname.__contains__('u_eastward') == 1 and varname.__contains__('v_northward') == 1):
        compute_ubar = True
        print 'ubar/vbar to be computed from u/v'
        if varname.__contains__('ubar'):
            varname.remove('ubar')
            nvar = nvar-1
        if varname.__contains__('vbar'):
            varname.remove('vbar')
            nvar = nvar-1

    # if rotate_uv=True, check that u and v are in varname
    if rotate_uv is True:
        if varname.__contains__(uvar) == 0 or varname.__contains__(vvar) == 0:
            raise Warning, 'varname must include uvar and vvar in order to' \
                   + ' rotate the velocity field'
        else:
            varname.remove(uvar)
            varname.remove(vvar)
            nvar = nvar-2

    # srcfile argument
    if type(srcfile).__name__ == 'list':
        nfile = len(srcfile)
    elif type(srcfile).__name__ == 'str':
        srcfile = sorted(glob.glob(srcfile))
        nfile = len(srcfile)
    else:
        raise ValueError, 'src_srcfile must be a str or a list of str'

    sides = ['_west','_east','_north','_south']
    long = {'_west':'Western', '_east':'Eastern', \
            '_north':'Northern', '_south':'Southern'}
    dimincl = {'_west':'eta_rho', '_east':'eta_rho', \
            '_north':'xi_rho', '_south':'xi_rho'}

    nctidx = 0
    # loop over the srcfile
    for nf in range(nfile):
        print 'Working with file', srcfile[nf], '...'

        # get time
        ocean_time = pyroms.utility.get_nc_var('ocean_time', srcfile[nf])
        ntime = len(ocean_time[:])

        # trange argument
        if trange is None:
            trange = range(ntime)

        # create destination file
        if nctidx == 0:
            dstfile = dstdir + os.path.basename(srcfile[nf])[:-3] + '_' \
                   + dst_grd.name + '_bdry.nc'
            if os.path.exists(dstfile) is False:
                print 'Creating destination file', dstfile
                pyroms_toolbox.nc_create_roms_file(dstfile, dst_grd, \
                    ocean_time, lgrid=False)

            # open destination file
            nc = netCDF.Dataset(dstfile, 'a', format='NETCDF3_64BIT')

        # loop over time
        for nt in trange:

            nc.variables['ocean_time'][nctidx] = ocean_time[nt]

            # loop over variable
            for nv in range(nvar):
                print ' '
                print 'extracting', varname[nv], 'from', srcgrd.name, \
                      'to', dst_grd.name
                print 'time =', ocean_time[nt]
                Mp, Lp = dst_grd.hgrid.mask_rho.shape
                if varname[nv] == uvar:
                    Lp = Lp-1
                if varname[nv] == vvar:
                    Mp = Mp-1

                # get source data
                src_var = pyroms.utility.get_nc_var(varname[nv], srcfile[nf])

                # determine variable dimension
                ndim = len(src_var.dimensions)-1

                # get spval
                try:
                    spval = src_var._FillValue
                except:
                    print Warning, 'Did not find a _FillValue attribute.'

                # srange
                if srange is None:
                    ssrange = (0,src_var.shape[1])
                else:
                    ssrange = srange

                # determine where on the C-grid these variable lies
                Cpos='rho'

                print 'Arakawa C-grid position is', Cpos

                # create variable in _destination file
                if nctidx == 0:
                    for sid in sides:
                       varn = varname[nv]+str(sid)
                       dimens = [i for i in src_var.dimensions]
                       print 'dimens', dimens, len(dimens)
                       if len(dimens) == 3:
                           dimens = ['ocean_time', 's_rho', \
                           dimincl[sid]]
                       elif len(dimens) == 2:
                           dimens = ['ocean_time', dimincl[sid]]
                       if varname[nv] == uvar:
                           foo = dimens[-1].replace('rho', 'u')
                           dimens[-1] = foo
                       if varname[nv] == vvar:
                           foo = dimens[-1].replace('rho', 'v')
                           dimens[-1] = foo
                       print 'Creating variable', varn, dimens
                       nc.createVariable(varn, 'f8', dimens, \
                           fill_value=spval)
                       nc.variables[varn].long_name = varname[nv] + \
                            ' ' + long[sid] + ' boundary condition'
                       try:
                           nc.variables[varn].units = src_var.units
                       except:
                           print varn+' has no units'
                       nc.variables[varn].time = src_var.time
                       nc.variables[varn].coordinates = \
                           str(dimens.reverse())
                       nc.variables[varn].field = src_var.field

                if ndim == 2:
                    # vertical interpolation from sigma to standard z level
                    print 'vertical interpolation from sigma to standard z level'
                    src_varz = pyroms.remapping.sta2z( \
                                 src_var[nt,:,ssrange[0]:ssrange[1]], \
                                 srcgrd, srcgrdz, Cpos=Cpos, spval=spval, \
                                 srange=ssrange)
                    # vertical flooding
                    # HACK!! Glacier bay grid is much deeper at its edge than
                    # the source grid is.
#                    pdb.set_trace()
#                    if varname[nv] == uvar or varname[nv] == vvar:
#                        print 'before', src_varz[:,0,0]
                    for s in range(ssrange[0],ssrange[1]):
                        kbot = -1
                        for k in range(nzlevel):
                            if src_varz[k,s]>=spval*1.e-3:
                                kbot = k
                        if kbot < nzlevel-1:
                            if varname[nv] == uvar:
#                                zsum = np.sum(src_varz[kbot+1:-1,s]*dzlevel[kbot+1:])
#                                src_varz[0:kbot+1,s] = src_varz[kbot+1,s]
#				print 'before', src_varz[:,s,0]
                                src_varz[0:kbot+1,s,0] = 0.0
#				print 'after', src_varz[:,s,0]
                            elif varname[nv] == vvar:
#                                zsum = np.sum(src_varz[kbot+1:-1,s]*dzlevel[kbot+1:])
#                                src_varz[0:kbot+1,s] = src_varz[kbot+1,s]
                                src_varz[0:kbot+1,s,0] = 0.0
                            else:
                                src_varz[0:kbot+1,s,0] = src_varz[kbot+1,s,0]

#                    if varname[nv] == uvar or varname[nv] == vvar:
#                        print 'after', src_varz[:,0,0]
                    # horizontal placement of stations into target grid.
                    # HACK - this is grid dependent!!!
#                    pdb.set_trace()
                    dst_varz = np.zeros((nzlevel, Mp, Lp))
                    dst_varz[:, 44:79, 0] = src_varz[:, 0:35, 0]
                    dst_varz[:, 0, 56:87] = src_varz[:, 35:, 0]
                    if varname[nv] == uvar:
                        dst_varz[:, 0, 56] = dst_varz[:, 0, 58]
                        dst_varz[:, 0, 57] = dst_varz[:, 0, 58]
                        dst_varz[:, 0, 85] = dst_varz[:, 0, 84]
                        dst_varz[:, 0, 86] = dst_varz[:, 0, 84]
                        Cpos = 'u'
                    if varname[nv] == vvar:
                        dst_varz[:, 76, 0] = dst_varz[:, 75, 0]
                        dst_varz[:, 77, 0] = dst_varz[:, 75, 0]
                        dst_varz[:, 78, 0] = dst_varz[:, 75, 0]
                        Cpos = 'v'

                else:
                    src_varz = src_var[nt,ssrange[0]:ssrange[1]]
                    # horizontal placement of stations into target grid.
                    dst_varz = np.zeros((Mp, Lp))
                    dst_varz[44:79, 0] = src_varz[0:35]
                    dst_varz[0, 56:87] = src_varz[35:]

                print datetime.datetime.now()
                # horizontal placement of stations into target grid.

                if ndim == 2:
                    dst_var_north = pyroms.remapping.z2roms(dst_varz[:, \
                          Mp-1:Mp,0:Lp], dst_grdz, dst_grd, Cpos=Cpos, \
                          spval=spval, flood=False, irange=(0,Lp), \
                          jrange=(Mp-1,Mp))
                    dst_var_south = pyroms.remapping.z2roms(dst_varz[:, \
                          0:1, :], dst_grdz, dst_grd, Cpos=Cpos, \
                          spval=spval, flood=False, irange=(0,Lp), \
                          jrange=(0,1))
                    dst_var_east = pyroms.remapping.z2roms(dst_varz[:, \
                          :, Lp-1:Lp], dst_grdz, dst_grd, Cpos=Cpos, \
                          spval=spval, flood=False, irange=(Lp-1,Lp), \
                          jrange=(0,Mp))
                    dst_var_west = pyroms.remapping.z2roms(dst_varz[:, \
                          :, 0:1], dst_grdz, dst_grd, Cpos=Cpos, \
                          spval=spval, flood=False, irange=(0,1), \
                          jrange=(0,Mp))
                    if varname[nv] == 'u':
                        dst_u_west = dst_var_west
                        dst_u_east = dst_var_east
                        dst_u_north = dst_var_north
                        dst_u_south = dst_var_south
                    if varname[nv] == 'v':
                        dst_v_west = dst_var_west
                        dst_v_east = dst_var_east
                        dst_v_north = dst_var_north
                        dst_v_south = dst_var_south

                else:
                    dst_var_north = dst_varz[-1, :]
                    dst_var_south = dst_varz[0, :]
                    dst_var_east = dst_varz[:, -1]
                    dst_var_west = dst_varz[:, 0]

#                print datetime.datetime.now()

                # write data in destination file
                print 'write data in destination file'
                sid = '_west'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_west)

                sid = '_east'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_east)

                sid = '_north'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_north)

                sid = '_south'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_south)

            # rotate the velocity field if requested
            if rotate_uv is True:
                print ' '
                print 'remapping and rotating u and v from', srcgrd.name, \
                      'to', dst_grd.name

                # get source data
                src_u = pyroms.utility.get_nc_var(uvar, srcfile[nf])
                src_v = pyroms.utility.get_nc_var(vvar, srcfile[nf])

                # get spval
                try:
                    spval = src_v._FillValue
                except:
                    print Warning, 'Did not find a _FillValue attribute.'

                if rotate_part:
                    ndim = len(src_u.dimensions)-1
                    ind = uvar.find('_eastward')
                    uvar_out = uvar[0:ind]
                    print "Warning: renaming uvar to", uvar_out
                    ind = vvar.find('_northward')
                    vvar_out = vvar[0:ind]
                    print "Warning: renaming vvar to", vvar_out
                    if ndim == 3:
                        dimens_u = ['ocean_time', 's_rho', 'eta_u', 'xi_u']
                        dimens_v = ['ocean_time', 's_rho', 'eta_v', 'xi_v']
                    else:
                        dimens_u = ['ocean_time', 'eta_u', 'xi_u']
                        dimens_v = ['ocean_time', 'eta_v', 'xi_v']

                else:
                    dimens_u = [i for i in src_u.dimensions]
                    dimens_v = [i for i in src_v.dimensions]
                    uvar_out = uvar
                    vvar_out = vvar

                # create variable in destination file
                if nctidx == 0:
                    print 'Creating boundary variables for '+uvar
                    for sid in sides:
                       varn = uvar_out+str(sid)
                       print 'Creating variable', varn
                       dimens = list(dimens_u)
#                       for dim in dimens:
#                           if re.match(dimexcl[sid],dim):
#                               dimens.remove(dim)
                       nc.createVariable(varn, 'f8', dimens, \
                         fill_value=spval)
                       nc.variables[varn].long_name = uvar_out + \
                           ' ' + long[sid] + ' boundary condition'
                       try:
                           nc.variables[varn].units = src_u.units
                       except:
                           print varn+' has no units'
                       nc.variables[varn].time = src_u.time
                       nc.variables[varn].coordinates = \
                           str(dimens.reverse())
                       nc.variables[varn].field = src_u.field
                    print 'Creating boundary variables for '+vvar
                    for sid in sides:
                       varn = vvar_out+str(sid)
                       print 'Creating variable', varn
                       dimens = list(dimens_v)
                       for dim in dimens:
                           if re.match(dimexcl[sid],dim):
                               dimens.remove(dim)
                       nc.createVariable(varn, 'f8', dimens, \
                         fill_value=spval)
                       nc.variables[varn].long_name = vvar_out + \
                                ' ' + long[sid] + ' boundary condition'
                       try:
                           nc.variables[varn].units = src_v.units
                       except:
                           print varn+' has no units'
                       nc.variables[varn].time = src_v.time
                       nc.variables[varn].coordinates = \
                           str(dimens.reverse())
                       nc.variables[varn].field = src_v.field

                # get the right remap weights file
                if rotate_part:
                    Cpos_u = 'rho'
                    Cpos_v = 'rho'
                else:
                    Cpos_u = 'u'
                    Cpos_v = 'v'

                # vertical interpolation from sigma to standard z level
                # irange
                if irange is None:
                    ssrange = (0,src_u.shape[-1])
                else:
                    ssrange = irange

                # jrange
                if jrange is None:
                    jjrange = (0,src_u.shape[-2])
                else:
                    jjrange = jrange

                ndim = len(src_v.dimensions)-1
                if ndim == 3:
                    print 'vertical interpolation from sigma to standard z level'
                    src_uz = pyroms.remapping.sta2z( \
                            src_u[nt,:,ssrange[0]:ssrange[1]], \
                            srcgrd, srcgrdz, Cpos=Cpos_u, spval=spval, \
                            srange=ssrange)
                else:
                    src_uz = src_u[nt,ssrange[0]:ssrange[1]]

                # srange
                if srange is None:
                    ssrange = (0,src_v.shape[-1])
                else:
                    ssrange = srange

                if ndim == 3:
                    src_vz = pyroms.remapping.sta2z( \
                            src_v[nt,:,ssrange[0]:ssrange[1]], \
                            srcgrd, srcgrdz, Cpos=Cpos_v, spval=spval, \
                            srange=ssrange)

                else:
                    src_vz = src_v[nt,ssrange[0]:ssrange[1]]
                    src_vz = pyroms.remapping.flood2d(src_vz, srcgrdz, Cpos=Cpos_v, \
                                      srange=ssrange, spval=spval, \
                                      dmax=dmax)

                # horizontal interpolation using scrip weights
                Mp, Lp = dst_grd.hgrid.mask_rho.shape

                if ndim == 3:
                    # vertical interpolation from standard z level to sigma
                    print 'vertical interpolation from standard z level to sigma'
                    dst_u_north = pyroms.remapping.z2roms(dst_uz[:, Mp-2:Mp, 0:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,Lp), jrange=(Mp-2,Mp))
                    dst_u_south = pyroms.remapping.z2roms(dst_uz[:, 0:2, 0:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,Lp), jrange=(0,2))
                    dst_u_east = pyroms.remapping.z2roms(dst_uz[:, 0:Mp, Lp-2:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(Lp-2,Lp), jrange=(0,Mp))
                    dst_u_west = pyroms.remapping.z2roms(dst_uz[:, 0:Mp, 0:2], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,2), jrange=(0,Mp))

                    dst_v_north = pyroms.remapping.z2roms(dst_vz[:, Mp-2:Mp, 0:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,Lp), jrange=(Mp-2,Mp))
                    dst_v_south = pyroms.remapping.z2roms(dst_vz[:, 0:2, 0:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,Lp), jrange=(0,2))
                    dst_v_east = pyroms.remapping.z2roms(dst_vz[:, 0:Mp, Lp-2:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(Lp-2,Lp), jrange=(0,Mp))
                    dst_v_west = pyroms.remapping.z2roms(dst_vz[:, 0:Mp, 0:2], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,2), jrange=(0,Mp))
                else:
                    dst_u_north = dst_uz[Mp-2:Mp, 0:Lp]
                    dst_u_south = dst_uz[0:2, 0:Lp]
                    dst_u_east = dst_uz[0:Mp, Lp-2:Lp]
                    dst_u_west = dst_uz[0:Mp, 0:2]
                    dst_v_north = dst_vz[Mp-2:Mp, 0:Lp]
                    dst_v_south = dst_vz[0:2, 0:Lp]
                    dst_v_east = dst_vz[0:Mp, Lp-2:Lp]
                    dst_v_west = dst_vz[0:Mp, 0:2]

                # rotate u,v fields
                if rotate_part:
                    src_angle = np.zeros(dst_grd.hgrid.angle_rho.shape)
                else:
                    src_ang = srcgrd.hgrid.angle_rho[ssrange[0]:ssrange[1]]

                dst_angle = dst_grd.hgrid.angle_rho
                angle = dst_angle - src_angle
                if ndim == 3:
                    angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))
                    U_north = dst_u_north + dst_v_north*1j
                    eitheta_north = np.exp(-1j*angle[:,Mp-2:Mp, 0:Lp])
                    U_south = dst_u_south + dst_v_south*1j
                    eitheta_south = np.exp(-1j*angle[:,0:2, 0:Lp])
                    U_east = dst_u_east + dst_v_east*1j
                    eitheta_east = np.exp(-1j*angle[:,0:Mp, Lp-2:Lp])
                    U_west = dst_u_west + dst_v_west*1j
                    eitheta_west = np.exp(-1j*angle[:,0:Mp, 0:2])
                else:
                    U_north = dst_u_north + dst_v_north*1j
                    eitheta_north = np.exp(-1j*angle[Mp-2:Mp, 0:Lp])
                    U_south = dst_u_south + dst_v_south*1j
                    eitheta_south = np.exp(-1j*angle[0:2, 0:Lp])
                    U_east = dst_u_east + dst_v_east*1j
                    eitheta_east = np.exp(-1j*angle[0:Mp, Lp-2:Lp])
                    U_west = dst_u_west + dst_v_west*1j
                    eitheta_west = np.exp(-1j*angle[0:Mp, 0:2])

                U_north = U_north * eitheta_north
                dst_u_north = np.real(U_north)
                dst_v_north = np.imag(U_north)

                U_south = U_south * eitheta_south
                dst_u_south = np.real(U_south)
                dst_v_south = np.imag(U_south)

                U_east = U_east * eitheta_east
                dst_u_east = np.real(U_east)
                dst_v_east = np.imag(U_east)

                U_west = U_west * eitheta_west
                dst_u_west = np.real(U_west)
                dst_v_east = np.imag(U_east)

                # move back to u,v points
                if ndim == 3:
                    dst_u_north = 0.5 * np.squeeze(dst_u_north[:,-1,:-1] + \
                            dst_u_north[:,-1,1:])
                    dst_v_north = 0.5 * np.squeeze(dst_v_north[:,:-1,:] + \
                            dst_v_north[:,1:,:])
                    dst_u_south = 0.5 * np.squeeze(dst_u_south[:,0,:-1] + \
                            dst_u_south[:,0,1:])
                    dst_v_south = 0.5 * np.squeeze(dst_v_south[:,:-1,:] + \
                            dst_v_south[:,1:,:])
                    dst_u_east = 0.5 * np.squeeze(dst_u_east[:,:,:-1] + \
                            dst_u_east[:,:,1:])
                    dst_v_east = 0.5 * np.squeeze(dst_v_east[:,:-1,-1] + \
                            dst_v_east[:,1:,-1])
                    dst_u_west = 0.5 * np.squeeze(dst_u_west[:,:,:-1] + \
                            dst_u_west[:,:,1:])
                    dst_v_west = 0.5 * np.squeeze(dst_v_west[:,:-1,0] + \
                            dst_v_west[:,1:,0])
                else:
                    dst_u_north = 0.5 * np.squeeze(dst_u_north[-1,:-1] + \
                            dst_u_north[-1,1:])
                    dst_v_north = 0.5 * np.squeeze(dst_v_north[:-1,:] + \
                            dst_v_north[1:,:])
                    dst_u_south = 0.5 * np.squeeze(dst_u_south[0,:-1] + \
                            dst_u_south[0,1:])
                    dst_v_south = 0.5 * np.squeeze(dst_v_south[:-1,:] + \
                            dst_v_south[1:,:])
                    dst_u_east = 0.5 * np.squeeze(dst_u_east[:,:-1] + \
                            dst_u_east[:,1:])
                    dst_v_east = 0.5 * np.squeeze(dst_v_east[:-1,-1] + \
                            dst_v_east[1:,-1])
                    dst_u_west = 0.5 * np.squeeze(dst_u_west[:,:-1] + \
                            dst_u_west[:,1:])
                    dst_v_west = 0.5 * np.squeeze(dst_v_west[:-1,0] + \
                            dst_v_west[1:,0])

                # spval
                idxu_north = np.where(dst_grd.hgrid.mask_u[-1,:] == 0)
                idxv_north = np.where(dst_grd.hgrid.mask_v[-1,:] == 0)
                idxu_south = np.where(dst_grd.hgrid.mask_u[0,:] == 0)
                idxv_south = np.where(dst_grd.hgrid.mask_v[0,:] == 0)
                idxu_east = np.where(dst_grd.hgrid.mask_u[:,-1] == 0)
                idxv_east = np.where(dst_grd.hgrid.mask_v[:,-1] == 0)
                idxu_west = np.where(dst_grd.hgrid.mask_u[:,0] == 0)
                idxv_west = np.where(dst_grd.hgrid.mask_v[:,0] == 0)
                if ndim == 3:
                    for n in range(dst_grd.vgrid.N):
                        dst_u_north[n, idxu_north[0]] = spval
                        dst_v_north[n, idxv_north[0]] = spval
                        dst_u_south[n, idxu_south[0]] = spval
                        dst_v_south[n, idxv_south[0]] = spval
                        dst_u_east[n, idxu_east[0]] = spval
                        dst_v_east[n, idxv_east[0]] = spval
                        dst_u_west[n, idxu_west[0]] = spval
                        dst_v_west[n, idxv_west[0]] = spval
                else:
                    dst_u_north[idxu_north[0]] = spval
                    dst_v_north[idxv_north[0]] = spval
                    dst_u_south[idxu_south[0]] = spval
                    dst_v_south[idxv_south[0]] = spval
                    dst_u_east[idxu_east[0]] = spval
                    dst_v_east[idxv_east[0]] = spval
                    dst_u_west[idxu_west[0]] = spval
                    dst_v_west[idxv_west[0]] = spval

                # write data in destination file
                print 'write data in destination file'
                sid = '_west'
                varn = uvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_u_west
                varn = vvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_v_west

                sid = '_north'
                varn = uvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_u_north
                varn = vvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_v_north

                sid = '_east'
                varn = uvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_u_east
                varn = vvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_v_east

                sid = '_south'
                varn = uvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_u_south
                varn = vvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_v_south

            if compute_ubar:
                if nctidx == 0:
                    print 'Creating variable ubar_north'
                    nc.createVariable('ubar_north', 'f8', \
                         ('ocean_time', 'xi_u'), fill_value=spval)
                    nc.variables['ubar_north'].long_name = \
                          '2D u-momentum north boundary condition'
                    nc.variables['ubar_north'].units = 'meter second-1'
                    nc.variables['ubar_north'].time = 'ocean_time'
                    nc.variables['ubar_north'].coordinates = 'xi_u ocean_time'
                    nc.variables['ubar_north'].field = 'ubar_north, scalar, series'
                    print 'Creating variable vbar_north'
                    nc.createVariable('vbar_north', 'f8', \
                         ('ocean_time', 'xi_v'), fill_value=spval)
                    nc.variables['vbar_north'].long_name = \
                          '2D v-momentum north boundary condition'
                    nc.variables['vbar_north'].units = 'meter second-1'
                    nc.variables['vbar_north'].time = 'ocean_time'
                    nc.variables['vbar_north'].coordinates = 'xi_v ocean_time'
                    nc.variables['vbar_north'].field = 'vbar_north,, scalar, series'

                    print 'Creating variable ubar_south'
                    nc.createVariable('ubar_south', 'f8', \
                         ('ocean_time', 'xi_u'), fill_value=spval)
                    nc.variables['ubar_south'].long_name = \
                          '2D u-momentum south boundary condition'
                    nc.variables['ubar_south'].units = 'meter second-1'
                    nc.variables['ubar_south'].time = 'ocean_time'
                    nc.variables['ubar_south'].coordinates = 'xi_u ocean_time'
                    nc.variables['ubar_south'].field = 'ubar_south, scalar, series'
                    print 'Creating variable vbar_south'
                    nc.createVariable('vbar_south', 'f8', \
                         ('ocean_time', 'xi_v'), fill_value=spval)
                    nc.variables['vbar_south'].long_name = \
                          '2D v-momentum south boundary condition'
                    nc.variables['vbar_south'].units = 'meter second-1'
                    nc.variables['vbar_south'].time = 'ocean_time'
                    nc.variables['vbar_south'].coordinates = 'xi_v ocean_time'

                    print 'Creating variable ubar_west'
                    nc.createVariable('ubar_west', 'f8', \
                         ('ocean_time', 'eta_u'), fill_value=spval)
                    nc.variables['ubar_west'].long_name = \
                          '2D u-momentum west boundary condition'
                    nc.variables['ubar_west'].units = 'meter second-1'
                    nc.variables['ubar_west'].time = 'ocean_time'
                    nc.variables['ubar_west'].coordinates = 'eta_u ocean_time'
                    nc.variables['ubar_west'].field = 'ubar_west, scalar, series'
                    print 'Creating variable vbar_west'
                    nc.createVariable('vbar_west', 'f8', \
                         ('ocean_time', 'eta_v'), fill_value=spval)
                    nc.variables['vbar_west'].long_name = \
                          '2D v-momentum west boundary condition'
                    nc.variables['vbar_west'].units = 'meter second-1'
                    nc.variables['vbar_west'].time = 'ocean_time'
                    nc.variables['vbar_west'].coordinates = 'eta_v ocean_time'

                    print 'Creating variable ubar_east'
                    nc.createVariable('ubar_east', 'f8', \
                         ('ocean_time', 'eta_u'), fill_value=spval)
                    nc.variables['ubar_east'].long_name = \
                          '2D u-momentum east boundary condition'
                    nc.variables['ubar_east'].units = 'meter second-1'
                    nc.variables['ubar_east'].time = 'ocean_time'
                    nc.variables['ubar_east'].coordinates = 'eta_u ocean_time'
                    nc.variables['ubar_east'].field = 'ubar_east, scalar, series'
                    print 'Creating variable vbar_east'
                    nc.createVariable('vbar_east', 'f8', \
                         ('ocean_time', 'eta_v'), fill_value=spval)
                    nc.variables['vbar_east'].long_name = \
                          '2D v-momentum east boundary condition'
                    nc.variables['vbar_east'].units = 'meter second-1'
                    nc.variables['vbar_east'].time = 'ocean_time'
                    nc.variables['vbar_east'].coordinates = 'eta_v ocean_time'

                # compute depth average velocity ubar and vbar
                # get z at the right position
                print 'Computing ubar/vbar from u/v'
                z_u_north = 0.5 * (dst_grd.vgrid.z_w[0,:,-1,:-1] +
                        dst_grd.vgrid.z_w[0,:,-1, 1:])
                z_v_north = 0.5 * (dst_grd.vgrid.z_w[0,:,-1,:] +
                        dst_grd.vgrid.z_w[0,:,-2,:])
                z_u_south = 0.5 * (dst_grd.vgrid.z_w[0,:,0,:-1] +
                        dst_grd.vgrid.z_w[0,:,0,1:])
                z_v_south = 0.5 * (dst_grd.vgrid.z_w[0,:,0,:] +
                        dst_grd.vgrid.z_w[0,:,1,:])
                z_u_east = 0.5 * (dst_grd.vgrid.z_w[0,:,:,-1] +
                        dst_grd.vgrid.z_w[0,:,:,-2])
                z_v_east = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,-1] +
                        dst_grd.vgrid.z_w[0,:,1:,-1])
                z_u_west = 0.5 * (dst_grd.vgrid.z_w[0,:,:,0] +
                        dst_grd.vgrid.z_w[0,:,:,1])
                z_v_west = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,0] +
                        dst_grd.vgrid.z_w[0,:,1:,0])
                if not rotate_uv:
                    dst_u_north = np.squeeze(dst_u_north)
                    dst_v_north = np.squeeze(dst_v_north)
                    dst_u_south = np.squeeze(dst_u_south)
                    dst_v_south = np.squeeze(dst_v_south)
                    dst_u_east = np.squeeze(dst_u_east)
                    dst_v_east = np.squeeze(dst_v_east)
                    dst_u_west = np.squeeze(dst_u_west)
                    dst_v_west = np.squeeze(dst_v_west)

                dst_ubar_north = np.zeros(dst_u_north.shape[1])
                dst_ubar_south = np.zeros(dst_u_south.shape[1])
                dst_ubar_east = np.zeros(dst_u_east.shape[1])
                dst_ubar_west = np.zeros(dst_u_west.shape[1])
                dst_vbar_north = np.zeros(dst_v_north.shape[1])
                dst_vbar_south = np.zeros(dst_v_south.shape[1])
                dst_vbar_east = np.zeros(dst_v_east.shape[1])
                dst_vbar_west = np.zeros(dst_v_west.shape[1])

#                print 'Shapes 3', dst_u_north.shape, dst_ubar_north.shape, z_u_north.shape, np.diff(z_u_north[:,1]).shape
                for i in range(dst_u_north.shape[1]):
                    dst_ubar_north[i] = (dst_u_north[:,i] * \
                        np.diff(z_u_north[:,i])).sum() / -z_u_north[0,i]
                    dst_ubar_south[i] = (dst_u_south[:,i] * \
                        np.diff(z_u_south[:,i])).sum() / -z_u_south[0,i]
                for i in range(dst_v_north.shape[1]):
                    dst_vbar_north[i] = (dst_v_north[:,i] * \
                        np.diff(z_v_north[:,i])).sum() / -z_v_north[0,i]
                    dst_vbar_south[i] = (dst_v_south[:,i] * \
                        np.diff(z_v_south[:,i])).sum() / -z_v_south[0,i]
                for j in range(dst_u_east.shape[1]):
                    dst_ubar_east[j] = (dst_u_east[:,j] * \
                        np.diff(z_u_east[:,j])).sum() / -z_u_east[0,j]
                    dst_ubar_west[j] = (dst_u_west[:,j] * \
                        np.diff(z_u_west[:,j])).sum() / -z_u_west[0,j]
                for j in range(dst_v_east.shape[1]):
                    dst_vbar_east[j] = (dst_v_east[:,j] * \
                        np.diff(z_v_east[:,j])).sum() / -z_v_east[0,j]
                    dst_vbar_west[j] = (dst_v_west[:,j] * \
                        np.diff(z_v_west[:,j])).sum() / -z_v_west[0,j]

                # spval
                idxu_north = np.where(dst_grd.hgrid.mask_u[-1,:] == 0)
                idxv_north = np.where(dst_grd.hgrid.mask_v[-1,:] == 0)
                idxu_south = np.where(dst_grd.hgrid.mask_u[0,:] == 0)
                idxv_south = np.where(dst_grd.hgrid.mask_v[0,:] == 0)
                idxu_east = np.where(dst_grd.hgrid.mask_u[:,-1] == 0)
                idxv_east = np.where(dst_grd.hgrid.mask_v[:,-1] == 0)
                idxu_west = np.where(dst_grd.hgrid.mask_u[:,0] == 0)
                idxv_west = np.where(dst_grd.hgrid.mask_v[:,0] == 0)

                dst_ubar_north[idxu_north[0]] = spval
                dst_vbar_north[idxv_north[0]] = spval
                dst_ubar_south[idxu_south[0]] = spval
                dst_vbar_south[idxv_south[0]] = spval
                dst_ubar_east[idxu_east[0]] = spval
                dst_vbar_east[idxv_east[0]] = spval
                dst_ubar_west[idxu_west[0]] = spval
                dst_vbar_west[idxv_west[0]] = spval

                nc.variables['ubar_north'][nctidx] = dst_ubar_north
                nc.variables['ubar_south'][nctidx] = dst_ubar_south
                nc.variables['ubar_east'][nctidx] = dst_ubar_east
                nc.variables['ubar_west'][nctidx] = dst_ubar_west

                nc.variables['vbar_north'][nctidx] = dst_vbar_north
                nc.variables['vbar_south'][nctidx] = dst_vbar_south
                nc.variables['vbar_east'][nctidx] = dst_vbar_east
                nc.variables['vbar_west'][nctidx] = dst_vbar_west

            nctidx = nctidx + 1
            print 'ADDING to nctidx ', nctidx
            nc.sync()
        # close files here? how?

    # close destination file
    nc.close()

    return
Ejemplo n.º 2
0
def remap_bdry_uv(src_file, src_grd, dst_grd, dxy=20, cdepth=0, kk=2, dst_dir='./'):

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'

    # get dimensions
    Mp, Lp = dst_grd.hgrid.mask_rho.shape

    # create destination file
    dst_file = src_file.rsplit('/')[-1]
    dst_fileu = dst_dir + dst_file[:-3] + '_u_bdry_' + dst_grd.name + '.nc'
    print '\nCreating destination file', dst_fileu
    if os.path.exists(dst_fileu) is True:
        os.remove(dst_fileu)
    pyroms_toolbox.nc_create_roms_file(dst_fileu, dst_grd, nctime)
    dst_filev = dst_dir + dst_file[:-3] + '_v_bdry_' + dst_grd.name + '.nc'
    print 'Creating destination file', dst_filev
    if os.path.exists(dst_filev) is True:
        os.remove(dst_filev)
    pyroms_toolbox.nc_create_roms_file(dst_filev, dst_grd, nctime)

    # open destination file
    ncu = netCDF.Dataset(dst_fileu, 'a', format='NETCDF3_64BIT')
    ncv = netCDF.Dataset(dst_filev, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_varu = cdf.variables['u']
    src_varv = cdf.variables['v']
    time = cdf.variables['ocean_time'][0]


    #get missing value
    spval = src_varu._FillValue
    src_varu = cdf.variables['u'][0]
    src_varv = cdf.variables['v'][0]

    # get weights file
    wts_file = 'remap_weights_GLBa0.08_to_ARCTIC2_bilinear_t_to_rho.nc'

    # build intermediate zgrid
    zlevel = -src_grd.z_t[::-1,0,0]
    nzlevel = len(zlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)

    # create variable in destination file
    print 'Creating variable u_north'
    ncu.createVariable('u_north', 'f8', ('ocean_time', 's_rho', 'xi_u'), fill_value=spval)
    ncu.variables['u_north'].long_name = '3D u-momentum north boundary condition'
    ncu.variables['u_north'].units = 'meter second-1'
    ncu.variables['u_north'].field = 'u_north, scalar, series'

    print 'Creating variable u_south'
    ncu.createVariable('u_south', 'f8', ('ocean_time', 's_rho', 'xi_u'), fill_value=spval)
    ncu.variables['u_south'].long_name = '3D u-momentum south boundary condition'
    ncu.variables['u_south'].units = 'meter second-1'
    ncu.variables['u_south'].field = 'u_south, scalar, series'

    print 'Creating variable u_east'
    ncu.createVariable('u_east', 'f8', ('ocean_time', 's_rho', 'eta_u'), fill_value=spval)
    ncu.variables['u_east'].long_name = '3D u-momentum east boundary condition'
    ncu.variables['u_east'].units = 'meter second-1'
    ncu.variables['u_east'].field = 'u_east, scalar, series'
    print 'Creating variable u_west'
    ncu.createVariable('u_west', 'f8', ('ocean_time', 's_rho', 'eta_u'), fill_value=spval)
    ncu.variables['u_west'].long_name = '3D u-momentum west boundary condition'
    ncu.variables['u_west'].units = 'meter second-1'
    ncu.variables['u_west'].field = 'u_east, scalar, series'

    # create variable in destination file
    print 'Creating variable ubar_north'
    ncu.createVariable('ubar_north', 'f8', ('ocean_time', 'xi_u'), fill_value=spval)
    ncu.variables['ubar_north'].long_name = '2D u-momentum north boundary condition'
    ncu.variables['ubar_north'].units = 'meter second-1'
    ncu.variables['ubar_north'].field = 'ubar_north, scalar, series'

    print 'Creating variable ubar_south'
    ncu.createVariable('ubar_south', 'f8', ('ocean_time', 'xi_u'), fill_value=spval)
    ncu.variables['ubar_south'].long_name = '2D u-momentum south boundary condition'
    ncu.variables['ubar_south'].units = 'meter second-1'
    ncu.variables['ubar_south'].field = 'ubar_south, scalar, series'

    print 'Creating variable ubar_east'
    ncu.createVariable('ubar_east', 'f8', ('ocean_time', 'eta_u'), fill_value=spval)
    ncu.variables['ubar_east'].long_name = '2D u-momentum east boundary condition'
    ncu.variables['ubar_east'].units = 'meter second-1'
    ncu.variables['ubar_east'].field = 'ubar_east, scalar, series'
    print 'Creating variable ubar_west'
    ncu.createVariable('ubar_west', 'f8', ('ocean_time', 'eta_u'), fill_value=spval)
    ncu.variables['ubar_west'].long_name = '2D u-momentum west boundary condition'
    ncu.variables['ubar_west'].units = 'meter second-1'
    ncu.variables['ubar_west'].field = 'ubar_east, scalar, series'


    print 'Creating variable v_north'
    ncv.createVariable('v_north', 'f8', ('ocean_time', 's_rho', 'xi_v'), fill_value=spval)
    ncv.variables['v_north'].long_name = '3D v-momentum north boundary condition'
    ncv.variables['v_north'].units = 'meter second-1'
    ncv.variables['v_north'].field = 'v_north, scalar, series'

    print 'Creating variable v_south'
    ncv.createVariable('v_south', 'f8', ('ocean_time', 's_rho', 'xi_v'), fill_value=spval)
    ncv.variables['v_south'].long_name = '3D v-momentum south boundary condition'
    ncv.variables['v_south'].units = 'meter second-1'
    ncv.variables['v_south'].field = 'v_south, scalar, series'

    print 'Creating variable v_east'
    ncv.createVariable('v_east', 'f8', ('ocean_time', 's_rho', 'eta_v'), fill_value=spval)
    ncv.variables['v_east'].long_name = '3D v-momentum east boundary condition'
    ncv.variables['v_east'].units = 'meter second-1'
    ncv.variables['v_east'].field = 'v_east, scalar, series'
    print 'Creating variable v_west'
    ncv.createVariable('v_west', 'f8', ('ocean_time', 's_rho', 'eta_v'), fill_value=spval)
    ncv.variables['v_west'].long_name = '3D v-momentum west boundary condition'
    ncv.variables['v_west'].units = 'meter second-1'
    ncv.variables['v_west'].field = 'v_east, scalar, series'

    print 'Creating variable vbar_north'
    ncv.createVariable('vbar_north', 'f8', ('ocean_time', 'xi_v'), fill_value=spval)
    ncv.variables['vbar_north'].long_name = '2D v-momentum north boundary condition'
    ncv.variables['vbar_north'].units = 'meter second-1'
    ncv.variables['vbar_north'].field = 'vbar_north, scalar, series'

    print 'Creating variable vbar_south'
    ncv.createVariable('vbar_south', 'f8', ('ocean_time', 'xi_v'), fill_value=spval)
    ncv.variables['vbar_south'].long_name = '2D v-momentum south boundary condition'
    ncv.variables['vbar_south'].units = 'meter second-1'
    ncv.variables['vbar_south'].field = 'vbar_south, scalar, series'

    print 'Creating variable vbar_east'
    ncv.createVariable('vbar_east', 'f8', ('ocean_time', 'eta_v'), fill_value=spval)
    ncv.variables['vbar_east'].long_name = '2D v-momentum east boundary condition'
    ncv.variables['vbar_east'].units = 'meter second-1'
    ncv.variables['vbar_east'].field = 'vbar_east, scalar, series'
    print 'Creating variable vbar_west'
    ncv.createVariable('vbar_west', 'f8', ('ocean_time', 'eta_v'), fill_value=spval)
    ncv.variables['vbar_west'].long_name = '2D v-momentum west boundary condition'
    ncv.variables['vbar_west'].units = 'meter second-1'
    ncv.variables['vbar_west'].field = 'vbar_east, scalar, series'

 

    # remaping
    print 'remapping and rotating u and v from', src_grd.name, \
                      'to', dst_grd.name
    print 'time =', time


    # flood the grid
    print 'flood the grid'
    src_uz = pyroms_toolbox.Grid_HYCOM.flood_fast(src_varu, src_grd, pos='t', \
                spval=spval, dxy=dxy, cdepth=cdepth, kk=kk)
    src_vz = pyroms_toolbox.Grid_HYCOM.flood_fast(src_varv, src_grd, pos='t', \
                spval=spval, dxy=dxy, cdepth=cdepth, kk=kk)

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_uz = pyroms.remapping.remap(src_uz, wts_file, \
                                      spval=spval)
    dst_vz = pyroms.remapping.remap(src_vz, wts_file, \
                                      spval=spval)

    # vertical interpolation from standard z level to sigma
    print 'vertical interpolation from standard z level to sigma'
    dst_u_north = pyroms.remapping.z2roms(dst_uz[::-1, Mp-2:Mp, 0:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,Lp), jrange=(Mp-2,Mp))
    dst_u_south = pyroms.remapping.z2roms(dst_uz[::-1, 0:2, 0:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,Lp), jrange=(0,2))
    dst_u_east = pyroms.remapping.z2roms(dst_uz[::-1, 0:Mp, Lp-2:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(Lp-2,Lp), jrange=(0,Mp))
    dst_u_west = pyroms.remapping.z2roms(dst_uz[::-1, 0:Mp, 0:2], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,2), jrange=(0,Mp))

    dst_v_north = pyroms.remapping.z2roms(dst_vz[::-1, Mp-2:Mp, 0:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,Lp), jrange=(Mp-2,Mp))
    dst_v_south = pyroms.remapping.z2roms(dst_vz[::-1, 0:2, 0:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,Lp), jrange=(0,2))
    dst_v_east = pyroms.remapping.z2roms(dst_vz[::-1, 0:Mp, Lp-2:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(Lp-2,Lp), jrange=(0,Mp))
    dst_v_west = pyroms.remapping.z2roms(dst_vz[::-1, 0:Mp, 0:2], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,2), jrange=(0,Mp))


    # rotate u,v fields
    src_angle = pyroms.remapping.remap(src_grd.angle, \
    'remap_weights_GLBa0.08_to_ARCTIC2_bilinear_t_to_rho.nc', \
                                      spval=spval)
    dst_angle = dst_grd.hgrid.angle_rho
    angle = dst_angle - src_angle
    angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))

    U_north = dst_u_north + dst_v_north*1j
    eitheta_north = np.exp(-1j*angle[:,Mp-2:Mp, 0:Lp])
    U_north = U_north * eitheta_north
    dst_u_north = np.real(U_north)
    dst_v_north = np.imag(U_north)

    U_south = dst_u_south + dst_v_south*1j
    eitheta_south = np.exp(-1j*angle[:,0:2, 0:Lp])
    U_south = U_south * eitheta_south
    dst_u_south = np.real(U_south)
    dst_v_south = np.imag(U_south)

    U_east = dst_u_east + dst_v_east*1j
    eitheta_east = np.exp(-1j*angle[:,0:Mp, Lp-2:Lp])
    U_east = U_east * eitheta_east
    dst_u_east = np.real(U_east)
    dst_v_east = np.imag(U_east)

    U_west = dst_u_west + dst_v_west*1j
    eitheta_west = np.exp(-1j*angle[:,0:Mp, 0:2])
    U_west = U_west * eitheta_west
    dst_u_west = np.real(U_west)
    dst_v_west = np.imag(U_west)


    # move back to u,v points
    dst_u_north = 0.5 * np.squeeze(dst_u_north[:,-1,:-1] + dst_u_north[:,-1,1:])
    dst_v_north = 0.5 * np.squeeze(dst_v_north[:,:-1,:] + dst_v_north[:,1:,:])
    dst_u_south = 0.5 * np.squeeze(dst_u_south[:,0,:-1] + dst_u_south[:,0,1:])
    dst_v_south = 0.5 * np.squeeze(dst_v_south[:,:-1,:] + dst_v_south[:,1:,:])
    dst_u_east = 0.5 * np.squeeze(dst_u_east[:,:,:-1] + dst_u_east[:,:,1:])
    dst_v_east = 0.5 * np.squeeze(dst_v_east[:,:-1,-1] + dst_v_east[:,1:,-1])
    dst_u_west = 0.5 * np.squeeze(dst_u_west[:,:,:-1] + dst_u_west[:,:,1:])
    dst_v_west = 0.5 * np.squeeze(dst_v_west[:,:-1,0] + dst_v_west[:,1:,0])

    # Fix north pole
#    print dst_u_north.shape
#    print dst_v_north.shape
#    dst_u_north[:,707] = 2/3.0*dst_u_north[:,706] + 1/3.0*dst_u_north[:,709]
#    dst_u_north[:,708] = 1/3.0*dst_u_north[:,706] + 2/3.0*dst_u_north[:,709]
#    dst_v_north[:,708] = 2/3.0*dst_v_north[:,707] + 1/3.0*dst_v_north[:,710]
#    dst_v_north[:,709] = 1/3.0*dst_v_north[:,707] + 2/3.0*dst_v_north[:,710]

    # spval
    idxu_north = np.where(dst_grd.hgrid.mask_u[-1,:] == 0)
    idxv_north = np.where(dst_grd.hgrid.mask_v[-1,:] == 0)
    idxu_south = np.where(dst_grd.hgrid.mask_u[0,:] == 0)
    idxv_south = np.where(dst_grd.hgrid.mask_v[0,:] == 0)
    idxu_east = np.where(dst_grd.hgrid.mask_u[:,-1] == 0)
    idxv_east = np.where(dst_grd.hgrid.mask_v[:,-1] == 0)
    idxu_west = np.where(dst_grd.hgrid.mask_u[:,0] == 0)
    idxv_west = np.where(dst_grd.hgrid.mask_v[:,0] == 0)
    for n in range(dst_grd.vgrid.N): 
        dst_u_north[n, idxu_north[0]] = spval
        dst_v_north[n, idxv_north[0]] = spval
        dst_u_south[n, idxu_south[0]] = spval
        dst_v_south[n, idxv_south[0]] = spval
        dst_u_east[n, idxu_east[0]] = spval
        dst_v_east[n, idxv_east[0]] = spval
        dst_u_west[n, idxu_west[0]] = spval
        dst_v_west[n, idxv_west[0]] = spval

    # compute depth average velocity ubar and vbar
    # get z at the right position
    z_u_north = 0.5 * (dst_grd.vgrid.z_w[0,:,-1,:-1] + dst_grd.vgrid.z_w[0,:,-1,1:])
    z_v_north = 0.5 * (dst_grd.vgrid.z_w[0,:,-1,:] + dst_grd.vgrid.z_w[0,:,-2,:])
    z_u_south = 0.5 * (dst_grd.vgrid.z_w[0,:,0,:-1] + dst_grd.vgrid.z_w[0,:,0,1:])
    z_v_south = 0.5 * (dst_grd.vgrid.z_w[0,:,0,:] + dst_grd.vgrid.z_w[0,:,1,:])
    z_u_east = 0.5 * (dst_grd.vgrid.z_w[0,:,:,-1] + dst_grd.vgrid.z_w[0,:,:,-2])
    z_v_east = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,-1] + dst_grd.vgrid.z_w[0,:,1:,-1])
    z_u_west = 0.5 * (dst_grd.vgrid.z_w[0,:,:,0] + dst_grd.vgrid.z_w[0,:,:,1])
    z_v_west = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,0] + dst_grd.vgrid.z_w[0,:,1:,0])

    dst_ubar_north = np.zeros(dst_u_north.shape[1])
    dst_ubar_south = np.zeros(dst_u_south.shape[1])
    dst_ubar_east = np.zeros(dst_u_east.shape[1])
    dst_ubar_west = np.zeros(dst_u_west.shape[1])
    dst_vbar_north = np.zeros(dst_v_north.shape[1])
    dst_vbar_south = np.zeros(dst_v_south.shape[1])
    dst_vbar_east = np.zeros(dst_v_east.shape[1])
    dst_vbar_west = np.zeros(dst_v_west.shape[1])

    for i in range(dst_u_north.shape[1]):
        dst_ubar_north[i] = (dst_u_north[:,i] * np.diff(z_u_north[:,i])).sum() / -z_u_north[0,i]
    for i in range(dst_v_north.shape[1]):
        dst_vbar_north[i] = (dst_v_north[:,i] * np.diff(z_v_north[:,i])).sum() / -z_v_north[0,i]
    for i in range(dst_u_south.shape[1]):
        dst_ubar_south[i] = (dst_u_south[:,i] * np.diff(z_u_south[:,i])).sum() / -z_u_south[0,i]
    for i in range(dst_v_south.shape[1]):
        dst_vbar_south[i] = (dst_v_south[:,i] * np.diff(z_v_south[:,i])).sum() / -z_v_south[0,i]
    for j in range(dst_u_east.shape[1]):
        dst_ubar_east[j] = (dst_u_east[:,j] * np.diff(z_u_east[:,j])).sum() / -z_u_east[0,j]
        dst_ubar_west[j] = (dst_u_west[:,j] * np.diff(z_u_west[:,j])).sum() / -z_u_west[0,j]
    for j in range(dst_v_east.shape[1]):
        dst_vbar_east[j] = (dst_v_east[:,j] * np.diff(z_v_east[:,j])).sum() / -z_v_east[0,j]
        dst_vbar_west[j] = (dst_v_west[:,j] * np.diff(z_v_west[:,j])).sum() / -z_v_west[0,j]
        
    #mask
    dst_ubar_north = np.ma.masked_where(dst_grd.hgrid.mask_u[-1,:] == 0, dst_ubar_north)   
    dst_ubar_south = np.ma.masked_where(dst_grd.hgrid.mask_u[0,:] == 0, dst_ubar_south)   
    dst_ubar_east = np.ma.masked_where(dst_grd.hgrid.mask_u[:,-1] == 0, dst_ubar_east)   
    dst_ubar_west = np.ma.masked_where(dst_grd.hgrid.mask_u[:,0] == 0, dst_ubar_west)   
    dst_vbar_north = np.ma.masked_where(dst_grd.hgrid.mask_v[-1,:] == 0, dst_vbar_north)   
    dst_vbar_south = np.ma.masked_where(dst_grd.hgrid.mask_v[0,:] == 0, dst_vbar_south)   
    dst_vbar_east = np.ma.masked_where(dst_grd.hgrid.mask_v[:,-1] == 0, dst_vbar_east)   
    dst_vbar_west = np.ma.masked_where(dst_grd.hgrid.mask_v[:,0] == 0, dst_vbar_west)   

    # write data in destination file
    print 'write data in destination file'
    ncu.variables['ocean_time'][0] = time
    ncu.variables['u_north'][0] = dst_u_north
    ncu.variables['u_south'][0] = dst_u_south
    ncu.variables['u_east'][0] = dst_u_east
    ncu.variables['u_west'][0] = dst_u_west
    ncu.variables['ubar_north'][0] = dst_ubar_north
    ncu.variables['ubar_south'][0] = dst_ubar_south
    ncu.variables['ubar_east'][0] = dst_ubar_east
    ncu.variables['ubar_west'][0] = dst_ubar_west

    ncv.variables['ocean_time'][0] = time
    ncv.variables['v_north'][0] = dst_v_north
    ncv.variables['v_south'][0] = dst_v_south
    ncv.variables['v_east'][0] = dst_v_east
    ncv.variables['v_west'][0] = dst_v_west
    ncv.variables['vbar_north'][0] = dst_vbar_north
    ncv.variables['vbar_south'][0] = dst_vbar_south
    ncv.variables['vbar_east'][0] = dst_vbar_east
    ncv.variables['vbar_west'][0] = dst_vbar_west

    # close file
    ncu.close()
    ncv.close()
    cdf.close()
Ejemplo n.º 3
0
def remap_clm(src_file, src_varname, src_grd, dst_grd, dxy=20, cdepth=0, kk=0, dst_dir='./'):

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
#    ref = datetime(1900, 1, 1, 0, 0, 0)
#    ref = date2num(ref)
#    tag = src_file.rsplit('/')[-1].rsplit('_')[-2].rsplit('-')[0]
#    print tag
#    year = int(tag[:4])
#    month = int(tag[4:6])
#    day = int(tag[6:])
#    time = datetime(year, month, day, 0, 0, 0)
#    time = date2num(time)
#    time = time - ref
#    time = time + 2.5 # 5-day average
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname][0]
    time = cdf.variables['ocean_time'][0]


    # create IC file
    dst_file = src_file.rsplit('/')[-1]
    dst_file = dst_dir + dst_file[:-3] + '_' + src_varname + '_clim_' + dst_grd.name + '.nc'
    print '\nCreating file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open IC file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    #get missing value
    spval = src_var._FillValue
    src_var = src_var[0]

    # determine variable dimension
    #ndim = len(src_var.dimensions)
    ndim = len(src_var.shape)

    if src_varname == 'ssh':
        pos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLBa0.08_to_PALAU1_bilinear_t_to_rho.nc'
        dst_varname = 'zeta'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'free-surface'
        units = 'meter'
        field = 'free-surface, scalar, series'
	vartime = 'ocean_time'
    elif src_varname == 'temp':
        pos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLBa0.08_to_PALAU1_bilinear_t_to_rho.nc'
        dst_varname = 'temp'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'potential temperature'
        units = 'Celsius'
        field = 'temperature, scalar, series'
	vartime = 'ocean_time'
    elif src_varname == 'salt':
        pos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLBa0.08_to_PALAU1_bilinear_t_to_rho.nc'
        dst_varname = 'salt'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'salinity'
        units = 'PSU'
        field = 'salinity, scalar, series'
	vartime = 'ocean_time'
    else:
        raise ValueError, 'Undefined src_varname'


    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1,0,0]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)


    # create variable in file
    print 'Creating variable', dst_varname
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field
    nc.variables[dst_varname].time = vartime


    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name
    print 'time =', time


    if ndim == 3:
        # flood the grid
        print 'flood the grid'
        src_varz = pyroms_toolbox.Grid_HYCOM.flood_fast(src_var, src_grd, pos=pos, spval=spval, \
                                dxy=dxy, cdepth=cdepth, kk=kk)
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, \
                                          spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print 'vertical interpolation from standard z level to sigma'
        dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \
                          dst_grd, Cpos=Cpos, spval=spval, flood=False)
    else:
        dst_var = dst_varz

    # write data in destination file
    print 'write data in destination file'
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname][0] = dst_var

    # close destination file
    nc.close()

    if src_varname == 'ssh':
        return dst_varz
Ejemplo n.º 4
0
def remapping_bound_sig(varname, srcfile, wts_files, srcgrd, dst_grd, \
              rotate_sig=False, trange=None, irange=None, jrange=None, \
              dstdir='./' ,zlevel=None, dmax=0, cdepth=0, kk=0):
    '''
    A remapping function to go from a ROMS grid to another ROMS grid.
    This is for 2D tensors: internal ice stress, hard-coding for sig11, sig22,
    sig12.
    '''

    # get input and output grid
    if type(srcgrd).__name__ == 'ROMS_Grid':
        srcgrd = srcgrd
    else:
        srcgrd = pyroms.grid.get_ROMS_grid(srcgrd)
    if type(dst_grd).__name__ == 'ROMS_Grid':
        dst_grd = dst_grd
    else:
        dst_grd = pyroms.grid.get_ROMS_grid(dst_grd)

    # varname argument
    if type(varname).__name__ == 'list':
        nvar = len(varname)
    elif type(varname).__name__ == 'str':
        varname = [varname]
        nvar = len(varname)
    else:
        raise ValueError, 'varname must be a str or a list of str'

    # srcfile argument
    if type(srcfile).__name__ == 'list':
        nfile = len(srcfile)
    elif type(srcfile).__name__ == 'str':
        srcfile = sorted(glob.glob(srcfile))
        nfile = len(srcfile)
    else:
        raise ValueError, 'src_srcfile must be a str or a list of str'

    # get wts_file
    if type(wts_files).__name__ == 'str':
        wts_files = sorted(glob.glob(wts_files))
 
    sides = ['_west','_east','_north','_south']
    long = {'_west':'Western', '_east':'Eastern', \
            '_north':'Northern', '_south':'Southern'}
    dimexcl = {'_west':'xi', '_east':'xi', \
            '_north':'eta', '_south':'eta'}

    nctidx = 0
    # loop over the srcfile
    for nf in range(nfile):
        print 'Working with file', srcfile[nf], '...'

        # get time 
        ocean_time = pyroms.utility.get_nc_var('ocean_time', srcfile[nf])
        ntime = len(ocean_time[:])

        # trange argument
        if trange is None:
            trange = range(ntime)

        # create destination file
        if nctidx == 0:
            dstfile = dstdir + os.path.basename(srcfile[nf])[:-3] + '_' \
                   + dst_grd.name + '_bdry.nc'
            if os.path.exists(dstfile) is False:
                print 'Creating destination file', dstfile
                pyroms_toolbox.nc_create_roms_file(dstfile, dst_grd, \
                    ocean_time, lgrid=False)

            # open destination file
            nc = netCDF.Dataset(dstfile, 'a', format='NETCDF3_64BIT')

        # loop over time
        for nt in trange:

            nc.variables['ocean_time'][nctidx] = ocean_time[nt]

            # loop over variable
            for nv in range(nvar):
                print ' '
                print 'remapping', varname[nv], 'from', srcgrd.name, \
                      'to', dst_grd.name
                print 'time =', ocean_time[nt]   
                Mp, Lp = dst_grd.hgrid.mask_rho.shape

                # get source data
                src_var = pyroms.utility.get_nc_var(varname[nv], srcfile[nf])

                # get spval
                try:
                    spval = src_var._FillValue
                except:
                    raise Warning, 'Did not find a _FillValue attribute.' 

                # irange
                if irange is None:
                    iirange = (0,src_var.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0,src_var.shape[-2])
                else:
                    jjrange = jrange

                # determine where on the C-grid these variable lies
                if src_var.dimensions[2].find('_rho') != -1:
                    Cpos='rho'
                else:
                    print "Sigma should be on rho points"

                print 'Arakawa C-grid position is', Cpos

                # create variable in _destination file
                if nctidx == 0:
                    for sid in sides:
                       varn = varname[nv]+str(sid)
                       print 'Creating variable', varn
                       dimens = [i for i in src_var.dimensions]
                       for dim in dimens:
                           if re.match(dimexcl[sid],dim):
                               dimens.remove(dim)
                       nc.createVariable(varn, 'f8', dimens, \
                           fill_value=spval)
                       nc.variables[varn].long_name = varname[nv] + \
                            ' ' + long[sid] + ' boundary condition'
                       try:
                           nc.variables[varn].units = src_var.units
                       except:
                           print varn+' has no units'
                       nc.variables[varn].time = src_var.time
                       nc.variables[varn].coordinates = \
                           str(dimens.reverse())
                       nc.variables[varn].field = src_var.field

                # get the right remap weights file
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__(Cpos+'_to_'+Cpos+'.nc'):
                        wts_file = wts_files[s]
                        break
                    else:
                        if s == len(wts_files) - 1:
                            raise ValueError, 'Did not find the appropriate remap weights file'

#                print datetime.datetime.now()
                # horizontal interpolation using scrip weights
#                print 'horizontal interpolation using scrip weights'
            if not rotate_sig:
                dst_var = pyroms.remapping.remap(tmp_src_var, wts_file, \
                                                  spval=spval)

                dst_var_north = dst_var[-1, :]
                dst_var_south = dst_var[0, :]
                dst_var_east = dst_var[:, -1]
                dst_var_west = dst_var[:, 0]

                # write data in destination file
                print 'write data in destination file'
                sid = '_west'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_west)

                sid = '_east'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_east)

                sid = '_north'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_north)

                sid = '_south'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_south)

            # rotate the velocity field if requested
            if rotate_sig:
                print ' ' 
                print 'remapping and rotating sigma from', srcgrd.name, \
                      'to', dst_grd.name

                # get source data
                src_11 = pyroms.utility.get_nc_var(varname[0], srcfile[nf])
                # get spval
                try:
                    spval = src_11._FillValue
                except:
                    raise Warning, 'Did not find a _FillValue attribute.' 

                src_11 = src_11[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]

                src_22 = pyroms.utility.get_nc_var(varname[1], srcfile[nf])
                src_22 = src_22[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]

                src_12 = pyroms.utility.get_nc_var(varname[2], srcfile[nf])
                src_12 = src_12[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]


                # horizontal interpolation using scrip weights
                print 'horizontal interpolation using scrip weights'
                dst_11 = pyroms.remapping.remap(src_11, wts_file, \
                                                  spval=spval)
                dst_22 = pyroms.remapping.remap(src_22, wts_file, \
                                                  spval=spval)
                dst_12 = pyroms.remapping.remap(src_12, wts_file, \
                                                  spval=spval)
                Mp, Lp = dst_grd.hgrid.mask_rho.shape

                dst_11_north = dst_11[Mp-1, 0:Lp]
                dst_22_north = dst_22[Mp-1, 0:Lp]
                dst_12_north = dst_12[Mp-1, 0:Lp]

                dst_11_south = dst_11[0, 0:Lp]
                dst_22_south = dst_22[0, 0:Lp]
                dst_12_south = dst_12[0, 0:Lp]

                dst_11_east = dst_11[0:Mp, Lp-1]
                dst_22_east = dst_22[0:Mp, Lp-1]
                dst_12_east = dst_12[0:Mp, Lp-1]

                dst_11_west = dst_11[0:Mp, 0]
                dst_22_west = dst_22[0:Mp, 0]
                dst_12_west = dst_12[0:Mp, 0]

                # rotate stress tensor
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__('rho_to_rho.nc'):
                        wts_file = wts_files[s]
                src_ang = srcgrd.hgrid.angle_rho[jjrange[0]:jjrange[1],iirange[0]:iirange[1]]
                src_angle = pyroms.remapping.remap(src_ang, wts_file)
                dst_angle = dst_grd.hgrid.angle_rho
                angle = dst_angle - src_angle
                cos_ang = np.cos(angle)
                sin_ang = np.sin(angle)
                Lp = cos_ang.shape[-1]
                Mp = cos_ang.shape[-2]
                print "Lp, Mp", Lp, Mp

                if rotate_sig:
                    # North
                    for i in range(Lp):
                        Qrot = [[cos_ang[Mp-1,i], sin_ang[Mp-1,i]],
                               [-sin_ang[Mp-1,i], cos_ang[Mp-1,i]]]
                        QrotT = [[cos_ang[Mp-1,i], -sin_ang[Mp-1,i]],
                                 [sin_ang[Mp-1,i],  cos_ang[Mp-1,i]]]
                        sig = [[dst_11_north[i], dst_12_north[i]],
                               [dst_12_north[i], dst_22_north[i]]]
                        sig_rot = np.dot(np.dot(Qrot, sig), QrotT)
                        dst_11_north[i] = sig_rot[0,0]
                        dst_12_north[i] = sig_rot[0,1]
                        dst_22_north[i] = sig_rot[1,1]

                    # South
                    for i in range(Lp):
                        Qrot = [[cos_ang[0,i], sin_ang[0,i]],
                               [-sin_ang[0,i], cos_ang[0,i]]]
                        QrotT = [[cos_ang[0,i], -sin_ang[0,i]],
                                 [sin_ang[0,i],  cos_ang[0,i]]]
                        sig = [[dst_11_south[i], dst_12_south[i]],
                               [dst_12_south[i], dst_22_south[i]]]
                        sig_rot = np.dot(np.dot(Qrot, sig), QrotT)
                        dst_11_south[i] = sig_rot[0,0]
                        dst_12_south[i] = sig_rot[0,1]
                        dst_22_south[i] = sig_rot[1,1]

                    # East
                    for j in range(Mp):
                        Qrot = [[cos_ang[j,Lp-1], sin_ang[j,Lp-1]],
                               [-sin_ang[j,Lp-1], cos_ang[j,Lp-1]]]
                        QrotT = [[cos_ang[j,Lp-1], -sin_ang[j,Lp-1]],
                                 [sin_ang[j,Lp-1],  cos_ang[j,Lp-1]]]
                        sig = [[dst_11_east[j], dst_12_east[j]],
                               [dst_12_east[j], dst_22_east[j]]]
                        sig_rot = np.dot(np.dot(Qrot, sig), QrotT)
                        dst_11_east[j] = sig_rot[0,0]
                        dst_12_east[j] = sig_rot[0,1]
                        dst_22_east[j] = sig_rot[1,1]

                    # West
                    for j in range(Mp):
                        Qrot = [[cos_ang[j,0], sin_ang[j,0]],
                               [-sin_ang[j,0], cos_ang[j,0]]]
                        QrotT = [[cos_ang[j,0], -sin_ang[j,0]],
                                 [sin_ang[j,0],  cos_ang[j,0]]]
                        sig = [[dst_11_west[j], dst_12_west[j]],
                               [dst_12_west[j], dst_22_west[j]]]
                        sig_rot = np.dot(np.dot(Qrot, sig), QrotT)
                        dst_11_west[j] = sig_rot[0,0]
                        dst_12_west[j] = sig_rot[0,1]
                        dst_22_west[j] = sig_rot[1,1]


                # spval
                idx_north = np.where(dst_grd.hgrid.mask_rho[-1,:] == 0)
                idx_south = np.where(dst_grd.hgrid.mask_rho[0,:] == 0)
                idx_east = np.where(dst_grd.hgrid.mask_rho[:,-1] == 0)
                idx_west = np.where(dst_grd.hgrid.mask_rho[:,0] == 0)

                dst_11_north[idx_north[0]] = spval
                dst_22_north[idx_north[0]] = spval
                dst_12_north[idx_north[0]] = spval
                dst_11_south[idx_south[0]] = spval
                dst_22_south[idx_south[0]] = spval
                dst_12_south[idx_south[0]] = spval
                dst_11_east[idx_east[0]] = spval
                dst_22_east[idx_east[0]] = spval
                dst_12_east[idx_east[0]] = spval
                dst_11_west[idx_west[0]] = spval
                dst_22_west[idx_west[0]] = spval
                dst_12_west[idx_west[0]] = spval

                # write data in destination file
                print 'write data in destination file'
                sid = '_west'
                varn = 'sig11'+str(sid)
                nc.variables[varn][nctidx] = dst_11_west
                varn = 'sig22'+str(sid)
                nc.variables[varn][nctidx] = dst_22_west
                varn = 'sig12'+str(sid)
                nc.variables[varn][nctidx] = dst_12_west

                sid = '_north'
                varn = 'sig11'+str(sid)
                nc.variables[varn][nctidx] = dst_11_north
                varn = 'sig22'+str(sid)
                nc.variables[varn][nctidx] = dst_22_north
                varn = 'sig12'+str(sid)
                nc.variables[varn][nctidx] = dst_12_north

                sid = '_east'
                varn = 'sig11'+str(sid)
                nc.variables[varn][nctidx] = dst_11_east
                varn = 'sig22'+str(sid)
                nc.variables[varn][nctidx] = dst_22_east
                varn = 'sig12'+str(sid)
                nc.variables[varn][nctidx] = dst_12_east

                sid = '_south'
                varn = 'sig11'+str(sid)
                nc.variables[varn][nctidx] = dst_11_south
                varn = 'sig22'+str(sid)
                nc.variables[varn][nctidx] = dst_22_south
                varn = 'sig12'+str(sid)
                nc.variables[varn][nctidx] = dst_12_south

            nctidx = nctidx + 1
        # close files here? how?
 
    # close destination file
    nc.close()

    return
Ejemplo n.º 5
0
def remap_bio(argdict, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'):
    
    # NWGOA3 grid sub-sample
    xrange=src_grd.xrange; yrange=src_grd.yrange

    src_varname = argdict['tracer']
    tracer = src_varname
    src_file = argdict['file']
    units = argdict['units']
    longname = argdict['longname']

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'

    # create clim file
    dst_file = tracer + '.nc'
    dst_file = dst_dir + dst_grd.name + '_ic_bio_' + dst_file
    print 'Creating clim file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open clim file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file) 
    src_var = cdf.variables[src_varname]

    tmp = cdf.variables['time'][:]
    if len(tmp) > 1:
        print 'error : multiple frames in input file' ; exit()
    else:
        time = tmp[0]

    # to be in sync with physics, add +0.5 day
    #time = time + 0.5
    # time will be given by physics anyway
    time = 0.

    #get missing value
    spval = src_var._FillValue

    # determine variable dimension
    ndim = len(src_var.dimensions) - 1

    # NWGOA3 grid sub-sample
    if ndim == 3:
        src_var = src_var[0,:, yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]
    elif ndim == 2:
        src_var = src_var[0,yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]


    Bpos = 't'
    Cpos = 'rho'
    z = src_grd.z_t
    Mp, Lp = dst_grd.hgrid.mask_rho.shape
    wts_file = 'remap_weights_ESM2M_to_NWGOA3_bilinear_t_to_rho.nc'
    dst_varname = tracer
    dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
    long_name = longname
    field = tracer + ', scalar, series'
    units = units

    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)


    # create variable in file
    print 'Creating variable', dst_varname
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field
    #nc.variables[dst_varname_north]._FillValue = spval


    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name

    if ndim == 3:
        # flood the grid
        print 'flood the grid'
        src_varz = pyroms_toolbox.BGrid_GFDL.flood(src_var, src_grd, Bpos=Bpos, spval=spval, \
                                dmax=dmax, cdepth=cdepth, kk=kk)
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print 'vertical interpolation from standard z level to sigma'
        dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \
                          dst_grd, Cpos=Cpos, spval=spval, flood=False)
    else:
        dst_var = dst_varz

    # write data in destination file
    print 'write data in destination file\n'
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname][0] = dst_var

    # close file
    nc.close()
    cdf.close()

    if src_varname == 'eta':
        return dst_varz
Ejemplo n.º 6
0
def remap_uv(src_file, src_grd, dst_grd, dxy=20, cdepth=0, kk=0, dst_dir="./"):

    # get time
    nctime.long_name = "time"
    nctime.units = "days since 1900-01-01 00:00:00"
    # time reference "days since 1900-01-01 00:00:00"
    #    ref = datetime(1900, 1, 1, 0, 0, 0)
    #    ref = date2num(ref)
    #    tag = src_file.rsplit('/')[-1].rsplit('_')[-1].rsplit('-')[0]
    #    year = int(tag[:4])
    #    month = int(tag[4:6])
    #    day = int(tag[6:])
    #    time = datetime(year, month, day, 0, 0, 0)
    #    time = date2num(time)
    #    time = time - ref
    #    time = time + 2.5 # 5-day average
    cdf = netCDF.Dataset(src_file)
    src_varu = cdf.variables["u"][0]
    src_varv = cdf.variables["v"][0]
    time = cdf.variables["ocean_time"][0]

    # get dimensions
    Mp, Lp = dst_grd.hgrid.mask_rho.shape

    # create destination file
    dst_file = src_file.rsplit("/")[-1]
    dst_fileu = dst_dir + dst_file[:-3] + "_u_ic_" + dst_grd.name + ".nc"
    print "\nCreating destination file", dst_fileu
    if os.path.exists(dst_fileu) is True:
        os.remove(dst_fileu)
    pyroms_toolbox.nc_create_roms_file(dst_fileu, dst_grd, nctime)
    dst_filev = dst_dir + dst_file[:-3] + "_v_ic_" + dst_grd.name + ".nc"
    print "Creating destination file", dst_filev
    if os.path.exists(dst_filev) is True:
        os.remove(dst_filev)
    pyroms_toolbox.nc_create_roms_file(dst_filev, dst_grd, nctime)

    # open destination file
    ncu = netCDF.Dataset(dst_fileu, "a", format="NETCDF3_64BIT")
    ncv = netCDF.Dataset(dst_filev, "a", format="NETCDF3_64BIT")

    # load var
    cdf = netCDF.Dataset(src_file)
    src_varu = cdf.variables["u"]
    src_varv = cdf.variables["v"]

    # get missing value
    spval = src_varu._FillValue
    src_varu = src_varu[0]
    src_varv = src_varv[0]

    # get weights file
    wts_file = "remap_weights_GLBa0.08_to_ARCTIC2_bilinear_t_to_rho.nc"

    # build intermediate zgrid
    zlevel = -src_grd.z_t[::-1, 0, 0]
    nzlevel = len(zlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + "_Z", dst_grd.hgrid, dst_zcoord)

    # create variable in destination file
    print "Creating variable u"
    ncu.createVariable("u", "f8", ("ocean_time", "s_rho", "eta_u", "xi_u"), fill_value=spval)
    ncu.variables["u"].long_name = "3D u-momentum component"
    ncu.variables["u"].units = "meter second-1"
    ncu.variables["u"].field = "u-velocity, scalar, series"
    # create variable in destination file
    print "Creating variable ubar"
    ncu.createVariable("ubar", "f8", ("ocean_time", "eta_u", "xi_u"), fill_value=spval)
    ncu.variables["ubar"].long_name = "2D u-momentum component"
    ncu.variables["ubar"].units = "meter second-1"
    ncu.variables["ubar"].field = "ubar-velocity,, scalar, series"

    print "Creating variable v"
    ncv.createVariable("v", "f8", ("ocean_time", "s_rho", "eta_v", "xi_v"), fill_value=spval)
    ncv.variables["v"].long_name = "3D v-momentum component"
    ncv.variables["v"].units = "meter second-1"
    ncv.variables["v"].field = "v-velocity, scalar, series"
    print "Creating variable vbar"
    ncv.createVariable("vbar", "f8", ("ocean_time", "eta_v", "xi_v"), fill_value=spval)
    ncv.variables["vbar"].long_name = "2D v-momentum component"
    ncv.variables["vbar"].units = "meter second-1"
    ncv.variables["vbar"].field = "vbar-velocity,, scalar, series"

    # remaping
    print "remapping and rotating u and v from", src_grd.name, "to", dst_grd.name
    print "time =", time

    # flood the grid
    print "flood the grid"
    src_uz = pyroms_toolbox.Grid_HYCOM.flood_fast(
        src_varu, src_grd, pos="t", spval=spval, dxy=dxy, cdepth=cdepth, kk=kk
    )
    src_vz = pyroms_toolbox.Grid_HYCOM.flood_fast(
        src_varv, src_grd, pos="t", spval=spval, dxy=dxy, cdepth=cdepth, kk=kk
    )

    # horizontal interpolation using scrip weights
    print "horizontal interpolation using scrip weights"
    dst_uz = pyroms.remapping.remap(src_uz, wts_file, spval=spval)
    dst_vz = pyroms.remapping.remap(src_vz, wts_file, spval=spval)

    # vertical interpolation from standard z level to sigma
    print "vertical interpolation from standard z level to sigma"
    dst_u = pyroms.remapping.z2roms(dst_uz[::-1, :, :], dst_grdz, dst_grd, Cpos="rho", spval=spval, flood=False)
    dst_v = pyroms.remapping.z2roms(dst_vz[::-1, :, :], dst_grdz, dst_grd, Cpos="rho", spval=spval, flood=False)

    # rotate u,v fields
    src_angle = pyroms.remapping.remap(
        src_grd.angle, "remap_weights_GLBa0.08_to_ARCTIC2_bilinear_t_to_rho.nc", spval=spval
    )

    dst_angle = dst_grd.hgrid.angle_rho
    angle = dst_angle - src_angle
    angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))
    U = dst_u + dst_v * 1j
    eitheta = np.exp(-1j * angle[:, :, :])
    U = U * eitheta
    dst_u = np.real(U)
    dst_v = np.imag(U)

    # move back to u,v points
    dst_u = 0.5 * (dst_u[:, :, :-1] + dst_u[:, :, 1:])
    dst_v = 0.5 * (dst_v[:, :-1, :] + dst_v[:, 1:, :])

    # spval
    idxu = np.where(dst_grd.hgrid.mask_u == 0)
    idxv = np.where(dst_grd.hgrid.mask_v == 0)
    for n in range(dst_grd.vgrid.N):
        dst_u[n, idxu[0], idxu[1]] = spval
        dst_v[n, idxv[0], idxv[1]] = spval

    # compute depth average velocity ubar and vbar
    # get z at the right position
    z_u = 0.5 * (dst_grd.vgrid.z_w[0, :, :, :-1] + dst_grd.vgrid.z_w[0, :, :, 1:])
    z_v = 0.5 * (dst_grd.vgrid.z_w[0, :, :-1, :] + dst_grd.vgrid.z_w[0, :, 1:, :])

    dst_ubar = np.zeros((dst_u.shape[1], dst_u.shape[2]))
    dst_vbar = np.zeros((dst_v.shape[1], dst_v.shape[2]))

    for i in range(dst_ubar.shape[1]):
        for j in range(dst_ubar.shape[0]):
            dst_ubar[j, i] = (dst_u[:, j, i] * np.diff(z_u[:, j, i])).sum() / -z_u[0, j, i]

    for i in range(dst_vbar.shape[1]):
        for j in range(dst_vbar.shape[0]):
            dst_vbar[j, i] = (dst_v[:, j, i] * np.diff(z_v[:, j, i])).sum() / -z_v[0, j, i]

    # spval
    dst_ubar[idxu[0], idxu[1]] = spval
    dst_vbar[idxv[0], idxv[1]] = spval

    # write data in destination file
    print "write data in destination file"
    ncu.variables["ocean_time"][0] = time
    ncu.variables["u"][0] = dst_u
    ncu.variables["ubar"][0] = dst_ubar

    ncv.variables["ocean_time"][0] = time
    ncv.variables["v"][0] = dst_v
    ncv.variables["vbar"][0] = dst_vbar

    # close destination file
    ncu.close()
    ncv.close()
Ejemplo n.º 7
0
def remap(src_file, src_varname, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'):
    
    # YELLOW grid sub-sample
    xrange=(225, 275); yrange=(190, 240)

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
    ref = datetime(1900, 1, 1, 0, 0, 0)
    ref = date2num(ref)
    tag = src_file.rsplit('/')[-1].rsplit('_')[-1].rsplit('-')[0]
    year = int(tag[:4])
    month = int(tag[4:6])
    day = int(tag[6:])
    time = datetime(year, month, day, 0, 0, 0)
    time = date2num(time)
    time = time - ref
    time = time + 2.5 # 5-day average

    # create IC file
    dst_file = src_file.rsplit('/')[-1]
    dst_file = dst_dir + dst_file[:-4] + '_' + src_varname + '_ic_' + dst_grd.name + '.nc'
    print '\nCreating file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open IC file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_CLASSIC')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    #get missing value
    spval = src_var._FillValue

    # determine variable dimension
    ndim = len(src_var.dimensions)

    # YELLOW grid sub-sample
    if ndim == 3:
        src_var = src_var[:, yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]
    elif ndim == 2:
        src_var = src_var[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]


    if src_varname == 'ssh':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_SODA_2.1.6_to_YELLOW_bilinear_t_to_rho.nc'
        dst_varname = 'zeta'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'free-surface'
        units = 'meter'
        field = 'free-surface, scalar, series'
    elif src_varname == 'temp':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_SODA_2.1.6_to_YELLOW_bilinear_t_to_rho.nc'
        dst_varname = 'temp'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'potential temperature'
        units = 'Celsius'
        field = 'temperature, scalar, series'
    elif src_varname == 'salt':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_SODA_2.1.6_to_YELLOW_bilinear_t_to_rho.nc'
        dst_varname = 'salt'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'salinity'
        units = 'PSU'
        field = 'salinity, scalar, series'
    else:
        raise ValueError, 'Undefined src_varname'


    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1,0,0]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)


    # create variable in file
    print 'Creating variable', dst_varname
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field
    #nc.variables[dst_varname_north]._FillValue = spval


    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name
    print 'time =', time


    if ndim == 3:
        # flood the grid
        print 'flood the grid'
        src_varz = pyroms_toolbox.BGrid_SODA.flood(src_var, src_grd, Bpos=Bpos, spval=spval, \
                                dmax=dmax, cdepth=cdepth, kk=kk)
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, \
                                          spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print 'vertical interpolation from standard z level to sigma'
        dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \
                          dst_grd, Cpos=Cpos, spval=spval, flood=False)
    else:
        dst_var = dst_varz

    # write data in destination file
    print 'write data in destination file'
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname][0] = dst_var

    # close destination file
    nc.close()

    if src_varname == 'SSH':
        return dst_varz
Ejemplo n.º 8
0
def remap_bio_woa(argdict,
                  src_grd,
                  dst_grd,
                  dmax=0,
                  cdepth=0,
                  kk=0,
                  dst_dir='./'):

    # NWGOA3 grid sub-sample
    xrange = src_grd.xrange
    yrange = src_grd.yrange

    src_varname = argdict['tracer']
    tracer = src_varname
    src_file = argdict['file']
    units = argdict['units']
    longname = argdict['longname']
    nframe = argdict['frame']

    if src_varname == 'sio4':
        src_varname = 'si'

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'

    # create clim file
    dst_file = tracer + '.nc'
    dst_file = dst_dir + dst_grd.name + '_clim_bio_' + dst_file
    print('Creating clim file', dst_file)
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open clim file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    # correct time to some classic value
    days_in_month = np.array(
        [31, 28.25, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])
    time = days_in_month[:nframe].sum() + days_in_month[nframe] / 2.

    #get missing value
    spval = src_var._FillValue

    spval2 = -1.0e+10

    # determine variable dimension
    ndim = len(src_var.dimensions) - 1

    # NWGOA3 grid sub-sample
    if ndim == 3:
        src_var = src_var[nframe, :, yrange[0]:yrange[1] + 1,
                          xrange[0]:xrange[1] + 1]
    elif ndim == 2:
        src_var = src_var[nframe, yrange[0]:yrange[1] + 1,
                          xrange[0]:xrange[1] + 1]

    if tracer == 'no3':
        unit_conversion = 1. / 1e6 / 1.035
    elif tracer == 'po4':
        unit_conversion = 1. / 1e6 / 1.035
    elif tracer == 'o2':
        unit_conversion = 1. / 1035 / 22391.6 * 1000.0
    elif tracer == 'sio4':
        unit_conversion = 1. / 1e6 / 1.035

    src_var = src_var * unit_conversion

    Bpos = 't'
    Cpos = 'rho'
    z = src_grd.z_t
    Mp, Lp = dst_grd.hgrid.mask_rho.shape
    wts_file = 'remap_weights_ESM2M_to_NWGOA3_bilinear_t_to_rho.nc'
    dst_varname = tracer
    dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
    long_name = longname
    field = tracer + ', scalar, series'
    units = units

    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel,
                                               nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + '_Z', dst_grd.hgrid,
                                         dst_zcoord)

    # create variable in file
    print('Creating variable', dst_varname)
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval2)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field
    #nc.variables[dst_varname_north]._FillValue = spval

    # remapping
    print('remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name)

    if ndim == 3:
        # flood the grid
        print('flood the grid')
        src_varz = pyroms_toolbox.BGrid_GFDL.flood(src_var, src_grd, Bpos=Bpos, spval=spval, \
                                dmax=dmax, cdepth=cdepth, kk=kk)
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print('horizontal interpolation using scrip weights')
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print('vertical interpolation from standard z level to sigma')
        dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \
                          dst_grd, Cpos=Cpos, spval=spval, flood=False)
    else:
        dst_var = dst_varz

    if ndim == 3:
        for kz in np.arange(dst_grd.vgrid.N):
            tmp = dst_var[kz, :, :].copy()
            tmp[np.where(dst_grd.hgrid.mask_rho == 0)] = spval2
            dst_var[kz, :, :] = tmp.copy()

    # write data in destination file
    print('write data in destination file\n')
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname][0] = dst_var

    # close file
    nc.close()
    cdf.close()

    if src_varname == 'eta':
        return dst_varz
Ejemplo n.º 9
0
def remapping(varname, srcfile, wts_files, srcgrd, dstgrd, \
              rotate_uv=False, trange=None, irange=None, jrange=None, \
              dstdir='./' ,zlevel=None, dmax=0, cdepth=0, kk=0, \
              uvar='u', vvar='v', rotate_part=False):
    '''
    A remapping function to go from a ROMS grid to another ROMS grid.
    If the u/v variables need to be rotated, it must be called for each
    u/v pair (such as u/v, uice/vice).
    '''

    # get input and output grid
    if type(srcgrd).__name__ == 'ROMS_Grid':
        srcgrd = srcgrd
    else:
        srcgrd = pyroms.grid.get_ROMS_grid(srcgrd)
    if type(dstgrd).__name__ == 'ROMS_Grid':
        dstgrd = dstgrd
    else:
        dstgrd = pyroms.grid.get_ROMS_grid(dstgrd)

    # build intermediate zgrid
    if zlevel is None:
        zlevel = np.array([-7500.,-7000.,-6500.,-6000.,-5500.,-5000.,\
                   -4500.,-4000.,-3500.,-3000.,-2500.,-2000.,-1750.,\
                   -1500.,-1250.,-1000.,-900.,-800.,-700.,-600.,-500.,\
                   -400.,-300.,-250.,-200.,-175.,-150.,-125.,-100.,-90.,\
                   -80.,-70.,-60.,-50.,-45.,-40.,-35.,-30.,-25.,-20.,-17.5,\
                   -15.,-12.5,-10.,-7.5,-5.,-2.5,0.])
    else:
        zlevel = np.sort(-abs(zlevel))
    nzlevel = len(zlevel)
    src_zcoord = pyroms.vgrid.z_coordinate(srcgrd.vgrid.h, zlevel, nzlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dstgrd.vgrid.h, zlevel, nzlevel)
    srcgrdz = pyroms.grid.ROMS_Grid(srcgrd.name + '_Z', srcgrd.hgrid,
                                    src_zcoord)
    dstgrdz = pyroms.grid.ROMS_Grid(dstgrd.name + '_Z', dstgrd.hgrid,
                                    dst_zcoord)

    # varname argument
    if type(varname).__name__ == 'list':
        nvar = len(varname)
    elif type(varname).__name__ == 'str':
        varname = [varname]
        nvar = len(varname)
    else:
        raise ValueError('varname must be a str or a list of str')

    # if we're working on u and v, we'll compute ubar,vbar afterwards
    compute_ubar = False
    if (varname.__contains__('u') == 1 and varname.__contains__('v') == 1) or \
       (varname.__contains__('u_eastward') == 1 and varname.__contains__('v_northward') == 1):
        compute_ubar = True
        print('ubar/vbar to be computed from u/v')
        if varname.__contains__('ubar'):
            varname.remove('ubar')
            nvar = nvar - 1
        if varname.__contains__('vbar'):
            varname.remove('vbar')
            nvar = nvar - 1

    # if rotate_uv=True, check that u and v are in varname
    if rotate_uv is True:
        if varname.__contains__(uvar) == 0 or varname.__contains__(vvar) == 0:
            raise Warning('varname must include uvar and vvar in order to' \
                   + ' rotate the velocity field')
        else:
            varname.remove(uvar)
            varname.remove(vvar)
            nvar = nvar - 2

    # srcfile argument
    print('files', srcfile)
    if type(srcfile).__name__ == 'list':
        nfile = len(srcfile)
    elif type(srcfile).__name__ == 'str':
        srcfile = sorted(glob.glob(srcfile))
        nfile = len(srcfile)
    else:
        raise ValueError('src_srcfile must be a str or a list of str')
    print('number of files', nfile, srcfile)

    # get wts_file
    if type(wts_files).__name__ == 'str':
        wts_files = sorted(glob.glob(wts_files))

    nctidx = 0
    # loop over the srcfile
    for nf in range(nfile):
        print('Working with file', srcfile[nf], '...')

        # get time
        ocean_time = pyroms.utility.get_nc_var('ocean_time', srcfile[nf])
        ntime = len(ocean_time[:])

        # trange argument
        if trange is None:
            trange = list(range(ntime))

        # create destination file
        if nctidx == 0:
            dstfile = dstdir + os.path.basename(srcfile[nf])[:-3] + '_' \
                     + dstgrd.name + '.nc'
            if os.path.exists(dstfile) is False:
                print('Creating destination file', dstfile)
                pyroms_toolbox.nc_create_roms_file(dstfile, dstgrd, ocean_time)

            # open destination file
            nc = netCDF.Dataset(dstfile, 'a', format='NETCDF3_64BIT')

        # loop over time
        for nt in trange:

            nc.variables['ocean_time'][nctidx] = ocean_time[nt]

            # loop over variable
            for nv in range(nvar):
                print(' ')
                print('remapping', varname[nv], 'from', srcgrd.name, \
                      'to', dstgrd.name)
                print('time =', ocean_time[nt])

                # get source data
                src_var = pyroms.utility.get_nc_var(varname[nv], srcfile[nf])

                # determine variable dimension
                ndim = len(src_var.dimensions) - 1

                # get spval
                try:
                    spval = src_var._FillValue
                except:
                    #                    raise Warning, 'Did not find a _FillValue attribute.'
                    print('Warning, Did not find a _FillValue attribute.')
                    spval = 1.e37

                # irange
                if irange is None:
                    iirange = (0, src_var.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0, src_var.shape[-2])
                else:
                    jjrange = jrange

                # determine where on the C-grid these variable lies
                if src_var.dimensions[2].find('_rho') != -1:
                    Cpos = 'rho'
                if src_var.dimensions[2].find('_u') != -1:
                    Cpos = 'u'
                if src_var.dimensions[2].find('_v') != -1:
                    Cpos = 'v'
                if src_var.dimensions[1].find('_w') != -1:
                    Cpos = 'w'

                print('Arakawa C-grid position is', Cpos)

                # create variable in _destination file
                if nctidx == 0:
                    print('Creating variable', varname[nv])
                    nc.createVariable(varname[nv],
                                      'f8',
                                      src_var.dimensions,
                                      fill_value=spval)
                    nc.variables[varname[nv]].long_name = src_var.long_name
                    try:
                        nc.variables[varname[nv]].units = src_var.units
                    except:
                        print(varname[nv] + ' has no units')
                    nc.variables[varname[nv]].time = src_var.time
                    nc.variables[varname[nv]].coordinates = \
                        src_var.coordinates
                    nc.variables[varname[nv]].field = src_var.field

                # get the right remap weights file
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__(Cpos + '_to_' + Cpos + '.nc'):
                        wts_file = wts_files[s]
                        break
                    else:
                        if s == len(wts_files) - 1:
                            raise ValueError(
                                'Did not find the appropriate remap weights file'
                            )

                if ndim == 3:
                    # vertical interpolation from sigma to standard z level
                    print(
                        'vertical interpolation from sigma to standard z level'
                    )
                    src_varz = pyroms.remapping.roms2z( \
                                 src_var[nt,:,jjrange[0]:jjrange[1],iirange[0]:iirange[1]], \
                                 srcgrd, srcgrdz, Cpos=Cpos, spval=spval, \
                                 irange=iirange, jrange=jjrange)

                    # flood the grid
                    print('flood the grid')
                    src_varz = pyroms.remapping.flood(src_varz, srcgrdz, Cpos=Cpos, \
                                      irange=iirange, jrange=jjrange, spval=spval, \
                                      dmax=dmax, cdepth=cdepth, kk=kk)

                else:
                    src_varz = src_var[nt, jjrange[0]:jjrange[1],
                                       iirange[0]:iirange[1]]

                # horizontal interpolation using scrip weights
                print('horizontal interpolation using scrip weights')
                dst_varz = pyroms.remapping.remap(src_varz, wts_file, \
                                                  spval=spval)

                if ndim == 3:
                    # vertical interpolation from standard z level to sigma
                    print(
                        'vertical interpolation from standard z level to sigma'
                    )
                    dst_var = pyroms.remapping.z2roms(dst_varz, dstgrdz, dstgrd, \
                                     Cpos=Cpos, spval=spval, flood=False)
                else:
                    dst_var = dst_varz

                if varname[nv] == 'u':
                    dst_u = dst_var
                if varname[nv] == 'v':
                    dst_v = dst_var

                # write data in destination file
                print('write data in destination file')
                nc.variables[varname[nv]][nctidx] = dst_var

            # rotate the velocity field if requested
            if rotate_uv is True:
                print(' ')
                print('remapping and rotating', uvar, 'and', vvar, 'from', \
                      srcgrd.name, 'to', dstgrd.name)

                # get source data
                src_u = pyroms.utility.get_nc_var(uvar, srcfile[nf])
                src_v = pyroms.utility.get_nc_var(vvar, srcfile[nf])

                # get spval
                try:
                    spval = src_v._FillValue
                except:
                    raise Warning('Did not find a _FillValue attribute.')

                if rotate_part:
                    ndim = len(src_u.dimensions) - 1
                    ind = uvar.find('_eastward')
                    uvar_out = uvar[0:ind]
                    print("Warning: renaming uvar to", uvar_out)
                    #                   print("uvar dims:", src_u.dimensions)
                    ind = vvar.find('_northward')
                    vvar_out = vvar[0:ind]
                    print("Warning: renaming vvar to", vvar_out)
                    #                   print("vvar dims:", src_v.dimensions)
                    if ndim == 3:
                        dimens_u = ['ocean_time', 's_rho', 'eta_u', 'xi_u']
                        dimens_v = ['ocean_time', 's_rho', 'eta_v', 'xi_v']
                    else:
                        dimens_u = ['ocean_time', 'eta_u', 'xi_u']
                        dimens_v = ['ocean_time', 'eta_v', 'xi_v']

                else:
                    dimens_u = [i for i in src_u.dimensions]
                    dimens_v = [i for i in src_v.dimensions]
                    uvar_out = uvar
                    vvar_out = vvar

                # create variable in destination file
                if nctidx == 0:
                    print('Creating variable ' + uvar_out)
                    nc.createVariable(uvar_out,
                                      'f8',
                                      dimens_u,
                                      fill_value=spval)
                    nc.variables[uvar_out].long_name = src_u.long_name
                    nc.variables[uvar_out].units = src_u.units
                    nc.variables[uvar_out].time = src_u.time
                    nc.variables[uvar_out].coordinates = \
                           str(dimens_u.reverse())
                    nc.variables[uvar_out].field = src_u.field
                    print('Creating variable ' + vvar_out)
                    nc.createVariable(vvar_out,
                                      'f8',
                                      dimens_v,
                                      fill_value=spval)
                    nc.variables[vvar_out].long_name = src_v.long_name
                    nc.variables[vvar_out].units = src_v.units
                    nc.variables[vvar_out].time = src_v.time
                    nc.variables[vvar_out].coordinates = \
                           str(dimens_v.reverse())
                    nc.variables[vvar_out].field = src_v.field

                # get the right remap weights file
                if rotate_part:
                    for s in range(len(wts_files)):
                        if wts_files[s].__contains__('rho_to_rho.nc'):
                            wts_file_u = wts_files[s]
                            wts_file_v = wts_files[s]
                    Cpos_u = 'rho'
                    Cpos_v = 'rho'
                else:
                    for s in range(len(wts_files)):
                        if wts_files[s].__contains__('u_to_rho.nc'):
                            wts_file_u = wts_files[s]
                        if wts_files[s].__contains__('v_to_rho.nc'):
                            wts_file_v = wts_files[s]
                    Cpos_u = 'u'
                    Cpos_v = 'v'

                # get the right ranges
                if rotate_part:
                    # irange
                    if irange is None:
                        iirange = (0, src_u.shape[-1])
                    else:
                        iirange = irange
                    # jrange
                    if jrange is None:
                        jjrange = (0, src_u.shape[-2])
                    else:
                        jjrange = jrange
                else:
                    # irange
                    if irange is None:
                        iirange = (0, src_u.shape[-1])
                    else:
                        iirange = (irange[0], irange[1] - 1)
                    # jrange
                    if jrange is None:
                        jjrange = (0, src_u.shape[-2])
                    else:
                        jjrange = jrange

                # vertical interpolation from sigma to standard z level

                ndim = len(src_v.dimensions) - 1
                if ndim == 3:
                    print(
                        'vertical interpolation from sigma to standard z level'
                    )
                    src_uz = pyroms.remapping.roms2z( \
                            src_u[nt,:,jjrange[0]:jjrange[1],iirange[0]:iirange[1]], \
                            srcgrd, srcgrdz, Cpos=Cpos_u, spval=spval, \
                            irange=iirange, jrange=jjrange)
                    # flood the grid
                    print('flood the u grid')
                    src_uz = pyroms.remapping.flood(src_uz, srcgrdz, Cpos=Cpos_u, \
                                  irange=iirange, jrange=jjrange, \
                                  spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
                else:
                    src_uz = src_u[nt, jjrange[0]:jjrange[1],
                                   iirange[0]:iirange[1]]
                    src_uz = pyroms.remapping.flood2d(src_uz, srcgrdz, Cpos=Cpos_u, \
                                      irange=iirange, jrange=jjrange, spval=spval, \
                                      dmax=dmax)

                # get the right ranges
                if rotate_part:
                    # irange
                    if irange is None:
                        iirange = (0, src_v.shape[-1])
                    else:
                        iirange = irange
                    # jrange
                    if jrange is None:
                        jjrange = (0, src_v.shape[-2])
                    else:
                        jjrange = jrange
                else:
                    # irange
                    if irange is None:
                        iirange = (0, src_v.shape[-1])
                    else:
                        iirange = irange
                    # jrange
                    if jrange is None:
                        jjrange = (0, src_v.shape[-2])
                    else:
                        jjrange = (jrange[0], jrange[1] - 1)

                if ndim == 3:
                    src_vz = pyroms.remapping.roms2z( \
                            src_v[nt,:,jjrange[0]:jjrange[1],iirange[0]:iirange[1]], \
                            srcgrd, srcgrdz, Cpos=Cpos_v, spval=spval, \
                            irange=iirange, jrange=jjrange)

                    # flood the grid
                    print('flood the v grid')
                    src_vz = pyroms.remapping.flood(src_vz, srcgrdz, Cpos=Cpos_v, \
                                  irange=iirange, jrange=jjrange, \
                                  spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
                else:
                    src_vz = src_v[nt, jjrange[0]:jjrange[1],
                                   iirange[0]:iirange[1]]
                    src_vz = pyroms.remapping.flood2d(src_vz, srcgrdz, Cpos=Cpos_v, \
                                      irange=iirange, jrange=jjrange, spval=spval, \
                                      dmax=dmax)

                # horizontal interpolation using scrip weights
                print('horizontal interpolation using scrip weights')
                dst_uz = pyroms.remapping.remap(src_uz, wts_file_u, \
                                                  spval=spval)
                dst_vz = pyroms.remapping.remap(src_vz, wts_file_v, \
                                                  spval=spval)

                if ndim == 3:
                    # vertical interpolation from standard z level to sigma
                    print(
                        'vertical interpolation from standard z level to sigma'
                    )
                    dst_u = pyroms.remapping.z2roms(dst_uz, dstgrdz, dstgrd, \
                                 Cpos='rho', spval=spval, flood=False)
                    dst_v = pyroms.remapping.z2roms(dst_vz, dstgrdz, dstgrd, \
                                 Cpos='rho', spval=spval, flood=False)
                else:
                    dst_u = dst_uz
                    dst_v = dst_vz

                # rotate u,v fields
                if rotate_part:
                    src_angle = np.zeros(dstgrd.hgrid.angle_rho.shape)
                else:
                    for s in range(len(wts_files)):
                        if wts_files[s].__contains__('rho_to_rho.nc'):
                            wts_file = wts_files[s]
                    src_ang = srcgrd.hgrid.angle_rho[jjrange[0]:jjrange[1],
                                                     iirange[0]:iirange[1]]
                    src_angle = pyroms.remapping.remap(src_ang, wts_file)

                dst_angle = dstgrd.hgrid.angle_rho
                angle = dst_angle - src_angle
                if ndim == 3:
                    angle = np.tile(angle, (dstgrd.vgrid.N, 1, 1))

                U = dst_u + dst_v * 1j
                eitheta = np.exp(-1j * angle)
                U = U * eitheta

                dst_u = np.real(U)
                dst_v = np.imag(U)

                # spval
                idxu = np.where(dstgrd.hgrid.mask_u == 0)
                idxv = np.where(dstgrd.hgrid.mask_v == 0)

                # move back to u,v points
                if ndim == 3:
                    dst_u = 0.5 * (dst_u[:, :, :-1] + dst_u[:, :, 1:])
                    dst_v = 0.5 * (dst_v[:, :-1, :] + dst_v[:, 1:, :])
                    for n in range(dstgrd.vgrid.N):
                        dst_u[n, idxu[0], idxu[1]] = spval
                        dst_v[n, idxv[0], idxv[1]] = spval
                else:
                    dst_u = 0.5 * (dst_u[:, :-1] + dst_u[:, 1:])
                    dst_v = 0.5 * (dst_v[:-1, :] + dst_v[1:, :])
                    dst_u[idxu[0], idxu[1]] = spval
                    dst_v[idxv[0], idxv[1]] = spval

                # write data in destination file
                print('write data in destination file')
                nc.variables[uvar_out][nctidx] = dst_u
                nc.variables[vvar_out][nctidx] = dst_v

            if compute_ubar:
                if nctidx == 0:
                    print('Creating variable ubar')
                    nc.createVariable('ubar', 'f8', \
                         ('ocean_time', 'eta_u', 'xi_u'), fill_value=spval)
                    nc.variables['ubar'].long_name = '2D u-momentum component'
                    nc.variables['ubar'].units = 'meter second-1'
                    nc.variables['ubar'].time = 'ocean_time'
                    nc.variables['ubar'].coordinates = 'xi_u eta_u ocean_time'
                    nc.variables[
                        'ubar'].field = 'ubar-velocity,, scalar, series'
                    print('Creating variable vbar')
                    nc.createVariable('vbar', 'f8', \
                         ('ocean_time', 'eta_v', 'xi_v'), fill_value=spval)
                    nc.variables['vbar'].long_name = '2D v-momentum component'
                    nc.variables['vbar'].units = 'meter second-1'
                    nc.variables['vbar'].time = 'ocean_time'
                    nc.variables['vbar'].coordinates = 'xi_v eta_v ocean_time'
                    nc.variables[
                        'vbar'].field = 'vbar-velocity,, scalar, series'

                # compute depth average velocity ubar and vbar
                # get z at the right position
                z_u = 0.5 * (dstgrd.vgrid.z_w[0,:,:,:-1] + \
                        dstgrd.vgrid.z_w[0,:,:,1:])
                z_v = 0.5 * (dstgrd.vgrid.z_w[0,:,:-1,:] + \
                        dstgrd.vgrid.z_w[0,:,1:,:])

                dst_ubar = np.zeros((dst_u.shape[1], dst_u.shape[2]))
                dst_vbar = np.zeros((dst_v.shape[1], dst_v.shape[2]))

                for i in range(dst_ubar.shape[1]):
                    for j in range(dst_ubar.shape[0]):
                        dst_ubar[j,i] = (dst_u[:,j,i] * \
                                np.diff(z_u[:,j,i])).sum() / -z_u[0,j,i]

                for i in range(dst_vbar.shape[1]):
                    for j in range(dst_vbar.shape[0]):
                        dst_vbar[j,i] = (dst_v[:,j,i] * \
                                np.diff(z_v[:,j,i])).sum() / -z_v[0,j,i]

                # spval
                idxu = np.where(dstgrd.hgrid.mask_u == 0)
                idxv = np.where(dstgrd.hgrid.mask_v == 0)
                dst_ubar[idxu[0], idxu[1]] = spval
                dst_vbar[idxv[0], idxv[1]] = spval

                nc.variables['ubar'][nctidx] = dst_ubar
                nc.variables['vbar'][nctidx] = dst_vbar

            nctidx = nctidx + 1
            print('ADDING to nctidx ', nctidx)
            nc.sync()

    # close destination file
    nc.close()

    return
Ejemplo n.º 10
0
def remap(src_varname,
          src_file,
          src_grd,
          dst_grd,
          dst_file,
          dmax=0,
          cdepth=0,
          kk=0,
          dst_dir='./'):

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'

    # create tide file
    print '\nCreating tide file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open tide file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    # load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    # get missing value
    spval = src_var.missing_value

    if src_varname == 'h_re':
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_t_to_rho.nc'
        dst_varname = 'h_re'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'tidal constituent amplitude (real)'
        units = 'meter'
        field = 'free-surface, scalar, series'
    if src_varname == 'h_im':
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_t_to_rho.nc'
        dst_varname = 'h_im'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'tidal constituent amplitude (imaginary)'
        units = 'meter'
        field = 'free-surface, scalar, series'

    if src_varname == 'u_re':
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_u_to_rho.nc'
        dst_varname = 'h_re'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'tidal constituent x-velocity (real)'
        units = 'meter per second'
        field = 'x-velocity, scalar, series'
    if src_varname == 'u_im':
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_u_to_rho.nc'
        dst_varname = 'u_im'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'tidal constituent x-velocity (imaginary)'
        units = 'meter per second'
        field = 'x-velocity, scalar, series'

    if src_varname == 'v_re':
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_v_to_rho.nc'
        dst_varname = 'v_re'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'tidal constituent y-velocity (real)'
        units = 'meter per second'
        field = 'y-velocity, scalar, series'
    if src_varname == 'v_im':
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_v_to_rho.nc'
        dst_varname = 'v_im'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'tidal constituent y-velocity (imaginary)'
        units = 'meter per second'
        field = 'y-velocity, scalar, series'

    else:
        raise ValueError, 'Undefined src_varname'

    # create variable in file
    print 'Creating variable', dst_varname
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    # nc.createVariable(dst_varname, 'f8', dimensions)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field

    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_var = pyroms.remapping.remap(src_var, wts_file, spval=spval)

    # write data in destination file
    print 'write data in destination file\n'
    nc.variables[dst_varname][:] = dst_var

    # close file
    nc.close()
    cdf.close()
Ejemplo n.º 11
0
def remap(src_file,
          src_varname,
          src_grd,
          dst_grd,
          dmax=0,
          cdepth=0,
          kk=0,
          dst_dir='./'):

    ystart = 240

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
    ref = datetime(1900, 1, 1, 0, 0, 0)
    ref = date2num(ref)
    # For IC
    tag = src_file.rsplit('/')[-1].rsplit('_')[-1].rsplit('-')[0]
    year = int(tag[:4])
    month = int(tag[4:6])
    day = int(tag[6:])
    time = datetime(year, month, day, 0, 0, 0)
    # For CLM
    #    year = int(src_file.rsplit('/')[-1].rsplit('_')[-2])
    #    month = int(src_file.rsplit('/')[-1].rsplit('_')[-1][0:2])
    #    day = np.array([15,14,15,15,15,15,15,15,15,15,15,15])
    #    hour = np.array([12,0,12,0,12,0,12,12,0,12,0,12])
    #    if year%4 == 0:
    #        hour = np.array([12,12,12,0,12,0,12,12,0,12,0,12])
    #    time = datetime(year, month, day[month-1], hour[month-1], 0, 0)
    time = date2num(time)
    time = time - ref
    time = time + 2.5  # 5-day average

    # create IC file
    dst_file = src_file.rsplit('/')[-1]
    dst_file = dst_dir + dst_file[:
                                  -4] + '_' + src_varname + '_ic_' + dst_grd.name + '.nc'
    print '\nCreating file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open IC file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    #get missing value
    spval = src_var._FillValue

    # determine variable dimension
    ndim = len(src_var.dimensions)

    # global grid
    if ndim == 3:
        src_var = src_var[:]
        src_var = src_var[:, np.r_[ystart:np.size(src_var, 1), -1], :]
    elif ndim == 2:
        src_var = src_var[:]
        src_var = src_var[np.r_[ystart:np.size(src_var, 0), -1], :]

    if src_varname == 'ssh':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_SODA_2.1.6_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'zeta'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'free-surface'
        units = 'meter'
        field = 'free-surface, scalar, series'
    elif src_varname == 'temp':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_SODA_2.1.6_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'temp'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'potential temperature'
        units = 'Celsius'
        field = 'temperature, scalar, series'
    elif src_varname == 'salt':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_SODA_2.1.6_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'salt'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'salinity'
        units = 'PSU'
        field = 'salinity, scalar, series'
    else:
        raise ValueError, 'Undefined src_varname'

    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1, 0, 0]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel,
                                               nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + '_Z', dst_grd.hgrid,
                                         dst_zcoord)

    # create variable in file
    print 'Creating variable', dst_varname
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field

    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name
    print 'time =', time

    if ndim == 3:
        # flood the grid
        print 'flood the grid'
        src_varz = pyroms_toolbox.BGrid_SODA.flood(src_var, src_grd, Bpos=Bpos, spval=spval, \
                                dmax=dmax, cdepth=cdepth, kk=kk)
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, \
                                          spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print 'vertical interpolation from standard z level to sigma'
        dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \
                          dst_grd, Cpos=Cpos, spval=spval, flood=False)
    else:
        dst_var = dst_varz

    # write data in destination file
    print 'write data in destination file'
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname][0] = dst_var

    # close destination file
    nc.close()

    if src_varname == 'SSH':
        return dst_varz
Ejemplo n.º 12
0
def remap_uv(src_file, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'):

    # YELLOW grid sub-sample
    xrange = (225, 275)
    yrange = (190, 240)

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
    ref = datetime(1900, 1, 1, 0, 0, 0)
    ref = date2num(ref)
    tag = src_file.rsplit('/')[-1].rsplit('_')[-1].rsplit('-')[0]
    year = int(tag[:4])
    month = int(tag[4:6])
    day = int(tag[6:])
    time = datetime(year, month, day, 0, 0, 0)
    time = date2num(time)
    time = time - ref
    time = time + 2.5  # 5-day average

    # get dimensions
    Mp, Lp = dst_grd.hgrid.mask_rho.shape

    # create destination file
    dst_file = src_file.rsplit('/')[-1]
    dst_fileu = dst_dir + dst_file[:-4] + '_u_ic_' + dst_grd.name + '.nc'
    print '\nCreating destination file', dst_fileu
    if os.path.exists(dst_fileu) is True:
        os.remove(dst_fileu)
    pyroms_toolbox.nc_create_roms_file(dst_fileu, dst_grd, nctime)
    dst_filev = dst_dir + dst_file[:-4] + '_v_ic_' + dst_grd.name + '.nc'
    print 'Creating destination file', dst_filev
    if os.path.exists(dst_filev) is True:
        os.remove(dst_filev)
    pyroms_toolbox.nc_create_roms_file(dst_filev, dst_grd, nctime)

    # open destination file
    ncu = netCDF.Dataset(dst_fileu, 'a', format='NETCDF3_CLASSIC')
    ncv = netCDF.Dataset(dst_filev, 'a', format='NETCDF3_CLASSIC')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_varu = cdf.variables['u']
    src_varv = cdf.variables['v']

    #get missing value
    spval = src_varu._FillValue

    # YELLOW grid sub-sample
    src_varu = src_varu[:, yrange[0]:yrange[1] + 1, xrange[0]:xrange[1] + 1]
    src_varv = src_varv[:, yrange[0]:yrange[1] + 1, xrange[0]:xrange[1] + 1]

    # get weights file
    wts_file = 'remap_weights_SODA_2.1.6_to_YELLOW_bilinear_uv_to_rho.nc'

    # build intermediate zgrid
    zlevel = -src_grd.z_t[::-1, 0, 0]
    nzlevel = len(zlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + '_Z', dst_grd.hgrid,
                                     dst_zcoord)

    # create variable in destination file
    print 'Creating variable u'
    ncu.createVariable('u',
                       'f8', ('ocean_time', 's_rho', 'eta_u', 'xi_u'),
                       fill_value=spval)
    ncu.variables['u'].long_name = '3D u-momentum component'
    ncu.variables['u'].units = 'meter second-1'
    ncu.variables['u'].field = 'u-velocity, scalar, series'
    #ncu.variables['u_north']._FillValue = spval
    # create variable in destination file
    print 'Creating variable ubar'
    ncu.createVariable('ubar',
                       'f8', ('ocean_time', 'eta_u', 'xi_u'),
                       fill_value=spval)
    ncu.variables['ubar'].long_name = '2D u-momentum component'
    ncu.variables['ubar'].units = 'meter second-1'
    ncu.variables['ubar'].field = 'ubar-velocity,, scalar, series'
    #ncu.variables['ubar_north']._FillValue = spval

    print 'Creating variable v'
    ncv.createVariable('v',
                       'f8', ('ocean_time', 's_rho', 'eta_v', 'xi_v'),
                       fill_value=spval)
    ncv.variables['v'].long_name = '3D v-momentum component'
    ncv.variables['v'].units = 'meter second-1'
    ncv.variables['v'].field = 'v-velocity, scalar, series'
    #ncv.variables['v_north']._FillValue = spval
    print 'Creating variable vbar'
    ncv.createVariable('vbar',
                       'f8', ('ocean_time', 'eta_v', 'xi_v'),
                       fill_value=spval)
    ncv.variables['vbar'].long_name = '2D v-momentum component'
    ncv.variables['vbar'].units = 'meter second-1'
    ncv.variables['vbar'].field = 'vbar-velocity,, scalar, series'
    #ncv.variables['vbar_north']._FillValue = spval

    # remaping
    print 'remapping and rotating u and v from', src_grd.name, \
                      'to', dst_grd.name
    print 'time =', time

    # flood the grid
    print 'flood the grid'
    src_uz = pyroms_toolbox.BGrid_SODA.flood(src_varu, src_grd, Bpos='uv', \
                spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
    src_vz = pyroms_toolbox.BGrid_SODA.flood(src_varv, src_grd, Bpos='uv', \
                spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_uz = pyroms.remapping.remap(src_uz, wts_file, \
                                      spval=spval)
    dst_vz = pyroms.remapping.remap(src_vz, wts_file, \
                                      spval=spval)

    # vertical interpolation from standard z level to sigma
    print 'vertical interpolation from standard z level to sigma'
    dst_u = pyroms.remapping.z2roms(dst_uz[::-1,:,:], dst_grdz, \
                        dst_grd, Cpos='rho', spval=spval, flood=False)
    dst_v = pyroms.remapping.z2roms(dst_vz[::-1,:,:], dst_grdz,  \
                        dst_grd, Cpos='rho', spval=spval, flood=False)

    # rotate u,v fields
    wtsfile = 'remap_weights_GFDL_CM2.1_to_NEP5_bilinear_t_to_rho.nc'
    src_angle = np.zeros(dst_grd.hgrid.angle_rho.shape)
    dst_angle = dst_grd.hgrid.angle_rho
    angle = dst_angle - src_angle
    angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))
    U = dst_u + dst_v * 1j
    eitheta = np.exp(-1j * angle[:, :, :])
    U = U * eitheta
    dst_u = np.real(U)
    dst_v = np.imag(U)

    # move back to u,v points
    dst_u = 0.5 * (dst_u[:, :, :-1] + dst_u[:, :, 1:])
    dst_v = 0.5 * (dst_v[:, :-1, :] + dst_v[:, 1:, :])

    # spval
    idxu = np.where(dst_grd.hgrid.mask_u == 0)
    idxv = np.where(dst_grd.hgrid.mask_v == 0)
    for n in range(dst_grd.vgrid.N):
        dst_u[n, idxu[0], idxu[1]] = spval
        dst_v[n, idxv[0], idxv[1]] = spval

    # compute depth average velocity ubar and vbar
    # get z at the right position
    z_u = 0.5 * (dst_grd.vgrid.z_w[0, :, :, :-1] +
                 dst_grd.vgrid.z_w[0, :, :, 1:])
    z_v = 0.5 * (dst_grd.vgrid.z_w[0, :, :-1, :] +
                 dst_grd.vgrid.z_w[0, :, 1:, :])

    dst_ubar = np.zeros((dst_u.shape[1], dst_u.shape[2]))
    dst_vbar = np.zeros((dst_v.shape[1], dst_v.shape[2]))

    for i in range(dst_ubar.shape[1]):
        for j in range(dst_ubar.shape[0]):
            dst_ubar[j, i] = (dst_u[:, j, i] *
                              np.diff(z_u[:, j, i])).sum() / -z_u[0, j, i]

    for i in range(dst_vbar.shape[1]):
        for j in range(dst_vbar.shape[0]):
            dst_vbar[j, i] = (dst_v[:, j, i] *
                              np.diff(z_v[:, j, i])).sum() / -z_v[0, j, i]

    # spval
    dst_ubar[idxu[0], idxu[1]] = spval
    dst_vbar[idxv[0], idxv[1]] = spval

    # write data in destination file
    print 'write data in destination file'
    ncu.variables['ocean_time'][0] = time
    ncu.variables['u'][0] = dst_u
    ncu.variables['ubar'][0] = dst_ubar

    ncv.variables['ocean_time'][0] = time
    ncv.variables['v'][0] = dst_v
    ncv.variables['vbar'][0] = dst_vbar

    # close destination file
    ncu.close()
    ncv.close()
Ejemplo n.º 13
0
def remap(zero, l_time, src_file, src_varname, src_grd, dst_grd, grid_name):
    nctime.long_name = 'time'
    nctime.units = 'hours since 2006-01-01 00:00:00'
    Mp, Lp = dst_grd.hgrid.mask_rho.shape
    cw = int(len(dst_grd.vgrid.Cs_r))
    cdf = Dataset(src_file)
    if src_varname == 'ssh':
        src_var = np.zeros((1, Mp, Lp))
    else:
        src_var = cdf.variables[src_varname][0:1]
    ndim = np.ndim(src_var)
    spval = -32767
    dst_file = src_file.rsplit('/')[-1]
    dst_file = src_varname + dst_grd.name + '.nc'
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)
    nc = Dataset(dst_file, 'a', format='NETCDF3_64BIT')
    print ndim
    if ndim == 4:
        time = cdf.variables['time'][zero:l_time]
        src_var = src_var[0, :, :, :]
    elif ndim == 3:
        time = cdf.variables['time'][zero:l_time]
        src_var = np.zeros((len(time), Mp, Lp))
    time = time - time[0]
    if src_varname == 'ssh':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' % (
            grid_name)
        dst_varname = 'zeta'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'free-surface'
        units = 'meter'
        field = 'free-surface, scalar, series'
    elif src_varname == 'votemper':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' % (
            grid_name)
        dst_varname = 'temp'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'potential temperature'
        units = 'Celsius'
        field = 'temperature, scalar, series'
    elif src_varname == 'vosaline':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' % (
            grid_name)
        dst_varname = 'salt'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'salinity'
        units = 'PSU'
        field = 'salinity, scalar, series'

    if ndim == 4:
        zlevel = -z[::-1, 0, 0]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel,
                                               nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + '_Z', dst_grd.hgrid,
                                         dst_zcoord)

    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field
    dxy = 5
    cdepth = 0
    kk = 0

    if ndim == 4:
        dst_var = np.zeros((l_time - zero, cw, Mp, Lp))
        for i in range(len(time)):
            if src_varname == 'votemper':
                src_varz = flood(
                    cdf.variables[src_varname][zero + i, :, :, :] - 273.15,
                    src_grd,
                    spval=spval)
            else:
                src_varz = flood(cdf.variables[src_varname][zero + i, :, :, :],
                                 src_grd,
                                 spval=spval)
            dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval)
            dst_cont = pyroms.remapping.z2roms(dst_varz[::-1, :, :],
                                               dst_grdz,
                                               dst_grd,
                                               Cpos=Cpos,
                                               spval=spval,
                                               flood=True)
            dst_var[i, :, :, :] = dst_cont

    else:
        dst_var = np.zeros((l_time - zero, Mp, Lp))
#for i in range(len(time)):
#	xx=np.arange(-7,7,1);yy=np.arange(-7,7,1)
#	R=np.zeros((len(xx),len(yy)))
#	for j in range(len(xx)):
#		for k in range(len(yy)):
#			dst_var[i,j+17,k+31]=2*np.exp(-0.05*(xx[j]**2+yy[k]**2))

    nc.variables['ocean_time'][:] = time / 24.
    nc.variables[dst_varname][:] = dst_var
    nc.close()
Ejemplo n.º 14
0
def remap_bio_glodap(argdict,
                     src_grd,
                     dst_grd,
                     dmax=0,
                     cdepth=0,
                     kk=0,
                     dst_dir='./'):

    # NWGOA3 grid sub-sample
    xrange = src_grd.xrange
    yrange = src_grd.yrange

    src_varname = argdict['tracer']
    tracer = src_varname
    src_file = argdict['file']
    units = argdict['units']
    longname = argdict['longname']
    nframe = argdict['nframe']

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'

    # create clim file
    dst_file = tracer + '.nc'
    dst_file = dst_dir + dst_grd.name + '_ic_bio_' + dst_file
    print 'Creating clim file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open clim file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    tmp = cdf.variables['time'][nframe]
    #if len(tmp) > 1:
    #    print 'error : multiple frames in input file' ; exit()
    #else:
    #    time = tmp[0]

    # to be in sync with physics, add +0.5 day
    #time = time + 0.5
    # time will be given by physics anyway
    time = 0.

    #get missing value
    spval = src_var._FillValue

    spval2 = -1.0e+10

    # determine variable dimension
    ndim = len(src_var.dimensions) - 1

    # NWGOA3 grid sub-sample
    if ndim == 3:
        src_var = src_var[0, :, yrange[0]:yrange[1] + 1,
                          xrange[0]:xrange[1] + 1]
    elif ndim == 2:
        src_var = src_var[0, yrange[0]:yrange[1] + 1, xrange[0]:xrange[1] + 1]

    if tracer == 'alk':
        unit_conversion = 1. / 1e6
    elif tracer == 'dic':
        unit_conversion = 1. / 1e6

    src_var = src_var * unit_conversion

    Bpos = 't'
    Cpos = 'rho'
    z = src_grd.z_t
    Mp, Lp = dst_grd.hgrid.mask_rho.shape
    wts_file = 'remap_weights_ESM2M_to_NWGOA3_bilinear_t_to_rho.nc'
    dst_varname = tracer
    dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
    long_name = longname
    field = tracer + ', scalar, series'
    units = units

    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel,
                                               nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + '_Z', dst_grd.hgrid,
                                         dst_zcoord)

    # create variable in file
    print 'Creating variable', dst_varname
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval2)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field
    #nc.variables[dst_varname_north]._FillValue = spval

    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name

    if ndim == 3:
        # flood the grid
        print 'flood the grid'
        src_varz = pyroms_toolbox.BGrid_GFDL.flood(src_var, src_grd, Bpos=Bpos, spval=spval, \
                                dmax=dmax, cdepth=cdepth, kk=kk)
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print 'vertical interpolation from standard z level to sigma'
        dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \
                          dst_grd, Cpos=Cpos, spval=spval, flood=False)
    else:
        dst_var = dst_varz

    if ndim == 3:
        for kz in np.arange(dst_grd.vgrid.N):
            tmp = dst_var[kz, :, :].copy()
            tmp[np.where(dst_grd.hgrid.mask_rho == 0)] = spval2
            dst_var[kz, :, :] = tmp.copy()

    # write data in destination file
    print 'write data in destination file\n'
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname][0] = dst_var

    # close file
    nc.close()
    cdf.close()

    if src_varname == 'eta':
        return dst_varz
Ejemplo n.º 15
0
def remapping_bound(varname, srcfile, wts_files, srcgrd, dst_grd, \
              rotate_uv=False, trange=None, irange=None, jrange=None, \
              dstdir='./' ,zlevel=None, dmax=0, cdepth=0, kk=0, \
              uvar='u', vvar='v', rotate_part=False):
    '''
    A remapping function to extract boundary conditions from one ROMS grid
    to another. It will optionally rotating u and v variables, but needs
    to be called separately for each u/v pair (such as u/v, uice/vice).
    '''

    # get input and output grid
    if type(srcgrd).__name__ == 'ROMS_Grid':
        srcgrd = srcgrd
    else:
        srcgrd = pyroms.grid.get_ROMS_grid(srcgrd)
    if type(dst_grd).__name__ == 'ROMS_Grid':
        dst_grd = dst_grd
    else:
        dst_grd = pyroms.grid.get_ROMS_grid(dst_grd)


    # build intermediaire zgrid
    if zlevel is None:
        zlevel = np.array([-7500.,-7000.,-6500.,-6000.,-5500.,-5000.,\
                   -4500.,-4000.,-3500.,-3000.,-2500.,-2000.,-1750.,\
                   -1500.,-1250.,-1000.,-900.,-800.,-700.,-600.,-500.,\
                   -400.,-300.,-250.,-200.,-175.,-150.,-125.,-100.,-90.,\
                   -80.,-70.,-60.,-50.,-45.,-40.,-35.,-30.,-25.,-20.,-17.5,\
                   -15.,-12.5,-10.,-7.5,-5.,-2.5,0.])
    else:
        zlevel = np.sort(-abs(zlevel))
    nzlevel = len(zlevel)
    src_zcoord = pyroms.vgrid.z_coordinate(srcgrd.vgrid.h, zlevel, nzlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
    srcgrdz = pyroms.grid.ROMS_Grid(srcgrd.name+'_Z', srcgrd.hgrid, src_zcoord)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)

    # varname argument
    if type(varname).__name__ == 'list':
        nvar = len(varname)
    elif type(varname).__name__ == 'str':
        varname = [varname]
        nvar = len(varname)
    else:
        raise ValueError, 'varname must be a str or a list of str'

    # if we're working on u and v, we'll compute ubar,vbar afterwards
    compute_ubar = False
    if (varname.__contains__('u') == 1 and varname.__contains__('v') == 1) or \
       (varname.__contains__('u_eastward') == 1 and varname.__contains__('v_northward') == 1):
        compute_ubar = True
        print 'ubar/vbar to be computed from u/v' 
        if varname.__contains__('ubar'):
            varname.remove('ubar')
            nvar = nvar-1
        if varname.__contains__('vbar'):
            varname.remove('vbar')
            nvar = nvar-1

    # if rotate_uv=True, check that u and v are in varname
    if rotate_uv is True:
        if varname.__contains__(uvar) == 0 or varname.__contains__(vvar) == 0:
            raise Warning, 'varname must include uvar and vvar in order to' \
                   + ' rotate the velocity field'
        else:
            varname.remove(uvar)
            varname.remove(vvar)
            nvar = nvar-2

    # srcfile argument
    if type(srcfile).__name__ == 'list':
        nfile = len(srcfile)
    elif type(srcfile).__name__ == 'str':
        srcfile = sorted(glob.glob(srcfile))
        nfile = len(srcfile)
    else:
        raise ValueError, 'src_srcfile must be a str or a list of str'

    # get wts_file
    if type(wts_files).__name__ == 'str':
        wts_files = sorted(glob.glob(wts_files))
 
    sides = ['_west','_east','_north','_south']
    long = {'_west':'Western', '_east':'Eastern', \
            '_north':'Northern', '_south':'Southern'}
    dimexcl = {'_west':'xi', '_east':'xi', \
            '_north':'eta', '_south':'eta'}

    nctidx = 0
    # loop over the srcfile
    for nf in range(nfile):
        print 'Working with file', srcfile[nf], '...'

        # get time 
        ocean_time = pyroms.utility.get_nc_var('ocean_time', srcfile[nf])
        ntime = len(ocean_time[:])

        # trange argument
        if trange is None:
            trange = range(ntime)

        # create destination file
        if nctidx == 0:
            dstfile = dstdir + os.path.basename(srcfile[nf])[:-3] + '_' \
                   + dst_grd.name + '_bdry.nc'
            if os.path.exists(dstfile) is False:
                print 'Creating destination file', dstfile
                pyroms_toolbox.nc_create_roms_file(dstfile, dst_grd, \
                    ocean_time, lgrid=False)

            # open destination file
            nc = netCDF.Dataset(dstfile, 'a', format='NETCDF3_64BIT')

        # loop over time
        for nt in trange:

            nc.variables['ocean_time'][nctidx] = ocean_time[nt]

            # loop over variable
            for nv in range(nvar):
                print ' '
                print 'remapping', varname[nv], 'from', srcgrd.name, \
                      'to', dst_grd.name
                print 'time =', ocean_time[nt]   
                Mp, Lp = dst_grd.hgrid.mask_rho.shape

                # get source data
                src_var = pyroms.utility.get_nc_var(varname[nv], srcfile[nf])

                # determine variable dimension
                ndim = len(src_var.dimensions)-1

                # get spval
                try:
                    spval = src_var._FillValue
                except:
                    raise Warning, 'Did not find a _FillValue attribute.' 

                # irange
                if irange is None:
                    iirange = (0,src_var.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0,src_var.shape[-2])
                else:
                    jjrange = jrange

                # determine where on the C-grid these variable lies
                if src_var.dimensions[2].find('_rho') != -1:
                    Cpos='rho'
                if src_var.dimensions[2].find('_u') != -1:
                    Cpos='u'
                    Lp = Lp-1
                if src_var.dimensions[2].find('_v') != -1:
                    Cpos='v'
                    Mp = Mp-1
                if src_var.dimensions[1].find('_w') != -1:
                    Cpos='w'

                print 'Arakawa C-grid position is', Cpos

                # create variable in _destination file
                if nctidx == 0:
                    for sid in sides:
                       varn = varname[nv]+str(sid)
                       dimens = [i for i in src_var.dimensions]
                       for dim in dimens:
                           if re.match(dimexcl[sid],dim):
                               dimens.remove(dim)
                       print 'Creating variable', varn, dimens
                       nc.createVariable(varn, 'f8', dimens, \
                           fill_value=spval)
                       nc.variables[varn].long_name = varname[nv] + \
                            ' ' + long[sid] + ' boundary condition'
                       try:
                           nc.variables[varn].units = src_var.units
                       except:
                           print varn+' has no units'
                       nc.variables[varn].time = src_var.time
                       nc.variables[varn].coordinates = \
                           str(dimens.reverse())
                       nc.variables[varn].field = src_var.field

                # get the right remap weights file
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__(Cpos+'_to_'+Cpos+'.nc'):
                        wts_file = wts_files[s]
                        break
                    else:
                        if s == len(wts_files) - 1:
                            raise ValueError, 'Did not find the appropriate remap weights file'

                if ndim == 3:
                    # vertical interpolation from sigma to standard z level
                    print 'vertical interpolation from sigma to standard z level'
                    src_varz = pyroms.remapping.roms2z( \
                                 src_var[nt,:,jjrange[0]:jjrange[1],iirange[0]:iirange[1]], \
                                 srcgrd, srcgrdz, Cpos=Cpos, spval=spval, \
                                 irange=iirange, jrange=jjrange)

                    # flood the grid
                    print 'flood the grid'
                    src_varz = pyroms.remapping.flood(src_varz, srcgrdz, Cpos=Cpos, \
                                      irange=iirange, jrange=jjrange, spval=spval, \
                                      dmax=dmax, cdepth=cdepth, kk=kk)

                else:
                    src_varz = src_var[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]

                print datetime.datetime.now()
                # horizontal interpolation using scrip weights
                print 'horizontal interpolation using scrip weights'
                dst_varz = pyroms.remapping.remap(src_varz, wts_file, \
                                                  spval=spval)

                if ndim == 3:
                    dst_var_north = pyroms.remapping.z2roms(dst_varz[:, \
                          Mp-1:Mp,0:Lp], dst_grdz, dst_grd, Cpos=Cpos, \
                          spval=spval, flood=False, irange=(0,Lp), \
                          jrange=(Mp-1,Mp))
                    dst_var_south = pyroms.remapping.z2roms(dst_varz[:, \
                          0:1, :], dst_grdz, dst_grd, Cpos=Cpos, \
                          spval=spval, flood=False, irange=(0,Lp), \
                          jrange=(0,1))
                    dst_var_east = pyroms.remapping.z2roms(dst_varz[:, \
                          :, Lp-1:Lp], dst_grdz, dst_grd, Cpos=Cpos, \
                          spval=spval, flood=False, irange=(Lp-1,Lp), \
                          jrange=(0,Mp))
                    dst_var_west = pyroms.remapping.z2roms(dst_varz[:, \
                          :, 0:1], dst_grdz, dst_grd, Cpos=Cpos, \
                          spval=spval, flood=False, irange=(0,1), \
                          jrange=(0,Mp))
                    if varname[nv] == 'u':
                        dst_u_west = dst_var_west
                        dst_u_east = dst_var_east
                        dst_u_north = dst_var_north
                        dst_u_south = dst_var_south
                    if varname[nv] == 'v':
                        dst_v_west = dst_var_west
                        dst_v_east = dst_var_east
                        dst_v_north = dst_var_north
                        dst_v_south = dst_var_south

                else:
                    dst_var_north = dst_varz[-1, :]
                    dst_var_south = dst_varz[0, :]
                    dst_var_east = dst_varz[:, -1]
                    dst_var_west = dst_varz[:, 0]

#                print datetime.datetime.now()

                # write data in destination file
                print 'write data in destination file'
                sid = '_west'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_west)

                sid = '_east'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_east)

                sid = '_north'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_north)

                sid = '_south'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_south)

            # rotate the velocity field if requested
            if rotate_uv is True:
                print ' ' 
                print 'remapping and rotating u and v from', srcgrd.name, \
                      'to', dst_grd.name

                # get source data
                src_u = pyroms.utility.get_nc_var(uvar, srcfile[nf])
                src_v = pyroms.utility.get_nc_var(vvar, srcfile[nf])

                # get spval
                try:
                    spval = src_v._FillValue
                except:
                    raise Warning, 'Did not find a _FillValue attribute.' 

                if rotate_part:
                    ndim = len(src_u.dimensions)-1
                    ind = uvar.find('_eastward')
                    uvar_out = uvar[0:ind]
                    print "Warning: renaming uvar to", uvar_out
                    ind = vvar.find('_northward')
                    vvar_out = vvar[0:ind]
                    print "Warning: renaming vvar to", vvar_out
                    if ndim == 3:
                        dimens_u = ['ocean_time', 's_rho', 'eta_u', 'xi_u']
                        dimens_v = ['ocean_time', 's_rho', 'eta_v', 'xi_v']
                    else:
                        dimens_u = ['ocean_time', 'eta_u', 'xi_u']
                        dimens_v = ['ocean_time', 'eta_v', 'xi_v']

                else:
                    dimens_u = [i for i in src_u.dimensions]
                    dimens_v = [i for i in src_v.dimensions]
                    uvar_out = uvar
                    vvar_out = vvar

                # create variable in destination file
                if nctidx == 0:
                    print 'Creating boundary variables for '+uvar
                    for sid in sides:
                       varn = uvar_out+str(sid)
                       print 'Creating variable', varn
                       dimens = list(dimens_u)
                       for dim in dimens:
                           if re.match(dimexcl[sid],dim):
                               dimens.remove(dim)
                       nc.createVariable(varn, 'f8', dimens, \
                         fill_value=spval)
                       nc.variables[varn].long_name = uvar_out + \
                           ' ' + long[sid] + ' boundary condition'
                       try:
                           nc.variables[varn].units = src_u.units
                       except:
                           print varn+' has no units'
                       nc.variables[varn].time = src_u.time
                       nc.variables[varn].coordinates = \
                           str(dimens.reverse())
                       nc.variables[varn].field = src_u.field
                    print 'Creating boundary variables for '+vvar
                    for sid in sides:
                       varn = vvar_out+str(sid)
                       print 'Creating variable', varn
                       dimens = list(dimens_v)
                       for dim in dimens:
                           if re.match(dimexcl[sid],dim):
                               dimens.remove(dim)
                       nc.createVariable(varn, 'f8', dimens, \
                         fill_value=spval)
                       nc.variables[varn].long_name = vvar_out + \
                                ' ' + long[sid] + ' boundary condition'
                       try:
                           nc.variables[varn].units = src_v.units
                       except:
                           print varn+' has no units'
                       nc.variables[varn].time = src_v.time
                       nc.variables[varn].coordinates = \
                           str(dimens.reverse())
                       nc.variables[varn].field = src_v.field

                # get the right remap weights file
                if rotate_part:
                    for s in range(len(wts_files)):
                        if wts_files[s].__contains__('rho_to_rho.nc'):
                            wts_file_u = wts_files[s]
                            wts_file_v = wts_files[s]
                    Cpos_u = 'rho'
                    Cpos_v = 'rho'
                else:
                    for s in range(len(wts_files)):
                        if wts_files[s].__contains__('u_to_rho.nc'):
                            wts_file_u = wts_files[s]
                        if wts_files[s].__contains__('v_to_rho.nc'):
                            wts_file_v = wts_files[s]
                    Cpos_u = 'u'
                    Cpos_v = 'v'

                # vertical interpolation from sigma to standard z level
                # irange
                if irange is None:
                    iirange = (0,src_u.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0,src_u.shape[-2])
                else:
                    jjrange = jrange

                ndim = len(src_v.dimensions)-1
                if ndim == 3:
                    print 'vertical interpolation from sigma to standard z level'
                    src_uz = pyroms.remapping.roms2z( \
                            src_u[nt,:,jjrange[0]:jjrange[1],iirange[0]:iirange[1]], \
                            srcgrd, srcgrdz, Cpos=Cpos_u, irange=iirange, jrange=jjrange)
                    # flood the grid
                    print 'flood the u grid'
                    src_uz = pyroms.remapping.flood(src_uz, srcgrdz, Cpos=Cpos_u, \
                                  irange=iirange, jrange=jjrange, \
                                  spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
                else:
                    src_uz = src_u[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]
                    src_uz = pyroms.remapping.flood2d(src_uz, srcgrdz, Cpos=Cpos_u, \
                                      irange=iirange, jrange=jjrange, spval=spval, \
                                      dmax=dmax)

                # irange
                if irange is None:
                    iirange = (0,src_v.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0,src_v.shape[-2])
                else:
                    jjrange = jrange

                if ndim == 3:
                    src_vz = pyroms.remapping.roms2z( \
                            src_v[nt,:,jjrange[0]:jjrange[1],iirange[0]:iirange[1]], \
                            srcgrd, srcgrdz, Cpos=Cpos_v, irange=iirange, jrange=jjrange)

                    # flood the grid
                    print 'flood the v grid'
                    src_vz = pyroms.remapping.flood(src_vz, srcgrdz, Cpos=Cpos_v, \
                                  irange=iirange, jrange=jjrange, \
                                  spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
                else:
                    src_vz = src_v[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]
                    src_vz = pyroms.remapping.flood2d(src_vz, srcgrdz, Cpos=Cpos_v, \
                                      irange=iirange, jrange=jjrange, spval=spval, \
                                      dmax=dmax)

                # horizontal interpolation using scrip weights
                print 'horizontal interpolation using scrip weights'
                dst_uz = pyroms.remapping.remap(src_uz, wts_file_u, \
                                                  spval=spval)
                dst_vz = pyroms.remapping.remap(src_vz, wts_file_v, \
                                                  spval=spval)
                Mp, Lp = dst_grd.hgrid.mask_rho.shape

                if ndim == 3:
                    # vertical interpolation from standard z level to sigma
                    print 'vertical interpolation from standard z level to sigma'
                    dst_u_north = pyroms.remapping.z2roms(dst_uz[:, Mp-2:Mp, 0:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,Lp), jrange=(Mp-2,Mp))
                    dst_u_south = pyroms.remapping.z2roms(dst_uz[:, 0:2, 0:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,Lp), jrange=(0,2))
                    dst_u_east = pyroms.remapping.z2roms(dst_uz[:, 0:Mp, Lp-2:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(Lp-2,Lp), jrange=(0,Mp))
                    dst_u_west = pyroms.remapping.z2roms(dst_uz[:, 0:Mp, 0:2], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,2), jrange=(0,Mp))

                    dst_v_north = pyroms.remapping.z2roms(dst_vz[:, Mp-2:Mp, 0:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,Lp), jrange=(Mp-2,Mp))
                    dst_v_south = pyroms.remapping.z2roms(dst_vz[:, 0:2, 0:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,Lp), jrange=(0,2))
                    dst_v_east = pyroms.remapping.z2roms(dst_vz[:, 0:Mp, Lp-2:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(Lp-2,Lp), jrange=(0,Mp))
                    dst_v_west = pyroms.remapping.z2roms(dst_vz[:, 0:Mp, 0:2], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,2), jrange=(0,Mp))
                else:
                    dst_u_north = dst_uz[Mp-2:Mp, 0:Lp]
                    dst_u_south = dst_uz[0:2, 0:Lp]
                    dst_u_east = dst_uz[0:Mp, Lp-2:Lp]
                    dst_u_west = dst_uz[0:Mp, 0:2]
                    dst_v_north = dst_vz[Mp-2:Mp, 0:Lp]
                    dst_v_south = dst_vz[0:2, 0:Lp]
                    dst_v_east = dst_vz[0:Mp, Lp-2:Lp]
                    dst_v_west = dst_vz[0:Mp, 0:2]

                # rotate u,v fields
                if rotate_part:
                    src_angle = np.zeros(dst_grd.hgrid.angle_rho.shape)
                else:
                    for s in range(len(wts_files)):
                        if wts_files[s].__contains__('rho_to_rho.nc'):
                            wts_file = wts_files[s]
                    src_ang = srcgrd.hgrid.angle_rho[jjrange[0]:jjrange[1],iirange[0]:iirange[1]]
                    src_angle = pyroms.remapping.remap(src_ang, wts_file)

                dst_angle = dst_grd.hgrid.angle_rho
                angle = dst_angle - src_angle
                if ndim == 3:
                    angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))
                    U_north = dst_u_north + dst_v_north*1j
                    eitheta_north = np.exp(-1j*angle[:,Mp-2:Mp, 0:Lp])
                    U_south = dst_u_south + dst_v_south*1j
                    eitheta_south = np.exp(-1j*angle[:,0:2, 0:Lp])
                    U_east = dst_u_east + dst_v_east*1j
                    eitheta_east = np.exp(-1j*angle[:,0:Mp, Lp-2:Lp])
                    U_west = dst_u_west + dst_v_west*1j
                    eitheta_west = np.exp(-1j*angle[:,0:Mp, 0:2])
                else:
                    U_north = dst_u_north + dst_v_north*1j
                    eitheta_north = np.exp(-1j*angle[Mp-2:Mp, 0:Lp])
                    U_south = dst_u_south + dst_v_south*1j
                    eitheta_south = np.exp(-1j*angle[0:2, 0:Lp])
                    U_east = dst_u_east + dst_v_east*1j
                    eitheta_east = np.exp(-1j*angle[0:Mp, Lp-2:Lp])
                    U_west = dst_u_west + dst_v_west*1j
                    eitheta_west = np.exp(-1j*angle[0:Mp, 0:2])

                U_north = U_north * eitheta_north
                dst_u_north = np.real(U_north)
                dst_v_north = np.imag(U_north)

                U_south = U_south * eitheta_south
                dst_u_south = np.real(U_south)
                dst_v_south = np.imag(U_south)

                U_east = U_east * eitheta_east
                dst_u_east = np.real(U_east)
                dst_v_east = np.imag(U_east)

                U_west = U_west * eitheta_west
                dst_u_west = np.real(U_west)
                dst_v_east = np.imag(U_east)

                # move back to u,v points
                if ndim == 3:
                    dst_u_north = 0.5 * np.squeeze(dst_u_north[:,-1,:-1] + \
                            dst_u_north[:,-1,1:])
                    dst_v_north = 0.5 * np.squeeze(dst_v_north[:,:-1,:] + \
                            dst_v_north[:,1:,:])
                    dst_u_south = 0.5 * np.squeeze(dst_u_south[:,0,:-1] + \
                            dst_u_south[:,0,1:])
                    dst_v_south = 0.5 * np.squeeze(dst_v_south[:,:-1,:] + \
                            dst_v_south[:,1:,:])
                    dst_u_east = 0.5 * np.squeeze(dst_u_east[:,:,:-1] + \
                            dst_u_east[:,:,1:])
                    dst_v_east = 0.5 * np.squeeze(dst_v_east[:,:-1,-1] + \
                            dst_v_east[:,1:,-1])
                    dst_u_west = 0.5 * np.squeeze(dst_u_west[:,:,:-1] + \
                            dst_u_west[:,:,1:])
                    dst_v_west = 0.5 * np.squeeze(dst_v_west[:,:-1,0] + \
                            dst_v_west[:,1:,0])
                else:
                    dst_u_north = 0.5 * np.squeeze(dst_u_north[-1,:-1] + \
                            dst_u_north[-1,1:])
                    dst_v_north = 0.5 * np.squeeze(dst_v_north[:-1,:] + \
                            dst_v_north[1:,:])
                    dst_u_south = 0.5 * np.squeeze(dst_u_south[0,:-1] + \
                            dst_u_south[0,1:])
                    dst_v_south = 0.5 * np.squeeze(dst_v_south[:-1,:] + \
                            dst_v_south[1:,:])
                    dst_u_east = 0.5 * np.squeeze(dst_u_east[:,:-1] + \
                            dst_u_east[:,1:])
                    dst_v_east = 0.5 * np.squeeze(dst_v_east[:-1,-1] + \
                            dst_v_east[1:,-1])
                    dst_u_west = 0.5 * np.squeeze(dst_u_west[:,:-1] + \
                            dst_u_west[:,1:])
                    dst_v_west = 0.5 * np.squeeze(dst_v_west[:-1,0] + \
                            dst_v_west[1:,0])

                # spval
                idxu_north = np.where(dst_grd.hgrid.mask_u[-1,:] == 0)
                idxv_north = np.where(dst_grd.hgrid.mask_v[-1,:] == 0)
                idxu_south = np.where(dst_grd.hgrid.mask_u[0,:] == 0)
                idxv_south = np.where(dst_grd.hgrid.mask_v[0,:] == 0)
                idxu_east = np.where(dst_grd.hgrid.mask_u[:,-1] == 0)
                idxv_east = np.where(dst_grd.hgrid.mask_v[:,-1] == 0)
                idxu_west = np.where(dst_grd.hgrid.mask_u[:,0] == 0)
                idxv_west = np.where(dst_grd.hgrid.mask_v[:,0] == 0)
                if ndim == 3:
                    for n in range(dst_grd.vgrid.N): 
                        dst_u_north[n, idxu_north[0]] = spval
                        dst_v_north[n, idxv_north[0]] = spval
                        dst_u_south[n, idxu_south[0]] = spval
                        dst_v_south[n, idxv_south[0]] = spval
                        dst_u_east[n, idxu_east[0]] = spval
                        dst_v_east[n, idxv_east[0]] = spval
                        dst_u_west[n, idxu_west[0]] = spval
                        dst_v_west[n, idxv_west[0]] = spval
                else:
                    dst_u_north[idxu_north[0]] = spval
                    dst_v_north[idxv_north[0]] = spval
                    dst_u_south[idxu_south[0]] = spval
                    dst_v_south[idxv_south[0]] = spval
                    dst_u_east[idxu_east[0]] = spval
                    dst_v_east[idxv_east[0]] = spval
                    dst_u_west[idxu_west[0]] = spval
                    dst_v_west[idxv_west[0]] = spval

                # write data in destination file
                print 'write data in destination file'
                sid = '_west'
                varn = uvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_u_west
                varn = vvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_v_west

                sid = '_north'
                varn = uvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_u_north
                varn = vvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_v_north

                sid = '_east'
                varn = uvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_u_east
                varn = vvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_v_east

                sid = '_south'
                varn = uvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_u_south
                varn = vvar_out+str(sid)
                nc.variables[varn][nctidx] = dst_v_south

            if compute_ubar:
                if nctidx == 0:
                    print 'Creating variable ubar_north'
                    nc.createVariable('ubar_north', 'f8', \
                         ('ocean_time', 'xi_u'), fill_value=spval)
                    nc.variables['ubar_north'].long_name = \
                          '2D u-momentum north boundary condition'
                    nc.variables['ubar_north'].units = 'meter second-1'
                    nc.variables['ubar_north'].time = 'ocean_time'
                    nc.variables['ubar_north'].coordinates = 'xi_u ocean_time'
                    nc.variables['ubar_north'].field = 'ubar_north, scalar, series'
                    print 'Creating variable vbar_north'
                    nc.createVariable('vbar_north', 'f8', \
                         ('ocean_time', 'xi_v'), fill_value=spval)
                    nc.variables['vbar_north'].long_name = \
                          '2D v-momentum north boundary condition'
                    nc.variables['vbar_north'].units = 'meter second-1'
                    nc.variables['vbar_north'].time = 'ocean_time'
                    nc.variables['vbar_north'].coordinates = 'xi_v ocean_time'
                    nc.variables['vbar_north'].field = 'vbar_north,, scalar, series'

                    print 'Creating variable ubar_south'
                    nc.createVariable('ubar_south', 'f8', \
                         ('ocean_time', 'xi_u'), fill_value=spval)
                    nc.variables['ubar_south'].long_name = \
                          '2D u-momentum south boundary condition'
                    nc.variables['ubar_south'].units = 'meter second-1'
                    nc.variables['ubar_south'].time = 'ocean_time'
                    nc.variables['ubar_south'].coordinates = 'xi_u ocean_time'
                    nc.variables['ubar_south'].field = 'ubar_south, scalar, series'
                    print 'Creating variable vbar_south'
                    nc.createVariable('vbar_south', 'f8', \
                         ('ocean_time', 'xi_v'), fill_value=spval)
                    nc.variables['vbar_south'].long_name = \
                          '2D v-momentum south boundary condition'
                    nc.variables['vbar_south'].units = 'meter second-1'
                    nc.variables['vbar_south'].time = 'ocean_time'
                    nc.variables['vbar_south'].coordinates = 'xi_v ocean_time'

                    print 'Creating variable ubar_west'
                    nc.createVariable('ubar_west', 'f8', \
                         ('ocean_time', 'eta_u'), fill_value=spval)
                    nc.variables['ubar_west'].long_name = \
                          '2D u-momentum west boundary condition'
                    nc.variables['ubar_west'].units = 'meter second-1'
                    nc.variables['ubar_west'].time = 'ocean_time'
                    nc.variables['ubar_west'].coordinates = 'eta_u ocean_time'
                    nc.variables['ubar_west'].field = 'ubar_west, scalar, series'
                    print 'Creating variable vbar_west'
                    nc.createVariable('vbar_west', 'f8', \
                         ('ocean_time', 'eta_v'), fill_value=spval)
                    nc.variables['vbar_west'].long_name = \
                          '2D v-momentum west boundary condition'
                    nc.variables['vbar_west'].units = 'meter second-1'
                    nc.variables['vbar_west'].time = 'ocean_time'
                    nc.variables['vbar_west'].coordinates = 'eta_v ocean_time'

                    print 'Creating variable ubar_east'
                    nc.createVariable('ubar_east', 'f8', \
                         ('ocean_time', 'eta_u'), fill_value=spval)
                    nc.variables['ubar_east'].long_name = \
                          '2D u-momentum east boundary condition'
                    nc.variables['ubar_east'].units = 'meter second-1'
                    nc.variables['ubar_east'].time = 'ocean_time'
                    nc.variables['ubar_east'].coordinates = 'eta_u ocean_time'
                    nc.variables['ubar_east'].field = 'ubar_east, scalar, series'
                    print 'Creating variable vbar_east'
                    nc.createVariable('vbar_east', 'f8', \
                         ('ocean_time', 'eta_v'), fill_value=spval)
                    nc.variables['vbar_east'].long_name = \
                          '2D v-momentum east boundary condition'
                    nc.variables['vbar_east'].units = 'meter second-1'
                    nc.variables['vbar_east'].time = 'ocean_time'
                    nc.variables['vbar_east'].coordinates = 'eta_v ocean_time'

                # compute depth average velocity ubar and vbar
                # get z at the right position
                print 'Computing ubar/vbar from u/v'
                z_u_north = 0.5 * (dst_grd.vgrid.z_w[0,:,-1,:-1] +
                        dst_grd.vgrid.z_w[0,:,-1, 1:])
                z_v_north = 0.5 * (dst_grd.vgrid.z_w[0,:,-1,:] +
                        dst_grd.vgrid.z_w[0,:,-2,:])
                z_u_south = 0.5 * (dst_grd.vgrid.z_w[0,:,0,:-1] +
                        dst_grd.vgrid.z_w[0,:,0,1:])
                z_v_south = 0.5 * (dst_grd.vgrid.z_w[0,:,0,:] +
                        dst_grd.vgrid.z_w[0,:,1,:])
                z_u_east = 0.5 * (dst_grd.vgrid.z_w[0,:,:,-1] +
                        dst_grd.vgrid.z_w[0,:,:,-2])
                z_v_east = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,-1] +
                        dst_grd.vgrid.z_w[0,:,1:,-1])
                z_u_west = 0.5 * (dst_grd.vgrid.z_w[0,:,:,0] +
                        dst_grd.vgrid.z_w[0,:,:,1])
                z_v_west = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,0] +
                        dst_grd.vgrid.z_w[0,:,1:,0])
                if not rotate_uv:
                    dst_u_north = np.squeeze(dst_u_north)
                    dst_v_north = np.squeeze(dst_v_north)
                    dst_u_south = np.squeeze(dst_u_south)
                    dst_v_south = np.squeeze(dst_v_south)
                    dst_u_east = np.squeeze(dst_u_east)
                    dst_v_east = np.squeeze(dst_v_east)
                    dst_u_west = np.squeeze(dst_u_west)
                    dst_v_west = np.squeeze(dst_v_west)

                dst_ubar_north = np.zeros(dst_u_north.shape[1])
                dst_ubar_south = np.zeros(dst_u_south.shape[1])
                dst_ubar_east = np.zeros(dst_u_east.shape[1])
                dst_ubar_west = np.zeros(dst_u_west.shape[1])
                dst_vbar_north = np.zeros(dst_v_north.shape[1])
                dst_vbar_south = np.zeros(dst_v_south.shape[1])
                dst_vbar_east = np.zeros(dst_v_east.shape[1])
                dst_vbar_west = np.zeros(dst_v_west.shape[1])

#                print 'Shapes 3', dst_u_north.shape, dst_ubar_north.shape, z_u_north.shape, np.diff(z_u_north[:,1]).shape
                for i in range(dst_u_north.shape[1]):
                    dst_ubar_north[i] = (dst_u_north[:,i] * \
                        np.diff(z_u_north[:,i])).sum() / -z_u_north[0,i]
                    dst_ubar_south[i] = (dst_u_south[:,i] * \
                        np.diff(z_u_south[:,i])).sum() / -z_u_south[0,i]
                for i in range(dst_v_north.shape[1]):
                    dst_vbar_north[i] = (dst_v_north[:,i] * \
                        np.diff(z_v_north[:,i])).sum() / -z_v_north[0,i]
                    dst_vbar_south[i] = (dst_v_south[:,i] * \
                        np.diff(z_v_south[:,i])).sum() / -z_v_south[0,i]
                for j in range(dst_u_east.shape[1]):
                    dst_ubar_east[j] = (dst_u_east[:,j] * \
                        np.diff(z_u_east[:,j])).sum() / -z_u_east[0,j]
                    dst_ubar_west[j] = (dst_u_west[:,j] * \
                        np.diff(z_u_west[:,j])).sum() / -z_u_west[0,j]
                for j in range(dst_v_east.shape[1]):
                    dst_vbar_east[j] = (dst_v_east[:,j] * \
                        np.diff(z_v_east[:,j])).sum() / -z_v_east[0,j]
                    dst_vbar_west[j] = (dst_v_west[:,j] * \
                        np.diff(z_v_west[:,j])).sum() / -z_v_west[0,j]

                # spval
                idxu_north = np.where(dst_grd.hgrid.mask_u[-1,:] == 0)
                idxv_north = np.where(dst_grd.hgrid.mask_v[-1,:] == 0)
                idxu_south = np.where(dst_grd.hgrid.mask_u[0,:] == 0)
                idxv_south = np.where(dst_grd.hgrid.mask_v[0,:] == 0)
                idxu_east = np.where(dst_grd.hgrid.mask_u[:,-1] == 0)
                idxv_east = np.where(dst_grd.hgrid.mask_v[:,-1] == 0)
                idxu_west = np.where(dst_grd.hgrid.mask_u[:,0] == 0)
                idxv_west = np.where(dst_grd.hgrid.mask_v[:,0] == 0)

                dst_ubar_north[idxu_north[0]] = spval
                dst_vbar_north[idxv_north[0]] = spval
                dst_ubar_south[idxu_south[0]] = spval
                dst_vbar_south[idxv_south[0]] = spval
                dst_ubar_east[idxu_east[0]] = spval
                dst_vbar_east[idxv_east[0]] = spval
                dst_ubar_west[idxu_west[0]] = spval
                dst_vbar_west[idxv_west[0]] = spval

                nc.variables['ubar_north'][nctidx] = dst_ubar_north
                nc.variables['ubar_south'][nctidx] = dst_ubar_south
                nc.variables['ubar_east'][nctidx] = dst_ubar_east
                nc.variables['ubar_west'][nctidx] = dst_ubar_west

                nc.variables['vbar_north'][nctidx] = dst_vbar_north
                nc.variables['vbar_south'][nctidx] = dst_vbar_south
                nc.variables['vbar_east'][nctidx] = dst_vbar_east
                nc.variables['vbar_west'][nctidx] = dst_vbar_west

            nctidx = nctidx + 1
        # close files here? how?
 
    # close destination file
    nc.close()

    return
Ejemplo n.º 16
0
def remap_uv(src_file, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'):

    ystart = 690
    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
    ref = datetime(1900, 1, 1, 0, 0, 0)
    ref = date2num(ref)
    tag = src_file.rsplit('/')[-1].rsplit('_')[2]
    print(("tag:", tag))
    year = int(tag[:4])
    month = int(tag[4:6])
    day = int(tag[6:])
    time = datetime(year, month, day, 0, 0, 0)
    time = date2num(time)
    time = time - ref
    time = time + 0.5  # 1-day average

    # get dimensions
    Mp, Lp = dst_grd.hgrid.mask_rho.shape

    # create destination file
    dst_file = src_file.rsplit('/')[-1]
    dst_fileu = dst_dir + dst_file[:-4] + '_u_ic_' + dst_grd.name + '.nc'
    print('\nCreating destination file', dst_fileu)
    if os.path.exists(dst_fileu) is True:
        os.remove(dst_fileu)
    pyroms_toolbox.nc_create_roms_file(dst_fileu, dst_grd, nctime)
    dst_filev = dst_dir + dst_file[:-4] + '_v_ic_' + dst_grd.name + '.nc'
    print('Creating destination file', dst_filev)
    if os.path.exists(dst_filev) is True:
        os.remove(dst_filev)
    pyroms_toolbox.nc_create_roms_file(dst_filev, dst_grd, nctime)

    # open destination file
    ncu = netCDF.Dataset(dst_fileu, 'a', format='NETCDF3_64BIT')
    ncv = netCDF.Dataset(dst_filev, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_varu = cdf.variables['vozocrtx']
    src_varv = cdf.variables['vomecrty']
    print("dims", src_varu.dimensions, src_varv.dimensions)

    #get missing value
    spval = src_varu._FillValue

    # ARCTIC grid sub-sample
    src_varu = src_varu[:]
    src_varv = src_varv[:]
    print("shape 1", src_varu.shape, src_varv.shape)
    src_varu = np.squeeze(src_varu)
    src_varv = np.squeeze(src_varv)
    print("shape 2", src_varu.shape, src_varv.shape)
    src_varu = src_varu[:, np.r_[ystart:np.size(src_varu, 1), -1], :]
    src_varv = src_varv[:, np.r_[ystart:np.size(src_varv, 1), -1], :]
    print("shape 3", src_varu.shape, src_varv.shape)

    # get weights file
    wts_file_a = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
    wts_file_u = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_u_to_rho.nc'
    wts_file_v = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_v_to_rho.nc'

    # build intermediate zgrid
    zlevel = -src_grd.z_t[::-1, 0, 0]
    nzlevel = len(zlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + '_Z', dst_grd.hgrid,
                                     dst_zcoord)

    # create variable in destination file
    print('Creating variable u')
    ncu.createVariable('u',
                       'f8', ('ocean_time', 's_rho', 'eta_u', 'xi_u'),
                       fill_value=spval)
    ncu.variables['u'].long_name = '3D u-momentum component'
    ncu.variables['u'].units = 'meter second-1'
    ncu.variables['u'].field = 'u-velocity, scalar, series'
    # create variable in destination file
    print('Creating variable ubar')
    ncu.createVariable('ubar',
                       'f8', ('ocean_time', 'eta_u', 'xi_u'),
                       fill_value=spval)
    ncu.variables['ubar'].long_name = '2D u-momentum component'
    ncu.variables['ubar'].units = 'meter second-1'
    ncu.variables['ubar'].field = 'ubar-velocity,, scalar, series'

    print('Creating variable v')
    ncv.createVariable('v',
                       'f8', ('ocean_time', 's_rho', 'eta_v', 'xi_v'),
                       fill_value=spval)
    ncv.variables['v'].long_name = '3D v-momentum component'
    ncv.variables['v'].units = 'meter second-1'
    ncv.variables['v'].field = 'v-velocity, scalar, series'
    print('Creating variable vbar')
    ncv.createVariable('vbar',
                       'f8', ('ocean_time', 'eta_v', 'xi_v'),
                       fill_value=spval)
    ncv.variables['vbar'].long_name = '2D v-momentum component'
    ncv.variables['vbar'].units = 'meter second-1'
    ncv.variables['vbar'].field = 'vbar-velocity,, scalar, series'

    # remaping
    print('remapping and rotating u and v from', src_grd.name, \
                      'to', dst_grd.name)
    print('time =', time)

    # flood the grid
    print('flood the grid', src_varu.shape)
    src_uz = pyroms_toolbox.CGrid_GLORYS.flood(src_varu, src_grd, Cpos='u', \
                spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
    src_vz = pyroms_toolbox.CGrid_GLORYS.flood(src_varv, src_grd, Cpos='v', \
                spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)

    # horizontal interpolation using scrip weights
    print('horizontal interpolation using scrip weights')
    dst_uz = pyroms.remapping.remap(src_uz, wts_file_u, \
                                      spval=spval)
    dst_vz = pyroms.remapping.remap(src_vz, wts_file_v, \
                                      spval=spval)

    # vertical interpolation from standard z level to sigma
    print('vertical interpolation from standard z level to sigma')
    dst_u = pyroms.remapping.z2roms(dst_uz[::-1,:,:], dst_grdz, \
                        dst_grd, Cpos='rho', spval=spval, flood=False)
    dst_v = pyroms.remapping.z2roms(dst_vz[::-1,:,:], dst_grdz,  \
                        dst_grd, Cpos='rho', spval=spval, flood=False)

    # rotate u,v fields
    src_angle = src_grd.angle
    src_angle = pyroms.remapping.remap(src_angle, wts_file_a)
    dst_angle = dst_grd.hgrid.angle_rho
    angle = dst_angle - src_angle
    angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))
    U = dst_u + dst_v * 1j
    eitheta = np.exp(-1j * angle[:, :, :])
    U = U * eitheta
    dst_u = np.real(U)
    dst_v = np.imag(U)

    # move back to u,v points
    dst_u = 0.5 * (dst_u[:, :, :-1] + dst_u[:, :, 1:])
    dst_v = 0.5 * (dst_v[:, :-1, :] + dst_v[:, 1:, :])

    # spval
    idxu = np.where(dst_grd.hgrid.mask_u == 0)
    idxv = np.where(dst_grd.hgrid.mask_v == 0)
    for n in range(dst_grd.vgrid.N):
        dst_u[n, idxu[0], idxu[1]] = spval
        dst_v[n, idxv[0], idxv[1]] = spval

    # compute depth average velocity ubar and vbar
    # get z at the right position
    z_u = 0.5 * (dst_grd.vgrid.z_w[0, :, :, :-1] +
                 dst_grd.vgrid.z_w[0, :, :, 1:])
    z_v = 0.5 * (dst_grd.vgrid.z_w[0, :, :-1, :] +
                 dst_grd.vgrid.z_w[0, :, 1:, :])

    dst_ubar = np.zeros((dst_u.shape[1], dst_u.shape[2]))
    dst_vbar = np.zeros((dst_v.shape[1], dst_v.shape[2]))

    for i in range(dst_ubar.shape[1]):
        for j in range(dst_ubar.shape[0]):
            dst_ubar[j, i] = (dst_u[:, j, i] *
                              np.diff(z_u[:, j, i])).sum() / -z_u[0, j, i]

    for i in range(dst_vbar.shape[1]):
        for j in range(dst_vbar.shape[0]):
            dst_vbar[j, i] = (dst_v[:, j, i] *
                              np.diff(z_v[:, j, i])).sum() / -z_v[0, j, i]

    # spval
    dst_ubar[idxu[0], idxu[1]] = spval
    dst_vbar[idxv[0], idxv[1]] = spval

    # write data in destination file
    print('write data in destination file')
    ncu.variables['ocean_time'][0] = time
    ncu.variables['u'][0] = dst_u
    ncu.variables['ubar'][0] = dst_ubar

    ncv.variables['ocean_time'][0] = time
    ncv.variables['v'][0] = dst_v
    ncv.variables['vbar'][0] = dst_vbar

    print(dst_u.shape)
    print(dst_ubar.shape)
    print(dst_v.shape)
    print(dst_vbar.shape)

    # close destination file
    ncu.close()
    ncv.close()
    cdf.close()
Ejemplo n.º 17
0
Archivo: remap.py Proyecto: ESMG/pyroms
def remap(src_varname, src_file, src_grd, dst_grd, dst_file, dmax=0, cdepth=0, kk=0, dst_dir='./'):

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'

    # create tide file
    print '\nCreating tide file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open tide file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    # load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    # get missing value
    spval = src_var.missing_value

    if src_varname == 'h_re':
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_t_to_rho.nc'
        dst_varname = 'h_re'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'tidal constituent amplitude (real)'
        units = 'meter'
        field = 'free-surface, scalar, series'
    if src_varname == 'h_im':
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_t_to_rho.nc'
        dst_varname = 'h_im'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'tidal constituent amplitude (imaginary)'
        units = 'meter'
        field = 'free-surface, scalar, series'

    if src_varname == 'u_re':
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_u_to_rho.nc'
        dst_varname = 'h_re'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'tidal constituent x-velocity (real)'
        units = 'meter per second'
        field = 'x-velocity, scalar, series'
    if src_varname == 'u_im':
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_u_to_rho.nc'
        dst_varname = 'u_im'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'tidal constituent x-velocity (imaginary)'
        units = 'meter per second'
        field = 'x-velocity, scalar, series'

    if src_varname == 'v_re':
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_v_to_rho.nc'
        dst_varname = 'v_re'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'tidal constituent y-velocity (real)'
        units = 'meter per second'
        field = 'y-velocity, scalar, series'
    if src_varname == 'v_im':
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_v_to_rho.nc'
        dst_varname = 'v_im'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'tidal constituent y-velocity (imaginary)'
        units = 'meter per second'
        field = 'y-velocity, scalar, series'

    else:
        raise ValueError, 'Undefined src_varname'

    # create variable in file
    print 'Creating variable', dst_varname
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    # nc.createVariable(dst_varname, 'f8', dimensions)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field

    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_var = pyroms.remapping.remap(src_var, wts_file, spval=spval)

    # write data in destination file
    print 'write data in destination file\n'
    nc.variables[dst_varname][:] = dst_var

    # close file
    nc.close()
    cdf.close()
Ejemplo n.º 18
0
def remap_clm(src_file,
              src_varname,
              src_grd,
              dst_grd,
              dxy=20,
              cdepth=0,
              kk=0,
              dst_dir='./'):

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
    #    ref = datetime(1900, 1, 1, 0, 0, 0)
    #    ref = date2num(ref)
    #    tag = src_file.rsplit('/')[-1].rsplit('_')[-2].rsplit('-')[0]
    #    print tag
    #    year = int(tag[:4])
    #    month = int(tag[4:6])
    #    day = int(tag[6:])
    #    time = datetime(year, month, day, 0, 0, 0)
    #    time = date2num(time)
    #    time = time - ref
    #    time = time + 2.5 # 5-day average
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname][0]
    time = cdf.variables['ocean_time'][0]

    # create IC file
    dst_file = src_file.rsplit('/')[-1]
    dst_file = dst_dir + dst_file[:
                                  -3] + '_' + src_varname + '_clim_' + dst_grd.name + '.nc'
    print '\nCreating file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open IC file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    #get missing value
    spval = src_var._FillValue
    src_var = src_var[0]

    # determine variable dimension
    #ndim = len(src_var.dimensions)
    ndim = len(src_var.shape)

    if src_varname == 'ssh':
        pos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLBa0.08_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'zeta'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'free-surface'
        units = 'meter'
        field = 'free-surface, scalar, series'
        vartime = 'ocean_time'
    elif src_varname == 'temp':
        pos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLBa0.08_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'temp'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'potential temperature'
        units = 'Celsius'
        field = 'temperature, scalar, series'
        vartime = 'ocean_time'
    elif src_varname == 'salt':
        pos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLBa0.08_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'salt'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'salinity'
        units = 'PSU'
        field = 'salinity, scalar, series'
        vartime = 'ocean_time'
    else:
        raise ValueError, 'Undefined src_varname'

    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1, 0, 0]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel,
                                               nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + '_Z', dst_grd.hgrid,
                                         dst_zcoord)

    # create variable in file
    print 'Creating variable', dst_varname
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field
    nc.variables[dst_varname].time = vartime
    #nc.variables[dst_varname_north]._FillValue = spval

    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name
    print 'time =', time

    if ndim == 3:
        # flood the grid
        print 'flood the grid'
        src_varz = pyroms_toolbox.Grid_HYCOM.flood_fast(src_var, src_grd, pos=pos, spval=spval, \
                                dxy=dxy, cdepth=cdepth, kk=kk)
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, \
                                          spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print 'vertical interpolation from standard z level to sigma'
        dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \
                          dst_grd, Cpos=Cpos, spval=spval, flood=False)
    else:
        dst_var = dst_varz

    # write data in destination file
    print 'write data in destination file'
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname][0] = dst_var

    # close destination file
    nc.close()

    if src_varname == 'ssh':
        return dst_varz
Ejemplo n.º 19
0
def remapping_tensor(varname, srcfile, wts_files, srcgrd, dstgrd, \
              rotate_sig=False, trange=None, irange=None, jrange=None, \
              dstdir='./', shapiro=False):
    '''
    A remapping function to go from a ROMS grid to another ROMS grid.
    This is for 2D tensors: internal ice stress, hard-coding for sig11, sig22,
    sig12.
    '''

    # get input and output grid
    if type(srcgrd).__name__ == 'ROMS_Grid':
        srcgrd = srcgrd
    else:
        srcgrd = pyroms.grid.get_ROMS_grid(srcgrd)
    if type(dstgrd).__name__ == 'ROMS_Grid':
        dstgrd = dstgrd
    else:
        dstgrd = pyroms.grid.get_ROMS_grid(dstgrd)

    # varname argument
    if type(varname).__name__ == 'list':
        nvar = len(varname)
    elif type(varname).__name__ == 'str':
        varname = [varname]
        nvar = len(varname)
    else:
        raise ValueError, 'varname must be a str or a list of str'

    # srcfile argument
    if type(srcfile).__name__ == 'list':
        nfile = len(srcfile)
    elif type(srcfile).__name__ == 'str':
        srcfile = sorted(glob.glob(srcfile))
        nfile = len(srcfile)
    else:
        raise ValueError, 'src_srcfile must be a str or a list of str'

    # get wts_file
    if type(wts_files).__name__ == 'str':
        wts_files = sorted(glob.glob(wts_files))
 
    # loop over the srcfile
    for nf in range(nfile):
        print 'Working with file', srcfile[nf], '...'

        # get time 
        ocean_time = pyroms.utility.get_nc_var('ocean_time', srcfile[nf])
        ntime = len(ocean_time[:])

        # trange argument
        if trange is None:
            trange = range(ntime)

        # create destination file
        dstfile = dstdir + os.path.basename(srcfile[nf])[:-3] + '_' + dstgrd.name + '.nc'
        if os.path.exists(dstfile) is False:
            print 'Creating destination file', dstfile
            pyroms_toolbox.nc_create_roms_file(dstfile, dstgrd, ocean_time)

        # open destination file
        nc = netCDF.Dataset(dstfile, 'a', format='NETCDF3_64BIT')

        nctidx = 0
        # loop over time
        for nt in trange:

            nc.variables['ocean_time'][nctidx] = ocean_time[nt]

            # loop over variable
            for nv in range(nvar):
                print ' '
                print 'remapping', varname[nv], 'from', srcgrd.name, \
                      'to', dstgrd.name
                print 'time =', ocean_time[nt]   

                # get source data
                src_var = pyroms.utility.get_nc_var(varname[nv], srcfile[nf])

                # get spval
                try:
                    spval = src_var._FillValue
                except:
                    raise Warning, 'Did not find a _FillValue attribute.' 

                # irange
                if irange is None:
                    iirange = (0,src_var.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0,src_var.shape[-2])
                else:
                    jjrange = jrange

                # determine where on the C-grid these variable lies
                if src_var.dimensions[2].find('_rho') != -1:
                    Cpos='rho'
                else:
                    print "Sigma should be on rho points"

                print 'Arakawa C-grid position is', Cpos

                # create variable in _destination file
                if nt == trange[0]:
                    print 'Creating variable', varname[nv]
                    nc.createVariable(varname[nv], 'f8', src_var.dimensions, fill_value=spval)
                    nc.variables[varname[nv]].long_name = src_var.long_name
                    try:
                        nc.variables[varname[nv]].units = src_var.units
                    except:
                        print varname[nv]+' has no units'
                    nc.variables[varname[nv]].time = src_var.time
                    nc.variables[varname[nv]].coordinates = \
                        src_var.coordinates
                    nc.variables[varname[nv]].field = src_var.field
#                    nc.variables[varname[nv]]._FillValue = spval

                # get the right remap weights file
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__(Cpos+'_to_'+Cpos+'.nc'):
                        wts_file = wts_files[s]
                        break
                    else:
                        if s == len(wts_files) - 1:
                            raise ValueError, 'Did not find the appropriate remap weights file'


                # write data in destination file
#                print 'write data in destination file'
#                nc.variables[varname[nv]][nctidx] = dst_var

            # rotate the velocity field if requested
#            print datetime.datetime.now()
            print ' ' 
            print 'remapping and rotating sigma from', srcgrd.name, \
                  'to', dstgrd.name

            # get source data
            src_11 = pyroms.utility.get_nc_var(varname[0], srcfile[nf])
            # get spval
            try:
                spval = src_11._FillValue
            except:
                raise Warning, 'Did not find a _FillValue attribute.' 

            src_11 = src_11[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]

            src_22 = pyroms.utility.get_nc_var(varname[1], srcfile[nf])
            src_22 = src_22[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]

            src_12 = pyroms.utility.get_nc_var(varname[2], srcfile[nf])
            src_12 = src_12[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]

            print "before", src_11[-1,30], src_12[-1,30], src_22[-1,30]
            if shapiro:
                src_11 = pyroms_toolbox.shapiro_filter.shapiro2(src_11,2)
                src_22 = pyroms_toolbox.shapiro_filter.shapiro2(src_22,2)
                src_12 = pyroms_toolbox.shapiro_filter.shapiro2(src_12,2)
            print "after", src_11[-1,30], src_12[-1,30], src_22[-1,30]

            # horizontal interpolation using scrip weights
            print 'horizontal interpolation using scrip weights'
            dst_11 = pyroms.remapping.remap(src_11, wts_file, \
                                              spval=spval)
            dst_22 = pyroms.remapping.remap(src_22, wts_file, \
                                              spval=spval)
            dst_12 = pyroms.remapping.remap(src_12, wts_file, \
                                              spval=spval)
            print "after remapping", dst_11[-1,30], dst_12[-1,30], dst_22[-1,30]

            if rotate_sig is True:
                # rotate stress tensor
                src_ang = srcgrd.hgrid.angle_rho[jjrange[0]:jjrange[1],iirange[0]:iirange[1]]
                src_angle = pyroms.remapping.remap(src_ang, wts_file)
                dst_angle = dstgrd.hgrid.angle_rho
                angle = dst_angle - src_angle
                cos_ang = np.cos(angle)
                sin_ang = np.sin(angle)
                Lp = cos_ang.shape[-1]
                Mp = cos_ang.shape[-2]
                print "Lp, Mp", Lp, Mp

                for j in range(Mp):
                    for i in range(Lp):
                        Qrot = [[cos_ang[j,i], sin_ang[j,i]],
                               [-sin_ang[j,i], cos_ang[j,i]]]
                        QrotT = [[cos_ang[j,i], -sin_ang[j,i]],
                                 [sin_ang[j,i],  cos_ang[j,i]]]
#                        Qrot = [[cos_ang[j,i], -sin_ang[j,i]],
#                               [sin_ang[j,i], cos_ang[j,i]]]
#                        QrotT = [[cos_ang[j,i], sin_ang[j,i]],
#                                 [-sin_ang[j,i],  cos_ang[j,i]]]
                        sig = [[dst_11[j,i], dst_12[j,i]],
                               [dst_12[j,i], dst_22[j,i]]]
                        sig_rot = np.dot(np.dot(Qrot, sig), QrotT)
                        dst_11[j,i] = sig_rot[0,0]
                        dst_12[j,i] = sig_rot[0,1]
                        dst_22[j,i] = sig_rot[1,1]
                print "after rotating", dst_11[-1,30], dst_12[-1,30], dst_22[-1,30]


            # spval
            idx = np.where(dstgrd.hgrid.mask_rho == 0)
            dst_11[idx[0], idx[1]] = spval
            dst_12[idx[0], idx[1]] = spval
            dst_22[idx[0], idx[1]] = spval

            # write data in destination file
            print 'write data in destination file'
            nc.variables['sig11'][nctidx] = dst_11
            nc.variables['sig12'][nctidx] = dst_12
            nc.variables['sig22'][nctidx] = dst_22

        nctidx = nctidx + 1
 
    # close destination file
    nc.close()

    return
Ejemplo n.º 20
0
def remap(src_file, src_varname, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'):
    
    ystart=690

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
    ref = datetime(1900, 1, 1, 0, 0, 0)
    ref = date2num(ref)
# For IC
    tag = src_file.rsplit('/')[-1].rsplit('_')[2]
    print(("date string:", tag))
    year = int(tag[:4])
    month = int(tag[4:6])
    day = int(tag[6:])
    time = datetime(year, month, day, 0, 0, 0)
    time = date2num(time)
    time = time - ref
    time = time + 0.5 # 1-day average

    # create IC file
    dst_file = src_file.rsplit('/')[-1]
    dst_file = dst_dir + dst_file[:-4] + '_' + src_varname + '_ic_' + dst_grd.name + '.nc'
    print('\nCreating file', dst_file)
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open IC file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    #get missing value
    spval = src_var._FillValue
    add_offset = src_var.add_offset
    scale_factor = src_var.scale_factor
    src_var = np.squeeze(src_var)

    # Use scale_factor, etc
    spval = spval*scale_factor
#    spval = spval*scale_factor + add_offset
#    src_var = src_var*scale_factor + add_offset
#    src_var = src_var + add_offset

    # determine variable dimension
    ndim = len(src_var.shape)

    # global grid
    if ndim == 3:
        src_var = src_var[:]
        src_var = src_var[:,np.r_[ystart:np.size(src_var,1),-1],:]
    elif ndim == 2:
        src_var = src_var[:]
        src_var = src_var[np.r_[ystart:np.size(src_var,0),-1],:]
    print("dimensions:", src_var.shape, ndim)

    if src_varname == 'sossheig':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'zeta'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'free-surface'
        units = 'meter'
        field = 'free-surface, scalar, series'
    elif src_varname == 'iicethic':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'hice'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'ice thickness'
        units = 'meter'
        field = 'ice thickness, scalar, series'
    elif src_varname == 'ileadfra':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'aice'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'ice concentration'
        units = 'meter'
        field = 'ice concentration, scalar, series'
    elif src_varname == 'iicetemp':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'tisrf'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'surface ice temperature'
        units = 'meter'
        field = 'surface ice temperature, scalar, series'
    elif src_varname == 'votemper':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'temp'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'potential temperature'
        units = 'Celsius'
        field = 'temperature, scalar, series'
    elif src_varname == 'vosaline':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'salt'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'salinity'
        units = 'PSU'
        field = 'salinity, scalar, series'
    else:
        raise ValueError('Undefined src_varname')


    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1,0,0]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)


    # create variable in file
    print('Creating variable', dst_varname)
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field


    # remapping
    print('remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name)
    print('time =', time)


    if ndim == 3:
        # flood the grid
        print('flood the grid')
        src_varz = pyroms_toolbox.CGrid_GLORYS.flood(src_var, src_grd, Cpos=Bpos, spval=spval, \
                                dmax=dmax, cdepth=cdepth, kk=kk)
        print('flooded the grid', src_varz[:,-1,189])
        print('flooded the grid', src_varz[:,-1,277])
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print('horizontal interpolation using scrip weights')
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, \
                                          spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print('vertical interpolation from standard z level to sigma')
        dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \
                          dst_grd, Cpos=Cpos, spval=spval, flood=False)
    else:
        dst_var = dst_varz

    # write data in destination file
    print('write data in destination file')
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname][0] = dst_var

    # close destination file
    nc.close()

    if src_varname == 'SSH':
        return dst_varz
Ejemplo n.º 21
0
def remap_clm(src_file, src_varname, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'):
    
    ystart=240

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
    ref = datetime(1900, 1, 1, 0, 0, 0)
    ref = date2num(ref)
# For IC
#    tag = src_file.rsplit('/')[-1].rsplit('_')[-1].rsplit('-')[0]
#    year = int(tag[:4])
#    month = int(tag[4:6])
#    day = int(tag[6:])
#    time = datetime(year, month, day, 0, 0, 0)
# For CLM
    year = int(src_file.rsplit('/')[-1].rsplit('_')[-2])
    month = int(src_file.rsplit('/')[-1].rsplit('_')[-1][0:2])
    day = np.array([15,14,15,15,15,15,15,15,15,15,15,15])
    hour = np.array([12,0,12,0,12,0,12,12,0,12,0,12])
    if year%4 == 0:
        hour = np.array([12,12,12,0,12,0,12,12,0,12,0,12])
    time = datetime(year, month, day[month-1], hour[month-1], 0, 0)
    time = date2num(time)
    time = time - ref
#    time = time + 2.5 # 5-day average

    # create IC file
    dst_file = src_file.rsplit('/')[-1]
    dst_file = dst_dir + dst_file[:-3] + '_' + src_varname + '_clim_' + dst_grd.name + '.nc'
    print '\nCreating file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open IC file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    #get missing value
    spval = src_var._FillValue

    # determine variable dimension
    ndim = len(src_var.dimensions)

    # global grid
    if ndim == 3:
        src_var = src_var[:]
        src_var = src_var[:,np.r_[ystart:np.size(src_var,1),-1],:]
    elif ndim == 2:
        src_var = src_var[:]
        src_var = src_var[np.r_[ystart:np.size(src_var,0),-1],:]

    if src_varname == 'ssh':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_SODA_2.1.6_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'zeta'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'free-surface'
        units = 'meter'
        field = 'free-surface, scalar, series'
        vartime = 'ocean_time'
    elif src_varname == 'temp':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_SODA_2.1.6_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'temp'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'potential temperature'
        units = 'Celsius'
        field = 'temperature, scalar, series'
        vartime = 'ocean_time'
    elif src_varname == 'salt':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_SODA_2.1.6_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'salt'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'salinity'
        units = 'PSU'
        field = 'salinity, scalar, series'
        vartime = 'ocean_time'
    else:
        raise ValueError, 'Undefined src_varname'


    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1,0,0]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)


    # create variable in file
    print 'Creating variable', dst_varname
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field
    nc.variables[dst_varname].time = vartime


    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name
    print 'time =', time


    if ndim == 3:
        # flood the grid
        print 'flood the grid'
        src_varz = pyroms_toolbox.BGrid_SODA.flood(src_var, src_grd, Bpos=Bpos, spval=spval, \
                                dmax=dmax, cdepth=cdepth, kk=kk)
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, \
                                          spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print 'vertical interpolation from standard z level to sigma'
        dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \
                          dst_grd, Cpos=Cpos, spval=spval, flood=False)
    else:
        dst_var = dst_varz

    # write data in destination file
    print 'write data in destination file'
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname][0] = dst_var

    # close destination file
    nc.close()

    if src_varname == 'SSH':
        return dst_varz
Ejemplo n.º 22
0
def remapping_bound_sig(varname, srcfile, wts_files, srcgrd, dst_grd, \
              rotate_sig=False, trange=None, irange=None, jrange=None, \
              dstdir='./' ,zlevel=None, dmax=0, cdepth=0, kk=0):
    '''
    A remapping function to go from a ROMS grid to another ROMS grid.
    This is for 2D tensors: internal ice stress, hard-coding for sig11, sig22,
    sig12.
    '''

    # get input and output grid
    if type(srcgrd).__name__ == 'ROMS_Grid':
        srcgrd = srcgrd
    else:
        srcgrd = pyroms.grid.get_ROMS_grid(srcgrd)
    if type(dst_grd).__name__ == 'ROMS_Grid':
        dst_grd = dst_grd
    else:
        dst_grd = pyroms.grid.get_ROMS_grid(dst_grd)

    # varname argument
    if type(varname).__name__ == 'list':
        nvar = len(varname)
    elif type(varname).__name__ == 'str':
        varname = [varname]
        nvar = len(varname)
    else:
        raise ValueError('varname must be a str or a list of str')

    # srcfile argument
    if type(srcfile).__name__ == 'list':
        nfile = len(srcfile)
    elif type(srcfile).__name__ == 'str':
        srcfile = sorted(glob.glob(srcfile))
        nfile = len(srcfile)
    else:
        raise ValueError('src_srcfile must be a str or a list of str')

    # get wts_file
    if type(wts_files).__name__ == 'str':
        wts_files = sorted(glob.glob(wts_files))

    sides = ['_west','_east','_north','_south']
    long = {'_west':'Western', '_east':'Eastern', \
            '_north':'Northern', '_south':'Southern'}
    dimexcl = {'_west':'xi', '_east':'xi', \
            '_north':'eta', '_south':'eta'}

    nctidx = 0
    # loop over the srcfile
    for nf in range(nfile):
        print('Working with file', srcfile[nf], '...')

        # get time
        ocean_time = pyroms.utility.get_nc_var('ocean_time', srcfile[nf])
        ntime = len(ocean_time[:])

        # trange argument
        if trange is None:
            trange = list(range(ntime))

        # create destination file
        if nctidx == 0:
            dstfile = dstdir + os.path.basename(srcfile[nf])[:-3] + '_' \
                   + dst_grd.name + '_bdry.nc'
            if os.path.exists(dstfile) is False:
                print('Creating destination file', dstfile)
                pyroms_toolbox.nc_create_roms_file(dstfile, dst_grd, \
                    ocean_time, lgrid=False)

            # open destination file
            nc = netCDF.Dataset(dstfile, 'a', format='NETCDF3_64BIT')

        # loop over time
        for nt in trange:

            nc.variables['ocean_time'][nctidx] = ocean_time[nt]

            # loop over variable
            for nv in range(nvar):
                print(' ')
                print('remapping', varname[nv], 'from', srcgrd.name, \
                      'to', dst_grd.name)
                print('time =', ocean_time[nt])
                Mp, Lp = dst_grd.hgrid.mask_rho.shape

                # get source data
                src_var = pyroms.utility.get_nc_var(varname[nv], srcfile[nf])

                # get spval
                try:
                    spval = src_var._FillValue
                except:
                    raise Warning('Did not find a _FillValue attribute.')

                # irange
                if irange is None:
                    iirange = (0,src_var.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0,src_var.shape[-2])
                else:
                    jjrange = jrange

                # determine where on the C-grid these variable lies
                if src_var.dimensions[2].find('_rho') != -1:
                    Cpos='rho'
                else:
                    print("Sigma should be on rho points")

                print('Arakawa C-grid position is', Cpos)

                # create variable in _destination file
                if nctidx == 0:
                    for sid in sides:
                       varn = varname[nv]+str(sid)
                       print('Creating variable', varn)
                       dimens = [i for i in src_var.dimensions]
                       for dim in dimens:
                           if re.match(dimexcl[sid],dim):
                               dimens.remove(dim)
                       nc.createVariable(varn, 'f8', dimens, \
                           fill_value=spval)
                       nc.variables[varn].long_name = varname[nv] + \
                            ' ' + long[sid] + ' boundary condition'
                       try:
                           nc.variables[varn].units = src_var.units
                       except:
                           print(varn+' has no units')
                       nc.variables[varn].time = src_var.time
                       nc.variables[varn].coordinates = \
                           str(dimens.reverse())
                       nc.variables[varn].field = src_var.field

                # get the right remap weights file
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__(Cpos+'_to_'+Cpos+'.nc'):
                        wts_file = wts_files[s]
                        break
                    else:
                        if s == len(wts_files) - 1:
                            raise ValueError('Did not find the appropriate remap weights file')

#                print datetime.datetime.now()
                # horizontal interpolation using scrip weights
#                print 'horizontal interpolation using scrip weights'
            if not rotate_sig:
                dst_var = pyroms.remapping.remap(tmp_src_var, wts_file, \
                                                  spval=spval)

                dst_var_north = dst_var[-1, :]
                dst_var_south = dst_var[0, :]
                dst_var_east = dst_var[:, -1]
                dst_var_west = dst_var[:, 0]

                # write data in destination file
                print('write data in destination file')
                sid = '_west'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_west)

                sid = '_east'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_east)

                sid = '_north'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_north)

                sid = '_south'
                varn = varname[nv]+str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_south)

            # rotate the velocity field if requested
            if rotate_sig:
                print(' ')
                print('remapping and rotating sigma from', srcgrd.name, \
                      'to', dst_grd.name)

                # get source data
                src_11 = pyroms.utility.get_nc_var(varname[0], srcfile[nf])
                # get spval
                try:
                    spval = src_11._FillValue
                except:
                    raise Warning('Did not find a _FillValue attribute.')

                src_11 = src_11[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]

                src_22 = pyroms.utility.get_nc_var(varname[1], srcfile[nf])
                src_22 = src_22[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]

                src_12 = pyroms.utility.get_nc_var(varname[2], srcfile[nf])
                src_12 = src_12[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]


                # horizontal interpolation using scrip weights
                print('horizontal interpolation using scrip weights')
                dst_11 = pyroms.remapping.remap(src_11, wts_file, \
                                                  spval=spval)
                dst_22 = pyroms.remapping.remap(src_22, wts_file, \
                                                  spval=spval)
                dst_12 = pyroms.remapping.remap(src_12, wts_file, \
                                                  spval=spval)
                Mp, Lp = dst_grd.hgrid.mask_rho.shape

                dst_11_north = dst_11[Mp-1, 0:Lp]
                dst_22_north = dst_22[Mp-1, 0:Lp]
                dst_12_north = dst_12[Mp-1, 0:Lp]

                dst_11_south = dst_11[0, 0:Lp]
                dst_22_south = dst_22[0, 0:Lp]
                dst_12_south = dst_12[0, 0:Lp]

                dst_11_east = dst_11[0:Mp, Lp-1]
                dst_22_east = dst_22[0:Mp, Lp-1]
                dst_12_east = dst_12[0:Mp, Lp-1]

                dst_11_west = dst_11[0:Mp, 0]
                dst_22_west = dst_22[0:Mp, 0]
                dst_12_west = dst_12[0:Mp, 0]

                # rotate stress tensor
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__('rho_to_rho.nc'):
                        wts_file = wts_files[s]
                src_ang = srcgrd.hgrid.angle_rho[jjrange[0]:jjrange[1],iirange[0]:iirange[1]]
                src_angle = pyroms.remapping.remap(src_ang, wts_file)
                dst_angle = dst_grd.hgrid.angle_rho
                angle = dst_angle - src_angle
                cos_ang = np.cos(angle)
                sin_ang = np.sin(angle)
                Lp = cos_ang.shape[-1]
                Mp = cos_ang.shape[-2]
                print("Lp, Mp", Lp, Mp)

                if rotate_sig:
                    # North
                    for i in range(Lp):
                        Qrot = [[cos_ang[Mp-1,i], sin_ang[Mp-1,i]],
                               [-sin_ang[Mp-1,i], cos_ang[Mp-1,i]]]
                        QrotT = [[cos_ang[Mp-1,i], -sin_ang[Mp-1,i]],
                                 [sin_ang[Mp-1,i],  cos_ang[Mp-1,i]]]
                        sig = [[dst_11_north[i], dst_12_north[i]],
                               [dst_12_north[i], dst_22_north[i]]]
                        sig_rot = np.dot(np.dot(Qrot, sig), QrotT)
                        dst_11_north[i] = sig_rot[0,0]
                        dst_12_north[i] = sig_rot[0,1]
                        dst_22_north[i] = sig_rot[1,1]

                    # South
                    for i in range(Lp):
                        Qrot = [[cos_ang[0,i], sin_ang[0,i]],
                               [-sin_ang[0,i], cos_ang[0,i]]]
                        QrotT = [[cos_ang[0,i], -sin_ang[0,i]],
                                 [sin_ang[0,i],  cos_ang[0,i]]]
                        sig = [[dst_11_south[i], dst_12_south[i]],
                               [dst_12_south[i], dst_22_south[i]]]
                        sig_rot = np.dot(np.dot(Qrot, sig), QrotT)
                        dst_11_south[i] = sig_rot[0,0]
                        dst_12_south[i] = sig_rot[0,1]
                        dst_22_south[i] = sig_rot[1,1]

                    # East
                    for j in range(Mp):
                        Qrot = [[cos_ang[j,Lp-1], sin_ang[j,Lp-1]],
                               [-sin_ang[j,Lp-1], cos_ang[j,Lp-1]]]
                        QrotT = [[cos_ang[j,Lp-1], -sin_ang[j,Lp-1]],
                                 [sin_ang[j,Lp-1],  cos_ang[j,Lp-1]]]
                        sig = [[dst_11_east[j], dst_12_east[j]],
                               [dst_12_east[j], dst_22_east[j]]]
                        sig_rot = np.dot(np.dot(Qrot, sig), QrotT)
                        dst_11_east[j] = sig_rot[0,0]
                        dst_12_east[j] = sig_rot[0,1]
                        dst_22_east[j] = sig_rot[1,1]

                    # West
                    for j in range(Mp):
                        Qrot = [[cos_ang[j,0], sin_ang[j,0]],
                               [-sin_ang[j,0], cos_ang[j,0]]]
                        QrotT = [[cos_ang[j,0], -sin_ang[j,0]],
                                 [sin_ang[j,0],  cos_ang[j,0]]]
                        sig = [[dst_11_west[j], dst_12_west[j]],
                               [dst_12_west[j], dst_22_west[j]]]
                        sig_rot = np.dot(np.dot(Qrot, sig), QrotT)
                        dst_11_west[j] = sig_rot[0,0]
                        dst_12_west[j] = sig_rot[0,1]
                        dst_22_west[j] = sig_rot[1,1]


                # spval
                idx_north = np.where(dst_grd.hgrid.mask_rho[-1,:] == 0)
                idx_south = np.where(dst_grd.hgrid.mask_rho[0,:] == 0)
                idx_east = np.where(dst_grd.hgrid.mask_rho[:,-1] == 0)
                idx_west = np.where(dst_grd.hgrid.mask_rho[:,0] == 0)

                dst_11_north[idx_north[0]] = spval
                dst_22_north[idx_north[0]] = spval
                dst_12_north[idx_north[0]] = spval
                dst_11_south[idx_south[0]] = spval
                dst_22_south[idx_south[0]] = spval
                dst_12_south[idx_south[0]] = spval
                dst_11_east[idx_east[0]] = spval
                dst_22_east[idx_east[0]] = spval
                dst_12_east[idx_east[0]] = spval
                dst_11_west[idx_west[0]] = spval
                dst_22_west[idx_west[0]] = spval
                dst_12_west[idx_west[0]] = spval

                # write data in destination file
                print('write data in destination file')
                sid = '_west'
                varn = 'sig11'+str(sid)
                nc.variables[varn][nctidx] = dst_11_west
                varn = 'sig22'+str(sid)
                nc.variables[varn][nctidx] = dst_22_west
                varn = 'sig12'+str(sid)
                nc.variables[varn][nctidx] = dst_12_west

                sid = '_north'
                varn = 'sig11'+str(sid)
                nc.variables[varn][nctidx] = dst_11_north
                varn = 'sig22'+str(sid)
                nc.variables[varn][nctidx] = dst_22_north
                varn = 'sig12'+str(sid)
                nc.variables[varn][nctidx] = dst_12_north

                sid = '_east'
                varn = 'sig11'+str(sid)
                nc.variables[varn][nctidx] = dst_11_east
                varn = 'sig22'+str(sid)
                nc.variables[varn][nctidx] = dst_22_east
                varn = 'sig12'+str(sid)
                nc.variables[varn][nctidx] = dst_12_east

                sid = '_south'
                varn = 'sig11'+str(sid)
                nc.variables[varn][nctidx] = dst_11_south
                varn = 'sig22'+str(sid)
                nc.variables[varn][nctidx] = dst_22_south
                varn = 'sig12'+str(sid)
                nc.variables[varn][nctidx] = dst_12_south

            nctidx = nctidx + 1
            nc.sync()
        # close files here? how?

    # close destination file
    nc.close()

    return
Ejemplo n.º 23
0
def remap_bdry_uv(src_file, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'):

    # YELLOW grid sub-sample
    xrange=(225, 275); yrange=(190, 240)

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
    ref = datetime(1900, 1, 1, 0, 0, 0)
    ref = date2num(ref)
    tag = src_file.rsplit('/')[-1].rsplit('_')[-1].rsplit('-')[0]
    year = int(tag[:4])
    month = int(tag[4:6])
    day = int(tag[6:])
    time = datetime(year, month, day, 0, 0, 0)
    time = date2num(time)
    time = time - ref
    time = time + 2.5 # 5-day average

    # get dimensions
    Mp, Lp = dst_grd.hgrid.mask_rho.shape

    # create destination file
    dst_file = src_file.rsplit('/')[-1]
    dst_fileu = dst_dir + dst_file[:-4] + '_u_bdry_' + dst_grd.name + '.nc'
    print '\nCreating destination file', dst_fileu
    if os.path.exists(dst_fileu) is True:
        os.remove(dst_fileu)
    pyroms_toolbox.nc_create_roms_file(dst_fileu, dst_grd, nctime)
    dst_filev = dst_dir + dst_file[:-4] + '_v_bdry_' + dst_grd.name + '.nc'
    print 'Creating destination file', dst_filev
    if os.path.exists(dst_filev) is True:
        os.remove(dst_filev)
    pyroms_toolbox.nc_create_roms_file(dst_filev, dst_grd, nctime)

    # open destination file
    ncu = netCDF.Dataset(dst_fileu, 'a', format='NETCDF3_CLASSIC')
    ncv = netCDF.Dataset(dst_filev, 'a', format='NETCDF3_CLASSIC')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_varu = cdf.variables['u']
    src_varv = cdf.variables['v']

    #get missing value
    spval = src_varu._FillValue

    # YELLOW grid sub-sample
    src_varu = src_varu[:, yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]
    src_varv = src_varv[:, yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]

    # get weights file
    wts_file = 'remap_weights_SODA_2.1.6_to_YELLOW_bilinear_uv_to_rho.nc'

    # build intermediate zgrid
    zlevel = -src_grd.z_t[::-1,0,0]
    nzlevel = len(zlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)

    # create variable in destination file
    print 'Creating variable u_north'
    ncu.createVariable('u_north', 'f8', ('ocean_time', 's_rho', 'xi_u'), fill_value=spval)
    ncu.variables['u_north'].long_name = '3D u-momentum north boundary condition'
    ncu.variables['u_north'].units = 'meter second-1'
    ncu.variables['u_north'].field = 'u_north, scalar, series'
    print 'Creating variable u_south'
    ncu.createVariable('u_south', 'f8', ('ocean_time', 's_rho', 'xi_u'), fill_value=spval)
    ncu.variables['u_south'].long_name = '3D u-momentum south boundary condition'
    ncu.variables['u_south'].units = 'meter second-1'
    ncu.variables['u_south'].field = 'u_south, scalar, series'
    print 'Creating variable u_east'
    ncu.createVariable('u_east', 'f8', ('ocean_time', 's_rho', 'eta_u'), fill_value=spval)
    ncu.variables['u_east'].long_name = '3D u-momentum east boundary condition'
    ncu.variables['u_east'].units = 'meter second-1'
    ncu.variables['u_east'].field = 'u_east, scalar, series'
    print 'Creating variable u_west'
    ncu.createVariable('u_west', 'f8', ('ocean_time', 's_rho', 'eta_u'), fill_value=spval)
    ncu.variables['u_west'].long_name = '3D u-momentum west boundary condition'
    ncu.variables['u_west'].units = 'meter second-1'
    ncu.variables['u_west'].field = 'u_east, scalar, series'

    # create variable in destination file
    print 'Creating variable ubar_north'
    ncu.createVariable('ubar_north', 'f8', ('ocean_time', 'xi_u'), fill_value=spval)
    ncu.variables['ubar_north'].long_name = '2D u-momentum north boundary condition'
    ncu.variables['ubar_north'].units = 'meter second-1'
    ncu.variables['ubar_north'].field = 'ubar_north, scalar, series'
    print 'Creating variable ubar_south'
    ncu.createVariable('ubar_south', 'f8', ('ocean_time', 'xi_u'), fill_value=spval)
    ncu.variables['ubar_south'].long_name = '2D u-momentum south boundary condition'
    ncu.variables['ubar_south'].units = 'meter second-1'
    ncu.variables['ubar_south'].field = 'ubar_south, scalar, series'
    print 'Creating variable ubar_east'
    ncu.createVariable('ubar_east', 'f8', ('ocean_time', 'eta_u'), fill_value=spval)
    ncu.variables['ubar_east'].long_name = '2D u-momentum east boundary condition'
    ncu.variables['ubar_east'].units = 'meter second-1'
    ncu.variables['ubar_east'].field = 'ubar_east, scalar, series'
    print 'Creating variable ubar_west'
    ncu.createVariable('ubar_west', 'f8', ('ocean_time', 'eta_u'), fill_value=spval)
    ncu.variables['ubar_west'].long_name = '2D u-momentum west boundary condition'
    ncu.variables['ubar_west'].units = 'meter second-1'
    ncu.variables['ubar_west'].field = 'ubar_east, scalar, series'


    print 'Creating variable v_north'
    ncv.createVariable('v_north', 'f8', ('ocean_time', 's_rho', 'xi_v'), fill_value=spval)
    ncv.variables['v_north'].long_name = '3D v-momentum north boundary condition'
    ncv.variables['v_north'].units = 'meter second-1'
    ncv.variables['v_north'].field = 'v_north, scalar, series'
    print 'Creating variable v_south'
    ncv.createVariable('v_south', 'f8', ('ocean_time', 's_rho', 'xi_v'), fill_value=spval)
    ncv.variables['v_south'].long_name = '3D v-momentum south boundary condition'
    ncv.variables['v_south'].units = 'meter second-1'
    ncv.variables['v_south'].field = 'v_south, scalar, series'
    print 'Creating variable v_east'
    ncv.createVariable('v_east', 'f8', ('ocean_time', 's_rho', 'eta_v'), fill_value=spval)
    ncv.variables['v_east'].long_name = '3D v-momentum east boundary condition'
    ncv.variables['v_east'].units = 'meter second-1'
    ncv.variables['v_east'].field = 'v_east, scalar, series'
    print 'Creating variable v_west'
    ncv.createVariable('v_west', 'f8', ('ocean_time', 's_rho', 'eta_v'), fill_value=spval)
    ncv.variables['v_west'].long_name = '3D v-momentum west boundary condition'
    ncv.variables['v_west'].units = 'meter second-1'
    ncv.variables['v_west'].field = 'v_east, scalar, series'

    print 'Creating variable vbar_north'
    ncv.createVariable('vbar_north', 'f8', ('ocean_time', 'xi_v'), fill_value=spval)
    ncv.variables['vbar_north'].long_name = '2D v-momentum north boundary condition'
    ncv.variables['vbar_north'].units = 'meter second-1'
    ncv.variables['vbar_north'].field = 'vbar_north, scalar, series'
    print 'Creating variable vbar_south'
    ncv.createVariable('vbar_south', 'f8', ('ocean_time', 'xi_v'), fill_value=spval)
    ncv.variables['vbar_south'].long_name = '2D v-momentum south boundary condition'
    ncv.variables['vbar_south'].units = 'meter second-1'
    ncv.variables['vbar_south'].field = 'vbar_south, scalar, series'
    print 'Creating variable vbar_east'
    ncv.createVariable('vbar_east', 'f8', ('ocean_time', 'eta_v'), fill_value=spval)
    ncv.variables['vbar_east'].long_name = '2D v-momentum east boundary condition'
    ncv.variables['vbar_east'].units = 'meter second-1'
    ncv.variables['vbar_east'].field = 'vbar_east, scalar, series'
    print 'Creating variable vbar_west'
    ncv.createVariable('vbar_west', 'f8', ('ocean_time', 'eta_v'), fill_value=spval)
    ncv.variables['vbar_west'].long_name = '2D v-momentum west boundary condition'
    ncv.variables['vbar_west'].units = 'meter second-1'
    ncv.variables['vbar_west'].field = 'vbar_east, scalar, series'

 

    # remaping
    print 'remapping and rotating u and v from', src_grd.name, \
                      'to', dst_grd.name
    print 'time =', time


    # flood the grid
    print 'flood the grid'
    src_uz = pyroms_toolbox.BGrid_SODA.flood(src_varu, src_grd, Bpos='uv', \
                spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
    src_vz = pyroms_toolbox.BGrid_SODA.flood(src_varv, src_grd, Bpos='uv', \
                spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_uz = pyroms.remapping.remap(src_uz, wts_file, \
                                      spval=spval)
    dst_vz = pyroms.remapping.remap(src_vz, wts_file, \
                                      spval=spval)

    # vertical interpolation from standard z level to sigma
    print 'vertical interpolation from standard z level to sigma'
    dst_u_north = pyroms.remapping.z2roms(dst_uz[::-1, Mp-2:Mp, 0:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,Lp), jrange=(Mp-2,Mp))
    dst_u_south = pyroms.remapping.z2roms(dst_uz[::-1, 0:2, 0:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,Lp), jrange=(0,2))
    dst_u_east = pyroms.remapping.z2roms(dst_uz[::-1, 0:Mp, Lp-2:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(Lp-2,Lp), jrange=(0,Mp))
    dst_u_west = pyroms.remapping.z2roms(dst_uz[::-1, 0:Mp, 0:2], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,2), jrange=(0,Mp))

    dst_v_north = pyroms.remapping.z2roms(dst_vz[::-1, Mp-2:Mp, 0:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,Lp), jrange=(Mp-2,Mp))
    dst_v_south = pyroms.remapping.z2roms(dst_vz[::-1, 0:2, 0:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,Lp), jrange=(0,2))
    dst_v_east = pyroms.remapping.z2roms(dst_vz[::-1, 0:Mp, Lp-2:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(Lp-2,Lp), jrange=(0,Mp))
    dst_v_west = pyroms.remapping.z2roms(dst_vz[::-1, 0:Mp, 0:2], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,2), jrange=(0,Mp))


    # rotate u,v fields
    wtsfile = 'remap_weights_GFDL_CM2.1_to_NEP5_bilinear_t_to_rho.nc'
    src_angle = np.zeros(dst_grd.hgrid.angle_rho.shape)
    dst_angle = dst_grd.hgrid.angle_rho
    angle = dst_angle - src_angle
    angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))
    U_north = dst_u_north + dst_v_north*1j
    eitheta_north = np.exp(-1j*angle[:,Mp-2:Mp, 0:Lp])
    U_north = U_north * eitheta_north
    dst_u_north = np.real(U_north)
    dst_v_north = np.imag(U_north)

    U_south = dst_u_south + dst_v_south*1j
    eitheta_south = np.exp(-1j*angle[:,0:2, 0:Lp])
    U_south = U_south * eitheta_south
    dst_u_south = np.real(U_south)
    dst_v_south = np.imag(U_south)

    U_east = dst_u_east + dst_v_east*1j
    eitheta_east = np.exp(-1j*angle[:,0:Mp, Lp-2:Lp])
    U_east = U_east * eitheta_east
    dst_u_east = np.real(U_east)
    dst_v_east = np.imag(U_east)

    U_west = dst_u_west + dst_v_west*1j
    eitheta_west = np.exp(-1j*angle[:,0:Mp, 0:2])
    U_west = U_west * eitheta_west
    dst_u_west = np.real(U_west)
    dst_v_west = np.imag(U_west)


    # move back to u,v points
    dst_u_north = 0.5 * np.squeeze(dst_u_north[:,-1,:-1] + dst_u_north[:,-1,1:])
    dst_v_north = 0.5 * np.squeeze(dst_v_north[:,:-1,:] + dst_v_north[:,1:,:])
    dst_u_south = 0.5 * np.squeeze(dst_u_south[:,0,:-1] + dst_u_south[:,0,1:])
    dst_v_south = 0.5 * np.squeeze(dst_v_south[:,:-1,:] + dst_v_south[:,1:,:])
    dst_u_east = 0.5 * np.squeeze(dst_u_east[:,:,:-1] + dst_u_east[:,:,1:])
    dst_v_east = 0.5 * np.squeeze(dst_v_east[:,:-1,-1] + dst_v_east[:,1:,-1])
    dst_u_west = 0.5 * np.squeeze(dst_u_west[:,:,:-1] + dst_u_west[:,:,1:])
    dst_v_west = 0.5 * np.squeeze(dst_v_west[:,:-1,0] + dst_v_west[:,1:,0])

    # spval
    idxu_north = np.where(dst_grd.hgrid.mask_u[-1,:] == 0)
    idxv_north = np.where(dst_grd.hgrid.mask_v[-1,:] == 0)
    idxu_south = np.where(dst_grd.hgrid.mask_u[0,:] == 0)
    idxv_south = np.where(dst_grd.hgrid.mask_v[0,:] == 0)
    idxu_east = np.where(dst_grd.hgrid.mask_u[:,-1] == 0)
    idxv_east = np.where(dst_grd.hgrid.mask_v[:,-1] == 0)
    idxu_west = np.where(dst_grd.hgrid.mask_u[:,0] == 0)
    idxv_west = np.where(dst_grd.hgrid.mask_v[:,0] == 0)
    for n in range(dst_grd.vgrid.N): 
        dst_u_north[n, idxu_north[0]] = spval
        dst_v_north[n, idxv_north[0]] = spval
        dst_u_south[n, idxu_south[0]] = spval
        dst_v_south[n, idxv_south[0]] = spval
        dst_u_east[n, idxu_east[0]] = spval
        dst_v_east[n, idxv_east[0]] = spval
        dst_u_west[n, idxu_west[0]] = spval
        dst_v_west[n, idxv_west[0]] = spval

    # compute depth average velocity ubar and vbar
    # get z at the right position
    z_u_north = 0.5 * (dst_grd.vgrid.z_w[0,:,-1,:-1] + dst_grd.vgrid.z_w[0,:,-1,1:])
    z_v_north = 0.5 * (dst_grd.vgrid.z_w[0,:,-1,:] + dst_grd.vgrid.z_w[0,:,-2,:])
    z_u_south = 0.5 * (dst_grd.vgrid.z_w[0,:,0,:-1] + dst_grd.vgrid.z_w[0,:,0,1:])
    z_v_south = 0.5 * (dst_grd.vgrid.z_w[0,:,0,:] + dst_grd.vgrid.z_w[0,:,1,:])
    z_u_east = 0.5 * (dst_grd.vgrid.z_w[0,:,:,-1] + dst_grd.vgrid.z_w[0,:,:,-2])
    z_v_east = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,-1] + dst_grd.vgrid.z_w[0,:,1:,-1])
    z_u_west = 0.5 * (dst_grd.vgrid.z_w[0,:,:,0] + dst_grd.vgrid.z_w[0,:,:,1])
    z_v_west = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,0] + dst_grd.vgrid.z_w[0,:,1:,0])

    dst_ubar_north = np.zeros(dst_u_north.shape[1])
    dst_ubar_south = np.zeros(dst_u_south.shape[1])
    dst_ubar_east = np.zeros(dst_u_east.shape[1])
    dst_ubar_west = np.zeros(dst_u_west.shape[1])
    dst_vbar_north = np.zeros(dst_v_north.shape[1])
    dst_vbar_south = np.zeros(dst_v_south.shape[1])
    dst_vbar_east = np.zeros(dst_v_east.shape[1])
    dst_vbar_west = np.zeros(dst_v_west.shape[1])

    for i in range(dst_u_north.shape[1]):
        dst_ubar_north[i] = (dst_u_north[:,i] * np.diff(z_u_north[:,i])).sum() / -z_u_north[0,i]
        dst_ubar_south[i] = (dst_u_south[:,i] * np.diff(z_u_south[:,i])).sum() / -z_u_south[0,i]
    for i in range(dst_v_north.shape[1]):
        dst_vbar_north[i] = (dst_v_north[:,i] * np.diff(z_v_north[:,i])).sum() / -z_v_north[0,i]
        dst_vbar_south[i] = (dst_v_south[:,i] * np.diff(z_v_south[:,i])).sum() / -z_v_south[0,i]
    for j in range(dst_u_east.shape[1]):
        dst_ubar_east[j] = (dst_u_east[:,j] * np.diff(z_u_east[:,j])).sum() / -z_u_east[0,j]
        dst_ubar_west[j] = (dst_u_west[:,j] * np.diff(z_u_west[:,j])).sum() / -z_u_west[0,j]
    for j in range(dst_v_east.shape[1]):
        dst_vbar_east[j] = (dst_v_east[:,j] * np.diff(z_v_east[:,j])).sum() / -z_v_east[0,j]
        dst_vbar_west[j] = (dst_v_west[:,j] * np.diff(z_v_west[:,j])).sum() / -z_v_west[0,j]
        
    #mask
    dst_ubar_north = np.ma.masked_where(dst_grd.hgrid.mask_u[-1,:] == 0, dst_ubar_north)   
    dst_ubar_south = np.ma.masked_where(dst_grd.hgrid.mask_u[0,:] == 0, dst_ubar_south)   
    dst_ubar_east = np.ma.masked_where(dst_grd.hgrid.mask_u[:,-1] == 0, dst_ubar_east)   
    dst_ubar_west = np.ma.masked_where(dst_grd.hgrid.mask_u[:,0] == 0, dst_ubar_west)   
    dst_vbar_north = np.ma.masked_where(dst_grd.hgrid.mask_v[-1,:] == 0, dst_vbar_north)   
    dst_vbar_south = np.ma.masked_where(dst_grd.hgrid.mask_v[0,:] == 0, dst_vbar_south)   
    dst_vbar_east = np.ma.masked_where(dst_grd.hgrid.mask_v[:,-1] == 0, dst_vbar_east)   
    dst_vbar_west = np.ma.masked_where(dst_grd.hgrid.mask_v[:,0] == 0, dst_vbar_west)   

    # write data in destination file
    print 'write data in destination file'
    ncu.variables['ocean_time'][0] = time
    ncu.variables['u_north'][0] = dst_u_north
    ncu.variables['u_south'][0] = dst_u_south
    ncu.variables['u_east'][0] = dst_u_east
    ncu.variables['u_west'][0] = dst_u_west
    ncu.variables['ubar_north'][0] = dst_ubar_north
    ncu.variables['ubar_south'][0] = dst_ubar_south
    ncu.variables['ubar_east'][0] = dst_ubar_east
    ncu.variables['ubar_west'][0] = dst_ubar_west

    ncv.variables['ocean_time'][0] = time
    ncv.variables['v_north'][0] = dst_v_north
    ncv.variables['v_south'][0] = dst_v_south
    ncv.variables['v_east'][0] = dst_v_east
    ncv.variables['v_west'][0] = dst_v_west
    ncv.variables['vbar_north'][0] = dst_vbar_north
    ncv.variables['vbar_south'][0] = dst_vbar_south
    ncv.variables['vbar_east'][0] = dst_vbar_east
    ncv.variables['vbar_west'][0] = dst_vbar_west

    # close file
    ncu.close()
    ncv.close()
    cdf.close()
Ejemplo n.º 24
0
zr = get_z(grd.vgrid.h, grd.vgrid.hc, grd.vgrid.N, grd.vgrid.s_rho,
           grd.vgrid.Cs_r, np.zeros(zice.shape), grd.vgrid.Vtrans, zice)

# ------------ generate ic file ----------------------------------------
ic_file = './fjord_ic_test.nc'


class ocean_time_info(object):
    pass


ocean_time = ocean_time_info()
ocean_time.long_name = 'seconds since 00-00-00'
ocean_time.units = 'second'

pyroms_toolbox.nc_create_roms_file(ic_file, grd, ocean_time, geogrid=False)

# ------------ write ic values -----------------------------------------
z_pyc = 10.
zeta = 0.
ubar = 0.
vbar = 0.
u = 0.
v = 0.
temp = np.zeros((1, grd.vgrid.N) + grd.vgrid.h.shape)
salt = np.zeros((1, grd.vgrid.N) + grd.vgrid.h.shape)
temp[0, :] = 4. + 2. * (np.tanh(0.025 * np.pi * (zr + z_pyc)) + 1)
salt[0, :] = 30. - 10. * (np.tanh(0.025 * np.pi * (zr + z_pyc)) + 1)
dye_01 = 0.
spval = -1.0e20
Ejemplo n.º 25
0
Archivo: remap.py Proyecto: ESMG/pyroms
def remap(src_file, src_varname, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'):
    
    ystart=690

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
    ref = datetime(1900, 1, 1, 0, 0, 0)
    ref = date2num(ref)
# For IC
    tag = src_file.rsplit('/')[-1].rsplit('_')[2]
    print("date string:", tag)
    year = int(tag[:4])
    month = int(tag[4:6])
    day = int(tag[6:])
    time = datetime(year, month, day, 0, 0, 0)
    time = date2num(time)
    time = time - ref
    time = time + 0.5 # 1-day average

    # create IC file
    dst_file = src_file.rsplit('/')[-1]
    dst_file = dst_dir + dst_file[:-4] + '_' + src_varname + '_ic_' + dst_grd.name + '.nc'
    print '\nCreating file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open IC file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    #get missing value
    spval = src_var._FillValue
    add_offset = src_var.add_offset
    scale_factor = src_var.scale_factor
    src_var = np.squeeze(src_var)

    # Use scale_factor, etc
    spval = spval*scale_factor
#    spval = spval*scale_factor + add_offset
#    src_var = src_var*scale_factor + add_offset
#    src_var = src_var + add_offset

    # determine variable dimension
    ndim = len(src_var.shape)

    # global grid
    if ndim == 3:
        src_var = src_var[:]
        src_var = src_var[:,np.r_[ystart:np.size(src_var,1),-1],:]
    elif ndim == 2:
        src_var = src_var[:]
        src_var = src_var[np.r_[ystart:np.size(src_var,0),-1],:]
    print "dimensions:", src_var.shape, ndim

    if src_varname == 'sossheig':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'zeta'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'free-surface'
        units = 'meter'
        field = 'free-surface, scalar, series'
    elif src_varname == 'iicethic':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'hice'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'ice thickness'
        units = 'meter'
        field = 'ice thickness, scalar, series'
    elif src_varname == 'ileadfra':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'aice'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'ice concentration'
        units = 'meter'
        field = 'ice concentration, scalar, series'
    elif src_varname == 'iicetemp':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'tisrf'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'surface ice temperature'
        units = 'meter'
        field = 'surface ice temperature, scalar, series'
    elif src_varname == 'votemper':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'temp'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'potential temperature'
        units = 'Celsius'
        field = 'temperature, scalar, series'
    elif src_varname == 'vosaline':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'salt'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'salinity'
        units = 'PSU'
        field = 'salinity, scalar, series'
    else:
        raise ValueError, 'Undefined src_varname'


    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1,0,0]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)


    # create variable in file
    print 'Creating variable', dst_varname
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field


    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name
    print 'time =', time


    if ndim == 3:
        # flood the grid
        print 'flood the grid'
        src_varz = pyroms_toolbox.CGrid_GLORYS.flood(src_var, src_grd, Cpos=Bpos, spval=spval, \
                                dmax=dmax, cdepth=cdepth, kk=kk)
        print 'flooded the grid', src_varz[:,-1,189]
        print 'flooded the grid', src_varz[:,-1,277]
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, \
                                          spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print 'vertical interpolation from standard z level to sigma'
        dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \
                          dst_grd, Cpos=Cpos, spval=spval, flood=False)
    else:
        dst_var = dst_varz

    # write data in destination file
    print 'write data in destination file'
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname][0] = dst_var

    # close destination file
    nc.close()

    if src_varname == 'SSH':
        return dst_varz
Ejemplo n.º 26
0
def remap_bdry_uv(src_file, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'):

    # Arctic
    ystart=240

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
    ref = datetime(1900, 1, 1, 0, 0, 0)
    ref = date2num(ref)
    tag = src_file.rsplit('/')[-1].rsplit('_')[-1].rsplit('-')[0]
    year = int(tag[:4])
    month = int(tag[4:6])
    day = int(tag[6:])
    time = datetime(year, month, day, 0, 0, 0)
    time = date2num(time)
    time = time - ref
    time = time + 2.5 # 5-day average

    # get dimensions
    Mp, Lp = dst_grd.hgrid.mask_rho.shape

    # create destination file
    dst_file = src_file.rsplit('/')[-1]
    dst_fileu = dst_dir + dst_file[:-4] + '_u_bdry_' + dst_grd.name + '.nc'
    print '\nCreating destination file', dst_fileu
    if os.path.exists(dst_fileu) is True:
        os.remove(dst_fileu)
    pyroms_toolbox.nc_create_roms_file(dst_fileu, dst_grd, nctime)
    dst_filev = dst_dir + dst_file[:-4] + '_v_bdry_' + dst_grd.name + '.nc'
    print 'Creating destination file', dst_filev
    if os.path.exists(dst_filev) is True:
        os.remove(dst_filev)
    pyroms_toolbox.nc_create_roms_file(dst_filev, dst_grd, nctime)

    # open destination file
    ncu = netCDF.Dataset(dst_fileu, 'a', format='NETCDF3_64BIT')
    ncv = netCDF.Dataset(dst_filev, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_varu = cdf.variables['u']
    src_varv = cdf.variables['v']

    #get missing value
    spval = src_varu._FillValue

    # ARCTIC2 grid sub-sample
    src_varu = src_varu[:]
    src_varu = src_varu[:,np.r_[ystart:np.size(src_varu,1),-1],:]
    src_varv = src_varv[:]
    src_varv = src_varv[:,np.r_[ystart:np.size(src_varv,1),-1],:]

    # get weights file
    wts_file = 'remap_weights_SODA_2.1.6_to_ARCTIC2_bilinear_uv_to_rho.nc'

    # build intermediate zgrid
    zlevel = -src_grd.z_t[::-1,0,0]
    nzlevel = len(zlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)

    # create variable in destination file
    print 'Creating variable u_north'
    ncu.createVariable('u_north', 'f8', ('ocean_time', 's_rho', 'xi_u'), fill_value=spval)
    ncu.variables['u_north'].long_name = '3D u-momentum north boundary condition'
    ncu.variables['u_north'].units = 'meter second-1'
    ncu.variables['u_north'].field = 'u_north, scalar, series'
    print 'Creating variable u_south'
    ncu.createVariable('u_south', 'f8', ('ocean_time', 's_rho', 'xi_u'), fill_value=spval)
    ncu.variables['u_south'].long_name = '3D u-momentum south boundary condition'
    ncu.variables['u_south'].units = 'meter second-1'
    ncu.variables['u_south'].field = 'u_south, scalar, series'
    print 'Creating variable u_east'
    ncu.createVariable('u_east', 'f8', ('ocean_time', 's_rho', 'eta_u'), fill_value=spval)
    ncu.variables['u_east'].long_name = '3D u-momentum east boundary condition'
    ncu.variables['u_east'].units = 'meter second-1'
    ncu.variables['u_east'].field = 'u_east, scalar, series'
    print 'Creating variable u_west'
    ncu.createVariable('u_west', 'f8', ('ocean_time', 's_rho', 'eta_u'), fill_value=spval)
    ncu.variables['u_west'].long_name = '3D u-momentum west boundary condition'
    ncu.variables['u_west'].units = 'meter second-1'
    ncu.variables['u_west'].field = 'u_east, scalar, series'

    # create variable in destination file
    print 'Creating variable ubar_north'
    ncu.createVariable('ubar_north', 'f8', ('ocean_time', 'xi_u'), fill_value=spval)
    ncu.variables['ubar_north'].long_name = '2D u-momentum north boundary condition'
    ncu.variables['ubar_north'].units = 'meter second-1'
    ncu.variables['ubar_north'].field = 'ubar_north, scalar, series'
    print 'Creating variable ubar_south'
    ncu.createVariable('ubar_south', 'f8', ('ocean_time', 'xi_u'), fill_value=spval)
    ncu.variables['ubar_south'].long_name = '2D u-momentum south boundary condition'
    ncu.variables['ubar_south'].units = 'meter second-1'
    ncu.variables['ubar_south'].field = 'ubar_south, scalar, series'
    print 'Creating variable ubar_east'
    ncu.createVariable('ubar_east', 'f8', ('ocean_time', 'eta_u'), fill_value=spval)
    ncu.variables['ubar_east'].long_name = '2D u-momentum east boundary condition'
    ncu.variables['ubar_east'].units = 'meter second-1'
    ncu.variables['ubar_east'].field = 'ubar_east, scalar, series'
    print 'Creating variable ubar_west'
    ncu.createVariable('ubar_west', 'f8', ('ocean_time', 'eta_u'), fill_value=spval)
    ncu.variables['ubar_west'].long_name = '2D u-momentum west boundary condition'
    ncu.variables['ubar_west'].units = 'meter second-1'
    ncu.variables['ubar_west'].field = 'ubar_east, scalar, series'


    print 'Creating variable v_north'
    ncv.createVariable('v_north', 'f8', ('ocean_time', 's_rho', 'xi_v'), fill_value=spval)
    ncv.variables['v_north'].long_name = '3D v-momentum north boundary condition'
    ncv.variables['v_north'].units = 'meter second-1'
    ncv.variables['v_north'].field = 'v_north, scalar, series'
    print 'Creating variable v_south'
    ncv.createVariable('v_south', 'f8', ('ocean_time', 's_rho', 'xi_v'), fill_value=spval)
    ncv.variables['v_south'].long_name = '3D v-momentum south boundary condition'
    ncv.variables['v_south'].units = 'meter second-1'
    ncv.variables['v_south'].field = 'v_south, scalar, series'
    print 'Creating variable v_east'
    ncv.createVariable('v_east', 'f8', ('ocean_time', 's_rho', 'eta_v'), fill_value=spval)
    ncv.variables['v_east'].long_name = '3D v-momentum east boundary condition'
    ncv.variables['v_east'].units = 'meter second-1'
    ncv.variables['v_east'].field = 'v_east, scalar, series'
    print 'Creating variable v_west'
    ncv.createVariable('v_west', 'f8', ('ocean_time', 's_rho', 'eta_v'), fill_value=spval)
    ncv.variables['v_west'].long_name = '3D v-momentum west boundary condition'
    ncv.variables['v_west'].units = 'meter second-1'
    ncv.variables['v_west'].field = 'v_east, scalar, series'

    print 'Creating variable vbar_north'
    ncv.createVariable('vbar_north', 'f8', ('ocean_time', 'xi_v'), fill_value=spval)
    ncv.variables['vbar_north'].long_name = '2D v-momentum north boundary condition'
    ncv.variables['vbar_north'].units = 'meter second-1'
    ncv.variables['vbar_north'].field = 'vbar_north, scalar, series'
    print 'Creating variable vbar_south'
    ncv.createVariable('vbar_south', 'f8', ('ocean_time', 'xi_v'), fill_value=spval)
    ncv.variables['vbar_south'].long_name = '2D v-momentum south boundary condition'
    ncv.variables['vbar_south'].units = 'meter second-1'
    ncv.variables['vbar_south'].field = 'vbar_south, scalar, series'
    print 'Creating variable vbar_east'
    ncv.createVariable('vbar_east', 'f8', ('ocean_time', 'eta_v'), fill_value=spval)
    ncv.variables['vbar_east'].long_name = '2D v-momentum east boundary condition'
    ncv.variables['vbar_east'].units = 'meter second-1'
    ncv.variables['vbar_east'].field = 'vbar_east, scalar, series'
    print 'Creating variable vbar_west'
    ncv.createVariable('vbar_west', 'f8', ('ocean_time', 'eta_v'), fill_value=spval)
    ncv.variables['vbar_west'].long_name = '2D v-momentum west boundary condition'
    ncv.variables['vbar_west'].units = 'meter second-1'
    ncv.variables['vbar_west'].field = 'vbar_east, scalar, series'

 

    # remaping
    print 'remapping and rotating u and v from', src_grd.name, \
                      'to', dst_grd.name
    print 'time =', time


    # flood the grid
    print 'flood the grid'
    src_uz = pyroms_toolbox.BGrid_SODA.flood(src_varu, src_grd, Bpos='uv', \
                spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
    src_vz = pyroms_toolbox.BGrid_SODA.flood(src_varv, src_grd, Bpos='uv', \
                spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_uz = pyroms.remapping.remap(src_uz, wts_file, \
                                      spval=spval)
    dst_vz = pyroms.remapping.remap(src_vz, wts_file, \
                                      spval=spval)

    # vertical interpolation from standard z level to sigma
    print 'vertical interpolation from standard z level to sigma'
    dst_u_north = pyroms.remapping.z2roms(dst_uz[::-1, Mp-2:Mp, 0:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,Lp), jrange=(Mp-2,Mp))
    dst_u_south = pyroms.remapping.z2roms(dst_uz[::-1, 0:2, 0:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,Lp), jrange=(0,2))
    dst_u_east = pyroms.remapping.z2roms(dst_uz[::-1, 0:Mp, Lp-2:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(Lp-2,Lp), jrange=(0,Mp))
    dst_u_west = pyroms.remapping.z2roms(dst_uz[::-1, 0:Mp, 0:2], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,2), jrange=(0,Mp))

    dst_v_north = pyroms.remapping.z2roms(dst_vz[::-1, Mp-2:Mp, 0:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,Lp), jrange=(Mp-2,Mp))
    dst_v_south = pyroms.remapping.z2roms(dst_vz[::-1, 0:2, 0:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,Lp), jrange=(0,2))
    dst_v_east = pyroms.remapping.z2roms(dst_vz[::-1, 0:Mp, Lp-2:Lp], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(Lp-2,Lp), jrange=(0,Mp))
    dst_v_west = pyroms.remapping.z2roms(dst_vz[::-1, 0:Mp, 0:2], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,2), jrange=(0,Mp))


    # rotate u,v fields
    src_angle = np.zeros(dst_grd.hgrid.angle_rho.shape)
    dst_angle = dst_grd.hgrid.angle_rho
    angle = dst_angle - src_angle
    angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))
    U_north = dst_u_north + dst_v_north*1j
    eitheta_north = np.exp(-1j*angle[:,Mp-2:Mp, 0:Lp])
    U_north = U_north * eitheta_north
    dst_u_north = np.real(U_north)
    dst_v_north = np.imag(U_north)

    U_south = dst_u_south + dst_v_south*1j
    eitheta_south = np.exp(-1j*angle[:,0:2, 0:Lp])
    U_south = U_south * eitheta_south
    dst_u_south = np.real(U_south)
    dst_v_south = np.imag(U_south)

    U_east = dst_u_east + dst_v_east*1j
    eitheta_east = np.exp(-1j*angle[:,0:Mp, Lp-2:Lp])
    U_east = U_east * eitheta_east
    dst_u_east = np.real(U_east)
    dst_v_east = np.imag(U_east)

    U_west = dst_u_west + dst_v_west*1j
    eitheta_west = np.exp(-1j*angle[:,0:Mp, 0:2])
    U_west = U_west * eitheta_west
    dst_u_west = np.real(U_west)
    dst_v_west = np.imag(U_west)


    # move back to u,v points
    dst_u_north = 0.5 * np.squeeze(dst_u_north[:,-1,:-1] + dst_u_north[:,-1,1:])
    dst_v_north = 0.5 * np.squeeze(dst_v_north[:,:-1,:] + dst_v_north[:,1:,:])
    dst_u_south = 0.5 * np.squeeze(dst_u_south[:,0,:-1] + dst_u_south[:,0,1:])
    dst_v_south = 0.5 * np.squeeze(dst_v_south[:,:-1,:] + dst_v_south[:,1:,:])
    dst_u_east = 0.5 * np.squeeze(dst_u_east[:,:,:-1] + dst_u_east[:,:,1:])
    dst_v_east = 0.5 * np.squeeze(dst_v_east[:,:-1,-1] + dst_v_east[:,1:,-1])
    dst_u_west = 0.5 * np.squeeze(dst_u_west[:,:,:-1] + dst_u_west[:,:,1:])
    dst_v_west = 0.5 * np.squeeze(dst_v_west[:,:-1,0] + dst_v_west[:,1:,0])

    # spval
    idxu_north = np.where(dst_grd.hgrid.mask_u[-1,:] == 0)
    idxv_north = np.where(dst_grd.hgrid.mask_v[-1,:] == 0)
    idxu_south = np.where(dst_grd.hgrid.mask_u[0,:] == 0)
    idxv_south = np.where(dst_grd.hgrid.mask_v[0,:] == 0)
    idxu_east = np.where(dst_grd.hgrid.mask_u[:,-1] == 0)
    idxv_east = np.where(dst_grd.hgrid.mask_v[:,-1] == 0)
    idxu_west = np.where(dst_grd.hgrid.mask_u[:,0] == 0)
    idxv_west = np.where(dst_grd.hgrid.mask_v[:,0] == 0)
    for n in range(dst_grd.vgrid.N): 
        dst_u_north[n, idxu_north[0]] = spval
        dst_v_north[n, idxv_north[0]] = spval
        dst_u_south[n, idxu_south[0]] = spval
        dst_v_south[n, idxv_south[0]] = spval
        dst_u_east[n, idxu_east[0]] = spval
        dst_v_east[n, idxv_east[0]] = spval
        dst_u_west[n, idxu_west[0]] = spval
        dst_v_west[n, idxv_west[0]] = spval

    # compute depth average velocity ubar and vbar
    # get z at the right position
    z_u_north = 0.5 * (dst_grd.vgrid.z_w[0,:,-1,:-1] + dst_grd.vgrid.z_w[0,:,-1,1:])
    z_v_north = 0.5 * (dst_grd.vgrid.z_w[0,:,-1,:] + dst_grd.vgrid.z_w[0,:,-2,:])
    z_u_south = 0.5 * (dst_grd.vgrid.z_w[0,:,0,:-1] + dst_grd.vgrid.z_w[0,:,0,1:])
    z_v_south = 0.5 * (dst_grd.vgrid.z_w[0,:,0,:] + dst_grd.vgrid.z_w[0,:,1,:])
    z_u_east = 0.5 * (dst_grd.vgrid.z_w[0,:,:,-1] + dst_grd.vgrid.z_w[0,:,:,-2])
    z_v_east = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,-1] + dst_grd.vgrid.z_w[0,:,1:,-1])
    z_u_west = 0.5 * (dst_grd.vgrid.z_w[0,:,:,0] + dst_grd.vgrid.z_w[0,:,:,1])
    z_v_west = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,0] + dst_grd.vgrid.z_w[0,:,1:,0])

    dst_ubar_north = np.zeros(dst_u_north.shape[1])
    dst_ubar_south = np.zeros(dst_u_south.shape[1])
    dst_ubar_east = np.zeros(dst_u_east.shape[1])
    dst_ubar_west = np.zeros(dst_u_west.shape[1])
    dst_vbar_north = np.zeros(dst_v_north.shape[1])
    dst_vbar_south = np.zeros(dst_v_south.shape[1])
    dst_vbar_east = np.zeros(dst_v_east.shape[1])
    dst_vbar_west = np.zeros(dst_v_west.shape[1])

    for i in range(dst_u_north.shape[1]):
        dst_ubar_north[i] = (dst_u_north[:,i] * np.diff(z_u_north[:,i])).sum() / -z_u_north[0,i]
        dst_ubar_south[i] = (dst_u_south[:,i] * np.diff(z_u_south[:,i])).sum() / -z_u_south[0,i]
    for i in range(dst_v_north.shape[1]):
        dst_vbar_north[i] = (dst_v_north[:,i] * np.diff(z_v_north[:,i])).sum() / -z_v_north[0,i]
        dst_vbar_south[i] = (dst_v_south[:,i] * np.diff(z_v_south[:,i])).sum() / -z_v_south[0,i]
    for j in range(dst_u_east.shape[1]):
        dst_ubar_east[j] = (dst_u_east[:,j] * np.diff(z_u_east[:,j])).sum() / -z_u_east[0,j]
        dst_ubar_west[j] = (dst_u_west[:,j] * np.diff(z_u_west[:,j])).sum() / -z_u_west[0,j]
    for j in range(dst_v_east.shape[1]):
        dst_vbar_east[j] = (dst_v_east[:,j] * np.diff(z_v_east[:,j])).sum() / -z_v_east[0,j]
        dst_vbar_west[j] = (dst_v_west[:,j] * np.diff(z_v_west[:,j])).sum() / -z_v_west[0,j]
        
    #mask
    dst_ubar_north = np.ma.masked_where(dst_grd.hgrid.mask_u[-1,:] == 0, dst_ubar_north)   
    dst_ubar_south = np.ma.masked_where(dst_grd.hgrid.mask_u[0,:] == 0, dst_ubar_south)   
    dst_ubar_east = np.ma.masked_where(dst_grd.hgrid.mask_u[:,-1] == 0, dst_ubar_east)   
    dst_ubar_west = np.ma.masked_where(dst_grd.hgrid.mask_u[:,0] == 0, dst_ubar_west)   
    dst_vbar_north = np.ma.masked_where(dst_grd.hgrid.mask_v[-1,:] == 0, dst_vbar_north)   
    dst_vbar_south = np.ma.masked_where(dst_grd.hgrid.mask_v[0,:] == 0, dst_vbar_south)   
    dst_vbar_east = np.ma.masked_where(dst_grd.hgrid.mask_v[:,-1] == 0, dst_vbar_east)   
    dst_vbar_west = np.ma.masked_where(dst_grd.hgrid.mask_v[:,0] == 0, dst_vbar_west)   

    # write data in destination file
    print 'write data in destination file'
    ncu.variables['ocean_time'][0] = time
    ncu.variables['u_north'][0] = dst_u_north
    ncu.variables['u_south'][0] = dst_u_south
    ncu.variables['u_east'][0] = dst_u_east
    ncu.variables['u_west'][0] = dst_u_west
    ncu.variables['ubar_north'][0] = dst_ubar_north
    ncu.variables['ubar_south'][0] = dst_ubar_south
    ncu.variables['ubar_east'][0] = dst_ubar_east
    ncu.variables['ubar_west'][0] = dst_ubar_west

    ncv.variables['ocean_time'][0] = time
    ncv.variables['v_north'][0] = dst_v_north
    ncv.variables['v_south'][0] = dst_v_south
    ncv.variables['v_east'][0] = dst_v_east
    ncv.variables['v_west'][0] = dst_v_west
    ncv.variables['vbar_north'][0] = dst_vbar_north
    ncv.variables['vbar_south'][0] = dst_vbar_south
    ncv.variables['vbar_east'][0] = dst_vbar_east
    ncv.variables['vbar_west'][0] = dst_vbar_west

#    print dst_u.shape
#    print dst_ubar.shape
#    print dst_v.shape
#    print dst_vbar.shape

    # close file
    ncu.close()
    ncv.close()
    cdf.close()
Ejemplo n.º 27
0
def remap_bdry(src_file, src_varname, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'):
    
    ystart=240

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
    ref = datetime(1900, 1, 1, 0, 0, 0)
    ref = date2num(ref)
    tag = src_file.rsplit('/')[-1].rsplit('_')[-1].rsplit('-')[0]
    year = int(tag[:4])
    month = int(tag[4:6])
    day = int(tag[6:])
    time = datetime(year, month, day, 0, 0, 0)
    time = date2num(time)
    time = time - ref
    time = time + 2.5 # 5-day average

    # create boundary file
    dst_file = src_file.rsplit('/')[-1]
    dst_file = dst_dir + dst_file[:-4] + '_' + src_varname + '_bdry_' + dst_grd.name + '.nc'
    print '\nCreating boundary file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open boundary file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file) 
    src_var = cdf.variables[src_varname]

    #get missing value
    spval = src_var._FillValue

    # determine variable dimension
    ndim = len(src_var.dimensions)

    # global grid
    if ndim == 3:
        src_var = src_var[:]
        src_var = src_var[:,np.r_[ystart:np.size(src_var,1),-1],:]
    elif ndim == 2:
        src_var = src_var[:]
        src_var = src_var[np.r_[ystart:np.size(src_var,0),-1],:]

    if src_varname == 'ssh':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_SODA_2.1.6_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'zeta'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'free-surface'
        dst_varname_north = 'zeta_north'
        dimensions_north = ('ocean_time', 'xi_rho')
        long_name_north = 'free-surface north boundary condition'
        field_north = 'zeta_north, scalar, series'
        dst_varname_south = 'zeta_south'
        dimensions_south = ('ocean_time', 'xi_rho')
        long_name_south = 'free-surface south boundary condition'
        field_south = 'zeta_south, scalar, series'
        dst_varname_east = 'zeta_east'
        dimensions_east = ('ocean_time', 'eta_rho')
        long_name_east = 'free-surface east boundary condition'
        field_east = 'zeta_east, scalar, series'
        dst_varname_west = 'zeta_west'
        dimensions_west = ('ocean_time', 'eta_rho')
        long_name_west = 'free-surface west boundary condition'
        field_west = 'zeta_west, scalar, series'
        units = 'meter'
    elif src_varname == 'temp':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_SODA_2.1.6_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'temperature'
        dst_varname_north = 'temp_north'
        dimensions_north = ('ocean_time', 's_rho', 'xi_rho')
        long_name_north = 'potential temperature north boundary condition'
        field_north = 'temp_north, scalar, series'
        dst_varname_south = 'temp_south'
        dimensions_south = ('ocean_time', 's_rho', 'xi_rho')
        long_name_south = 'potential temperature south boundary condition'
        field_south = 'temp_south, scalar, series'
        dst_varname_east = 'temp_east'
        dimensions_east = ('ocean_time', 's_rho', 'eta_rho')
        long_name_east = 'potential temperature east boundary condition'
        field_east = 'temp_east, scalar, series'
        dst_varname_west = 'temp_west'
        dimensions_west = ('ocean_time', 's_rho', 'eta_rho')
        long_name_west = 'potential temperature west boundary condition'
        field_west = 'temp_west, scalar, series'
        units = 'Celsius'
    elif src_varname == 'salt':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_SODA_2.1.6_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'salinity'
        dst_varname_north = 'salt_north'
        dimensions_north = ('ocean_time', 's_rho', 'xi_rho')
        long_name_north = 'salinity north boundary condition'
        field_north = 'salt_north, scalar, series'
        dst_varname_south = 'salt_south'
        dimensions_south = ('ocean_time', 's_rho', 'xi_rho')
        long_name_south = 'salinity south boundary condition'
        field_south = 'salt_south, scalar, series'
        dst_varname_east = 'salt_east'
        dimensions_east = ('ocean_time', 's_rho', 'eta_rho')
        long_name_east = 'salinity east boundary condition'
        field_east = 'salt_east, scalar, series'
        dst_varname_west = 'salt_west'
        dimensions_west = ('ocean_time', 's_rho', 'eta_rho')
        long_name_west = 'salinity west boundary condition'
        field_west = 'salt_west, scalar, series'
        units = 'PSU'
    else:
        raise ValueError, 'Undefined src_varname'


    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1,0,0]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)


    # create variable in boudary file
    print 'Creating variable', dst_varname_north
    nc.createVariable(dst_varname_north, 'f8', dimensions_north, fill_value=spval)
    nc.variables[dst_varname_north].long_name = long_name_north
    nc.variables[dst_varname_north].units = units
    nc.variables[dst_varname_north].field = field_north

    print 'Creating variable', dst_varname_south
    nc.createVariable(dst_varname_south, 'f8', dimensions_south, fill_value=spval)
    nc.variables[dst_varname_south].long_name = long_name_south
    nc.variables[dst_varname_south].units = units
    nc.variables[dst_varname_south].field = field_south

    print 'Creating variable', dst_varname_east
    nc.createVariable(dst_varname_east, 'f8', dimensions_east, fill_value=spval)
    nc.variables[dst_varname_east].long_name = long_name_east
    nc.variables[dst_varname_east].units = units
    nc.variables[dst_varname_east].field = field_east

    print 'Creating variable', dst_varname_west
    nc.createVariable(dst_varname_west, 'f8', dimensions_west, fill_value=spval)
    nc.variables[dst_varname_west].long_name = long_name_west
    nc.variables[dst_varname_west].units = units
    nc.variables[dst_varname_west].field = field_west


    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name
    print 'time =', time


    if ndim == 3:
        # flood the grid
        print 'flood the grid'
	print src_var.shape
	print src_grd.z_t.shape
        src_varz = pyroms_toolbox.BGrid_SODA.flood(src_var, src_grd, Bpos=Bpos, spval=spval, \
                                dmax=dmax, cdepth=cdepth, kk=kk)
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print 'vertical interpolation from standard z level to sigma'
        dst_var_north = pyroms.remapping.z2roms(dst_varz[::-1, Mp-1:Mp, 0:Lp], \
                          dst_grdz, dst_grd, Cpos=Cpos, spval=spval, \
                          flood=False, irange=(0,Lp), jrange=(Mp-1,Mp))
        dst_var_south = pyroms.remapping.z2roms(dst_varz[::-1, 0:1, :], \
                          dst_grdz, dst_grd, Cpos=Cpos, spval=spval, \
                          flood=False, irange=(0,Lp), jrange=(0,1))
        dst_var_east = pyroms.remapping.z2roms(dst_varz[::-1, :, Lp-1:Lp], \
                          dst_grdz, dst_grd, Cpos=Cpos, spval=spval, \
                          flood=False, irange=(Lp-1,Lp), jrange=(0,Mp))
        dst_var_west = pyroms.remapping.z2roms(dst_varz[::-1, :, 0:1], \
                          dst_grdz, dst_grd, Cpos=Cpos, spval=spval, \
                          flood=False, irange=(0,1), jrange=(0,Mp))
    else:
        dst_var_north = dst_varz[-1, :]
        dst_var_south = dst_varz[0, :]
        dst_var_east = dst_varz[:, -1]
        dst_var_west = dst_varz[:, 0]

    # write data in destination file
    print 'write data in destination file'
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname_north][0] = np.squeeze(dst_var_north)
    nc.variables[dst_varname_south][0] = np.squeeze(dst_var_south)
    nc.variables[dst_varname_east][0] = np.squeeze(dst_var_east)
    nc.variables[dst_varname_west][0] = np.squeeze(dst_var_west)

    # close file
    nc.close()
    cdf.close()

    if src_varname == 'ssh':
        return dst_varz
Ejemplo n.º 28
0
def remap_bdry(src_file,
               src_varname,
               src_grd,
               dst_grd,
               dmax=0,
               cdepth=0,
               kk=0,
               dst_dir='./'):

    ystart = 690

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
    ref = datetime(1900, 1, 1, 0, 0, 0)
    ref = date2num(ref)
    tag = src_file.rsplit('/')[-1].rsplit('_')[2]
    print("date string:", tag)
    year = int(tag[:4])
    month = int(tag[4:6])
    day = int(tag[6:])
    time = datetime(year, month, day, 0, 0, 0)
    time = date2num(time)
    time = time - ref
    time = time + 2.5  # 5-day average

    # create boundary file
    dst_file = src_file.rsplit('/')[-1]
    dst_file = dst_dir + dst_file[:
                                  -4] + '_' + src_varname + '_bdry_' + dst_grd.name + '.nc'
    print '\nCreating boundary file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open boundary file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    #get missing value
    spval = src_var._FillValue
    add_offset = src_var.add_offset
    scale_factor = src_var.scale_factor
    src_var = np.squeeze(src_var)

    # Use scale_factor, etc
    spval = spval * scale_factor
    #    spval = spval*scale_factor + add_offset
    #    src_var = src_var*scale_factor + add_offset
    #    src_var = src_var + add_offset

    # determine variable dimension
    ndim = len(src_var.shape)

    # global grid
    if ndim == 3:
        src_var = src_var[:]
        src_var = src_var[:, np.r_[ystart:np.size(src_var, 1), -1], :]
    elif ndim == 2:
        src_var = src_var[:]
        src_var = src_var[np.r_[ystart:np.size(src_var, 0), -1], :]

    if src_varname == 'sossheig':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'zeta'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'free-surface'
        dst_varname_north = 'zeta_north'
        dimensions_north = ('ocean_time', 'xi_rho')
        long_name_north = 'free-surface north boundary condition'
        field_north = 'zeta_north, scalar, series'
        dst_varname_south = 'zeta_south'
        dimensions_south = ('ocean_time', 'xi_rho')
        long_name_south = 'free-surface south boundary condition'
        field_south = 'zeta_south, scalar, series'
        dst_varname_east = 'zeta_east'
        dimensions_east = ('ocean_time', 'eta_rho')
        long_name_east = 'free-surface east boundary condition'
        field_east = 'zeta_east, scalar, series'
        dst_varname_west = 'zeta_west'
        dimensions_west = ('ocean_time', 'eta_rho')
        long_name_west = 'free-surface west boundary condition'
        field_west = 'zeta_west, scalar, series'
        units = 'meter'
    elif src_varname == 'votemper':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'temperature'
        dst_varname_north = 'temp_north'
        dimensions_north = ('ocean_time', 's_rho', 'xi_rho')
        long_name_north = 'potential temperature north boundary condition'
        field_north = 'temp_north, scalar, series'
        dst_varname_south = 'temp_south'
        dimensions_south = ('ocean_time', 's_rho', 'xi_rho')
        long_name_south = 'potential temperature south boundary condition'
        field_south = 'temp_south, scalar, series'
        dst_varname_east = 'temp_east'
        dimensions_east = ('ocean_time', 's_rho', 'eta_rho')
        long_name_east = 'potential temperature east boundary condition'
        field_east = 'temp_east, scalar, series'
        dst_varname_west = 'temp_west'
        dimensions_west = ('ocean_time', 's_rho', 'eta_rho')
        long_name_west = 'potential temperature west boundary condition'
        field_west = 'temp_west, scalar, series'
        units = 'Celsius'
    elif src_varname == 'vosaline':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_GLORYS_to_ARCTIC2_bilinear_t_to_rho.nc'
        dst_varname = 'salt'
        dst_varname_north = 'salt_north'
        dimensions_north = ('ocean_time', 's_rho', 'xi_rho')
        long_name_north = 'salinity north boundary condition'
        field_north = 'salt_north, scalar, series'
        dst_varname_south = 'salt_south'
        dimensions_south = ('ocean_time', 's_rho', 'xi_rho')
        long_name_south = 'salinity south boundary condition'
        field_south = 'salt_south, scalar, series'
        dst_varname_east = 'salt_east'
        dimensions_east = ('ocean_time', 's_rho', 'eta_rho')
        long_name_east = 'salinity east boundary condition'
        field_east = 'salt_east, scalar, series'
        dst_varname_west = 'salt_west'
        dimensions_west = ('ocean_time', 's_rho', 'eta_rho')
        long_name_west = 'salinity west boundary condition'
        field_west = 'salt_west, scalar, series'
        units = 'PSU'
    else:
        raise ValueError, 'Undefined src_varname'

    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1, 0, 0]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel,
                                               nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + '_Z', dst_grd.hgrid,
                                         dst_zcoord)

    # create variable in boudary file
    print 'Creating variable', dst_varname_north
    nc.createVariable(dst_varname_north,
                      'f8',
                      dimensions_north,
                      fill_value=spval)
    nc.variables[dst_varname_north].long_name = long_name_north
    nc.variables[dst_varname_north].units = units
    nc.variables[dst_varname_north].field = field_north

    print 'Creating variable', dst_varname_south
    nc.createVariable(dst_varname_south,
                      'f8',
                      dimensions_south,
                      fill_value=spval)
    nc.variables[dst_varname_south].long_name = long_name_south
    nc.variables[dst_varname_south].units = units
    nc.variables[dst_varname_south].field = field_south

    print 'Creating variable', dst_varname_east
    nc.createVariable(dst_varname_east,
                      'f8',
                      dimensions_east,
                      fill_value=spval)
    nc.variables[dst_varname_east].long_name = long_name_east
    nc.variables[dst_varname_east].units = units
    nc.variables[dst_varname_east].field = field_east

    print 'Creating variable', dst_varname_west
    nc.createVariable(dst_varname_west,
                      'f8',
                      dimensions_west,
                      fill_value=spval)
    nc.variables[dst_varname_west].long_name = long_name_west
    nc.variables[dst_varname_west].units = units
    nc.variables[dst_varname_west].field = field_west

    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name
    print 'time =', time

    if ndim == 3:
        # flood the grid
        print 'flood the grid'
        src_varz = pyroms_toolbox.CGrid_GLORYS.flood(src_var, src_grd, Cpos=Bpos, spval=spval, \
                                dmax=dmax, cdepth=cdepth, kk=kk)
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print 'vertical interpolation from standard z level to sigma'
        dst_var_north = pyroms.remapping.z2roms(dst_varz[::-1, Mp-1:Mp, 0:Lp], \
                          dst_grdz, dst_grd, Cpos=Cpos, spval=spval, \
                          flood=False, irange=(0,Lp), jrange=(Mp-1,Mp))
        dst_var_south = pyroms.remapping.z2roms(dst_varz[::-1, 0:1, :], \
                          dst_grdz, dst_grd, Cpos=Cpos, spval=spval, \
                          flood=False, irange=(0,Lp), jrange=(0,1))
        dst_var_east = pyroms.remapping.z2roms(dst_varz[::-1, :, Lp-1:Lp], \
                          dst_grdz, dst_grd, Cpos=Cpos, spval=spval, \
                          flood=False, irange=(Lp-1,Lp), jrange=(0,Mp))
        dst_var_west = pyroms.remapping.z2roms(dst_varz[::-1, :, 0:1], \
                          dst_grdz, dst_grd, Cpos=Cpos, spval=spval, \
                          flood=False, irange=(0,1), jrange=(0,Mp))
    else:
        dst_var_north = dst_varz[-1, :]
        dst_var_south = dst_varz[0, :]
        dst_var_east = dst_varz[:, -1]
        dst_var_west = dst_varz[:, 0]

    # write data in destination file
    print 'write data in destination file'
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname_north][0] = np.squeeze(dst_var_north)
    nc.variables[dst_varname_south][0] = np.squeeze(dst_var_south)
    nc.variables[dst_varname_east][0] = np.squeeze(dst_var_east)
    nc.variables[dst_varname_west][0] = np.squeeze(dst_var_west)

    # close file
    nc.close()
    cdf.close()

    if src_varname == 'ssh':
        return dst_varz
Ejemplo n.º 29
0
def remapping(
    varname,
    srcfile,
    wts_files,
    srcgrd,
    dstgrd,
    rotate_uv=False,
    trange=None,
    irange=None,
    jrange=None,
    dstdir="./",
    zlevel=None,
    dmax=0,
    cdepth=0,
    kk=0,
):
    """
    A remaping function to go from a ROMS grid to another ROMS grid.
    """

    # get input and output grid
    if type(srcgrd).__name__ == "ROMS_Grid":
        srcgrd = srcgrd
    else:
        srcgrd = pyroms.grid.get_ROMS_grid(srcgrd)
    if type(dstgrd).__name__ == "ROMS_Grid":
        dstgrd = dstgrd
    else:
        dstgrd = pyroms.grid.get_ROMS_grid(dstgrd)

    # build intermediaire zgrid
    if zlevel is None:
        zlevel = np.array(
            [
                -4500.0,
                -4000.0,
                -3500.0,
                -3000.0,
                -2500.0,
                -2000.0,
                -1750.0,
                -1500.0,
                -1250.0,
                -1000.0,
                -900.0,
                -800.0,
                -700.0,
                -600.0,
                -500.0,
                -400.0,
                -300.0,
                -250.0,
                -200.0,
                -175.0,
                -150.0,
                -125.0,
                -100.0,
                -90.0,
                -80.0,
                -70.0,
                -60.0,
                -50.0,
                -45.0,
                -40.0,
                -35.0,
                -30.0,
                -25.0,
                -20.0,
                -17.5,
                -15.0,
                -12.5,
                -10.0,
                -7.5,
                -5.0,
                -2.5,
                0.0,
            ]
        )
    else:
        zlevel = np.sort(-abs(zlevel))
    nzlevel = len(zlevel)
    src_zcoord = pyroms.vgrid.z_coordinate(srcgrd.vgrid.h, zlevel, nzlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dstgrd.vgrid.h, zlevel, nzlevel)
    srcgrdz = pyroms.grid.ROMS_Grid(srcgrd.name + "_Z", srcgrd.hgrid, src_zcoord)
    dstgrdz = pyroms.grid.ROMS_Grid(dstgrd.name + "_Z", dstgrd.hgrid, dst_zcoord)

    # varname argument
    if type(varname).__name__ == "list":
        nvar = len(varname)
    elif type(varname).__name__ == "str":
        varname = [varname]
        nvar = len(varname)
    else:
        raise ValueError, "varname must be a str or a list of str"
    # if rotate_uv=True, check that u and v are in varname
    if rotate_uv is True:
        if varname.__contains__("u") == 0 or varname.__contains__("v") == 0:
            raise Warning, "varname must include u and v in order to rotate \
the velocity field"
        else:
            varname.remove("u")
            varname.remove("v")
            nvar = nvar - 2

    # srcfile argument
    if type(srcfile).__name__ == "list":
        nfile = len(srcfile)
    elif type(srcfile).__name__ == "str":
        srcfile = sorted(glob.glob(srcfile))
        nfile = len(srcfile)
    else:
        raise ValueError, "src_srcfile must be a str or a list of str"

    # get wts_file
    if type(wts_files).__name__ == "str":
        wts_files = sorted(glob.glob(wts_files))

    # loop over the srcfile
    for nf in range(nfile):
        print "Working with file", srcfile[nf], "..."

        # get time
        ocean_time = pyroms.utility.get_nc_var("ocean_time", srcfile[nf])
        ntime = len(ocean_time[:])

        # trange argument
        if trange is None:
            trange = range(ntime)
        else:
            trange = range(trange[0], trange[1] + 1)

        # create destination file
        dstfile = dstdir + os.path.basename(srcfile[nf])[:-3] + "_" + dstgrd.name + ".nc"
        print "Creating destination file", dstfile
        if os.path.exists(dstfile) is True:
            os.remove(dstfile)
        pyroms_toolbox.nc_create_roms_file(dstfile, dstgrd, ocean_time)

        # open destination file
        nc = netCDF.Dataset(dstfile, "a", format="NETCDF3_CLASSIC")

        nctidx = 0
        # loop over time
        for nt in trange:

            nc.variables["ocean_time"][nctidx] = ocean_time[nt]

            # loop over variable
            for nv in range(nvar):
                print " "
                print "remapping", varname[nv], "from", srcgrd.name, "to", dstgrd.name
                print "time =", ocean_time[nt]

                # get source data
                src_var = pyroms.utility.get_nc_var(varname[nv], srcfile[nf])

                # determine variable dimension
                ndim = len(src_var.dimensions) - 1

                # get spval
                try:
                    spval = src_var._FillValue
                except:
                    raise Warning, "Did not find a _FillValue attribute."

                # irange
                if irange is None:
                    iirange = (0, src_var._shape()[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0, src_var._shape()[-2])
                else:
                    jjrange = jrange

                # determine where on the C-grid these variable lies
                if src_var.dimensions[2].find("_rho") != -1:
                    Cpos = "rho"
                if src_var.dimensions[2].find("_u") != -1:
                    Cpos = "u"
                if src_var.dimensions[2].find("_v") != -1:
                    Cpos = "v"
                if src_var.dimensions[1].find("_w") != -1:
                    Cpos = "w"

                print "Arakawa C-grid position is", Cpos

                # create variable in _destination file
                if nt == trange[0]:
                    print "Creating variable", varname[nv]
                    nc.createVariable(varname[nv], "f8", src_var.dimensions)
                    nc.variables[varname[nv]].long_name = src_var.long_name
                    if varname[nv] != "salt":
                        nc.variables[varname[nv]].units = src_var.units
                    nc.variables[varname[nv]].field = src_var.field
                    nc.variables[varname[nv]]._FillValue = spval

                # get the right remap weights file
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__(Cpos + "_to_" + Cpos + ".nc"):
                        wts_file = wts_files[s]
                        break
                    else:
                        if s == len(wts_files) - 1:
                            raise ValueError, "Did not find the appropriate remap weights file"

                if ndim == 3:
                    # vertical interpolation from sigma to standard z level
                    print "vertical interpolation from sigma to standard z level"
                    src_varz = pyroms.remapping.roms2z(
                        src_var[nt, :, jjrange[0] : jjrange[1], iirange[0] : iirange[1]],
                        srcgrd,
                        srcgrdz,
                        Cpos=Cpos,
                        spval=spval,
                        irange=iirange,
                        jrange=jjrange,
                    )

                    # flood the grid
                    print "flood the grid"
                    src_varz = pyroms.remapping.flood(
                        src_varz,
                        srcgrdz,
                        Cpos=Cpos,
                        irange=iirange,
                        jrange=jjrange,
                        spval=spval,
                        dmax=dmax,
                        cdepth=cdepth,
                        kk=kk,
                    )

                    tmp_src_varz = np.zeros((nzlevel, src_var[:].shape[-2], src_var[:].shape[-1]))
                    tmp_src_varz[:, jjrange[0] : jjrange[1], iirange[0] : iirange[1]] = src_varz
                else:
                    src_varz = src_var[nt, jjrange[0] : jjrange[1], iirange[0] : iirange[1]]
                    tmp_src_varz = np.zeros(src_var[nt, :].shape)
                    tmp_src_varz[jjrange[0] : jjrange[1], iirange[0] : iirange[1]] = src_varz

                print datetime.datetime.now()
                # horizontal interpolation using scrip weights
                print "horizontal interpolation using scrip weights"
                dst_varz = pyroms.remapping.remap(tmp_src_varz, wts_file, spval=spval)

                print datetime.datetime.now()

                if ndim == 3:
                    # vertical interpolation from standard z level to sigma
                    print "vertical interpolation from standard z level to sigma"
                    dst_var = pyroms.remapping.z2roms(dst_varz, dstgrdz, dstgrd, Cpos=Cpos, spval=spval, flood=False)
                else:
                    dst_var = dst_varz

                # write data in destination file
                print "write data in destination file"
                nc.variables[varname[nv]][nctidx] = dst_var

            # rotate the velocity field if requested
            if rotate_uv is True:
                print " "
                print "remapping and rotating u and v from", srcgrd.name, "to", dstgrd.name

                # get source data
                src_u = pyroms.utility.get_nc_var("u", srcfile[nf])
                src_v = pyroms.utility.get_nc_var("v", srcfile[nf])

                # create variable in destination file
                print "Creating variable u"
                nc.createVariable("u", "f8", src_u.dimensions)
                nc.variables["u"].long_name = src_u.long_name
                nc.variables["u"].units = src_u.units
                nc.variables["u"].field = src_u.field
                nc.variables["u"]._FillValue = spval
                print "Creating variable v"
                nc.createVariable("v", "f8", src_v.dimensions)
                nc.variables["v"].long_name = src_v.long_name
                nc.variables["v"].units = src_v.units
                nc.variables["v"].field = src_v.field
                nc.variables["v"]._FillValue = spval

                # get the right remap weights file
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__("u_to_rho.nc"):
                        wts_file_u = wts_files[s]
                    if wts_files[s].__contains__("v_to_rho.nc"):
                        wts_file_v = wts_files[s]

                # vertical interpolation from sigma to standard z level
                print "vertical interpolation from sigma to standard z level"
                src_uz = pyroms.remapping.roms2z(
                    src_u[nt, :, jjrange[0] : jjrange[1], iirange[0] : iirange[1]],
                    srcgrd,
                    srcgrdz,
                    Cpos="u",
                    irange=iirange,
                    jrange=jjrange,
                )
                src_vz = pyroms.remapping.roms2z(
                    src_v[nt, :, jjrange[0] : jjrange[1], iirange[0] : iirange[1]],
                    srcgrd,
                    srcgrdz,
                    Cpos="v",
                    irange=iirange,
                    jrange=jjrange,
                )

                # flood the grid
                print "flood the grid"
                src_uz = pyroms.remapping.flood(
                    src_uz,
                    srcgrdz,
                    Cpos="u",
                    irange=iirange,
                    jrange=jjrange,
                    spval=spval,
                    dmax=dmax,
                    cdepth=cdepth,
                    kk=kk,
                )
                src_vz = pyroms.remapping.flood(
                    src_vz,
                    srcgrdz,
                    Cpos="v",
                    irange=iirange,
                    jrange=jjrange,
                    spval=spval,
                    dmax=dmax,
                    cdepth=cdepth,
                    kk=kk,
                )

                # horizontal interpolation using scrip weights
                print "horizontal interpolation using scrip weights"
                dst_uz = pyroms.remapping.remap(src_uz, wts_file_u, spval=spval)
                dst_vz = pyroms.remapping.remap(src_vz, wts_file_v, spval=spval)

                # vertical interpolation from standard z level to sigma
                print "vertical interpolation from standard z level to sigma"
                dst_u = pyroms.remapping.z2roms(dst_uz, dstgrdz, dstgrd, Cpos="rho", spval=spval, flood=False)
                dst_v = pyroms.remapping.z2roms(dst_vz, dstgrdz, dstgrd, Cpos="rho", spval=spval, flood=False)

                # rotate u,v fields
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__("rho_to_rho.nc"):
                        wts_file = wts_files[s]
                src_angle = pyroms.remapping.remap(srcgrd.hgrid.angle_rho, wts_file)
                dst_angle = dstgrd.hgrid.angle_rho
                angle = dst_angle - src_angle
                angle = np.tile(angle, (dstgrd.vgrid.N, 1, 1))

                U = dst_u + dst_v * 1j
                eitheta = np.exp(-1j * angle)
                U = U * eitheta

                dst_u = np.real(U)
                dst_v = np.imag(U)

                # move back to u,v points
                dst_u = 0.5 * (dst_u[:, :, :-1] + dst_u[:, :, 1:])
                dst_v = 0.5 * (dst_v[:, :-1, :] + dst_v[:, 1:, :])

                # write data in destination file
                print "write data in destination file"
                nc.variables["u"][nctidx] = dst_u
                nc.variables["v"][nctidx] = dst_v

        nctidx = nctidx + 1

    # close destination file
    nc.close()

    return
Ejemplo n.º 30
0
def remap_bio_woa(argdict, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'):
    
    # NWGOA3 grid sub-sample
    xrange=src_grd.xrange; yrange=src_grd.yrange

    src_varname = argdict['tracer']
    tracer = src_varname
    src_file = argdict['file']
    units = argdict['units']
    longname = argdict['longname']
    nframe = argdict['frame']

    if src_varname == 'sio4':
       src_varname = 'si'

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'

    # create clim file
    dst_file = tracer + '.nc'
    dst_file = dst_dir + dst_grd.name + '_clim_bio_' + dst_file
    print 'Creating clim file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open clim file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file) 
    src_var = cdf.variables[src_varname]

    # correct time to some classic value
    days_in_month = np.array([31,28.25,31,30,31,30,31,31,30,31,30,31])
    time = days_in_month[:nframe].sum() + days_in_month[nframe] / 2.

    #get missing value
    spval = src_var._FillValue

    spval2 = -1.0e+10

    # determine variable dimension
    ndim = len(src_var.dimensions) - 1

    # NWGOA3 grid sub-sample
    if ndim == 3:
        src_var = src_var[nframe,:, yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]
    elif ndim == 2:
        src_var = src_var[nframe,yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]


    if tracer == 'no3':
       unit_conversion = 1. / 1e6 / 1.035
    elif tracer == 'po4':
       unit_conversion = 1. / 1e6 / 1.035
    elif tracer == 'o2':
       unit_conversion = 1. / 1035 / 22391.6 * 1000.0
    elif tracer == 'sio4':
       unit_conversion = 1. / 1e6 / 1.035

    src_var = src_var * unit_conversion

    Bpos = 't'
    Cpos = 'rho'
    z = src_grd.z_t
    Mp, Lp = dst_grd.hgrid.mask_rho.shape
    wts_file = 'remap_weights_ESM2M_to_NWGOA3_bilinear_t_to_rho.nc'
    dst_varname = tracer
    dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
    long_name = longname
    field = tracer + ', scalar, series'
    units = units

    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)


    # create variable in file
    print 'Creating variable', dst_varname
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval2)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field
    #nc.variables[dst_varname_north]._FillValue = spval


    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name

    if ndim == 3:
        # flood the grid
        print 'flood the grid'
        src_varz = pyroms_toolbox.BGrid_GFDL.flood(src_var, src_grd, Bpos=Bpos, spval=spval, \
                                dmax=dmax, cdepth=cdepth, kk=kk)
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print 'vertical interpolation from standard z level to sigma'
        dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \
                          dst_grd, Cpos=Cpos, spval=spval, flood=False)
    else:
        dst_var = dst_varz

    if ndim == 3:
       for kz in np.arange(dst_grd.vgrid.N):
           tmp = dst_var[kz,:,:].copy()
       	   tmp[np.where(dst_grd.hgrid.mask_rho == 0)] = spval2
           dst_var[kz,:,:] = tmp.copy()

    # write data in destination file
    print 'write data in destination file\n'
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname][0] = dst_var

    # close file
    nc.close()
    cdf.close()

    if src_varname == 'eta':
        return dst_varz
Ejemplo n.º 31
0
def remapping(varname, srcfile, wts_files, srcgrd, dstgrd, \
              rotate_uv=False, trange=None, irange=None, jrange=None, \
              dstdir='./' ,zlevel=None, dmax=0, cdepth=0, kk=0, \
              uvar='u', vvar='v', rotate_part=False):
    '''
    A remapping function to go from a ROMS grid to another ROMS grid.
    If the u/v variables need to be rotated, it must be called for each
    u/v pair (such as u/v, uice/vice).
    '''

    # get input and output grid
    if type(srcgrd).__name__ == 'ROMS_Grid':
        srcgrd = srcgrd
    else:
        srcgrd = pyroms.grid.get_ROMS_grid(srcgrd)
    if type(dstgrd).__name__ == 'ROMS_Grid':
        dstgrd = dstgrd
    else:
        dstgrd = pyroms.grid.get_ROMS_grid(dstgrd)

    # build intermediate zgrid
    if zlevel is None:
        zlevel = np.array([-7500.,-7000.,-6500.,-6000.,-5500.,-5000.,\
                   -4500.,-4000.,-3500.,-3000.,-2500.,-2000.,-1750.,\
                   -1500.,-1250.,-1000.,-900.,-800.,-700.,-600.,-500.,\
                   -400.,-300.,-250.,-200.,-175.,-150.,-125.,-100.,-90.,\
                   -80.,-70.,-60.,-50.,-45.,-40.,-35.,-30.,-25.,-20.,-17.5,\
                   -15.,-12.5,-10.,-7.5,-5.,-2.5,0.])
    else:
        zlevel = np.sort(-abs(zlevel))
    nzlevel = len(zlevel)
    src_zcoord = pyroms.vgrid.z_coordinate(srcgrd.vgrid.h, zlevel, nzlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dstgrd.vgrid.h, zlevel, nzlevel)
    srcgrdz = pyroms.grid.ROMS_Grid(srcgrd.name+'_Z', srcgrd.hgrid, src_zcoord)
    dstgrdz = pyroms.grid.ROMS_Grid(dstgrd.name+'_Z', dstgrd.hgrid, dst_zcoord)

    # varname argument
    if type(varname).__name__ == 'list':
        nvar = len(varname)
    elif type(varname).__name__ == 'str':
        varname = [varname]
        nvar = len(varname)
    else:
        raise ValueError, 'varname must be a str or a list of str'

    # if we're working on u and v, we'll compute ubar,vbar afterwards
    compute_ubar = False
    if (varname.__contains__('u') == 1 and varname.__contains__('v') == 1) or \
       (varname.__contains__('u_eastward') == 1 and varname.__contains__('v_northward') == 1):
        compute_ubar = True
        print 'ubar/vbar to be computed from u/v' 
        if varname.__contains__('ubar'):
            varname.remove('ubar')
            nvar = nvar-1
        if varname.__contains__('vbar'):
            varname.remove('vbar')
            nvar = nvar-1

    # if rotate_uv=True, check that u and v are in varname
    if rotate_uv is True:
        if varname.__contains__(uvar) == 0 or varname.__contains__(vvar) == 0:
            raise Warning, 'varname must include uvar and vvar in order to' \
                   + ' rotate the velocity field'
        else:
            varname.remove(uvar)
            varname.remove(vvar)
            nvar = nvar-2

    # srcfile argument
    if type(srcfile).__name__ == 'list':
        nfile = len(srcfile)
    elif type(srcfile).__name__ == 'str':
        srcfile = sorted(glob.glob(srcfile))
        nfile = len(srcfile)
    else:
        raise ValueError, 'src_srcfile must be a str or a list of str'

    # get wts_file
    if type(wts_files).__name__ == 'str':
        wts_files = sorted(glob.glob(wts_files))
 
    # loop over the srcfile
    for nf in range(nfile):
        print 'Working with file', srcfile[nf], '...'

        # get time 
        ocean_time = pyroms.utility.get_nc_var('ocean_time', srcfile[nf])
        ntime = len(ocean_time[:])

        # trange argument
        if trange is None:
            trange = range(ntime)

        # create destination file
        dstfile = dstdir + os.path.basename(srcfile[nf])[:-3] + '_' + dstgrd.name + '.nc'
        if os.path.exists(dstfile) is False:
            print 'Creating destination file', dstfile
            pyroms_toolbox.nc_create_roms_file(dstfile, dstgrd, ocean_time)

        # open destination file
        nc = netCDF.Dataset(dstfile, 'a', format='NETCDF3_64BIT')

        nctidx = 0
        # loop over time
        for nt in trange:

            nc.variables['ocean_time'][nctidx] = ocean_time[nt]

            # loop over variable
            for nv in range(nvar):
                print ' '
                print 'remapping', varname[nv], 'from', srcgrd.name, \
                      'to', dstgrd.name
                print 'time =', ocean_time[nt]   

                # get source data
                src_var = pyroms.utility.get_nc_var(varname[nv], srcfile[nf])

                # determine variable dimension
                ndim = len(src_var.dimensions)-1

                # get spval
                try:
                    spval = src_var._FillValue
                except:
                    raise Warning, 'Did not find a _FillValue attribute.' 

                # irange
                if irange is None:
                    iirange = (0,src_var.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0,src_var.shape[-2])
                else:
                    jjrange = jrange

                # determine where on the C-grid these variable lies
                if src_var.dimensions[2].find('_rho') != -1:
                    Cpos='rho'
                if src_var.dimensions[2].find('_u') != -1:
                    Cpos='u'
                if src_var.dimensions[2].find('_v') != -1:
                    Cpos='v'
                if src_var.dimensions[1].find('_w') != -1:
                    Cpos='w'

                print 'Arakawa C-grid position is', Cpos

                # create variable in _destination file
                if nt == trange[0]:
                    print 'Creating variable', varname[nv]
                    nc.createVariable(varname[nv], 'f8', src_var.dimensions, fill_value=spval)
                    nc.variables[varname[nv]].long_name = src_var.long_name
                    try:
                        nc.variables[varname[nv]].units = src_var.units
                    except:
                        print varname[nv]+' has no units'
                    nc.variables[varname[nv]].time = src_var.time
                    nc.variables[varname[nv]].coordinates = \
                        src_var.coordinates
                    nc.variables[varname[nv]].field = src_var.field

                # get the right remap weights file
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__(Cpos+'_to_'+Cpos+'.nc'):
                        wts_file = wts_files[s]
                        break
                    else:
                        if s == len(wts_files) - 1:
                            raise ValueError, 'Did not find the appropriate remap weights file'

                if ndim == 3:
                    # vertical interpolation from sigma to standard z level
                    print 'vertical interpolation from sigma to standard z level'
                    src_varz = pyroms.remapping.roms2z( \
                                 src_var[nt,:,jjrange[0]:jjrange[1],iirange[0]:iirange[1]], \
                                 srcgrd, srcgrdz, Cpos=Cpos, spval=spval, \
                                 irange=iirange, jrange=jjrange)

                    # flood the grid
                    print 'flood the grid'
                    src_varz = pyroms.remapping.flood(src_varz, srcgrdz, Cpos=Cpos, \
                                      irange=iirange, jrange=jjrange, spval=spval, \
                                      dmax=dmax, cdepth=cdepth, kk=kk)

                else:
                    src_varz = src_var[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]

#                print datetime.datetime.now()
                # horizontal interpolation using scrip weights
                print 'horizontal interpolation using scrip weights'
                dst_varz = pyroms.remapping.remap(src_varz, wts_file, \
                                                  spval=spval)

#                print datetime.datetime.now()

                if ndim == 3:
                    # vertical interpolation from standard z level to sigma
                    print 'vertical interpolation from standard z level to sigma'
                    dst_var = pyroms.remapping.z2roms(dst_varz, dstgrdz, dstgrd, \
                                     Cpos=Cpos, spval=spval, flood=False)
                else:
                    dst_var = dst_varz

                # write data in destination file
                print 'write data in destination file'
                nc.variables[varname[nv]][nctidx] = dst_var


            # rotate the velocity field if requested
            if rotate_uv is True:
                print ' ' 
                print 'remapping and rotating u and v from', srcgrd.name, \
                      'to', dstgrd.name

                # get source data
                src_u = pyroms.utility.get_nc_var(uvar, srcfile[nf])
                src_v = pyroms.utility.get_nc_var(vvar, srcfile[nf])

                # get spval
                try:
                    spval = src_v._FillValue
                except:
                    raise Warning, 'Did not find a _FillValue attribute.' 

                if rotate_part:
                    ndim = len(src_u.dimensions)-1
                    ind = uvar.find('_eastward')
                    uvar = uvar[0:ind]
                    print "Warning: renaming uvar to", uvar
                    ind = vvar.find('_northward')
                    vvar = vvar[0:ind]
                    print "Warning: renaming vvar to", vvar
                    if ndim == 3:
                        dimens_u = ['ocean_time', 's_rho', 'eta_u', 'xi_u']
                        dimens_v = ['ocean_time', 's_rho', 'eta_v', 'xi_v']
                    else:
                        dimens_u = ['ocean_time', 'eta_u', 'xi_u']
                        dimens_v = ['ocean_time', 'eta_v', 'xi_v']

                else:
                    dimens_u = [i for i in src_u.dimensions]
                    dimens_v = [i for i in src_v.dimensions]

                # create variable in destination file
                print 'Creating variable '+uvar
                nc.createVariable(uvar, 'f8', dimens_u, fill_value=spval)
                nc.variables[uvar].long_name = src_u.long_name
                nc.variables[uvar].units = src_u.units
                nc.variables[uvar].time = src_u.time
                nc.variables[uvar].coordinates = \
                           str(dimens_u.reverse())
                nc.variables[uvar].field = src_u.field
                print 'Creating variable '+vvar
                nc.createVariable(vvar, 'f8', dimens_v, fill_value=spval)
                nc.variables[vvar].long_name = src_v.long_name
                nc.variables[vvar].units = src_v.units
                nc.variables[vvar].time = src_v.time
                nc.variables[vvar].coordinates = \
                           str(dimens_v.reverse())
                nc.variables[vvar].field = src_v.field

                # get the right remap weights file
                if rotate_part:
                    for s in range(len(wts_files)):
                        if wts_files[s].__contains__('rho_to_rho.nc'):
                            wts_file_u = wts_files[s]
                            wts_file_v = wts_files[s]
                    Cpos_u = 'rho'
                    Cpos_v = 'rho'
                else:
                    for s in range(len(wts_files)):
                        if wts_files[s].__contains__('u_to_rho.nc'):
                            wts_file_u = wts_files[s]
                        if wts_files[s].__contains__('v_to_rho.nc'):
                            wts_file_v = wts_files[s]
                    Cpos_u = 'u'
                    Cpos_v = 'v'

                # vertical interpolation from sigma to standard z level
                # irange
                if irange is None:
                    iirange = (0,src_u.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0,src_u.shape[-2])
                else:
                    jjrange = jrange

                ndim = len(src_v.dimensions)-1
                if ndim == 3:
                    print 'vertical interpolation from sigma to standard z level'
                    src_uz = pyroms.remapping.roms2z( \
                            src_u[nt,:,jjrange[0]:jjrange[1],iirange[0]:iirange[1]], \
                            srcgrd, srcgrdz, Cpos=Cpos_u, irange=iirange, jrange=jjrange)
                    # flood the grid
                    print 'flood the u grid'
                    src_uz = pyroms.remapping.flood(src_uz, srcgrdz, Cpos=Cpos_u, \
                                  irange=iirange, jrange=jjrange, \
                                  spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
                else:
                    src_uz = src_u[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]
                    src_uz = pyroms.remapping.flood2d(src_uz, srcgrdz, Cpos=Cpos_u, \
                                      irange=iirange, jrange=jjrange, spval=spval, \
                                      dmax=dmax)

                # irange
                if irange is None:
                    iirange = (0,src_v.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0,src_v.shape[-2])
                else:
                    jjrange = jrange

                if ndim == 3:
                    src_vz = pyroms.remapping.roms2z( \
                            src_v[nt,:,jjrange[0]:jjrange[1],iirange[0]:iirange[1]], \
                            srcgrd, srcgrdz, Cpos=Cpos_v, irange=iirange, jrange=jjrange)

                    # flood the grid
                    print 'flood the v grid'
                    src_vz = pyroms.remapping.flood(src_vz, srcgrdz, Cpos=Cpos_v, \
                                  irange=iirange, jrange=jjrange, \
                                  spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
                else:
                    src_vz = src_v[nt,jjrange[0]:jjrange[1],iirange[0]:iirange[1]]
                    src_vz = pyroms.remapping.flood2d(src_vz, srcgrdz, Cpos=Cpos_v, \
                                      irange=iirange, jrange=jjrange, spval=spval, \
                                      dmax=dmax)

                # horizontal interpolation using scrip weights
                print 'horizontal interpolation using scrip weights'
                dst_uz = pyroms.remapping.remap(src_uz, wts_file_u, \
                                                  spval=spval)
                dst_vz = pyroms.remapping.remap(src_vz, wts_file_v, \
                                                  spval=spval)

                if ndim == 3:
                    # vertical interpolation from standard z level to sigma
                    print 'vertical interpolation from standard z level to sigma'
                    dst_u = pyroms.remapping.z2roms(dst_uz, dstgrdz, dstgrd, \
                                 Cpos='rho', spval=spval, flood=False)
                    dst_v = pyroms.remapping.z2roms(dst_vz, dstgrdz, dstgrd, \
                                 Cpos='rho', spval=spval, flood=False)
                else:
                    dst_u = dst_uz
                    dst_v = dst_vz

                # rotate u,v fields
                if rotate_part:
                    src_angle = np.zeros(dstgrd.hgrid.angle_rho.shape)
                else:
                    for s in range(len(wts_files)):
                        if wts_files[s].__contains__('rho_to_rho.nc'):
                            wts_file = wts_files[s]
                    src_ang = srcgrd.hgrid.angle_rho[jjrange[0]:jjrange[1],iirange[0]:iirange[1]]
                    src_angle = pyroms.remapping.remap(src_ang, wts_file)

                dst_angle = dstgrd.hgrid.angle_rho
                angle = dst_angle - src_angle
                angle = np.tile(angle, (dstgrd.vgrid.N, 1, 1))

                U = dst_u + dst_v*1j
                eitheta = np.exp(-1j*angle)
                U = U * eitheta

                dst_u = np.real(U)
                dst_v = np.imag(U)

                # move back to u,v points
                dst_u = 0.5 * (dst_u[:,:,:-1] + dst_u[:,:,1:])
                dst_v = 0.5 * (dst_v[:,:-1,:] + dst_v[:,1:,:])

                # spval
                idxu = np.where(dstgrd.hgrid.mask_u == 0)
                idxv = np.where(dstgrd.hgrid.mask_v == 0)
                for n in range(dstgrd.vgrid.N):
                    dst_u[n,idxu[0], idxu[1]] = spval
                    dst_v[n,idxv[0], idxv[1]] = spval

                # write data in destination file
                print 'write data in destination file'
                nc.variables[uvar][nctidx] = dst_u
                nc.variables[vvar][nctidx] = dst_v

            if compute_ubar:
                print 'Creating variable ubar'
                nc.createVariable('ubar', 'f8', \
                     ('ocean_time', 'eta_u', 'xi_u'), fill_value=spval)
                nc.variables['ubar'].long_name = '2D u-momentum component'
                nc.variables['ubar'].units = 'meter second-1'
                nc.variables['ubar'].time = 'ocean_time'
                nc.variables['ubar'].coordinates = 'xi_u eta_u ocean_time'
                nc.variables['ubar'].field = 'ubar-velocity,, scalar, series'
                print 'Creating variable vbar'
                nc.createVariable('vbar', 'f8', \
                     ('ocean_time', 'eta_v', 'xi_v'), fill_value=spval)
                nc.variables['vbar'].long_name = '2D v-momentum component'
                nc.variables['vbar'].units = 'meter second-1'
                nc.variables['vbar'].time = 'ocean_time'
                nc.variables['vbar'].coordinates = 'xi_v eta_v ocean_time'
                nc.variables['vbar'].field = 'vbar-velocity,, scalar, series'

                # compute depth average velocity ubar and vbar
                # get z at the right position
                z_u = 0.5 * (dstgrd.vgrid.z_w[0,:,:,:-1] + \
                        dstgrd.vgrid.z_w[0,:,:,1:])
                z_v = 0.5 * (dstgrd.vgrid.z_w[0,:,:-1,:] + \
                        dstgrd.vgrid.z_w[0,:,1:,:])

                dst_ubar = np.zeros((dst_u.shape[1], dst_u.shape[2]))
                dst_vbar = np.zeros((dst_v.shape[1], dst_v.shape[2]))

                for i in range(dst_ubar.shape[1]):
                    for j in range(dst_ubar.shape[0]):
                        dst_ubar[j,i] = (dst_u[:,j,i] * \
                                np.diff(z_u[:,j,i])).sum() / -z_u[0,j,i]

                for i in range(dst_vbar.shape[1]):
                    for j in range(dst_vbar.shape[0]):
                        dst_vbar[j,i] = (dst_v[:,j,i] * \
                                np.diff(z_v[:,j,i])).sum() / -z_v[0,j,i]

                # spval
                idxu = np.where(dstgrd.hgrid.mask_u == 0)
                idxv = np.where(dstgrd.hgrid.mask_v == 0)
                dst_ubar[idxu[0], idxu[1]] = spval
                dst_vbar[idxv[0], idxv[1]] = spval

                nc.variables['ubar'][0] = dst_ubar
                nc.variables['vbar'][0] = dst_vbar

        nctidx = nctidx + 1
 
    # close destination file
    nc.close()

    return
Ejemplo n.º 32
0
def remapping(
    varname,
    srcfile,
    wts_files,
    srcgrd,
    dstgrd,
    rotate_uv=False,
    trange=None,
    irange=None,
    jrange=None,
    dstdir="./",
    zlevel=None,
    dmax=0,
    cdepth=0,
    kk=0,
    uvar="u",
    vvar="v",
):
    """
    A remapping function to go from a ROMS grid to another ROMS grid.
    If the u/v variables need to be rotated, it must be called for each
    u/v pair (such as ubar/vbar, uice/vice).
    """

    # get input and output grid
    if type(srcgrd).__name__ == "ROMS_Grid":
        srcgrd = srcgrd
    else:
        srcgrd = pyroms.grid.get_ROMS_grid(srcgrd)
    if type(dstgrd).__name__ == "ROMS_Grid":
        dstgrd = dstgrd
    else:
        dstgrd = pyroms.grid.get_ROMS_grid(dstgrd)

    # build intermediaire zgrid
    if zlevel is None:
        zlevel = np.array(
            [
                -7500.0,
                -7000.0,
                -6500.0,
                -6000.0,
                -5500.0,
                -5000.0,
                -4500.0,
                -4000.0,
                -3500.0,
                -3000.0,
                -2500.0,
                -2000.0,
                -1750.0,
                -1500.0,
                -1250.0,
                -1000.0,
                -900.0,
                -800.0,
                -700.0,
                -600.0,
                -500.0,
                -400.0,
                -300.0,
                -250.0,
                -200.0,
                -175.0,
                -150.0,
                -125.0,
                -100.0,
                -90.0,
                -80.0,
                -70.0,
                -60.0,
                -50.0,
                -45.0,
                -40.0,
                -35.0,
                -30.0,
                -25.0,
                -20.0,
                -17.5,
                -15.0,
                -12.5,
                -10.0,
                -7.5,
                -5.0,
                -2.5,
                0.0,
            ]
        )
    else:
        zlevel = np.sort(-abs(zlevel))
    nzlevel = len(zlevel)
    src_zcoord = pyroms.vgrid.z_coordinate(srcgrd.vgrid.h, zlevel, nzlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dstgrd.vgrid.h, zlevel, nzlevel)
    srcgrdz = pyroms.grid.ROMS_Grid(srcgrd.name + "_Z", srcgrd.hgrid, src_zcoord)
    dstgrdz = pyroms.grid.ROMS_Grid(dstgrd.name + "_Z", dstgrd.hgrid, dst_zcoord)

    # varname argument
    if type(varname).__name__ == "list":
        nvar = len(varname)
    elif type(varname).__name__ == "str":
        varname = [varname]
        nvar = len(varname)
    else:
        raise ValueError, "varname must be a str or a list of str"

    # if we're working on u and v, we'll compute ubar,vbar afterwards
    compute_ubar = False
    if varname.__contains__("u") == 1 and varname.__contains__("v") == 1:
        compute_ubar = True
        print "ubar/vbar to be computed from u/v"
        if varname.__contains__("ubar"):
            varname.remove("ubar")
            nvar = nvar - 1
        if varname.__contains__("vbar"):
            varname.remove("vbar")
            nvar = nvar - 1

    # if rotate_uv=True, check that u and v are in varname
    if rotate_uv is True:
        if varname.__contains__(uvar) == 0 or varname.__contains__(vvar) == 0:
            raise Warning, "varname must include uvar and vvar in order to" + " rotate the velocity field"
        else:
            varname.remove(uvar)
            varname.remove(vvar)
            nvar = nvar - 2

    # srcfile argument
    if type(srcfile).__name__ == "list":
        nfile = len(srcfile)
    elif type(srcfile).__name__ == "str":
        srcfile = sorted(glob.glob(srcfile))
        nfile = len(srcfile)
    else:
        raise ValueError, "src_srcfile must be a str or a list of str"

    # get wts_file
    if type(wts_files).__name__ == "str":
        wts_files = sorted(glob.glob(wts_files))

    # loop over the srcfile
    for nf in range(nfile):
        print "Working with file", srcfile[nf], "..."

        # get time
        ocean_time = pyroms.utility.get_nc_var("ocean_time", srcfile[nf])
        ntime = len(ocean_time[:])

        # trange argument
        if trange is None:
            trange = range(ntime)
        else:
            trange = range(trange[0], trange[1] + 1)

        # create destination file
        dstfile = dstdir + os.path.basename(srcfile[nf])[:-3] + "_" + dstgrd.name + ".nc"
        if os.path.exists(dstfile) is False:
            print "Creating destination file", dstfile
            pyroms_toolbox.nc_create_roms_file(dstfile, dstgrd, ocean_time)

        # open destination file
        nc = netCDF.Dataset(dstfile, "a", format="NETCDF3_CLASSIC")

        nctidx = 0
        # loop over time
        for nt in trange:

            nc.variables["ocean_time"][nctidx] = ocean_time[nt]

            # loop over variable
            for nv in range(nvar):
                print " "
                print "remapping", varname[nv], "from", srcgrd.name, "to", dstgrd.name
                print "time =", ocean_time[nt]

                # get source data
                src_var = pyroms.utility.get_nc_var(varname[nv], srcfile[nf])

                # determine variable dimension
                ndim = len(src_var.dimensions) - 1

                # get spval
                try:
                    spval = src_var._FillValue
                except:
                    raise Warning, "Did not find a _FillValue attribute."

                # irange
                if irange is None:
                    iirange = (0, src_var._shape()[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0, src_var._shape()[-2])
                else:
                    jjrange = jrange

                # determine where on the C-grid these variable lies
                if src_var.dimensions[2].find("_rho") != -1:
                    Cpos = "rho"
                if src_var.dimensions[2].find("_u") != -1:
                    Cpos = "u"
                if src_var.dimensions[2].find("_v") != -1:
                    Cpos = "v"
                if src_var.dimensions[1].find("_w") != -1:
                    Cpos = "w"

                print "Arakawa C-grid position is", Cpos

                # create variable in _destination file
                if nt == trange[0]:
                    print "Creating variable", varname[nv]
                    nc.createVariable(varname[nv], "f8", src_var.dimensions)
                    nc.variables[varname[nv]].long_name = src_var.long_name
                    try:
                        nc.variables[varname[nv]].units = src_var.units
                    except:
                        print varname[nv] + " has no units"
                    nc.variables[varname[nv]].time = src_var.time
                    nc.variables[varname[nv]].coordinates = src_var.coordinates
                    nc.variables[varname[nv]].field = src_var.field
                    nc.variables[varname[nv]]._FillValue = spval

                # get the right remap weights file
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__(Cpos + "_to_" + Cpos + ".nc"):
                        wts_file = wts_files[s]
                        break
                    else:
                        if s == len(wts_files) - 1:
                            raise ValueError, "Did not find the appropriate remap weights file"

                if ndim == 3:
                    # vertical interpolation from sigma to standard z level
                    print "vertical interpolation from sigma to standard z level"
                    src_varz = pyroms.remapping.roms2z(
                        src_var[nt, :, jjrange[0] : jjrange[1], iirange[0] : iirange[1]],
                        srcgrd,
                        srcgrdz,
                        Cpos=Cpos,
                        spval=spval,
                        irange=iirange,
                        jrange=jjrange,
                    )

                    # flood the grid
                    print "flood the grid"
                    src_varz = pyroms.remapping.flood(
                        src_varz,
                        srcgrdz,
                        Cpos=Cpos,
                        irange=iirange,
                        jrange=jjrange,
                        spval=spval,
                        dmax=dmax,
                        cdepth=cdepth,
                        kk=kk,
                    )

                    tmp_src_varz = np.zeros((nzlevel, src_var[:].shape[-2], src_var[:].shape[-1]))
                    tmp_src_varz[:, jjrange[0] : jjrange[1], iirange[0] : iirange[1]] = src_varz
                else:
                    src_varz = src_var[nt, jjrange[0] : jjrange[1], iirange[0] : iirange[1]]
                    tmp_src_varz = np.zeros(src_var[nt, :].shape)
                    tmp_src_varz[jjrange[0] : jjrange[1], iirange[0] : iirange[1]] = src_varz

                print datetime.datetime.now()
                # horizontal interpolation using scrip weights
                print "horizontal interpolation using scrip weights"
                dst_varz = pyroms.remapping.remap(tmp_src_varz, wts_file, spval=spval)

                print datetime.datetime.now()

                if ndim == 3:
                    # vertical interpolation from standard z level to sigma
                    print "vertical interpolation from standard z level to sigma"
                    dst_var = pyroms.remapping.z2roms(dst_varz, dstgrdz, dstgrd, Cpos=Cpos, spval=spval, flood=False)
                else:
                    dst_var = dst_varz

                # write data in destination file
                print "write data in destination file"
                nc.variables[varname[nv]][nctidx] = dst_var
                if varname[nv] == "u":
                    dst_u = dst_var
                if varname[nv] == "v":
                    dst_v = dst_var

            # rotate the velocity field if requested
            if rotate_uv is True:
                print " "
                print "remapping and rotating u and v from", srcgrd.name, "to", dstgrd.name

                # get source data
                src_u = pyroms.utility.get_nc_var(uvar, srcfile[nf])
                src_v = pyroms.utility.get_nc_var(vvar, srcfile[nf])

                # get spval
                try:
                    spval = src_v._FillValue
                except:
                    raise Warning, "Did not find a _FillValue attribute."

                # create variable in destination file
                print "Creating variable " + uvar
                nc.createVariable(uvar, "f8", src_u.dimensions)
                nc.variables[uvar].long_name = src_u.long_name
                nc.variables[uvar].units = src_u.units
                nc.variables[uvar].time = src_u.time
                nc.variables[uvar].coordinates = src_u.coordinates
                nc.variables[uvar].field = src_u.field
                nc.variables[uvar]._FillValue = spval
                print "Creating variable " + vvar
                nc.createVariable(vvar, "f8", src_v.dimensions)
                nc.variables[vvar].long_name = src_v.long_name
                nc.variables[vvar].units = src_v.units
                nc.variables[vvar].time = src_v.time
                nc.variables[uvar].coordinates = src_u.coordinates
                nc.variables[uvar].field = src_u.field
                nc.variables[vvar]._FillValue = spval

                # get the right remap weights file
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__("u_to_rho.nc"):
                        wts_file_u = wts_files[s]
                    if wts_files[s].__contains__("v_to_rho.nc"):
                        wts_file_v = wts_files[s]

                # vertical interpolation from sigma to standard z level
                print "vertical interpolation from sigma to standard z level"
                # irange
                if irange is None:
                    iirange = (0, src_u._shape()[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0, src_u._shape()[-2])
                else:
                    jjrange = jrange

                ndim = len(src_v.dimensions) - 1
                if ndim == 3:
                    src_uz = pyroms.remapping.roms2z(
                        src_u[nt, :, jjrange[0] : jjrange[1], iirange[0] : iirange[1]],
                        srcgrd,
                        srcgrdz,
                        Cpos="u",
                        irange=iirange,
                        jrange=jjrange,
                    )
                    # flood the grid
                    print "flood the u grid"
                    src_uz = pyroms.remapping.flood(
                        src_uz,
                        srcgrdz,
                        Cpos="u",
                        irange=iirange,
                        jrange=jjrange,
                        spval=spval,
                        dmax=dmax,
                        cdepth=cdepth,
                        kk=kk,
                    )
                    tmp_src_uz = np.zeros((nzlevel, src_u[:].shape[-2], src_u[:].shape[-1]))
                    tmp_src_uz[:, jjrange[0] : jjrange[1], iirange[0] : iirange[1]] = src_uz
                else:
                    src_uz = src_u[nt, jjrange[0] : jjrange[1], iirange[0] : iirange[1]]
                    tmp_src_uz = np.zeros(src_u[nt, :].shape)
                    tmp_src_uz[jjrange[0] : jjrange[1], iirange[0] : iirange[1]] = src_uz

                # irange
                if irange is None:
                    iirange = (0, src_v._shape()[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0, src_v._shape()[-2])
                else:
                    jjrange = jrange

                if ndim == 3:
                    src_vz = pyroms.remapping.roms2z(
                        src_v[nt, :, jjrange[0] : jjrange[1], iirange[0] : iirange[1]],
                        srcgrd,
                        srcgrdz,
                        Cpos="v",
                        irange=iirange,
                        jrange=jjrange,
                    )

                    # flood the grid
                    print "flood the v grid"
                    src_vz = pyroms.remapping.flood(
                        src_vz,
                        srcgrdz,
                        Cpos="v",
                        irange=iirange,
                        jrange=jjrange,
                        spval=spval,
                        dmax=dmax,
                        cdepth=cdepth,
                        kk=kk,
                    )
                    tmp_src_vz = np.zeros((nzlevel, src_v[:].shape[-2], src_v[:].shape[-1]))
                    tmp_src_vz[:, jjrange[0] : jjrange[1], iirange[0] : iirange[1]] = src_vz
                else:
                    src_vz = src_v[nt, jjrange[0] : jjrange[1], iirange[0] : iirange[1]]
                    tmp_src_vz = np.zeros(src_v[nt, :].shape)
                    tmp_src_vz[jjrange[0] : jjrange[1], iirange[0] : iirange[1]] = src_vz

                # horizontal interpolation using scrip weights
                print "horizontal interpolation using scrip weights"
                dst_uz = pyroms.remapping.remap(tmp_src_uz, wts_file_u, spval=spval)
                dst_vz = pyroms.remapping.remap(tmp_src_vz, wts_file_v, spval=spval)

                if ndim == 3:
                    # vertical interpolation from standard z level to sigma
                    print "vertical interpolation from standard z level to sigma"
                    dst_u = pyroms.remapping.z2roms(dst_uz, dstgrdz, dstgrd, Cpos="rho", spval=spval, flood=False)
                    dst_v = pyroms.remapping.z2roms(dst_vz, dstgrdz, dstgrd, Cpos="rho", spval=spval, flood=False)
                else:
                    dst_u = dst_uz
                    dst_v = dst_vz

                # rotate u,v fields
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__("rho_to_rho.nc"):
                        wts_file = wts_files[s]
                src_angle = pyroms.remapping.remap(srcgrd.hgrid.angle_rho, wts_file)
                dst_angle = dstgrd.hgrid.angle_rho
                angle = dst_angle - src_angle
                angle = np.tile(angle, (dstgrd.vgrid.N, 1, 1))

                U = dst_u + dst_v * 1j
                eitheta = np.exp(-1j * angle)
                U = U * eitheta

                dst_u = np.real(U)
                dst_v = np.imag(U)

                # move back to u,v points
                dst_u = 0.5 * (dst_u[:, :, :-1] + dst_u[:, :, 1:])
                dst_v = 0.5 * (dst_v[:, :-1, :] + dst_v[:, 1:, :])

                # spval
                idxu = np.where(dstgrd.hgrid.mask_u == 0)
                idxv = np.where(dstgrd.hgrid.mask_v == 0)
                for n in range(dstgrd.vgrid.N):
                    dst_u[n, idxu[0], idxu[1]] = spval
                    dst_v[n, idxv[0], idxv[1]] = spval

                # write data in destination file
                print "write data in destination file"
                nc.variables[uvar][nctidx] = dst_u
                nc.variables[vvar][nctidx] = dst_v

            if compute_ubar:
                print "Creating variable ubar"
                nc.createVariable("ubar", "f8", ("ocean_time", "eta_u", "xi_u"), fill_value=spval)
                nc.variables["ubar"].long_name = "2D u-momentum component"
                nc.variables["ubar"].units = "meter second-1"
                nc.variables["ubar"].time = "ocean_time"
                nc.variables["ubar"].coordinates = "xi_u eta_u ocean_time"
                nc.variables["ubar"].field = "ubar-velocity,, scalar, series"
                nc.variables["ubar"]._FillValue = spval
                print "Creating variable vbar"
                nc.createVariable("vbar", "f8", ("ocean_time", "eta_v", "xi_v"), fill_value=spval)
                nc.variables["vbar"].long_name = "2D v-momentum component"
                nc.variables["vbar"].units = "meter second-1"
                nc.variables["vbar"].time = "ocean_time"
                nc.variables["vbar"].coordinates = "xi_v eta_v ocean_time"
                nc.variables["vbar"].field = "vbar-velocity,, scalar, series"
                nc.variables["vbar"]._FillValue = spval

                # compute depth average velocity ubar and vbar
                # get z at the right position
                z_u = 0.5 * (dstgrd.vgrid.z_w[0, :, :, :-1] + dstgrd.vgrid.z_w[0, :, :, 1:])
                z_v = 0.5 * (dstgrd.vgrid.z_w[0, :, :-1, :] + dstgrd.vgrid.z_w[0, :, 1:, :])

                dst_ubar = np.zeros((dst_u.shape[1], dst_u.shape[2]))
                dst_vbar = np.zeros((dst_v.shape[1], dst_v.shape[2]))

                for i in range(dst_ubar.shape[1]):
                    for j in range(dst_ubar.shape[0]):
                        dst_ubar[j, i] = (dst_u[:, j, i] * np.diff(z_u[:, j, i])).sum() / -z_u[0, j, i]

                for i in range(dst_vbar.shape[1]):
                    for j in range(dst_vbar.shape[0]):
                        dst_vbar[j, i] = (dst_v[:, j, i] * np.diff(z_v[:, j, i])).sum() / -z_v[0, j, i]

                # spval
                idxu = np.where(dstgrd.hgrid.mask_u == 0)
                idxv = np.where(dstgrd.hgrid.mask_v == 0)
                dst_ubar[idxu[0], idxu[1]] = spval
                dst_vbar[idxv[0], idxv[1]] = spval

                nc.variables["ubar"][0] = dst_ubar
                nc.variables["vbar"][0] = dst_vbar

        nctidx = nctidx + 1

    # close destination file
    nc.close()

    return
Ejemplo n.º 33
0
def remap_clm_uv(src_file, src_grd, dst_grd, dxy=20, cdepth=0, kk=0, dst_dir='./'):

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'
    # time reference "days since 1900-01-01 00:00:00"
#    ref = datetime(1900, 1, 1, 0, 0, 0)
#    ref = date2num(ref)
#    tag = src_file.rsplit('/')[-1].rsplit('_')[-1].rsplit('-')[0]
#    year = int(tag[:4])
#    month = int(tag[4:6])
#    day = int(tag[6:])
#    time = datetime(year, month, day, 0, 0, 0)
#    time = date2num(time)
#    time = time - ref
#    time = time + 2.5 # 5-day average
    cdf = netCDF.Dataset(src_file)
    src_varu = cdf.variables['u'][0]
    src_varv = cdf.variables['v'][0]
    time = cdf.variables['ocean_time'][0]

    # get dimensions
    Mp, Lp = dst_grd.hgrid.mask_rho.shape

    # create destination file
    dst_file = src_file.rsplit('/')[-1]
    dst_fileu = dst_dir + dst_file[:-3] + '_u_clim_' + dst_grd.name + '.nc'
    print '\nCreating destination file', dst_fileu
    if os.path.exists(dst_fileu) is True:
        os.remove(dst_fileu)
    pyroms_toolbox.nc_create_roms_file(dst_fileu, dst_grd, nctime)
    dst_filev = dst_dir + dst_file[:-3] + '_v_clim_' + dst_grd.name + '.nc'
    print 'Creating destination file', dst_filev
    if os.path.exists(dst_filev) is True:
        os.remove(dst_filev)
    pyroms_toolbox.nc_create_roms_file(dst_filev, dst_grd, nctime)

    # open destination file
    ncu = netCDF.Dataset(dst_fileu, 'a', format='NETCDF3_64BIT')
    ncv = netCDF.Dataset(dst_filev, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_varu = cdf.variables['u']
    src_varv = cdf.variables['v']

    #get missing value
    spval = src_varu._FillValue
    src_varu = src_varu[0]
    src_varv = src_varv[0]

    # get weights file
    wts_file = 'remap_weights_GLBa0.08_to_PALAU1_bilinear_t_to_rho.nc'

    # build intermediate zgrid
    zlevel = -src_grd.z_t[::-1,0,0]
    nzlevel = len(zlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)

    # create variable in destination file
    print 'Creating variable u'
    ncu.createVariable('u', 'f8', ('ocean_time', 's_rho', 'eta_u', 'xi_u'), fill_value=spval)
    ncu.variables['u'].long_name = '3D u-momentum component'
    ncu.variables['u'].units = 'meter second-1'
    ncu.variables['u'].field = 'u-velocity, scalar, series'
    ncu.variables['u'].time = 'ocean_time'
    # create variable in destination file
    print 'Creating variable ubar'
    ncu.createVariable('ubar', 'f8', ('ocean_time', 'eta_u', 'xi_u'), fill_value=spval)
    ncu.variables['ubar'].long_name = '2D u-momentum component'
    ncu.variables['ubar'].units = 'meter second-1'
    ncu.variables['ubar'].field = 'ubar-velocity,, scalar, series'
    ncu.variables['ubar'].time = 'ocean_time'

    print 'Creating variable v'
    ncv.createVariable('v', 'f8', ('ocean_time', 's_rho', 'eta_v', 'xi_v'), fill_value=spval)
    ncv.variables['v'].long_name = '3D v-momentum component'
    ncv.variables['v'].units = 'meter second-1'
    ncv.variables['v'].field = 'v-velocity, scalar, series'
    ncv.variables['v'].time = 'ocean_time'
    print 'Creating variable vbar'
    ncv.createVariable('vbar', 'f8', ('ocean_time', 'eta_v', 'xi_v'), fill_value=spval)
    ncv.variables['vbar'].long_name = '2D v-momentum component'
    ncv.variables['vbar'].units = 'meter second-1'
    ncv.variables['vbar'].field = 'vbar-velocity,, scalar, series'
    ncv.variables['vbar'].time = 'ocean_time'


    # remaping
    print 'remapping and rotating u and v from', src_grd.name, \
                      'to', dst_grd.name
    print 'time =', time


    # flood the grid
    print 'flood the grid'
    src_uz = pyroms_toolbox.Grid_HYCOM.flood_fast(src_varu, src_grd, pos='t', \
                spval=spval, dxy=dxy, cdepth=cdepth, kk=kk)
    src_vz = pyroms_toolbox.Grid_HYCOM.flood_fast(src_varv, src_grd, pos='t', \
                spval=spval, dxy=dxy, cdepth=cdepth, kk=kk)

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_uz = pyroms.remapping.remap(src_uz, wts_file, \
                                      spval=spval)
    dst_vz = pyroms.remapping.remap(src_vz, wts_file, \
                                      spval=spval)

    # vertical interpolation from standard z level to sigma
    print 'vertical interpolation from standard z level to sigma'
    dst_u = pyroms.remapping.z2roms(dst_uz[::-1,:,:], dst_grdz, \
                        dst_grd, Cpos='rho', spval=spval, flood=False)
    dst_v = pyroms.remapping.z2roms(dst_vz[::-1,:,:], dst_grdz,  \
                        dst_grd, Cpos='rho', spval=spval, flood=False)


    # rotate u,v fields
    src_angle = pyroms.remapping.remap(src_grd.angle, \
           'remap_weights_GLBa0.08_to_PALAU1_bilinear_t_to_rho.nc', \
                                           spval=spval)

    dst_angle = dst_grd.hgrid.angle_rho
    angle = dst_angle - src_angle
    angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))
    U = dst_u + dst_v*1j
    eitheta = np.exp(-1j*angle[:,:,:])
    U = U * eitheta
    dst_u = np.real(U)
    dst_v = np.imag(U)


    # move back to u,v points
    dst_u = 0.5 * (dst_u[:,:,:-1] + dst_u[:,:,1:])
    dst_v = 0.5 * (dst_v[:,:-1,:] + dst_v[:,1:,:])

    # spval
    idxu = np.where(dst_grd.hgrid.mask_u == 0)
    idxv = np.where(dst_grd.hgrid.mask_v == 0)
    for n in range(dst_grd.vgrid.N):
        dst_u[n,idxu[0], idxu[1]] = spval
        dst_v[n,idxv[0], idxv[1]] = spval


    # compute depth average velocity ubar and vbar
    # get z at the right position
    z_u = 0.5 * (dst_grd.vgrid.z_w[0,:,:,:-1] + dst_grd.vgrid.z_w[0,:,:,1:])
    z_v = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,:] + dst_grd.vgrid.z_w[0,:,1:,:])

    dst_ubar = np.zeros((dst_u.shape[1], dst_u.shape[2]))
    dst_vbar = np.zeros((dst_v.shape[1], dst_v.shape[2]))

    for i in range(dst_ubar.shape[1]):
        for j in range(dst_ubar.shape[0]):
            dst_ubar[j,i] = (dst_u[:,j,i] * np.diff(z_u[:,j,i])).sum() / -z_u[0,j,i]

    for i in range(dst_vbar.shape[1]):
        for j in range(dst_vbar.shape[0]):
            dst_vbar[j,i] = (dst_v[:,j,i] * np.diff(z_v[:,j,i])).sum() / -z_v[0,j,i]

    # spval
    dst_ubar[idxu[0], idxu[1]] = spval
    dst_vbar[idxv[0], idxv[1]] = spval

    # write data in destination file
    print 'write data in destination file'
    ncu.variables['ocean_time'][0] = time
    ncu.variables['u'][0] = dst_u
    ncu.variables['ubar'][0] = dst_ubar

    ncv.variables['ocean_time'][0] = time
    ncv.variables['v'][0] = dst_v
    ncv.variables['vbar'][0] = dst_vbar

    # close destination file
    ncu.close()
    ncv.close()
Ejemplo n.º 34
0
Archivo: remap.py Proyecto: ESMG/pyroms
def remap(src_varname, src_file, src_grd, dst_grd, dst_file, dmax=0, cdepth=0, kk=0, dst_dir='./'):
    
    # CCS grid sub-sample
    xrange=src_grd.xrange; yrange=src_grd.yrange

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'

    # create IC file
    print '\nCreating initial condition file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)

    # open IC file
    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT')

    #load var
    cdf = netCDF.Dataset(src_file)
    src_var = cdf.variables[src_varname]

    tmp = cdf.variables['time'][:]
    if len(tmp) > 1:
        print 'error : multiple frames in input file' ; exit()
    else:
        time = tmp[0]
    
    # we need to correct the time axis
    ref_soda = dt.datetime(1980,1,1,0,0)
    ref_roms = dt.datetime(1900,1,1,0,0)
    ndays = (ref_soda - ref_roms).days
    time = time + ndays 

    #get missing value
    spval = src_var.missing_value

    # determine variable dimension
    ndim = len(src_var.dimensions) - 1

    # CCS grid sub-sample
    if ndim == 3:
        src_var = src_var[0,:, yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]
    elif ndim == 2:
        src_var = src_var[0,yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]


    if src_varname == 'ssh':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_t_to_rho.nc'
        dst_varname = 'zeta'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'free-surface'
        units = 'meter'
        field = 'free-surface, scalar, series'
    elif src_varname == 'temp':
        src_var = src_var 
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_t_to_rho.nc'
        dst_varname = 'temp'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'potential temperature'
        units = 'Celsius'
        field = 'temperature, scalar, series'
    elif src_varname == 'salt':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_t_to_rho.nc'
        dst_varname = 'salt'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'salinity'
        units = 'PSU'
        field = 'salinity, scalar, series'
    else:
        raise ValueError, 'Undefined src_varname'


    if ndim == 3:
        # build intermediate zgrid
        zlevel = -z[::-1]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)


    # create variable in file
    print 'Creating variable', dst_varname
    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field
    #nc.variables[dst_varname_north]._FillValue = spval


    # remapping
    print 'remapping', dst_varname, 'from', src_grd.name, \
              'to', dst_grd.name

    if ndim == 3:
        # flood the grid
        print 'flood the grid'
        src_varz = pyroms_toolbox.BGrid_SODA.flood(src_var, src_grd, Bpos=Bpos, spval=spval, \
                                dmax=dmax, cdepth=cdepth, kk=kk)
    else:
        src_varz = src_var

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval)

    if ndim == 3:
        # vertical interpolation from standard z level to sigma
        print 'vertical interpolation from standard z level to sigma'
        dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \
                          dst_grd, Cpos=Cpos, spval=spval, flood=False)
    else:
        dst_var = dst_varz

    # write data in destination file
    print 'write data in destination file\n'
    nc.variables['ocean_time'][0] = time
    nc.variables[dst_varname][0] = dst_var

    # close file
    nc.close()
    cdf.close()

    if src_varname == 'ssh':
        return dst_varz
Ejemplo n.º 35
0
def remap_uv(src_fileuv, src_grd, dst_grd, dst_fileu, dst_filev, dmax=0, cdepth=0, kk=0, dst_dir='./'):

    # CCS grid sub-sample
    xrange=src_grd.xrange; yrange=src_grd.yrange

    # get time
    nctime.long_name = 'time'
    nctime.units = 'days since 1900-01-01 00:00:00'

    # get dimensions
    Mp, Lp = dst_grd.hgrid.mask_rho.shape

    # create destination file
    print '\nCreating destination file', dst_fileu
    if os.path.exists(dst_fileu) is True:
        os.remove(dst_fileu)
    pyroms_toolbox.nc_create_roms_file(dst_fileu, dst_grd, nctime)
    print 'Creating destination file', dst_filev
    if os.path.exists(dst_filev) is True:
        os.remove(dst_filev)
    pyroms_toolbox.nc_create_roms_file(dst_filev, dst_grd, nctime)

    # open destination file
    ncu = netCDF.Dataset(dst_fileu, 'a', format='NETCDF3_64BIT')
    ncv = netCDF.Dataset(dst_filev, 'a', format='NETCDF3_64BIT')

    #load var
    cdfuv = netCDF.Dataset(src_fileuv)
    src_varu = cdfuv.variables['u']
    src_varv = cdfuv.variables['v']

    tmp = cdfuv.variables['time'][:]
    if len(tmp) > 1:
        print 'error : multiple frames in input file' ; exit()
    else:
        time = tmp[0]
    
    # we need to correct the time axis
    ref_soda = dt.datetime(1980,1,1,0,0)
    ref_roms = dt.datetime(1900,1,1,0,0)
    ndays = (ref_soda - ref_roms).days
    time = time + ndays 

    #get missing value
    spval = src_varu.missing_value

    # CCS grid sub-sample
    src_varu = src_varu[0,:, yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]
    src_varv = src_varv[0,:, yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]

    # get weights file
    wts_file = 'remap_weights_' + src_grd.name + '_to_' + dst_grd.name + '_bilinear_uv_to_rho.nc'

    # build intermediate zgrid
    zlevel = -src_grd.z_t[::-1]
    nzlevel = len(zlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)

    # create variable in destination file
    print 'Creating variable u'
    ncu.createVariable('u', 'f8', ('ocean_time', 's_rho', 'eta_u', 'xi_u'), fill_value=spval)
    ncu.variables['u'].long_name = '3D u-momentum component'
    ncu.variables['u'].units = 'meter second-1'
    ncu.variables['u'].field = 'u-velocity, scalar, series'
    #ncu.variables['u_north']._FillValue = spval
    # create variable in destination file
    print 'Creating variable ubar'
    ncu.createVariable('ubar', 'f8', ('ocean_time', 'eta_u', 'xi_u'), fill_value=spval)
    ncu.variables['ubar'].long_name = '2D u-momentum component'
    ncu.variables['ubar'].units = 'meter second-1'
    ncu.variables['ubar'].field = 'ubar-velocity,, scalar, series'
    #ncu.variables['ubar_north']._FillValue = spval

    print 'Creating variable v'
    ncv.createVariable('v', 'f8', ('ocean_time', 's_rho', 'eta_v', 'xi_v'), fill_value=spval)
    ncv.variables['v'].long_name = '3D v-momentum component'
    ncv.variables['v'].units = 'meter second-1'
    ncv.variables['v'].field = 'v-velocity, scalar, series'
    #ncv.variables['v_north']._FillValue = spval
    print 'Creating variable vbar'
    ncv.createVariable('vbar', 'f8', ('ocean_time', 'eta_v', 'xi_v'), fill_value=spval)
    ncv.variables['vbar'].long_name = '2D v-momentum component'
    ncv.variables['vbar'].units = 'meter second-1'
    ncv.variables['vbar'].field = 'vbar-velocity,, scalar, series'
    #ncv.variables['vbar_north']._FillValue = spval


    # remaping
    print 'remapping and rotating u and v from', src_grd.name, \
                      'to', dst_grd.name

    # flood the grid
    print 'flood the grid'
    src_uz = pyroms_toolbox.BGrid_SODA.flood(src_varu, src_grd, Bpos='uv', \
                spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
    src_vz = pyroms_toolbox.BGrid_SODA.flood(src_varv, src_grd, Bpos='uv', \
                spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)

    # horizontal interpolation using scrip weights
    print 'horizontal interpolation using scrip weights'
    dst_uz = pyroms.remapping.remap(src_uz, wts_file, \
                                      spval=spval)
    dst_vz = pyroms.remapping.remap(src_vz, wts_file, \
                                      spval=spval)

    # vertical interpolation from standard z level to sigma
    print 'vertical interpolation from standard z level to sigma'
    dst_u = pyroms.remapping.z2roms(dst_uz[::-1,:,:], dst_grdz, \
                        dst_grd, Cpos='rho', spval=spval, flood=False)
    dst_v = pyroms.remapping.z2roms(dst_vz[::-1,:,:], dst_grdz,  \
                        dst_grd, Cpos='rho', spval=spval, flood=False)


    # rotate u,v fields
    src_angle = np.zeros(dst_grd.hgrid.angle_rho.shape)
    dst_angle = dst_grd.hgrid.angle_rho
    angle = dst_angle - src_angle
    angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))
    U = dst_u + dst_v*1j
    eitheta = np.exp(-1j*angle[:,:,:])
    U = U * eitheta
    dst_u = np.real(U)
    dst_v = np.imag(U)


    # move back to u,v points
    dst_u = 0.5 * (dst_u[:,:,:-1] + dst_u[:,:,1:])
    dst_v = 0.5 * (dst_v[:,:-1,:] + dst_v[:,1:,:])

    # spval
    idxu = np.where(dst_grd.hgrid.mask_u == 0)
    idxv = np.where(dst_grd.hgrid.mask_v == 0)
    for n in range(dst_grd.vgrid.N):
        dst_u[n,idxu[0], idxu[1]] = spval
        dst_v[n,idxv[0], idxv[1]] = spval


    # compute depth average velocity ubar and vbar
    # get z at the right position
    z_u = 0.5 * (dst_grd.vgrid.z_w[0,:,:,:-1] + dst_grd.vgrid.z_w[0,:,:,1:])
    z_v = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,:] + dst_grd.vgrid.z_w[0,:,1:,:])

    dst_ubar = np.zeros((dst_u.shape[1], dst_u.shape[2]))
    dst_vbar = np.zeros((dst_v.shape[1], dst_v.shape[2]))

    for i in range(dst_ubar.shape[1]):
        for j in range(dst_ubar.shape[0]):
            dst_ubar[j,i] = (dst_u[:,j,i] * np.diff(z_u[:,j,i])).sum() / -z_u[0,j,i]

    for i in range(dst_vbar.shape[1]):
        for j in range(dst_vbar.shape[0]):
            dst_vbar[j,i] = (dst_v[:,j,i] * np.diff(z_v[:,j,i])).sum() / -z_v[0,j,i]

    # spval
    dst_ubar[idxu[0], idxu[1]] = spval
    dst_vbar[idxv[0], idxv[1]] = spval

    # write data in destination file
    print 'write data in destination file\n'
    ncu.variables['ocean_time'][0] = time
    ncu.variables['u'][0] = dst_u
    ncu.variables['ubar'][0] = dst_ubar

    ncv.variables['ocean_time'][0] = time
    ncv.variables['v'][0] = dst_v
    ncv.variables['vbar'][0] = dst_vbar

    # close file
    ncu.close()
    ncv.close()
    cdfuv.close()
Ejemplo n.º 36
0
def remapping_bound(varname, srcfile, wts_files, srcgrd, dst_grd, \
              rotate_uv=False, trange=None, irange=None, jrange=None, \
              dstdir='./' ,zlevel=None, dmax=0, cdepth=0, kk=0, \
              uvar='u', vvar='v', rotate_part=False):
    '''
    A remapping function to extract boundary conditions from one ROMS grid
    to another. It will optionally rotating u and v variables, but needs
    to be called separately for each u/v pair (such as u/v, uice/vice).
    '''

    # get input and output grid
    if type(srcgrd).__name__ == 'ROMS_Grid':
        srcgrd = srcgrd
    else:
        srcgrd = pyroms.grid.get_ROMS_grid(srcgrd)
    if type(dst_grd).__name__ == 'ROMS_Grid':
        dst_grd = dst_grd
    else:
        dst_grd = pyroms.grid.get_ROMS_grid(dst_grd)

    # build intermediaire zgrid
    if zlevel is None:
        zlevel = np.array([-7500.,-7000.,-6500.,-6000.,-5500.,-5000.,\
                   -4500.,-4000.,-3500.,-3000.,-2500.,-2000.,-1750.,\
                   -1500.,-1250.,-1000.,-900.,-800.,-700.,-600.,-500.,\
                   -400.,-300.,-250.,-200.,-175.,-150.,-125.,-100.,-90.,\
                   -80.,-70.,-60.,-50.,-45.,-40.,-35.,-30.,-25.,-20.,-17.5,\
                   -15.,-12.5,-10.,-7.5,-5.,-2.5,0.])
    else:
        zlevel = np.sort(-abs(zlevel))
    nzlevel = len(zlevel)
    src_zcoord = pyroms.vgrid.z_coordinate(srcgrd.vgrid.h, zlevel, nzlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
    srcgrdz = pyroms.grid.ROMS_Grid(srcgrd.name + '_Z', srcgrd.hgrid,
                                    src_zcoord)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + '_Z', dst_grd.hgrid,
                                     dst_zcoord)

    # varname argument
    if type(varname).__name__ == 'list':
        nvar = len(varname)
    elif type(varname).__name__ == 'str':
        varname = [varname]
        nvar = len(varname)
    else:
        raise ValueError, 'varname must be a str or a list of str'

    # if we're working on u and v, we'll compute ubar,vbar afterwards
    compute_ubar = False
    if (varname.__contains__('u') == 1 and varname.__contains__('v') == 1) or \
       (varname.__contains__('u_eastward') == 1 and varname.__contains__('v_northward') == 1):
        compute_ubar = True
        print 'ubar/vbar to be computed from u/v'
        if varname.__contains__('ubar'):
            varname.remove('ubar')
            nvar = nvar - 1
        if varname.__contains__('vbar'):
            varname.remove('vbar')
            nvar = nvar - 1

    # if rotate_uv=True, check that u and v are in varname
    if rotate_uv is True:
        if varname.__contains__(uvar) == 0 or varname.__contains__(vvar) == 0:
            raise Warning, 'varname must include uvar and vvar in order to' \
                   + ' rotate the velocity field'
        else:
            varname.remove(uvar)
            varname.remove(vvar)
            nvar = nvar - 2

    # srcfile argument
    if type(srcfile).__name__ == 'list':
        nfile = len(srcfile)
    elif type(srcfile).__name__ == 'str':
        srcfile = sorted(glob.glob(srcfile))
        nfile = len(srcfile)
    else:
        raise ValueError, 'src_srcfile must be a str or a list of str'

    # get wts_file
    if type(wts_files).__name__ == 'str':
        wts_files = sorted(glob.glob(wts_files))

    sides = ['_west', '_east', '_north', '_south']
    long = {'_west':'Western', '_east':'Eastern', \
            '_north':'Northern', '_south':'Southern'}
    dimexcl = {'_west':'xi', '_east':'xi', \
            '_north':'eta', '_south':'eta'}

    nctidx = 0
    # loop over the srcfile
    for nf in range(nfile):
        print 'Working with file', srcfile[nf], '...'

        # get time
        ocean_time = pyroms.utility.get_nc_var('ocean_time', srcfile[nf])
        ntime = len(ocean_time[:])

        # trange argument
        if trange is None:
            trange = range(ntime)

        # create destination file
        if nctidx == 0:
            dstfile = dstdir + os.path.basename(srcfile[nf])[:-3] + '_' \
                   + dst_grd.name + '_bdry.nc'
            if os.path.exists(dstfile) is False:
                print 'Creating destination file', dstfile
                pyroms_toolbox.nc_create_roms_file(dstfile, dst_grd, \
                    ocean_time, lgrid=False)

            # open destination file
            nc = netCDF.Dataset(dstfile, 'a', format='NETCDF3_64BIT')

        # loop over time
        for nt in trange:

            nc.variables['ocean_time'][nctidx] = ocean_time[nt]

            # loop over variable
            for nv in range(nvar):
                print ' '
                print 'remapping', varname[nv], 'from', srcgrd.name, \
                      'to', dst_grd.name
                print 'time =', ocean_time[nt]
                Mp, Lp = dst_grd.hgrid.mask_rho.shape

                # get source data
                src_var = pyroms.utility.get_nc_var(varname[nv], srcfile[nf])

                # determine variable dimension
                ndim = len(src_var.dimensions) - 1

                # get spval
                try:
                    spval = src_var._FillValue
                except:
                    raise Warning, 'Did not find a _FillValue attribute.'

                # irange
                if irange is None:
                    iirange = (0, src_var.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0, src_var.shape[-2])
                else:
                    jjrange = jrange

                # determine where on the C-grid these variable lies
                if src_var.dimensions[2].find('_rho') != -1:
                    Cpos = 'rho'
                if src_var.dimensions[2].find('_u') != -1:
                    Cpos = 'u'
                    Lp = Lp - 1
                if src_var.dimensions[2].find('_v') != -1:
                    Cpos = 'v'
                    Mp = Mp - 1
                if src_var.dimensions[1].find('_w') != -1:
                    Cpos = 'w'

                print 'Arakawa C-grid position is', Cpos

                # create variable in _destination file
                if nctidx == 0:
                    for sid in sides:
                        varn = varname[nv] + str(sid)
                        dimens = [i for i in src_var.dimensions]
                        for dim in dimens:
                            if re.match(dimexcl[sid], dim):
                                dimens.remove(dim)
                        print 'Creating variable', varn, dimens
                        nc.createVariable(varn, 'f8', dimens, \
                            fill_value=spval)
                        nc.variables[varn].long_name = varname[nv] + \
                             ' ' + long[sid] + ' boundary condition'
                        try:
                            nc.variables[varn].units = src_var.units
                        except:
                            print varn + ' has no units'
                        nc.variables[varn].time = src_var.time
                        nc.variables[varn].coordinates = \
                            str(dimens.reverse())
                        nc.variables[varn].field = src_var.field

                # get the right remap weights file
                for s in range(len(wts_files)):
                    if wts_files[s].__contains__(Cpos + '_to_' + Cpos + '.nc'):
                        wts_file = wts_files[s]
                        break
                    else:
                        if s == len(wts_files) - 1:
                            raise ValueError, 'Did not find the appropriate remap weights file'

                if ndim == 3:
                    # vertical interpolation from sigma to standard z level
                    print 'vertical interpolation from sigma to standard z level'
                    src_varz = pyroms.remapping.roms2z( \
                                 src_var[nt,:,jjrange[0]:jjrange[1],iirange[0]:iirange[1]], \
                                 srcgrd, srcgrdz, Cpos=Cpos, spval=spval, \
                                 irange=iirange, jrange=jjrange)

                    # flood the grid
                    print 'flood the grid'
                    src_varz = pyroms.remapping.flood(src_varz, srcgrdz, Cpos=Cpos, \
                                      irange=iirange, jrange=jjrange, spval=spval, \
                                      dmax=dmax, cdepth=cdepth, kk=kk)

                else:
                    src_varz = src_var[nt, jjrange[0]:jjrange[1],
                                       iirange[0]:iirange[1]]

                print datetime.datetime.now()
                # horizontal interpolation using scrip weights
                print 'horizontal interpolation using scrip weights'
                dst_varz = pyroms.remapping.remap(src_varz, wts_file, \
                                                  spval=spval)

                if ndim == 3:
                    dst_var_north = pyroms.remapping.z2roms(dst_varz[:, \
                          Mp-1:Mp,0:Lp], dst_grdz, dst_grd, Cpos=Cpos, \
                          spval=spval, flood=False, irange=(0,Lp), \
                          jrange=(Mp-1,Mp))
                    dst_var_south = pyroms.remapping.z2roms(dst_varz[:, \
                          0:1, :], dst_grdz, dst_grd, Cpos=Cpos, \
                          spval=spval, flood=False, irange=(0,Lp), \
                          jrange=(0,1))
                    dst_var_east = pyroms.remapping.z2roms(dst_varz[:, \
                          :, Lp-1:Lp], dst_grdz, dst_grd, Cpos=Cpos, \
                          spval=spval, flood=False, irange=(Lp-1,Lp), \
                          jrange=(0,Mp))
                    dst_var_west = pyroms.remapping.z2roms(dst_varz[:, \
                          :, 0:1], dst_grdz, dst_grd, Cpos=Cpos, \
                          spval=spval, flood=False, irange=(0,1), \
                          jrange=(0,Mp))
                    if varname[nv] == 'u':
                        dst_u_west = dst_var_west
                        dst_u_east = dst_var_east
                        dst_u_north = dst_var_north
                        dst_u_south = dst_var_south
                    if varname[nv] == 'v':
                        dst_v_west = dst_var_west
                        dst_v_east = dst_var_east
                        dst_v_north = dst_var_north
                        dst_v_south = dst_var_south

                else:
                    dst_var_north = dst_varz[-1, :]
                    dst_var_south = dst_varz[0, :]
                    dst_var_east = dst_varz[:, -1]
                    dst_var_west = dst_varz[:, 0]

#                print datetime.datetime.now()

# write data in destination file
                print 'write data in destination file'
                sid = '_west'
                varn = varname[nv] + str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_west)

                sid = '_east'
                varn = varname[nv] + str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_east)

                sid = '_north'
                varn = varname[nv] + str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_north)

                sid = '_south'
                varn = varname[nv] + str(sid)
                nc.variables[varn][nctidx] = np.squeeze(dst_var_south)

            # rotate the velocity field if requested
            if rotate_uv is True:
                print ' '
                print 'remapping and rotating u and v from', srcgrd.name, \
                      'to', dst_grd.name

                # get source data
                src_u = pyroms.utility.get_nc_var(uvar, srcfile[nf])
                src_v = pyroms.utility.get_nc_var(vvar, srcfile[nf])

                # get spval
                try:
                    spval = src_v._FillValue
                except:
                    raise Warning, 'Did not find a _FillValue attribute.'

                if rotate_part:
                    ndim = len(src_u.dimensions) - 1
                    ind = uvar.find('_eastward')
                    uvar_out = uvar[0:ind]
                    print "Warning: renaming uvar to", uvar_out
                    ind = vvar.find('_northward')
                    vvar_out = vvar[0:ind]
                    print "Warning: renaming vvar to", vvar_out
                    if ndim == 3:
                        dimens_u = ['ocean_time', 's_rho', 'eta_u', 'xi_u']
                        dimens_v = ['ocean_time', 's_rho', 'eta_v', 'xi_v']
                    else:
                        dimens_u = ['ocean_time', 'eta_u', 'xi_u']
                        dimens_v = ['ocean_time', 'eta_v', 'xi_v']

                else:
                    dimens_u = [i for i in src_u.dimensions]
                    dimens_v = [i for i in src_v.dimensions]
                    uvar_out = uvar
                    vvar_out = vvar

                # create variable in destination file
                if nctidx == 0:
                    print 'Creating boundary variables for ' + uvar
                    for sid in sides:
                        varn = uvar_out + str(sid)
                        print 'Creating variable', varn
                        dimens = list(dimens_u)
                        for dim in dimens:
                            if re.match(dimexcl[sid], dim):
                                dimens.remove(dim)
                        nc.createVariable(varn, 'f8', dimens, \
                          fill_value=spval)
                        nc.variables[varn].long_name = uvar_out + \
                            ' ' + long[sid] + ' boundary condition'
                        try:
                            nc.variables[varn].units = src_u.units
                        except:
                            print varn + ' has no units'
                        nc.variables[varn].time = src_u.time
                        nc.variables[varn].coordinates = \
                            str(dimens.reverse())
                        nc.variables[varn].field = src_u.field
                    print 'Creating boundary variables for ' + vvar
                    for sid in sides:
                        varn = vvar_out + str(sid)
                        print 'Creating variable', varn
                        dimens = list(dimens_v)
                        for dim in dimens:
                            if re.match(dimexcl[sid], dim):
                                dimens.remove(dim)
                        nc.createVariable(varn, 'f8', dimens, \
                          fill_value=spval)
                        nc.variables[varn].long_name = vvar_out + \
                                 ' ' + long[sid] + ' boundary condition'
                        try:
                            nc.variables[varn].units = src_v.units
                        except:
                            print varn + ' has no units'
                        nc.variables[varn].time = src_v.time
                        nc.variables[varn].coordinates = \
                            str(dimens.reverse())
                        nc.variables[varn].field = src_v.field

                # get the right remap weights file
                if rotate_part:
                    for s in range(len(wts_files)):
                        if wts_files[s].__contains__('rho_to_rho.nc'):
                            wts_file_u = wts_files[s]
                            wts_file_v = wts_files[s]
                    Cpos_u = 'rho'
                    Cpos_v = 'rho'
                else:
                    for s in range(len(wts_files)):
                        if wts_files[s].__contains__('u_to_rho.nc'):
                            wts_file_u = wts_files[s]
                        if wts_files[s].__contains__('v_to_rho.nc'):
                            wts_file_v = wts_files[s]
                    Cpos_u = 'u'
                    Cpos_v = 'v'

                # vertical interpolation from sigma to standard z level
                # irange
                if irange is None:
                    iirange = (0, src_u.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0, src_u.shape[-2])
                else:
                    jjrange = jrange

                ndim = len(src_v.dimensions) - 1
                if ndim == 3:
                    print 'vertical interpolation from sigma to standard z level'
                    src_uz = pyroms.remapping.roms2z( \
                            src_u[nt,:,jjrange[0]:jjrange[1],iirange[0]:iirange[1]], \
                            srcgrd, srcgrdz, Cpos=Cpos_u, irange=iirange, jrange=jjrange)
                    # flood the grid
                    print 'flood the u grid'
                    src_uz = pyroms.remapping.flood(src_uz, srcgrdz, Cpos=Cpos_u, \
                                  irange=iirange, jrange=jjrange, \
                                  spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
                else:
                    src_uz = src_u[nt, jjrange[0]:jjrange[1],
                                   iirange[0]:iirange[1]]
                    src_uz = pyroms.remapping.flood2d(src_uz, srcgrdz, Cpos=Cpos_u, \
                                      irange=iirange, jrange=jjrange, spval=spval, \
                                      dmax=dmax)

                # irange
                if irange is None:
                    iirange = (0, src_v.shape[-1])
                else:
                    iirange = irange

                # jrange
                if jrange is None:
                    jjrange = (0, src_v.shape[-2])
                else:
                    jjrange = jrange

                if ndim == 3:
                    src_vz = pyroms.remapping.roms2z( \
                            src_v[nt,:,jjrange[0]:jjrange[1],iirange[0]:iirange[1]], \
                            srcgrd, srcgrdz, Cpos=Cpos_v, irange=iirange, jrange=jjrange)

                    # flood the grid
                    print 'flood the v grid'
                    src_vz = pyroms.remapping.flood(src_vz, srcgrdz, Cpos=Cpos_v, \
                                  irange=iirange, jrange=jjrange, \
                                  spval=spval, dmax=dmax, cdepth=cdepth, kk=kk)
                else:
                    src_vz = src_v[nt, jjrange[0]:jjrange[1],
                                   iirange[0]:iirange[1]]
                    src_vz = pyroms.remapping.flood2d(src_vz, srcgrdz, Cpos=Cpos_v, \
                                      irange=iirange, jrange=jjrange, spval=spval, \
                                      dmax=dmax)

                # horizontal interpolation using scrip weights
                print 'horizontal interpolation using scrip weights'
                dst_uz = pyroms.remapping.remap(src_uz, wts_file_u, \
                                                  spval=spval)
                dst_vz = pyroms.remapping.remap(src_vz, wts_file_v, \
                                                  spval=spval)
                Mp, Lp = dst_grd.hgrid.mask_rho.shape

                if ndim == 3:
                    # vertical interpolation from standard z level to sigma
                    print 'vertical interpolation from standard z level to sigma'
                    dst_u_north = pyroms.remapping.z2roms(dst_uz[:, Mp-2:Mp, 0:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,Lp), jrange=(Mp-2,Mp))
                    dst_u_south = pyroms.remapping.z2roms(dst_uz[:, 0:2, 0:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,Lp), jrange=(0,2))
                    dst_u_east = pyroms.remapping.z2roms(dst_uz[:, 0:Mp, Lp-2:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(Lp-2,Lp), jrange=(0,Mp))
                    dst_u_west = pyroms.remapping.z2roms(dst_uz[:, 0:Mp, 0:2], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,2), jrange=(0,Mp))

                    dst_v_north = pyroms.remapping.z2roms(dst_vz[:, Mp-2:Mp, 0:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,Lp), jrange=(Mp-2,Mp))
                    dst_v_south = pyroms.remapping.z2roms(dst_vz[:, 0:2, 0:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(0,Lp), jrange=(0,2))
                    dst_v_east = pyroms.remapping.z2roms(dst_vz[:, 0:Mp, Lp-2:Lp], \
                         dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                         flood=False, irange=(Lp-2,Lp), jrange=(0,Mp))
                    dst_v_west = pyroms.remapping.z2roms(dst_vz[:, 0:Mp, 0:2], \
                      dst_grdz, dst_grd, Cpos='rho', spval=spval, \
                      flood=False, irange=(0,2), jrange=(0,Mp))
                else:
                    dst_u_north = dst_uz[Mp - 2:Mp, 0:Lp]
                    dst_u_south = dst_uz[0:2, 0:Lp]
                    dst_u_east = dst_uz[0:Mp, Lp - 2:Lp]
                    dst_u_west = dst_uz[0:Mp, 0:2]
                    dst_v_north = dst_vz[Mp - 2:Mp, 0:Lp]
                    dst_v_south = dst_vz[0:2, 0:Lp]
                    dst_v_east = dst_vz[0:Mp, Lp - 2:Lp]
                    dst_v_west = dst_vz[0:Mp, 0:2]

                # rotate u,v fields
                if rotate_part:
                    src_angle = np.zeros(dst_grd.hgrid.angle_rho.shape)
                else:
                    for s in range(len(wts_files)):
                        if wts_files[s].__contains__('rho_to_rho.nc'):
                            wts_file = wts_files[s]
                    src_ang = srcgrd.hgrid.angle_rho[jjrange[0]:jjrange[1],
                                                     iirange[0]:iirange[1]]
                    src_angle = pyroms.remapping.remap(src_ang, wts_file)

                dst_angle = dst_grd.hgrid.angle_rho
                angle = dst_angle - src_angle
                if ndim == 3:
                    angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))
                    U_north = dst_u_north + dst_v_north * 1j
                    eitheta_north = np.exp(-1j * angle[:, Mp - 2:Mp, 0:Lp])
                    U_south = dst_u_south + dst_v_south * 1j
                    eitheta_south = np.exp(-1j * angle[:, 0:2, 0:Lp])
                    U_east = dst_u_east + dst_v_east * 1j
                    eitheta_east = np.exp(-1j * angle[:, 0:Mp, Lp - 2:Lp])
                    U_west = dst_u_west + dst_v_west * 1j
                    eitheta_west = np.exp(-1j * angle[:, 0:Mp, 0:2])
                else:
                    U_north = dst_u_north + dst_v_north * 1j
                    eitheta_north = np.exp(-1j * angle[Mp - 2:Mp, 0:Lp])
                    U_south = dst_u_south + dst_v_south * 1j
                    eitheta_south = np.exp(-1j * angle[0:2, 0:Lp])
                    U_east = dst_u_east + dst_v_east * 1j
                    eitheta_east = np.exp(-1j * angle[0:Mp, Lp - 2:Lp])
                    U_west = dst_u_west + dst_v_west * 1j
                    eitheta_west = np.exp(-1j * angle[0:Mp, 0:2])

                U_north = U_north * eitheta_north
                dst_u_north = np.real(U_north)
                dst_v_north = np.imag(U_north)

                U_south = U_south * eitheta_south
                dst_u_south = np.real(U_south)
                dst_v_south = np.imag(U_south)

                U_east = U_east * eitheta_east
                dst_u_east = np.real(U_east)
                dst_v_east = np.imag(U_east)

                U_west = U_west * eitheta_west
                dst_u_west = np.real(U_west)
                dst_v_east = np.imag(U_east)

                # move back to u,v points
                if ndim == 3:
                    dst_u_north = 0.5 * np.squeeze(dst_u_north[:,-1,:-1] + \
                            dst_u_north[:,-1,1:])
                    dst_v_north = 0.5 * np.squeeze(dst_v_north[:,:-1,:] + \
                            dst_v_north[:,1:,:])
                    dst_u_south = 0.5 * np.squeeze(dst_u_south[:,0,:-1] + \
                            dst_u_south[:,0,1:])
                    dst_v_south = 0.5 * np.squeeze(dst_v_south[:,:-1,:] + \
                            dst_v_south[:,1:,:])
                    dst_u_east = 0.5 * np.squeeze(dst_u_east[:,:,:-1] + \
                            dst_u_east[:,:,1:])
                    dst_v_east = 0.5 * np.squeeze(dst_v_east[:,:-1,-1] + \
                            dst_v_east[:,1:,-1])
                    dst_u_west = 0.5 * np.squeeze(dst_u_west[:,:,:-1] + \
                            dst_u_west[:,:,1:])
                    dst_v_west = 0.5 * np.squeeze(dst_v_west[:,:-1,0] + \
                            dst_v_west[:,1:,0])
                else:
                    dst_u_north = 0.5 * np.squeeze(dst_u_north[-1,:-1] + \
                            dst_u_north[-1,1:])
                    dst_v_north = 0.5 * np.squeeze(dst_v_north[:-1,:] + \
                            dst_v_north[1:,:])
                    dst_u_south = 0.5 * np.squeeze(dst_u_south[0,:-1] + \
                            dst_u_south[0,1:])
                    dst_v_south = 0.5 * np.squeeze(dst_v_south[:-1,:] + \
                            dst_v_south[1:,:])
                    dst_u_east = 0.5 * np.squeeze(dst_u_east[:,:-1] + \
                            dst_u_east[:,1:])
                    dst_v_east = 0.5 * np.squeeze(dst_v_east[:-1,-1] + \
                            dst_v_east[1:,-1])
                    dst_u_west = 0.5 * np.squeeze(dst_u_west[:,:-1] + \
                            dst_u_west[:,1:])
                    dst_v_west = 0.5 * np.squeeze(dst_v_west[:-1,0] + \
                            dst_v_west[1:,0])

                # spval
                idxu_north = np.where(dst_grd.hgrid.mask_u[-1, :] == 0)
                idxv_north = np.where(dst_grd.hgrid.mask_v[-1, :] == 0)
                idxu_south = np.where(dst_grd.hgrid.mask_u[0, :] == 0)
                idxv_south = np.where(dst_grd.hgrid.mask_v[0, :] == 0)
                idxu_east = np.where(dst_grd.hgrid.mask_u[:, -1] == 0)
                idxv_east = np.where(dst_grd.hgrid.mask_v[:, -1] == 0)
                idxu_west = np.where(dst_grd.hgrid.mask_u[:, 0] == 0)
                idxv_west = np.where(dst_grd.hgrid.mask_v[:, 0] == 0)
                if ndim == 3:
                    for n in range(dst_grd.vgrid.N):
                        dst_u_north[n, idxu_north[0]] = spval
                        dst_v_north[n, idxv_north[0]] = spval
                        dst_u_south[n, idxu_south[0]] = spval
                        dst_v_south[n, idxv_south[0]] = spval
                        dst_u_east[n, idxu_east[0]] = spval
                        dst_v_east[n, idxv_east[0]] = spval
                        dst_u_west[n, idxu_west[0]] = spval
                        dst_v_west[n, idxv_west[0]] = spval
                else:
                    dst_u_north[idxu_north[0]] = spval
                    dst_v_north[idxv_north[0]] = spval
                    dst_u_south[idxu_south[0]] = spval
                    dst_v_south[idxv_south[0]] = spval
                    dst_u_east[idxu_east[0]] = spval
                    dst_v_east[idxv_east[0]] = spval
                    dst_u_west[idxu_west[0]] = spval
                    dst_v_west[idxv_west[0]] = spval

                # write data in destination file
                print 'write data in destination file'
                sid = '_west'
                varn = uvar_out + str(sid)
                nc.variables[varn][nctidx] = dst_u_west
                varn = vvar_out + str(sid)
                nc.variables[varn][nctidx] = dst_v_west

                sid = '_north'
                varn = uvar_out + str(sid)
                nc.variables[varn][nctidx] = dst_u_north
                varn = vvar_out + str(sid)
                nc.variables[varn][nctidx] = dst_v_north

                sid = '_east'
                varn = uvar_out + str(sid)
                nc.variables[varn][nctidx] = dst_u_east
                varn = vvar_out + str(sid)
                nc.variables[varn][nctidx] = dst_v_east

                sid = '_south'
                varn = uvar_out + str(sid)
                nc.variables[varn][nctidx] = dst_u_south
                varn = vvar_out + str(sid)
                nc.variables[varn][nctidx] = dst_v_south

            if compute_ubar:
                if nctidx == 0:
                    print 'Creating variable ubar_north'
                    nc.createVariable('ubar_north', 'f8', \
                         ('ocean_time', 'xi_u'), fill_value=spval)
                    nc.variables['ubar_north'].long_name = \
                          '2D u-momentum north boundary condition'
                    nc.variables['ubar_north'].units = 'meter second-1'
                    nc.variables['ubar_north'].time = 'ocean_time'
                    nc.variables['ubar_north'].coordinates = 'xi_u ocean_time'
                    nc.variables[
                        'ubar_north'].field = 'ubar_north, scalar, series'
                    print 'Creating variable vbar_north'
                    nc.createVariable('vbar_north', 'f8', \
                         ('ocean_time', 'xi_v'), fill_value=spval)
                    nc.variables['vbar_north'].long_name = \
                          '2D v-momentum north boundary condition'
                    nc.variables['vbar_north'].units = 'meter second-1'
                    nc.variables['vbar_north'].time = 'ocean_time'
                    nc.variables['vbar_north'].coordinates = 'xi_v ocean_time'
                    nc.variables[
                        'vbar_north'].field = 'vbar_north,, scalar, series'

                    print 'Creating variable ubar_south'
                    nc.createVariable('ubar_south', 'f8', \
                         ('ocean_time', 'xi_u'), fill_value=spval)
                    nc.variables['ubar_south'].long_name = \
                          '2D u-momentum south boundary condition'
                    nc.variables['ubar_south'].units = 'meter second-1'
                    nc.variables['ubar_south'].time = 'ocean_time'
                    nc.variables['ubar_south'].coordinates = 'xi_u ocean_time'
                    nc.variables[
                        'ubar_south'].field = 'ubar_south, scalar, series'
                    print 'Creating variable vbar_south'
                    nc.createVariable('vbar_south', 'f8', \
                         ('ocean_time', 'xi_v'), fill_value=spval)
                    nc.variables['vbar_south'].long_name = \
                          '2D v-momentum south boundary condition'
                    nc.variables['vbar_south'].units = 'meter second-1'
                    nc.variables['vbar_south'].time = 'ocean_time'
                    nc.variables['vbar_south'].coordinates = 'xi_v ocean_time'

                    print 'Creating variable ubar_west'
                    nc.createVariable('ubar_west', 'f8', \
                         ('ocean_time', 'eta_u'), fill_value=spval)
                    nc.variables['ubar_west'].long_name = \
                          '2D u-momentum west boundary condition'
                    nc.variables['ubar_west'].units = 'meter second-1'
                    nc.variables['ubar_west'].time = 'ocean_time'
                    nc.variables['ubar_west'].coordinates = 'eta_u ocean_time'
                    nc.variables[
                        'ubar_west'].field = 'ubar_west, scalar, series'
                    print 'Creating variable vbar_west'
                    nc.createVariable('vbar_west', 'f8', \
                         ('ocean_time', 'eta_v'), fill_value=spval)
                    nc.variables['vbar_west'].long_name = \
                          '2D v-momentum west boundary condition'
                    nc.variables['vbar_west'].units = 'meter second-1'
                    nc.variables['vbar_west'].time = 'ocean_time'
                    nc.variables['vbar_west'].coordinates = 'eta_v ocean_time'

                    print 'Creating variable ubar_east'
                    nc.createVariable('ubar_east', 'f8', \
                         ('ocean_time', 'eta_u'), fill_value=spval)
                    nc.variables['ubar_east'].long_name = \
                          '2D u-momentum east boundary condition'
                    nc.variables['ubar_east'].units = 'meter second-1'
                    nc.variables['ubar_east'].time = 'ocean_time'
                    nc.variables['ubar_east'].coordinates = 'eta_u ocean_time'
                    nc.variables[
                        'ubar_east'].field = 'ubar_east, scalar, series'
                    print 'Creating variable vbar_east'
                    nc.createVariable('vbar_east', 'f8', \
                         ('ocean_time', 'eta_v'), fill_value=spval)
                    nc.variables['vbar_east'].long_name = \
                          '2D v-momentum east boundary condition'
                    nc.variables['vbar_east'].units = 'meter second-1'
                    nc.variables['vbar_east'].time = 'ocean_time'
                    nc.variables['vbar_east'].coordinates = 'eta_v ocean_time'

                # compute depth average velocity ubar and vbar
                # get z at the right position
                print 'Computing ubar/vbar from u/v'
                z_u_north = 0.5 * (dst_grd.vgrid.z_w[0, :, -1, :-1] +
                                   dst_grd.vgrid.z_w[0, :, -1, 1:])
                z_v_north = 0.5 * (dst_grd.vgrid.z_w[0, :, -1, :] +
                                   dst_grd.vgrid.z_w[0, :, -2, :])
                z_u_south = 0.5 * (dst_grd.vgrid.z_w[0, :, 0, :-1] +
                                   dst_grd.vgrid.z_w[0, :, 0, 1:])
                z_v_south = 0.5 * (dst_grd.vgrid.z_w[0, :, 0, :] +
                                   dst_grd.vgrid.z_w[0, :, 1, :])
                z_u_east = 0.5 * (dst_grd.vgrid.z_w[0, :, :, -1] +
                                  dst_grd.vgrid.z_w[0, :, :, -2])
                z_v_east = 0.5 * (dst_grd.vgrid.z_w[0, :, :-1, -1] +
                                  dst_grd.vgrid.z_w[0, :, 1:, -1])
                z_u_west = 0.5 * (dst_grd.vgrid.z_w[0, :, :, 0] +
                                  dst_grd.vgrid.z_w[0, :, :, 1])
                z_v_west = 0.5 * (dst_grd.vgrid.z_w[0, :, :-1, 0] +
                                  dst_grd.vgrid.z_w[0, :, 1:, 0])
                if not rotate_uv:
                    dst_u_north = np.squeeze(dst_u_north)
                    dst_v_north = np.squeeze(dst_v_north)
                    dst_u_south = np.squeeze(dst_u_south)
                    dst_v_south = np.squeeze(dst_v_south)
                    dst_u_east = np.squeeze(dst_u_east)
                    dst_v_east = np.squeeze(dst_v_east)
                    dst_u_west = np.squeeze(dst_u_west)
                    dst_v_west = np.squeeze(dst_v_west)

                dst_ubar_north = np.zeros(dst_u_north.shape[1])
                dst_ubar_south = np.zeros(dst_u_south.shape[1])
                dst_ubar_east = np.zeros(dst_u_east.shape[1])
                dst_ubar_west = np.zeros(dst_u_west.shape[1])
                dst_vbar_north = np.zeros(dst_v_north.shape[1])
                dst_vbar_south = np.zeros(dst_v_south.shape[1])
                dst_vbar_east = np.zeros(dst_v_east.shape[1])
                dst_vbar_west = np.zeros(dst_v_west.shape[1])

                #                print 'Shapes 3', dst_u_north.shape, dst_ubar_north.shape, z_u_north.shape, np.diff(z_u_north[:,1]).shape
                for i in range(dst_u_north.shape[1]):
                    dst_ubar_north[i] = (dst_u_north[:,i] * \
                        np.diff(z_u_north[:,i])).sum() / -z_u_north[0,i]
                    dst_ubar_south[i] = (dst_u_south[:,i] * \
                        np.diff(z_u_south[:,i])).sum() / -z_u_south[0,i]
                for i in range(dst_v_north.shape[1]):
                    dst_vbar_north[i] = (dst_v_north[:,i] * \
                        np.diff(z_v_north[:,i])).sum() / -z_v_north[0,i]
                    dst_vbar_south[i] = (dst_v_south[:,i] * \
                        np.diff(z_v_south[:,i])).sum() / -z_v_south[0,i]
                for j in range(dst_u_east.shape[1]):
                    dst_ubar_east[j] = (dst_u_east[:,j] * \
                        np.diff(z_u_east[:,j])).sum() / -z_u_east[0,j]
                    dst_ubar_west[j] = (dst_u_west[:,j] * \
                        np.diff(z_u_west[:,j])).sum() / -z_u_west[0,j]
                for j in range(dst_v_east.shape[1]):
                    dst_vbar_east[j] = (dst_v_east[:,j] * \
                        np.diff(z_v_east[:,j])).sum() / -z_v_east[0,j]
                    dst_vbar_west[j] = (dst_v_west[:,j] * \
                        np.diff(z_v_west[:,j])).sum() / -z_v_west[0,j]

                # spval
                idxu_north = np.where(dst_grd.hgrid.mask_u[-1, :] == 0)
                idxv_north = np.where(dst_grd.hgrid.mask_v[-1, :] == 0)
                idxu_south = np.where(dst_grd.hgrid.mask_u[0, :] == 0)
                idxv_south = np.where(dst_grd.hgrid.mask_v[0, :] == 0)
                idxu_east = np.where(dst_grd.hgrid.mask_u[:, -1] == 0)
                idxv_east = np.where(dst_grd.hgrid.mask_v[:, -1] == 0)
                idxu_west = np.where(dst_grd.hgrid.mask_u[:, 0] == 0)
                idxv_west = np.where(dst_grd.hgrid.mask_v[:, 0] == 0)

                dst_ubar_north[idxu_north[0]] = spval
                dst_vbar_north[idxv_north[0]] = spval
                dst_ubar_south[idxu_south[0]] = spval
                dst_vbar_south[idxv_south[0]] = spval
                dst_ubar_east[idxu_east[0]] = spval
                dst_vbar_east[idxv_east[0]] = spval
                dst_ubar_west[idxu_west[0]] = spval
                dst_vbar_west[idxv_west[0]] = spval

                nc.variables['ubar_north'][nctidx] = dst_ubar_north
                nc.variables['ubar_south'][nctidx] = dst_ubar_south
                nc.variables['ubar_east'][nctidx] = dst_ubar_east
                nc.variables['ubar_west'][nctidx] = dst_ubar_west

                nc.variables['vbar_north'][nctidx] = dst_vbar_north
                nc.variables['vbar_south'][nctidx] = dst_vbar_south
                nc.variables['vbar_east'][nctidx] = dst_vbar_east
                nc.variables['vbar_west'][nctidx] = dst_vbar_west

            nctidx = nctidx + 1
        # close files here? how?

    # close destination file
    nc.close()

    return