Changeset 409 in lmdz_wrf for trunk


Ignore:
Timestamp:
May 4, 2015, 6:58:59 PM (10 years ago)
Author:
lfita
Message:

Adding 'remapnn' Function to remap to the nearest neightbor a variable using projection from another file

Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var.py

    r408 r409  
    2929  'maskvar',                                                                         \
    3030  'ncreplace', 'ncstepdiff', 'netcdf_concatenation', 'netcdf_fold_concatenation',    \
    31   'compute_opersvarsfiles',                                                          \
     31  'remapnn',                                                                         \
    3232  'seasmean', 'sellonlatbox', 'sellonlatlevbox', 'setvar_asciivalues',               \
    3333  'sorttimesmat', 'spacemean', 'statcompare_files', 'submns', 'subyrs', 'TimeInf',   \
     
    189189elif oper == 'opersvarsfiles':
    190190    ncvar.compute_opersvarsfiles(opts.values, opts.varname)
     191elif oper == 'remapnn':
     192    ncvar.remapnn(opts.values, opts.ncfile, opts.varname)
    191193elif oper == 'seasmean':
    192194    ncvar.seasmean(timename, opts.ncfile, opts.varname)
  • trunk/tools/nc_var_tools.py

    r408 r409  
    73347334            self.quantiles = mask_quantiles(finalvalues, Nq)
    73357335
    7336 def remapnn(values, filename, varn, ddegL, ddegl):
     7336def remapnn(values, filename, varname):
     7337    """ Function to remap to the nearest neightbor a variable using projection from another file
     7338    values=[newprojectionfile]|[newlonname,newlatname]|[newlondim,newlatdim]|[oldlonname,oldlatname]|
     7339     [oldlondim,oldlatdim]
     7340      [newprojectionfile]: name of the file with the new projection
     7341      [newlonname,newlatname]: name of the longitude and the latitude variables in the new file
     7342      [newlondim,newlatdim]: name of the dimensions for the longitude and the latitude in the new file
     7343      [oldlonname,oldlatname]: name of the longitude and the latitude variables in the old file
     7344      [oldlondim,oldlatdim]: name of the dimensions for the longitude and the latitude in the old file
     7345    filename= netCDF file name
     7346    varn= variable name ('all', for all variables)
     7347    """
     7348    fname = 'remapnn'
     7349
     7350    if values == 'h':
     7351        print fname + '_____________________________________________________________'
     7352        print remapnn.__doc__
     7353        quit()
     7354
     7355    expectargs = '[newprojectionfile]|[newlonname,newlatname]|[newlondim,' +         \
     7356      'newlatdim]|[oldlonname,oldlatname]|[oldlondim,oldlatdim]'
     7357 
     7358    check_arguments(fname,len(expectargs.split('|')),values,'|',expectargs)
     7359
     7360    newprojectionfile = values.split('|')[0]
     7361    newlonlatname = values.split('|')[1]
     7362    newlonlatdim = values.split('|')[2].split(',')
     7363    oldlonlatname = values.split('|')[3]
     7364    oldlonlatdim = values.split('|')[4].split(',')
     7365
     7366    if varname != 'all':
     7367        ofile = 'remapnn_' + varname + '.nc'
     7368    else:
     7369        ofile = 'remapnn_' + filename
     7370
     7371    filexist(filename, errormsg, 'old file')
     7372    filexist(newprojectionfile, errormsg, 'new file')
     7373
     7374    oldlon=oldlonlatname.split(',')[0]
     7375    oldlat=oldlonlatname.split(',')[1]
     7376
     7377    oldncfile = NetCDFFile(filename,'r')
     7378    varinfile(oldncfile, filename, errormsg, 'old', oldlon)
     7379    varinfile(oldncfile, filename, errormsg, 'old', oldlat)
     7380
     7381    newlon=newlonlatname.split(',')[0]
     7382    newlat=newlonlatname.split(',')[1]
     7383
     7384    newncfile = NetCDFFile(newprojectionfile,'r')
     7385    varinfile(newncfile, newprojectionfile, errormsg, 'old', newlon)
     7386    varinfile(newncfile, newprojectionfile, errormsg, 'old', newlat)
     7387
     7388    oldlon2d, oldlat2d = lonlat2D(oldncfile, oldlon, oldlat)
     7389    newlon2d, newlat2d = lonlat2D(newncfile, newlon, newlat)
     7390
     7391    newdimx = newlon2d.shape[1]
     7392    newdimy = newlon2d.shape[0]
     7393
     7394    olddimx = oldlon2d.shape[1]
     7395    olddimy = oldlon2d.shape[0]
     7396
     7397# We are going to do the search in two phases
     7398#   1.- Searching on grid points every 10% of the size of the origina domain
     7399#   2.- Within the correspondant box of 20%x20% percent
     7400
     7401# 1.- first pairs old-->new
     7402##
     7403    dx10 = int(olddimx/10)
     7404    dy10 = int(olddimy/10)
     7405
     7406    oldlon2d10 = oldlon2d[slice(dy10,olddimy,dy10), slice(dx10,olddimx,dx10)]
     7407    oldlat2d10 = oldlat2d[slice(dy10,olddimy,dy10), slice(dx10,olddimx,dx10)]
     7408
     7409    firstmappairs = np.ones((2, newdimy, newdimx), dtype=int)
     7410    print '     ' + fname + ' first searching nearest neighbor by',dx10,',',dy10,'...'
     7411    for jnew in range(newdimy):
     7412        for inew in range(newdimx):
     7413            dist=np.sqrt((newlon2d[jnew, inew] - oldlon2d10)**2. +                   \
     7414              (newlat2d[jnew, inew] - oldlat2d10)**2.)
     7415            mindist = np.min(dist)
     7416            minydist10, minxdist10 = index_mat(dist,mindist)
     7417            firstmappairs[:,jnew,inew] = [int(dy10*(1+minydist10)),                  \
     7418              int(dx10*(1+minxdist10))]
     7419
     7420# 2.- Looking around the closest coarse point
     7421##
     7422    mappairs = np.ones((2, newdimy, newdimx), dtype=int)
     7423    dx2 = dx10/2
     7424    dy2 = dy10/2
     7425
     7426    print '     ' + fname + ' searching nearest neighbor...'
     7427    for jnew in range(newdimy):
     7428        for inew in range(newdimx):
     7429            i10 = firstmappairs[1,jnew,inew]
     7430            j10 = firstmappairs[0,jnew,inew]
     7431
     7432            oldlon2d2 = oldlon2d[slice(j10-dy2,j10+dy2), slice(i10-dx2,i10+dx2)]
     7433            oldlat2d2 = oldlat2d[slice(j10-dy2,j10+dy2), slice(i10-dx2,i10+dx2)]
     7434
     7435            dist=np.sqrt((newlon2d[jnew, inew] - oldlon2d2)**2. +                    \
     7436              (newlat2d[jnew, inew] - oldlat2d2)**2.)
     7437#            print 'oldlon2d2________________',i10,j10
     7438#            print oldlon2d2
     7439#            print 'oldlat2d2________________'
     7440#            print oldlat2d2
     7441#            print 'dist________________'
     7442#            print dist
     7443
     7444            mindist = np.min(dist)
     7445            minydist, minxdist = index_mat(dist,mindist)
     7446            mappairs[:,jnew,inew] = [int(j10+minydist), int(i10+minxdist)]
     7447#            print jnew,inew,'|',firstmappairs[:,jnew,inew],':',minxdist,minydist,    \
     7448#              'final:',mappairs[:,jnew,inew],'lon,lat old:',oldlon2d[minydist,minxdist],\
     7449#              oldlat2d[minydist,minxdist], 'new:', newlon2d[jnew, inew],             \
     7450#              newlat2d[jnew, inew],'mindist:',mindist
     7451
     7452
     7453#            quit()
     7454
     7455# Creation of the new file
     7456##
     7457    ncfnew = NetCDFFile(ofile,'w')
     7458   
     7459    for dn in oldncfile.dimensions:
     7460        if dn == oldlon:
     7461            ncfnew.createDimension(newlonlatdim[0], newdimx)
     7462        elif dn == oldlat:
     7463            ncfnew.createDimension(newlonlatdim[1], newdimy)
     7464        else:
     7465            if oldncfile.dimensions[dn].isunlimited():
     7466                ncfnew.createDimension(dn, None)
     7467            else:
     7468                ncfnew.createDimension(dn, len(oldncfile.dimensions[dn]))
     7469
     7470    ncfnew.sync()
     7471
     7472# looping along all the variables
     7473##
     7474    if varname == 'all':
     7475        oldvarnames = oldncfile.variables
     7476    else:
     7477        oldvarnames = [varname]
     7478
     7479    for varn in oldvarnames:
     7480        print '  adding:',varn,'...'
     7481        ovar = oldncfile.variables[varn]
     7482        vardims = ovar.dimensions
     7483        vartype = ovar.dtype
     7484        varattrs = ovar.ncattrs()
     7485
     7486#       Looking if variable has lon and/or lat:
     7487        varlonlat = False
     7488        if searchInlist(vardims, oldlonlatdim[0]): varlonlat = True
     7489        if searchInlist(vardims, oldlonlatdim[1]): varlonlat = True
     7490
     7491        if varn != oldlon and varn != oldlat and varlonlat:
     7492            newvarshape = []
     7493            newvardimn = []
     7494            newslice = []
     7495            oldslice = []
     7496            for dn in vardims:
     7497                if dn == oldlat:
     7498                    newvarshape.append(newdimy)
     7499                    newvardimn.append(newlonlatdim[1])
     7500                elif dn == oldlon:
     7501                    newvarshape.append(newdimx)
     7502                    newvardimn.append(newlonlatdim[0])
     7503                else:
     7504                    newvarshape.append(len(oldncfile.dimensions[dn]))
     7505                    newvardimn.append(dn)
     7506                    newslice.append(slice(0,len(oldncfile.dimensions[dn])))
     7507                    oldslice.append(slice(0,len(oldncfile.dimensions[dn])))
     7508
     7509            newvarval = np.zeros(tuple(newvarshape), dtype=vartype)
     7510
     7511            for jnew in range(newdimy):
     7512                for inew in range(newdimx):
     7513                    oldslice0 = oldslice[:]
     7514                    newslice0 = newslice[:]
     7515
     7516                    if searchInlist(vardims,oldlat):
     7517                        oldslice0.append(mappairs[0,jnew,inew])
     7518                        newslice0.append(jnew)
     7519
     7520                    if searchInlist(vardims,oldlon):
     7521                        oldslice0.append(mappairs[1,jnew,inew])
     7522                        newslice0.append(inew)
     7523
     7524#                    if ((jnew*newdimx + inew)%100 == 0): print '      ' + fname + ': ',  \
     7525#                      '{0:5.2f}'.format(float((jnew*newdimx + inew)*100./(newdimx*newdimy))),\
     7526#                       '% done'
     7527
     7528                    newvarval[tuple(newslice0)] = ovar[tuple(oldslice0)]
     7529
     7530        elif varn == oldlon:
     7531            ovar = newncfile.variables[newlon]
     7532            vardims = ovar.dimensions
     7533            vartype = ovar.dtype
     7534            varattrs = ovar.ncattrs()
     7535
     7536            newvardimn = (newlonlatdim[1], newlonlatdim[0])
     7537            newvarval = newlon2d
     7538
     7539        elif varn == oldlat:
     7540            ovar = newncfile.variables[newlat]
     7541            vardims = ovar.dimensions
     7542            vartype = ovar.dtype
     7543            varattrs = ovar.ncattrs()
     7544
     7545            newvardimn = (newlonlatdim[1], newlonlatdim[0])
     7546            newvarval = newlat2d
     7547
     7548        else:
     7549            newvardimn = vardims
     7550            newvarval = ovar[:]
     7551
     7552        if searchInlist(varattrs, '_FillValue'):
     7553            fvalv = ovar.getncattr('_FillValue')
     7554            newvar = ncfnew.createVariable(varn, vartype, tuple(newvardimn),         \
     7555              fill_value=fvalv)
     7556        else:
     7557            newvar = ncfnew.createVariable(varn, vartype, tuple(newvardimn))
     7558
     7559        for ncattr in varattrs:
     7560            if ncattr != '_FillValue':
     7561                attrv = ovar.getncattr(ncattr)
     7562                newattr = set_attribute(newvar,ncattr,attrv)
     7563               
     7564        attr = newvar.setncattr('mask', 'variable remapped at nearest neighbors ' +  \
     7565          'using ' + values.split(':')[0] + ' using as longitude and latitude values ')
     7566
     7567        newvar[:] = newvarval
     7568
     7569
     7570    ncfnew.sync()
     7571    ncfnew.close()
     7572
     7573    newncfile.close()
     7574    oldncfile.close()
     7575
     7576# Adding attributes
     7577    fgaddattr(filename, ofile)
     7578
     7579    print 'remapnn: new file "' + ofile + '" with remapped variable written !!'
     7580
     7581#remapnn('met_em.d01.1979-01-01_00:00:00.nc|XLONG_M,XLAT_M|east_weast,south_north|longitude,latitude|longitude,latitude', \
     7582#  'Albedo.nc', 'all')
     7583#quit()
     7584
     7585def remapnn_old(values, filename, varn, ddegL, ddegl):
    73377586    """ Function to remap to the nearest neightbor a variable using projection from another file
    73387587    values=[newprojectionfile]:[newlonname,newlatname]:[oldlonname,oldlatname]
     
    73817630# pairs old-->new
    73827631##
    7383     mappairs = np.ones((newdimy, newdimx, 2), dtype=int)
     7632    mappairs = np.ones((2, newdimy, newdimx), dtype=int)
    73847633    mappairs = mappairs*fillValue
    73857634    print '     ' + fname + ' searching nearest neighbor...'
     
    74207669                               mindist = dist
    74217670##                               print jold, iold, 'dist: ', dist, 'L', maskindlon[iold,:], 'l', maskindlat[jold,:]
    7422                                mappairs[jnew, inew, 0] = maskindlon[iold,1]
    7423                                mappairs[jnew, inew, 1] = maskindlat[jold,0]
     7671                               mappairs[0, jnew, inew] = maskindlon[iold,1]
     7672                               mappairs[1, jnew, inew] = maskindlat[jold,0]
    74247673
    74257674##                quit()
Note: See TracChangeset for help on using the changeset viewer.