Changeset 1484 in lmdz_wrf for trunk


Ignore:
Timestamp:
Apr 1, 2017, 10:31:26 PM (8 years ago)
Author:
lfita
Message:

Adding:

`lonlat_polygon': Function to define a lon/lat region giving the coordinates of the vertexs of a given polygon

Location:
trunk/tools
Files:
1 added
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/documentation/ncmanage/ncmanage.html

    r1403 r1484  
    1010      <A CLASS="lc" HREF="curve_section.html" TARGET="value">curve_section</A><BR>
    1111      <A CLASS="lc" HREF="field_stats.html" TARGET="value">field_stats</A><BR>
     12      <A CLASS="lc" HREF="lonlat_polygon.html" TARGET="value">lonlat_polygon</A><BR>
    1213    </DIV>
    1314    <DIV CLASS="valmenu">
  • trunk/tools/nc_var.py

    r1428 r1484  
    88#   Attribution-ShareAlike 4.0 International License (http://creativecommons.org/licenses/by-sa/4.0)
    99#
     10
     11## e.g. # nc_var.py -o lonlat_polygon -f wrfout_d01_1995-01-01_00:00:00 -S star.dat -v XLONG,XLAT
    1012
    1113## e.g. ccrc468-17 # ./nc_var.py -v time -f 123/CCRC_NARCliM_Sydney_All_1990-1999_pr10max.nc -o out -S 1:-1
     
    102104# ivattrs: Give all the attributes of a variable and its type
    103105# LMDZ_toCF: Function to pass a LMDZ original file to CF-conventions
     106# lonlat_polygon: Function to define a lon/lat region giving the coordinates of the vertexs of a given polygon
    104107# maskvar: Function to mask a variable using a mask. It is assumed that mask[...,dimM,dimJ,dimK] and
    105108# model_characteristics: Function to provide major characterisitcs of a given model output
     
    171174  'getvalues_lonlat', 'getvars_tofile', 'grattr',                                    \
    172175  'grmattr', 'idims', 'igattrs', 'increaseDimvar', 'isgattrs',                       \
    173   'isvattrs', 'ivars', 'ivattrs', 'LMDZ_toCF', 'maskvar', 'model_characteristics',   \
     176  'isvattrs', 'ivars', 'ivattrs', 'LMDZ_toCF', 'lonlat_polygon', 'maskvar',          \
     177  'model_characteristics',                                                           \
    174178  'mthDYNAMICO_toCF', 'ncreplace', 'ncstepdiff', 'netcdf_concatenation',             \
    175179  'netcdf_fold_concatenation',                                                       \
     
    372376elif oper == 'LMDZ_toCF':
    373377    ncvar.LMDZ_toCF(opts.values, opts.ncfile)
     378elif oper == 'lonlat_polygon':
     379    ncvar.lonlat_polygon(opts.values, opts.ncfile, opts.varname)
    374380elif oper == 'maskvar':
    375381    ncvar.maskvar(opts.values, opts.ncfile, opts.varname)
  • trunk/tools/nc_var_tools.py

    r1481 r1484  
    8989# load_ncvariable_lastdims: Function to load the last [Nlastdims] dimensions of a variable [varn] from a netCDF object at the other dimensions at [prevdims]
    9090# lonlatProj: Function to compute longitudes and latitudes for a given projection following subroutine calc_resolution_in from ORCHIDEE/src_global/module_InterpWeight
     91# lonlat_polygon: Function to define a lon/lat region giving the coordinates of the vertexs of a given polygon
    9192# maskvar: Function to mask a variable using a mask. It is assumed that mask[...,dimM,dimJ,dimK] and var[...,dimM,dimJ,dimK] share the last dimensions
    9293# ModelChar: Class object to determine major characterisitcs of a given model output
     
    1913519136    return varunits
    1913619137
     19138def lonlat_polygon(values,ncfile,varn):
     19139    """ Function to define a lon/lat region giving the coordinates of the vertexs of a given polygon
     19140      lonlat_polygon(values,ncfile,varn)
     19141      values= [asciipolygfile]
     19142        [asciipoligfile]: ASCII file with the clocwise consecutive poligon vertexs as: ('#' for coments)
     19143          [lon1] [lat1]
     19144          (...)
     19145          [lonN] [latN]
     19146      ncfile= name of the file with the variable to fill
     19147      varn= [lonvname],[latvname] name of the longitude and latitude variable in the file
     19148    """
     19149    import matplotlib.path as mpltPath
     19150    fname = 'lonlat_polygon'
     19151
     19152    ofile = fname + '.nc'
     19153
     19154    if values == 'h':
     19155        print fname + '_____________________________________________________________'
     19156        print lonlat_polygon.__doc__
     19157        quit()
     19158
     19159    asciipolygfile = values
     19160
     19161    lonvname = varn.split(',')[0]
     19162    latvname = varn.split(',')[1]
     19163
     19164    if not os.path.isfile(asciipolygfile):
     19165        print errormsg
     19166        print '  ' + fname + ": ASCII vertex polygon file '" + asciipolygfile +      \
     19167          "' does not exist !!"
     19168        quit(-1)
     19169
     19170    # getting lon,lat
     19171    onc = NetCDFFile(ncfile, 'r')
     19172    if not onc.variables.has_key(lonvname):
     19173        print errormsg
     19174        print '  ' + fname + ": netCDF file '" + ncfile + "' does not have variable"+\
     19175          " longitude '" + lonvname + "' !!"
     19176        quit(-1)
     19177    if not onc.variables.has_key(latvname):
     19178        print errormsg
     19179        print '  ' + fname + ": netCDF file '" + ncfile + "' does not have variable"+\
     19180          " latitude '" + latvname + "' !!"
     19181        quit(-1)
     19182
     19183    lon, lat = gen.lonlat2D(onc.variables[lonvname], onc.variables[latvname])
     19184
     19185    onc.close()
     19186
     19187    # getting vertices
     19188    overtf = open(asciipolygfile, 'r')
     19189    lLvertices = []
     19190    for line in overtf:
     19191        if line[0:1] != '#' and len(line) > 3:
     19192            linevals = line.replace('\n','').split(' ')
     19193            lLvertices.append([np.float(linevals[0]), np.float(linevals[1])])
     19194    overtf.close()
     19195
     19196    # Getting ij in lon,lat space of the vertices
     19197    Nvertices = len(lLvertices)
     19198    ijvertices = []
     19199    for iv in range(Nvertices):
     19200        vertex = lLvertices[iv]
     19201        ijvertices.append(gen.lonlatFind(lon,lat,vertex[0],vertex[1])[0])
     19202        print iv, vertex, ijvertices[iv]
     19203
     19204    plane = np.zeros((lon.shape), dtype=int)
     19205    # Getting the points which are corssed by the faces of the polygon
     19206    for iiv in range(Nvertices):
     19207        lL = lLvertices[iiv]
     19208        l = lL[0]
     19209        L = lL[1]
     19210        ij = ijvertices[iiv]
     19211        iv = ij[1]
     19212        jv = ij[0]
     19213
     19214        # Next point
     19215        if iiv == Nvertices - 1:
     19216            nextiiv = 0
     19217        else:
     19218            nextiiv = iiv+1
     19219       
     19220        lLdest = lLvertices[nextiiv]
     19221        ldest = lLdest[0]
     19222        Ldest = lLdest[1]
     19223        ijdest = ijvertices[nextiiv]
     19224        ivdest = ijdest[1]
     19225        jvdest = ijdest[0]
     19226
     19227        # connecting line y = a + by
     19228        dlon = ldest - l
     19229        dlat = Ldest - L
     19230        if dlon != 0.:
     19231            b = 1.*dlat/dlon
     19232            sdx = dlon/np.abs(dlon)
     19233        else:
     19234            b = 0.
     19235            sdx = 1
     19236        if dlat != 0.:
     19237            sdy = dlat/np.abs(dlat)
     19238        else:
     19239            sdy = 1
     19240
     19241        # Get more grid points (just in case)
     19242        Nlon = np.abs(int((ivdest - iv)*1.5))
     19243        Nlat = np.abs(int((jvdest - jv)*1.5))
     19244
     19245        if dlon != 0. and Nlon == 0: Nlon = Nlat
     19246        if Nlat > Nlon: Nlon = Nlat
     19247       
     19248        #print iiv, ',', lL, lLdest, ':', dlon, dlat, b, 'Npts:', Nlon, Nlat
     19249        # Moving across the line folloing lon,lat
     19250        if dlon != 0.:
     19251            for iil in range(Nlon + 1):
     19252                ilon = dlon*iil/Nlon
     19253                ilat = L + ilon*b
     19254                [iy,ix], dist = gen.lonlatFind(lon,lat,l+ilon,ilat)
     19255                #print '  ',iil,l+ilon,ilat,ix,iy,dist
     19256                plane[iy,ix] = 1
     19257        else:
     19258            ilon = l
     19259            for iiL in range(Nlat + 1):
     19260                ilat = L + dlat*iiL/Nlat
     19261                [iy,ix], dist = gen.lonlatFind(lon,lat,ilon,ilat)
     19262                #print '  ',iiL,ilon,ilat,ix,iy,dist
     19263                plane[iy,ix] = 1
     19264
     19265        #print '    last point of the face:', l+ilon, ilat, 'destiny:', ldest, Ldest
     19266
     19267    # Filling the polygon
     19268    # FROM: http://stackoverflow.com/questions/36399381/whats-the-fastest-way-of-checking-if-a-point-is-inside-a-polygon-in-python
     19269    lonvals = lon.flatten()
     19270    latvals = lat.flatten()
     19271    lonlatvals = zip(lonvals, latvals)
     19272   
     19273    path = mpltPath.Path(lLvertices)
     19274    inside = path.contains_points(lonlatvals)
     19275    insidemat = inside.reshape(lon.shape)
     19276
     19277    insideones = np.where(insidemat, 1, 0)
     19278
     19279    # output file
     19280    newnc = NetCDFFile(ofile, 'w')
     19281
     19282    # dimensions
     19283    newdim = newnc.createDimension('lon',lon.shape[1])
     19284    newdim = newnc.createDimension('lat',lon.shape[0])
     19285    newdim = newnc.createDimension('vertex',Nvertices)
     19286   
     19287    # variable-dimensions
     19288    newvar = newnc.createVariable('lon', 'f8', ('lat', 'lon'))
     19289    newvar[:] = lon
     19290    basicvardef(newvar,'longitude','Longitude','degrees_East')
     19291    newvar.setncattr('axis', 'X')
     19292    newvar.setncattr('_CoordinateAxisType', 'Lon')
     19293    newvar = newnc.createVariable('lat', 'f8', ('lat', 'lon'))
     19294    newvar[:] = lat
     19295    basicvardef(newvar,'latitude','Latitude','degrees_North')
     19296    newvar.setncattr('axis', 'Y')
     19297    newvar.setncattr('_CoordinateAxisType', 'Lat')
     19298    lnewvar = newnc.createVariable('vertexlon', 'f8', ('vertex'))
     19299    basicvardef(lnewvar,'vertexlon','longitude coordinate of the vertex of polygon','degrees_East')
     19300    Lnewvar = newnc.createVariable('vertexlat', 'f8', ('vertex'))
     19301    basicvardef(Lnewvar,'vertexlat','latitude coordinate of the vertex of polygon','degrees_North')
     19302    inewvar = newnc.createVariable('ivertex', 'i', ('vertex'))
     19303    basicvardef(inewvar,'ivertex','coordinate on axis-x of the vertex of polygon','1')
     19304    jnewvar = newnc.createVariable('jvertex', 'i', ('vertex'))
     19305    basicvardef(jnewvar,'jvertex','coordinate on axis-y of the vertex of polygon','1')
     19306    for i in range(Nvertices):
     19307        lL = lLvertices[i]
     19308        ij = ijvertices[i]
     19309        lnewvar[i] = lL[0]
     19310        Lnewvar[i] = lL[1]
     19311        inewvar[i] = ij[0]
     19312        jnewvar[i] = ij[1]
     19313    newattr = set_attribute(lnewvar, 'src_polygon_file', asciipolygfile)
     19314    newattr = set_attribute(Lnewvar, 'src_polygon_file', asciipolygfile)
     19315    newattr = set_attribute(inewvar, 'src_projection_file', ncfile)
     19316    newattr = set_attribute(jnewvar, 'src_projection_file', ncfile)
     19317
     19318    # variable
     19319    newvar = newnc.createVariable('polygon_countour', 'i', ('lat', 'lon'))
     19320    newvar[:] = plane
     19321    basicvardef(newvar,'polygon_countour','countour of the Polygon','1')
     19322    newvar.setncattr('coordinates', 'lon lat')
     19323    newvar = newnc.createVariable('polygon_sfc', 'i', ('lat', 'lon'))
     19324    newvar[:] = insideones
     19325    basicvardef(newvar,'polygon_surface','surface of the Polygon','1')
     19326    newvar.setncattr('coordinates', 'lon lat')
     19327
     19328    newnc.sync()
     19329
     19330    # Global attributes
     19331    add_global_PyNCplot(newnc, main, fname, '1.0')
     19332
     19333    newnc.close()
     19334
     19335    print fname + ": succesfull written of file with polygon surface '" + ofile + "' !!"
     19336
     19337    return
     19338
     19339#lonlat_polygon('/home/lluis/PY/square.dat','/home/lluis/PY/wrfout_d01_1995-01-01_00:00:00', 'XLONG,XLAT')
     19340#lonlat_polygon('/home/lluis/PY/star.dat','/home/lluis/PY/wrfout_d01_1995-01-01_00:00:00', 'XLONG,XLAT')
     19341
     19342
    1913719343#quit()
Note: See TracChangeset for help on using the changeset viewer.