Changeset 1398 in lmdz_wrf


Ignore:
Timestamp:
Dec 20, 2016, 5:43:18 PM (8 years ago)
Author:
lfita
Message:

Adding:

`nterp_curve': Function to interpolate (as weighted mean with 4-closest ones) a variable following a curve (only working now for 'gridline')

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var_tools.py

    r1392 r1398  
    7979# increaseDimvar: Function to increase with 1 dimension an existing variable within a netcdf file. Values of the variable will be repeated along the new dimension
    8080# insert_variable: Function to insert a variable in an existing file
     81# interp_curve: Function to interpolate (as weighted mean with 4-closest ones) a variable following a curve
    8182# isgattrs: Give a single global attribute of a file and its type
    8283# isvattrs: Give a single attribute of a variable
     
    1827218273      varn= name of the variable to fill
    1827318274    """
    18274     fname = 'addVar'
     18275    fname = 'setvar_nc'
    1827518276
    1827618277    if values == 'h':
     
    1838518386    return
    1838618387
     18388def interp_curve(ov, xdn, ydn, curvpos, wgts, Nwgt, ijcurv):
     18389    """ Function to interpolate (as weighted mean with 4-closest ones) a variable following a curve
     18390      using a 3x3 matrix of weights
     18391      ov= netcdf object to interpolate
     18392      xdn= x-dimension name of the curve
     18393      ydn= y-dimension name of the curve
     18394      curvpos= position of the curve within the grid
     18395      wgts= matrix with the weights to use to interpolate
     18396      Nwgt= number of useful weights (<=4)
     18397      ijcurv= j,i indices of the distance-sorted grid points from 3x3
     18398    """
     18399    fname = 'interp_curve'
     18400    dimvar = ov.dimensions
     18401
     18402    Ncurv = curvpos.shape[0]
     18403
     18404    dictslice = {}
     18405    for dn in ov.dimensions:
     18406        if dn == xdn or dn == ydn: ds = 0
     18407        else: ds = -1
     18408        dictslice[dn] = ds
     18409
     18410    varslice, dimrefvals = SliceVarDict(ov, dictslice)
     18411    varref = ov[varslice]
     18412    dimref = list(varref.shape)
     18413    curvevar = np.zeros(tuple(dimref+[Ncurv]), dtype=np.float)
     18414
     18415    for icv in range(Ncurv):
     18416        # Getting all `useful' weights
     18417        ix = int(curvpos[icv,1])
     18418        iy = int(curvpos[icv,0])
     18419        sortedwgt = list(wgts[icv,:,:].flatten())
     18420        sortedwgt.sort(reverse=True)
     18421
     18422#        print fname + '; Lluis icv:', icv ,' _____', Nwgt[icv]
     18423        for isp in range(Nwgt[icv]):
     18424            dictslice[ydn] = iy + int(ijcurv[icv,0,isp])
     18425            dictslice[xdn] = ix + int(ijcurv[icv,1,isp])
     18426            varslice, dimvarvals = SliceVarDict(ov, dictslice)
     18427            iwgt = sortedwgt[isp]
     18428            curvevar[...,icv] = curvevar[...,icv] + ov[tuple(varslice)]*iwgt
     18429#            print '    isp:', isp, 'iwgt:', iwgt, '<>', iy + int(ijcurv[icv,0,isp]), \
     18430#              ix + int(ijcurv[icv,1,isp]), 'ival:', ov[tuple(varslice)][0,0], 'curvevar:', curvevar[0,0,icv]
     18431
     18432    return curvevar
     18433
     18434def curve_section(values,ncfile,varn):
     18435    """ Function to provide a section of a file following a given curve
     18436      values= [kindcurve]: kind of curve to follow
     18437        'gridline',[xdimn],[ydimn],[iBL],[jBL],[iUR],[jUR],[Ncurve]: line from starting `bottom-left' grid point
     18438          [iBL],[jBL] to `right-up' grid point [iUR],[jUR] and [Ncurve] number of line-points with
     18439          [xdimn],[ydimn] name of the x and y dimensions
     18440        'lonlatline',[londimn]|[lonvarname],[latdimn]|[latvarname],[iSW],[jSW],[iNE],[jNE],[Ncurve]: line from starting
     18441          `SW' lonlat point [lonSW],[latSW] to `NE' lonlat point [lonNE],[latNE] and [Ncurve] line-points
     18442          with '[lon/latdimn]|[lon/latvarn]' name of the dimension and variable-dimension of longitude
     18443          and latitude
     18444        'gridfilecurve',[xdimn],[ydimn],[curvefile]: line following grid-values in the file
     18445          [curvefile](x y; two columns space separated, '#' commment) with [xdimn],[ydimn] name of the x and y dimensions
     18446        'lonlatfilecurve',[londimn]|[lonvarname],[latdimn]|[latvarname],[curvefile]: line following
     18447          lonlat-values in the file [curvefile](lon lat; two columns space separated, '#' commment) with
     18448          '[lon/latdimn]|[lon/latvarn]' name of the dimension and variable-dimension of longitude
     18449          and latitude
     18450      ncfile= name of the file with the variable to fill
     18451      varn= name of the variable to get ('all', for all variables)
     18452    """
     18453    fname = 'curve_section'
     18454
     18455    if values == 'h':
     18456        print fname + '_____________________________________________________________'
     18457        print curve_section.__doc__
     18458        quit()
     18459
     18460    availcurves = ['gridline', 'lonlatline', 'gridfilecurve', 'lonlatfilecurve']
     18461
     18462    if values.split(',')[0] == 'gridline':
     18463        expectargs = 'gridline,[xdimn],[ydimn],[iBL],[jBL],[iUR],[jUR],[Ncurve]'
     18464    elif values.split(',')[0] == 'lonlatline':
     18465        expectargs = 'lonlatline,[londimn]|[lonvarname],[latdimn]|[latvarname],' +   \
     18466          '[iSW],[jSW],[iNE],[jNE],[Ncurve]'
     18467    elif values.split(',')[0] == 'gridfilecurve':
     18468        expectargs = 'gridfilecurve,[xdimn],[ydimn],[curvefile]'
     18469    elif values.split(',')[0] == 'lonlatfilecurve':
     18470        expectargs = 'lonlatfilecurve,[londimn]|[lonvarname],[latdimn]|' +           \
     18471          '[latvarname],[curvefile]'
     18472    else:
     18473        print errormsg
     18474        print '  ' + fname + ": kind of curve: '" + values.split(',')[0] +           \
     18475          "' not ready !!"
     18476        print '    available ones:', availcurves
     18477        quit(-1)
     18478
     18479    gen.check_arguments(fname,values,expectargs,',')
     18480
     18481    ofile = 'curve_section.nc'
     18482
     18483    onc = NetCDFFile(ncfile, 'r')
     18484
     18485    if varn == 'all':
     18486        varns = onc.variables.keys()
     18487    else:
     18488        varns = [varn]
     18489
     18490    # Getting curve
     18491    if values.split(',')[0] == 'gridline':
     18492        # 'gridline,[xdimn],[ydimn],[iBL],[jBL],[iUR],[jUR],[Ncurve]'
     18493        xdimn = values.split(',')[1]
     18494        ydimn = values.split(',')[2]
     18495        iBL = np.float(values.split(',')[3])
     18496        jBL = np.float(values.split(',')[4])
     18497        iUR = np.float(values.split(',')[5])
     18498        jUR = np.float(values.split(',')[6])
     18499        Ncurve = int(values.split(',')[7])
     18500        Dxcurve = (iUR-iBL)/(Ncurve-1.)
     18501        Dycurve = (jUR-jBL)/(Ncurve-1.)
     18502
     18503        curve = np.zeros((Ncurve,2), dtype=np.float)
     18504        for icv in range(Ncurve):
     18505            curve[icv,0] = jBL + Dycurve*icv
     18506            curve[icv,1] = iBL + Dxcurve*icv
     18507
     18508    elif values.split(',')[0] == 'lonlatline':
     18509        # 'lonlatline,[londimn]|[lonvarname],[latdimn]|[latvarname],[iSW],[jSW],[iNE],[jNE],[Ncurve]'
     18510        Lcurve = 'lon/lat'
     18511
     18512        xdimn = values.split(',')[1].split('|')[0]
     18513        xvardimn = values.split(',')[1].split('|')[1]
     18514        ydimn = values.split(',')[2].split('|')[0]
     18515        yvardimn = values.split(',')[2].split('|')[1]
     18516        lonSW = np.float(values.split(',')[3])
     18517        latSW = np.float(values.split(',')[4])
     18518        lonNE = np.float(values.split(',')[5])
     18519        latNE = np.float(values.split(',')[6])
     18520        Ncurve = int(values.split(',')[7])
     18521        Dxcurve = (lonNE-lonSW)/(Ncurve-1.)
     18522        Dycurve = (latNE-latSW)/(Ncurve-1.)
     18523
     18524        curve = np.zeros((Ncurve,2), dtype=np.float)
     18525        for icv in range(Ncurve):
     18526            curve[icv,0] = lonSW + Dycurve*icv
     18527            curve[icv,1] = latSW + Dxcurve*icv
     18528
     18529    elif values.split(',')[0] == 'gridfilecurve':
     18530        # 'gridfilecurve,[xdimn],[ydimn],[curvefile]'
     18531        xdimn = values.split(',')[1]
     18532        ydimn = values.split(',')[2]
     18533        curvefile = values.split(',')[3]
     18534
     18535        Scurve = []
     18536        Ncurve = 0
     18537        ocurve = open(curvefile, 'r')
     18538        for line in ocurve:
     18539            if line[0:1] != '#':
     18540                Scurve.append(line.split(' '))
     18541                Ncurve = Ncurve + 1
     18542        ocurve.close()
     18543
     18544        curve = np.zeros((Ncurve,2), dtype=np.float)
     18545        for icv in range(Ncurve):
     18546            curv = Scurve[icv]
     18547            curve[icv,0] = np.float(curv[1])
     18548            curve[icv,1] = np.float(curv[0])
     18549
     18550    elif values.split(',')[0] == 'lonlatfilecurve':
     18551        # 'lonlatfilecurve,[londimn]|[lonvarname],[latdimn]|[latvarname],[curvefile]'
     18552        xdimn = values.split(',')[1].split('|')[0]
     18553        xvardimn = values.split(',')[1].split('|')[1]
     18554        ydimn = values.split(',')[2].split('|')[0]
     18555        yvardimn = values.split(',')[2].split('|')[1]
     18556        curvefile = values.split(',')[3]
     18557
     18558        Scurve = []
     18559        Ncurve = 0
     18560        ocurve = open(curvefile, 'r')
     18561        for line in ocurve:
     18562            if line[0:1] != '#':
     18563                Scurve.append(line.split(' '))
     18564                Ncurve = Ncurve + 1
     18565        ocurve.close()
     18566
     18567        curve = np.zeros((Ncurve,2), dtype=np.float)
     18568        for icv in range(Ncurve):
     18569            curv = Scurve[icv]
     18570            curve[icv,0] = np.float(curv[1])
     18571            curve[icv,1] = np.float(curv[0])
     18572
     18573    # Getting dimension-variables
     18574    onc = NetCDFFile(ncfile, 'r')
     18575    if not gen.searchInlist(onc.dimensions, xdimn):
     18576        print errormsg
     18577        print '  ' + fname + ": file '" + ncfile + "' does not have dimension '" +   \
     18578          xdimn + "' !!"
     18579        print '    available dimensions:', onc.dimensions
     18580        onc.close()
     18581        quit(-1)
     18582
     18583    if not gen.searchInlist(onc.dimensions, ydimn):
     18584        print errormsg
     18585        print '  ' + fname + ": file '" + ncfile + "' does not have dimension '" +   \
     18586          ydimn + "' !!"
     18587        print '    available dimensions:', onc.dimensions
     18588        onc.close()
     18589        quit(-1)
     18590    dimx = len(onc.dimensions[xdimn])
     18591    dimy = len(onc.dimensions[ydimn])
     18592
     18593    if values.split(',')[0]== 'lonlatline' or values.split(',')[0]=='lonlatfilecurve':
     18594        if not onc.variables.has_key(xvardimn):
     18595            print errormsg
     18596            print '  ' + fname + ": file '" + ncfile + "' does not have variable-" + \
     18597              "dimension '" + xvardimn + "' !!"
     18598            print '    available variables:', onc.variables.keys()
     18599            onc.close()
     18600            quit(-1)
     18601        if not onc.variables.has_key(yvardimn):
     18602            print errormsg
     18603            print '  ' + fname + ": file '" + ncfile + "' does not have variable-" + \
     18604              "dimension '" + yvardimn + "' !!"
     18605            print '    available variables:', onc.variables.keys()
     18606            onc.close()
     18607            quit(-1)
     18608        ovar = onc.variables[xvardimn]
     18609        xvals0 = ovar[:]
     18610        Lcurvex = xvardimn
     18611        cxunit = ovar.units
     18612
     18613        ovar = onc.variables[yvardimn]
     18614        yvals0 = ovar[:]
     18615        Lcurvey = yvardimn
     18616        cyunit = ovar.units
     18617
     18618        xvals, yvals = gen.lonlat2D(xvals0, yvals0)
     18619    else:
     18620        x1vals = np.arange((dimx), dtype=np.float)
     18621        y1vals = np.arange((dimy), dtype=np.float)
     18622        xvals, yvals = gen.lonlat2D(x1vals, y1vals)
     18623        Lcurvex = 'grid'
     18624        Lcurvey = 'grid'
     18625        cxunit = '1'
     18626        cyunit = '1'
     18627
     18628    # Getting curve-values
     18629    loccurve, curvewgts, Nwgts, curveloc3x3 = gen.curvelocalize_2D(curve,xvals,yvals)
     18630
     18631    # Creation of file
     18632    newnc = NetCDFFile(ofile, 'w')
     18633
     18634    # Dimensions
     18635    newdim = newnc.createDimension('curve', Ncurve)
     18636    newdim = newnc.createDimension('box', 3)
     18637    newdim = newnc.createDimension('pt', 2)
     18638    newdim = newnc.createDimension('boxbox', 9)
     18639
     18640    # Var-dimensions
     18641    newvar = newnc.createVariable('xcurve', 'f8', ('curve'))
     18642    newvar[:] = curve[:,1]
     18643    basicvardef(newvar,'xcurve', 'x-' +Lcurvex+ ' localization of the curve', cxunit)
     18644
     18645    newvar = newnc.createVariable('ycurve', 'f8', ('curve'))
     18646    newvar[:] = curve[:,0]
     18647    basicvardef(newvar,'ycurve', 'y-' +Lcurvey+ ' localization of the curve', cyunit)
     18648
     18649    # variables
     18650    newvar = newnc.createVariable('weights', 'f', ('box','box','curve'))
     18651    for icv in range(Ncurve):
     18652        newvar[:,:,icv] = curvewgts[icv,:,:]
     18653    basicvardef(newvar,'weights', 'weights on the 3x3 around box following curve','1')
     18654
     18655    # variables
     18656    newvar = newnc.createVariable('Nweights', 'f', ('curve'))
     18657    newvar[:] = Nwgts[:]
     18658    basicvardef(newvar,'Nweights', 'number of usable weights of the 3x3 around box '+\
     18659      'following curve', '-')
     18660
     18661    # variables
     18662    newvar = newnc.createVariable('coordweights', 'f', ('pt','boxbox','curve'))
     18663    for icv in range(Ncurve):
     18664        newvar[:,:,icv] = curveloc3x3[icv,:,:]
     18665    basicvardef(newvar,'coordweights', 'coordinates of the usable weights of the ' + \
     18666      '3x3 around box following curve', '-')
     18667
     18668    for vn in varns:
     18669        if not onc.variables.has_key(vn):
     18670            print errormsg
     18671            print '  ' + fname + ": file '" + ncfile + "' does not have variable '" +\
     18672              vn + "' !!"
     18673            print '    available ones:', onc.variables.keys()
     18674            onc.close()
     18675            quit(-1)
     18676
     18677        ovar = onc.variables[vn]
     18678        dimvar = list(ovar.dimensions)
     18679        if gen.searchInlist(dimvar, xdimn): dimvar.remove(xdimn)
     18680        if gen.searchInlist(dimvar, ydimn): dimvar.remove(ydimn)
     18681
     18682        varcurve = interp_curve(ovar, xdimn, ydimn, loccurve, curvewgts, Nwgts,      \
     18683          curveloc3x3)
     18684
     18685        # Writing values of variable along the curve
     18686        add_dims(onc,newnc,dimvar)
     18687
     18688        newvar = newnc.createVariable(vn+'curve', 'f4', tuple(dimvar+['curve']))
     18689        newvar[:] = varcurve[:]
     18690        add_varattrs(onc,newnc,[vn],[vn+'curve'])
     18691        set_attribute(newvar,'along','xcurve,ycurve')
     18692 
     18693    # Global attributes
     18694    add_globattrs(onc,newnc,'all')
     18695    newnc.setncattr('author', 'L. Fita')
     18696    newattr = set_attributek(newnc, 'institution', unicode('Laboratoire de M' +      \
     18697      unichr(233) + 't' + unichr(233) + 'orologie Dynamique'), 'U')
     18698    newnc.setncattr('university', 'Pierre Marie Curie - Jussieu')
     18699    newnc.setncattr('center', 'Centre National de Recherches Scientifiques')
     18700    newnc.setncattr('city', 'Paris')
     18701    newnc.setncattr('country', 'France')
     18702    newnc.setncattr('source', 'http://www.xn--llusfb-5va.cat/python/PyNCplot/')
     18703    newnc.setncattr('script', 'nc_var_tools.py')
     18704    newnc.setncattr('function', fname)
     18705
     18706    print fname + ": successfull writing of '" + ofile + "' !!"
     18707
     18708    return
     18709
     18710values = 'gridline,x,y,8.,8.,16.,16.,32'
     18711curve_section(values,'/home/lluis/PY/test.nc','var')
     18712
    1838718713#quit()
Note: See TracChangeset for help on using the changeset viewer.