Changeset 704 in lmdz_wrf for trunk


Ignore:
Timestamp:
Mar 23, 2016, 11:57:41 AM (9 years ago)
Author:
lfita
Message:

Adding `plot_basin' to plot basins (mostly from ORCDHIEE files)

Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/drawing.py

    r698 r704  
    2727## e.g. # drawing.py -f carteveg5km.nc -o draw_points_lonlat -S 'longitude:latitude:pdf:points!veget|type:green:.:0.5:None:0:legend'
    2828## e.g. # drawing.py -o draw_vectors -f wrfout_d01_2001-11-11_00:00:00 -S 'T|Time|Times|2,Y|south_north|XLAT|-1,X|west_east|XLONG|-1:3@3,wind@rainbow,9:10m wind,ms-1:cyl,l:WRF 10 m winds:pdf:winds' -v U10,V10
     29## e.g. # drawing.py -o draw_basins -f routing.py -S 'Y|y|nav_lat|-1,X|x|nav_lon|-1:1@1,rainbow,9:basins,-:cyl,l:ORCDHIEE river-basins:pdf:basins_named' -v nav_lon,nav_lat,trip,basins
    2930
    3031main = 'drawing.py'
     
    3637namegraphics = ['create_movie', 'draw_2D_shad', 'draw_2D_shad_time',                 \
    3738  'draw_2D_shad_cont', 'draw_2D_shad_cont_time', 'draw_2D_shad_line',                \
    38   'draw_2D_shad_line_time', 'draw_barbs',                                            \
     39  'draw_2D_shad_line_time', 'draw_barbs', 'draw_basins',                             \
    3940  'draw_lines', 'draw_lines_time', 'draw_Neighbourghood_evol',                       \
    4041  'draw_points', 'draw_points_lonlat',                                               \
     
    31663167            'wind'@[colorbar]: color of the vectors according to wind speed sqrt(u^2+v^2) and given [colorbar]
    31673168              all vectors the same length
    3168             '3rdvar'@[colorbar]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar]
     3169            '3rdvar'@[colorbar]@[varn]@[units]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar]
    31693170              all vectors the same length
    31703171          [length]: length of the wind vectors ('auto', for 9)
     
    33273328
    33283329    return
     3330
     3331
     3332def draw_basins(ncfile, values, varns):
     3333    """ Function to plot wind basins
     3334      values= [dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:[mapvalues]:
     3335        [gtit]:[kindfig]:[figuren]
     3336        'X/Y/Z/T'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
     3337          [dimname]: name of the dimension in the file
     3338          [vardimname]: name of the variable with the values for the dimension in the file
     3339          [value]: which value of the given dimension (-1, all; [ibeg]@[iend], i-range beginning, end)
     3340          No value takes all the range of the dimension
     3341        [vecvals]= [frequency],[color],[length]
     3342          [frequency]: [xfreq]@[yfreq] frequency of values allong each axis ('None', all grid points;
     3343            'auto', computed automatically to have 20 vectors along each axis)
     3344          [color]: [colorbar]@[varn]@[units]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar]
     3345              all vectors the same length
     3346          [length]: length of the wind vectors ('auto', for 9)
     3347        [windlabs]= [windname],[windunits]
     3348          [windname]: name of the wind variable in the graph
     3349          [windunits]: units of the wind variable in the graph ('None', for the value in the file)
     3350        [mapvalues]= map characteristics: [proj],[res]
     3351          see full documentation: http://matplotlib.org/basemap/
     3352          [proj]: projection
     3353            * 'cyl', cilindric
     3354            * 'lcc', lambert conformal
     3355          [res]: resolution:
     3356            * 'c', crude
     3357            * 'l', low
     3358            * 'i', intermediate
     3359            * 'h', high
     3360            * 'f', full
     3361        gtit= title of the graph ('|', for spaces)
     3362        kindfig= kind of figure
     3363        figuren= name of the figure
     3364      ncfile= file to use
     3365      varns= [lon],[lat],[outflow],[basinID] ',' list of the name of the variables with the lon,lat, the outflow and the basin ID
     3366    """
     3367    fname = 'draw_basins'
     3368
     3369    if values == 'h':
     3370        print fname + '_____________________________________________________________'
     3371        print draw_vectors.__doc__
     3372        quit()
     3373
     3374    expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:' +  \
     3375      '[mapvalues]:[gtit]:[kindfig]:[figuren]'
     3376 
     3377    drw.check_arguments(fname,values,expectargs,':')
     3378
     3379    dimvals = values.split(':')[0]
     3380    vecvals = values.split(':')[1]
     3381    windlabels = values.split(':')[2]
     3382    mapvalues = values.split(':')[3]
     3383    gtit = values.split(':')[4]
     3384    kindfig = values.split(':')[5]
     3385    figuren = values.split(':')[6]
     3386
     3387    of = NetCDFFile(ncfile,'r')
     3388
     3389    dims = {}
     3390    for dimv in dimvals.split(','):
     3391        dns = dimv.split('|')
     3392        dims[dns[0]] = [dns[1], dns[2], dns[3]]
     3393
     3394    varNs = []
     3395    for dn in dims.keys():
     3396        if dn == 'X':
     3397            varNs.append(dims[dn][1])
     3398            dimx = len(of.dimensions[dims[dn][0]])
     3399        elif dn == 'Y':
     3400            varNs.append(dims[dn][1])
     3401            dimy = len(of.dimensions[dims[dn][0]])
     3402
     3403    ivar = 0
     3404    for wvar in varns.split(','):
     3405        if not drw.searchInlist(of.variables.keys(), wvar):
     3406            print errormsg
     3407            print '  ' + fname + ": file does not have variable '" + wvar + "' !!"
     3408            quit(-1)
     3409        if ivar == 0:
     3410            varNs.append(wvar)
     3411        else:
     3412            varNs.append(wvar)
     3413
     3414    ivar = 0
     3415    for varN in varNs:
     3416        varslice = []
     3417
     3418        ovarN = of.variables[varN]
     3419        vard = ovarN.dimensions
     3420        for vdn in vard:
     3421            found = False
     3422            for dd in dims.keys():
     3423                if dims[dd][0] == vdn:
     3424                    if dims[dd][2].find('@') != -1:
     3425                        rvals = dims[dd][2].split('@')
     3426                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
     3427                    elif dims[dd][2] == '-1':
     3428                        varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
     3429                    else:
     3430                        varslice.append(int(dims[dd][2]))
     3431
     3432                    found = True
     3433                    break
     3434            if not found:
     3435                varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
     3436
     3437        if varN == dims['X'][1]:
     3438            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
     3439        elif varN == dims['Y'][1]:
     3440            latvals0 = np.squeeze(ovarN[tuple(varslice)])
     3441
     3442        ivar = ivar + 1
     3443
     3444    if len(lonvals0.shape) == 1:
     3445        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
     3446    else:
     3447        lonvals = lonvals0
     3448        latvals = latvals0
     3449
     3450# Vector values
     3451    if vecvals.split(',')[0] == 'None':
     3452        freqv = None
     3453    else:
     3454        freqv = vecvals.split(',')[0]
     3455
     3456    colorvals = vecvals.split(',')[1]
     3457    if len(varn.split(',')) != 3:
     3458        print errormsg
     3459            print '  ' + fname + ": color of vectors should be according to '" +     \
     3460              coln + "' but a third varibale is not provided !!"
     3461            quit(-1)
     3462
     3463    ocolvec = of.variables[varNs[3]]
     3464    colorv = ocolvec[:]
     3465    stdvn, lonvn, unitsvn = drw.var_3desc(ocolvec)
     3466    colorvals = colorvals + '@' + stdvn + '@' + unitsvn
     3467
     3468    lengthv = vecvals.split(',')[2]
     3469
     3470# Vector labels
     3471    windname = windlabels.split(',')[0]
     3472    windunits = windlabels.split(',')[1]
     3473
     3474# Vector angles
     3475    oflow = ofile.variables[varNs[2]]
     3476    angle = (oflow[:] - 1)*np.pi/4
     3477    xflow = np.where(oflow[:] < 9, np.float(lengthv)*np.sin(angle), 0.)
     3478    yflow = np.where(oflow[:] < 9, np.float(lengthv)*np.cos(angle), 0.)
     3479
     3480    drw.plot_basins(lonvals, latvals, xflow, yflow, freqv, colorvals, colorv,      \
     3481      lengthv, windname, windunits, mapvalues, gtit, kindfig, figuren)
     3482
     3483    of.close()
     3484
     3485    return
    33293486#quit()
    33303487
     
    33973554elif oper == 'draw_barbs':
    33983555    draw_barbs(opts.ncfile, opts.values, opts.varname)
     3556elif oper == 'draw_basins':
     3557    draw_basins(opts.ncfile, opts.values, opts.varname)
    33993558elif oper == 'draw_Neighbourghood_evol':
    34003559    draw_Neighbourghood_evol(opts.ncfile, opts.values, opts.varname)
  • trunk/tools/drawing_tools.py

    r698 r704  
    33# From http://stackoverflow.com/questions/13336823/matplotlib-python-error
    44import numpy as np
     5from matplotlib.pylab import *
    56import matplotlib as mpl
    67mpl.use('Agg')
     
    60796080        'singlecol'@[colorn]: all the vectors same color ('auto': for 'red')
    60806081        'wind'@[colorbar]: color of the vectors according to wind speed sqrt(u^2+v^2) and given [colorbar]
    6081         '3rdvar'@[colorbar]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar]
     6082        '3rdvar'@[colorbar]@[varn]@[units]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar]
    60826083      veccolor= color of the vectors
    60836084      veclength= length of the wind vectors:
     
    62106211    return
    62116212
     6213def plot_basins(xvals,yvals,fvals,vecfreq,vecoln,veccolor,veclength,windn,wuts,\
     6214  mapv,graphtit,kfig,figname):
     6215    """ Function to plot vectors
     6216      xvals= values for the x-axis
     6217      yvals= values for the y-axis
     6218      fvals= values for the flow (1-8: N, NE, E, ..., NW; 97: sub-basin; 98: small to sea; 99: large to sea)
     6219      vecfreq= [xfreq],[yfreq] frequency of values allong each axis (None, all grid points;
     6220        'auto', computed automatically to have 20 vectors along each axis)
     6221      veccoln= name for the color of the vectors (as '3rdvar@[basinsvar]@[varn]@[units]' from plot_vector)
     6222      veccolor= color of the vectors
     6223      veclength= length of the wind vectors:
     6224        'singlecol': 'auto', for 9
     6225        'wind' and '3rdvar': 'auto' length as wind speed, otherwise fix length
     6226      windn= name of the wind variable in the graph
     6227      wuts= units of the wind variable in the graph
     6228      mapv= map characteristics: [proj],[res]
     6229        see full documentation: http://matplotlib.org/basemap/
     6230        [proj]: projection
     6231          * 'cyl', cilindric
     6232          * 'lcc', lambert conformal
     6233        [res]: resolution:
     6234          * 'c', crude
     6235          * 'l', low
     6236          * 'i', intermediate
     6237          * 'h', high
     6238          * 'f', full
     6239      graphtit= title of the graph ('|', for spaces)
     6240      kfig= kind of figure
     6241      figname= name of the figure
     6242    """
     6243    fname = 'plot_basins'
     6244
     6245    dx=xvals.shape[1]
     6246    dy=xvals.shape[0]
     6247
     6248# Frequency of vectors
     6249    if vecfreq is None:
     6250        xfreq = 1
     6251        yfreq = 1
     6252    elif vecfreq == 'auto':
     6253        xfreq = dx/20
     6254        yfreq = dy/20
     6255    else:
     6256        xfreq=int(vecfreq.split('@')[0])
     6257        yfreq=int(vecfreq.split('@')[1])
     6258
     6259# Vector length
     6260    if veclength == 'auto':
     6261        vlength = 9
     6262    else:
     6263        vlength = veclength
     6264
     6265# flow direction
     6266    angle = (fvals[::yfreq,::xfreq] - 1)*np.pi/4
     6267    uvals = np.where(fvals[::yfreq,::xfreq] < 9, np.float(veclength)*np.sin(angle), 0.)
     6268    vvals = np.where(fvals[::yfreq,::xfreq] < 9, np.float(veclength)*np.cos(angle), 0.)
     6269
     6270# Colors
     6271    vcolor = vecoln.split('@')[0]
     6272
     6273    plt.rc('text', usetex=True)
     6274
     6275    ddx = np.abs(xvals[dy/2+1,dx/2] - xvals[dy/2,dx/2])
     6276    ddy = np.abs(yvals[dy/2,dx/2+1] - yvals[dy/2,dx/2])
     6277    fontcharac = {'family': 'serif', 'weight': 'normal', 'size': 3}
     6278
     6279# Setting up colors for each label
     6280#   From: http://stackoverflow.com/questions/15235630/matplotlib-pick-up-one-color-associated-to-one-value-in-a-colorbar
     6281    my_cmap = plt.cm.get_cmap(vcolor)
     6282    vcolmin = np.min(veccolor[::yfreq,::xfreq])
     6283    vcolmax = np.max(veccolor[::yfreq,::xfreq])
     6284    vcolmin = 0.
     6285    vcolmax = 2500.
     6286    norm = mpl.colors.Normalize(vcolmin, vcolmax)
     6287    print 'min col:',vcolmin,'max col:',vcolmax
     6288
     6289    xlabpos = []
     6290    ylabpos = []
     6291    labels = []
     6292    labcol = []
     6293    flow = []
     6294    flowvals = []
     6295   
     6296    for j in range(0,dy,yfreq):
     6297        for i in range(0,dx,xfreq):
     6298            if veccolor[j,i] != '--':
     6299                xlabpos.append(xvals[j,i])
     6300                ylabpos.append(yvals[j,i])
     6301                labels.append(int(veccolor[j,i]))
     6302                labcol.append(my_cmap(norm(veccolor[j,i])))
     6303                flowvals.append(fvals[j,i])
     6304
     6305    if not mapv is None:
     6306        lon00 = np.where(xvals[:] < 0., 360. + xvals[:], xvals[:])
     6307        lat00 = yvals[:]
     6308
     6309        map_proj=mapv.split(',')[0]
     6310        map_res=mapv.split(',')[1]
     6311
     6312        nlon = np.min(xvals[::yfreq,::xfreq])
     6313        xlon = np.max(xvals[::yfreq,::xfreq])
     6314        nlat = np.min(yvals[::yfreq,::xfreq])
     6315        xlat = np.max(yvals[::yfreq,::xfreq])
     6316
     6317        lon2 = xvals[dy/2,dx/2]
     6318        lat2 = yvals[dy/2,dx/2]
     6319
     6320        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
     6321          xlon, ',', xlat
     6322
     6323        if map_proj == 'cyl':
     6324            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
     6325              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
     6326        elif map_proj == 'lcc':
     6327            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
     6328              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
     6329        else:
     6330            print errormsg
     6331            print '  ' + fname + ": projection '" + map_proj + "' not ready!!"
     6332            print '    projections available: cyl, lcc'
     6333            quit(-1)
     6334
     6335        m.drawcoastlines()
     6336
     6337        meridians = pretty_int(nlon,xlon,5)
     6338        m.drawmeridians(meridians,labels=[True,False,False,True],color="black")
     6339
     6340        parallels = pretty_int(nlat,xlat,5)
     6341        m.drawparallels(parallels,labels=[False,True,True,False],color="black")
     6342
     6343        plt.xlabel('W-E')
     6344        plt.ylabel('S-N')
     6345
     6346    if veclength != 'auto':
     6347        wind = np.sqrt(uvals**2 + vvals**2)
     6348        uvals = np.where(wind == 0., 0., uvals)
     6349        vvals = np.where(wind == 0., 0., vvals)
     6350        uvals = np.float(veclength)*uvals/wind
     6351        vvals = np.float(veclength)*vvals/wind
     6352
     6353    plt.quiver(xvals[::yfreq,::xfreq], yvals[::yfreq,::xfreq],                       \
     6354      uvals[::yfreq,::xfreq], vvals[::yfreq,::xfreq], veccolor[::yfreq,::xfreq],     \
     6355       cmap=plt.get_cmap(vcolor), pivot='middle')
     6356    cbar = plt.colorbar()
     6357
     6358    vN = vecoln.split('@')[1]
     6359    vU = vecoln.split('@')[2]
     6360    cbar.set_label(vN + ' (' + units_lunits(vU) + ')')
     6361
     6362    for i in range(len(xlabpos)):
     6363        plt.text(xlabpos[i]+0.5*ddx, ylabpos[i]+0.95*ddy, labels[i],                  \
     6364          color=labcol[i], fontdict=fontcharac)
     6365
     6366# Sea-flow
     6367    for i in range(len(xlabpos)):
     6368        if flowvals[i] == 97:
     6369            plt.plot(xlabpos[i], ylabpos[i], 'x', color=labcol[i])
     6370        elif flowvals[i] == 98:
     6371            plt.plot(xlabpos[i], ylabpos[i], '*', color=labcol[i])
     6372        elif flowvals[i] == 99:
     6373            plt.plot(xlabpos[i], ylabpos[i], 'h', color=labcol[i])
     6374
     6375    plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')',           \
     6376      xy=(0.80,-0.15), xycoords='axes fraction', color='black')
     6377
     6378    plt.title(graphtit.replace('|',' ').replace('&','\&'))
     6379
     6380    output_kind(kfig, figname, True)
     6381
     6382    return
     6383
    62126384def var_3desc(ovar):
    62136385    """ Function to provide std_name, long_name and units from an object variable
Note: See TracChangeset for help on using the changeset viewer.