Changeset 1283 in lmdz_wrf


Ignore:
Timestamp:
Nov 8, 2016, 4:54:42 PM (8 years ago)
Author:
lfita
Message:

Improving `draw_points' with dimxyfmt, slice capabilities and colobarvalues

Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/drawing.py

    r1279 r1283  
    3030## e.g. # drawing.py -o draw_lines_time -f wrfout_d01_2001-11-11_00:00:00_west_east_B20-E20-I1_south_north_B20-E20-I1.nc,wrfout_d01_2001-11-11_00:00:00_west_east_B25-E25-I1_south_north_B25-E25-I1.nc,wrfout_d01_2001-11-11_00:00:00_west_east_B35-E35-I1_south_north_B35-E35-I1.nc -S 'WRFtime;y;time ([DD]${[HH]}$);auto;we=20$\times$sn=20,we=25$\times$sn=25,we=35$\times$sn=35;tas;tas|evolution|at|3|different|grid|points;None;time|hours!since!1949-12-01_00:00:00|exct,3,h|%d$^{%H}$;0|12;pdf;-;r,g,b;.;2.;2.;all;-1;True' -v T2
    3131## e.g. # drawing.py -o draw_Neighbourghood_evol -S 'vas:Time|-1|WRFtime,south_north|44|XLAT,west_east|88|XLONG:south_north,west_east:5:auto:time|($[DD]^{[HH]}$),time|($[DD]^{[HH]}$):exct,1,h|exct,3,h:$%d^{%H}$,$%d^{%H}$:5|pts|neighbourghood|temporal|evolution|on|2001|Nov.|at|x=88,|y=44:0.0,20.:rainbow,auto,auto:auto:png:vas_Neigh_evol:True' -f ~/PY/wrfout_d01_2001-11-11_00:00:00 -v V10
    32 
     32## e.g. # drawing.py -o draw_points -S 'SuperStorm/tslist.dat,#,3,2,1:SuperStorm|sfc|stations:auto:cyl,i:labelled,10,r:auto:None:0:png:stations_loc:True' -f 'geo_em.d02.nc,XLONG_M,XLAT_M,HGT_M,Time|0@west_east|30;180;1@south_north|175;255;1,height,0.,1500.,terrain,auto,auto,m'
    3333
    3434## e.g. # drawing.py -o draw_trajectories -f 'WRF/control/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_HighRes_C/geo_em.d03.nc#XLONG_M#XLAT_M,WRF_LMDZ/wlmdza/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M,WRF_LMDZ/wlmdzb/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M,WRF_LMDZ/wlmdzb_ii/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M' -S '$WRF_{CRM}$,$LMDZ_{AR4.0}$,$LMDZ_{NPv3.1}$,$LMDZ_{NPv3.1b}$|None|medicane trajectories|pdf|cyl,i' -v obs/trajectory.dat,satellite,-1
     
    26992699       [timefmts]:[gtitle]:[shadxtrms]:[colobarvals]:[neighlinevals]:[gkind]:[ofile]:[close]
    27002700        [gvarname]: ':' list of names of the variables in the plot
    2701         [dimsval]: [dimn1]|[val1]|[dimv1],...,[dimnN]|[valN]|[dimvN] dimension names, values to get
    2702           (-1, for all; no name/value pair given full length) and variable with values of the dimension
     2701        [dimsval]: [dimn1]|[val1]|[dimv1],...,[dimnN]|[valN]|[dimvN] dimension names, values to get:
     2702          * [integer]: which value of the dimension
     2703          * -1: all along the dimension
     2704          * NOTE, no dim name all the dimension size
    27032705          'WRFtime' for WRF times
    27042706          NOTE: when dimsval[X,Y] == neigdims[X,Y], valX,valY --> valX,valY-Nneig/2, valX,valY+Nneig/2
     
    29512953
    29522954def draw_points(filen, values):
    2953     """ Function to plot a series of points
    2954       [values]= [ptasciifile]:[gtit]:[mapvalues]:[kindfigure]:[pointcolor]:[pointlabels]:
    2955         [legvals]:[figureko]:[figuren]
     2955    """ Function to plot a series of points read from an ASCII file with lon, lat, label
     2956      draw_points(filen, values)
     2957      [values]= [ptasciifile]:[gtit]:[dimxyfmt]:[mapvalues]:[kindfigure]:[pointcolor]:[pointlabels]:
     2958        [legvals]:[figureko]:[figuren]:[close]
    29562959        [ptasciifile]:[file],[comchar],[collon],[collat],[lab]
    29572960          [file]: column ASCII file with the location of the points
     
    29622965            the values from the [pointlabels] variable
    29632966        [gtit]: title of the figure ('|' for spaces)
     2967        [dimxyfmt]: [dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
     2968          [dxs]: style of x-axis ('auto' for 'pretty')
     2969            'Nfix', values computed at even 'Ndx'
     2970            'Vfix', values computed at even 'Ndx' increments
     2971            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
     2972          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
     2973          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
     2974          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
     2975          [dys]: style of y-axis ('auto' for 'pretty')
     2976          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
     2977          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
     2978          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
    29642979        [mapvalues]: drawing coastaline ([proj],[res]) or None
    29652980          [proj]: projection
     
    29762991          'labelled',[txtsize],[txtcol]: points with the names and size, color of text
    29772992        [pointcolor]: color for the points ('auto' for "red")
    2978         [pointlabels]: ',' of labels [only used if [collab]='None'] ('None' for no labels)
     2993        [pointlabels]: ',' of labels [only used if [collab]='None'] ('None' for no labels, '!' for spaces)
    29792994        [legvals]=[locleg]|[fontsize]:
    29802995          [locleg]: location of the legend (0, autmoatic)
     
    29853000        [figureko]: kind of the output file (pdf, png, ...)
    29863001        [figuren]: name of the figure
    2987       [filen]= [ncfile],[lonvarn],[latvarn][,[varn],[dimvals],[vargn],[min],[max],[cbar],[varu]]
     3002        [close]: Whether figure should be finished or not
     3003      [filen]= [ncfile],[lonvarn],[latvarn][,[varn],[dimvals],[vargn],[min],[max],[colbarn],[fmtcolorbar],[orientation],[varu]]
    29883004        [ncfile]: netCDF to use to geolocalize the points
    29893005        [lonvarn]: name of the variable with the longitudes
    29903006        [latvarn]: name of the variable with the latitudes
    2991         [varn]: optional variable to add staff into the graph
    2992         [dimval]: '@' list of [dimn]|[dimval] to get the values for [varn]
    2993           [dimn]: name of the dimension
    2994           [dimval]: value of the dimension variable a given value is required:
    2995             * [integer]: which value of the dimension
    2996             * -1: all along the dimension
    2997             * -9: last value of the dimension
    2998             * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
    2999             * NOTE, no dim name all the dimension size
    3000         [vargn]: name of the variable in the graph
    3001         [min]: minimum value for the extra variable
    3002         [max]: maximum value for the extra variable
    3003         [cbar]: color bar
    3004         [varu]: units of the variable
     3007        Optional values:
     3008          [varn]: optional variable to add staff into the graph
     3009          [dimval]: '@' list of [dimn]|[dimval] to get the values for [varn]
     3010            [dimn]: name of the dimension
     3011            [dimval]: value of the dimension variable a given value is required:
     3012              * [integer]: which value of the dimension
     3013              * -1: all along the dimension
     3014              * -9: last value of the dimension
     3015              * [beg];[end];[inc] slice from [beg] to [end] every [inc]
     3016              * NOTE, no dim name all the dimension size
     3017          [vargn]: name of the variable in the graph
     3018          [min]: minimum value for the extra variable
     3019          [max]: maximum value for the extra variable
     3020          [colbarn]: name of the color bar
     3021          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
     3022          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
     3023          [varu]: units of the variable
    30053024    """
    30063025    fname = 'draw_points'
     
    30113030        quit()
    30123031
    3013     expectargs = '[ptasciifile]:[gtit]:[mapvalues]:[kindfigure]:[pointcolor]:' +     \
    3014       '[pointlabels]:[locleg]:[figurek]:[figuren]'
     3032    expectargs = '[ptasciifile]:[gtit]:[dimxyfmt]:[mapvalues]:[kindfigure]:' +       \
     3033      '[pointcolor]:[pointlabels]:[locleg]:[figurek]:[figuren]:[close]'
    30153034 
    30163035    drw.check_arguments(fname,values,expectargs,':')
     
    30183037    ptasciifile = values.split(':')[0]
    30193038    gtit = values.split(':')[1]
    3020     mapvalues = values.split(':')[2]
    3021     kindfigure = values.split(':')[3]
    3022     pointcolor = values.split(':')[4]
    3023     pointlabels = values.split(':')[5]
    3024     locleg = int(values.split(':')[6])
    3025     figureko = values.split(':')[7]
    3026     figuren = values.split(':')[8]
     3039    dimxyfmt = values.split(':')[2]
     3040    mapvalues = values.split(':')[3]
     3041    kindfigure = values.split(':')[4]
     3042    pointcolor = values.split(':')[5]
     3043    pointlabels = values.split(':')[6].replace('!',' ')
     3044    locleg = int(values.split(':')[7])
     3045    figureko = values.split(':')[8]
     3046    figuren = values.split(':')[9]
     3047    close = gen.Str_Bool(values.split(':')[10])
    30273048
    30283049# Getting station locations
     
    30743095    varn = None
    30753096    varextrav = None
    3076     if Nvals == 10:
     3097    if Nvals == 12:
    30773098        varn = filev[3]
    30783099        dimvals = filev[4]
    30793100        varextrav = [filev[5], np.float(filev[6]), np.float(filev[7]), filev[8],     \
    3080           filev[9]]
     3101          filev[9], filev[10], filev[11]]
     3102        if filev[9] == 'auto': varextrav[4] = '%6g'
     3103        if filev[10] == 'auto': varextrav[5] = 'vertical'
    30813104   
    30823105    if not os.path.isfile(ncfile):
     
    30873110    onc = NetCDFFile(ncfile, 'r')
    30883111   
    3089     lonv, latv = drw.lonlat2D(onc.variables[lonvarn], onc.variables[latvarn])
     3112    # Slicing lon,lats
     3113    dd = {}
     3114    for dn in dimvals.split('@'):
     3115        ddn = dn.split('|')[0]
     3116        ddv = dn.split('|')[1]
     3117        dd[ddn] = ddv
     3118
     3119    objlon = onc.variables[lonvarn]
     3120    vard = objlon.dimensions
     3121    slicevar = []
     3122    for dv in vard:
     3123        found= False
     3124        for dn in dd.keys():
     3125            if dn == dv:
     3126                if dd[dn].find(';') == -1:
     3127                    if dd[dn] == '-1':
     3128                        slicevar.append(slice(0,len(onc.dimensions[dv])))
     3129                    elif dd[dn] == '-9':
     3130                        slicevar.append(len(onc.dimensions[dv]))
     3131                    else:
     3132                        slicevar.append(int(dd[dn]))
     3133                else:
     3134                    islc = int(dd[dn].split(';')[0])
     3135                    eslc = int(dd[dn].split(';')[1])
     3136                    tslc = int(dd[dn].split(';')[2])
     3137                    slicevar.append(slice(islc,eslc,tslc))
     3138                found = True
     3139                break
     3140        if not found:
     3141            slicevar.append(slice(0,len(onc.dimensions[dv])))
     3142    lonvals = np.squeeze(objlon[tuple(slicevar)])
     3143
     3144    objlat = onc.variables[latvarn]
     3145    vard = objlat.dimensions
     3146    slicevar = []
     3147    for dv in vard:
     3148        found= False
     3149        for dn in dd.keys():
     3150            if dn == dv:
     3151                if dd[dn].find(';') == -1:
     3152                    if dd[dn] == '-1':
     3153                        slicevar.append(slice(0,len(onc.dimensions[dv])))
     3154                    elif dd[dn] == '-9':
     3155                        slicevar.append(len(onc.dimensions[dv]))
     3156                    else:
     3157                        slicevar.append(int(dd[dn]))
     3158                else:
     3159                    islc = int(dd[dn].split(';')[0])
     3160                    eslc = int(dd[dn].split(';')[1])
     3161                    tslc = int(dd[dn].split(';')[2])
     3162                    slicevar.append(slice(islc,eslc,tslc))
     3163                found = True
     3164                break
     3165        if not found:
     3166            slicevar.append(slice(0,len(onc.dimensions[dv])))
     3167    latvals = np.squeeze(objlat[tuple(slicevar)])
     3168
     3169    lonv, latv = drw.lonlat2D(lonvals, latvals)
    30903170
    30913171    if varn is not None:
    30923172        objextra = onc.variables[varn]
    30933173        vard = objextra.dimensions
    3094         dd = {}
    3095         for dn in dimvals.split('@'):
    3096             ddn = dn.split('|')[0]
    3097             ddv = dn.split('|')[1]
    3098             dd[ddn] = ddv
    30993174        slicevar = []
    31003175        for dv in vard:
     
    31023177            for dn in dd.keys():
    31033178                if dn == dv:
    3104                     slicevar.append(int(dd[dn]))
     3179                    if dd[dn].find(';') == -1:
     3180                        if dd[dn] == '-1':
     3181                            slicevar.append(slice(0,len(onc.dimensions[dv])))
     3182                        elif dd[dn] == '-9':
     3183                            slicevar.append(len(onc.dimensions[dv]))
     3184                        else:
     3185                            slicevar.append(int(dd[dn]))
     3186                    else:
     3187                        islc = int(dd[dn].split(';')[0])
     3188                        eslc = int(dd[dn].split(';')[1])
     3189                        tslc = int(dd[dn].split(';')[2])
     3190                        slicevar.append(slice(islc,eslc,tslc))
    31053191                    found = True
    31063192                    break
     
    31103196        varextra = np.squeeze(objextra[tuple(slicevar)])
    31113197
     3198    # Axis values
     3199    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
     3200    xaxis = [xstyl, xaxf, Nxax, xaxor]
     3201    yaxis = [ystyl, yaxf, Nyax, yaxor]
     3202
    31123203    if mapvalues == 'None':
    31133204        mapV = None
     
    31153206        mapV = mapvalues
    31163207
    3117     drw.plot_points(xptval, yptval, lonv, latv, varextra, varextrav, gtit, mapV,     \
    3118       kindfigure, pointcolor, ptlabels, locleg, figureko, figuren)
     3208    drw.plot_points(xptval, yptval, lonv, latv, varextra, varextrav, gtit, xaxis,    \
     3209      yaxis, mapV, kindfigure, pointcolor, ptlabels, locleg, figureko, figuren, close)
    31193210
    31203211    onc.close()
  • trunk/tools/drawing_tools.py

    r1277 r1283  
    30213021#quit()
    30223022
    3023 def plot_points(xval, yval, vlon, vlat, extravals, extrapar, vtit, mapv, figk, color,\
    3024   labels, lloc, kfig, figname):
     3023def plot_points(xval, yval, vlon, vlat, extravals, extrapar, vtit, xaxv, yaxv, mapv, \
     3024  figk, color, labels, lloc, kfig, figname, ifclose):
    30253025    """ plotting points
    30263026      [x/yval]: x,y values to plot
     
    30303030      extrapar= [varname, min, max, cbar, varunits] of the extra variable
    30313031      vtit= title of the graph ('|' for spaces)
     3032      xaxv= list with the x-axis paramteres [style, format, number and orientation]
     3033      yaxv= list with the y-axis paramteres [style, format, number and orientation]
    30323034      mapv= map characteristics: [proj],[res]
    30333035        see full documentation: http://matplotlib.org/basemap/
     
    30493051      kfig= kind of figure (jpg, pdf, png)
    30503052      figname= name of the figure
    3051 
     3053      ifclose= boolean value whether figure should be close (finish) or not
    30523054    """
    30533055    fname = 'plot_points'
     3056
     3057    # Axis ticks
     3058    # Usually axis > x must be the lon, thus...
     3059    dimxv0 = np.array(xval)
     3060    dimyv0 = np.array(yval)
     3061
     3062    dxn = dimxv0.min()
     3063    dxx = dimxv0.max()
     3064    dyn = dimyv0.min()
     3065    dyx = dimyv0.max()
     3066
     3067    if xaxv[0] == 'pretty':
     3068        dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2]))
     3069    elif xaxv[0] == 'Nfix':
     3070        dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2]))
     3071    elif xaxv[0] == 'Vfix':
     3072        dimxt0 = np.arange(0,dxx,xaxv[2])
     3073    if yaxv[0] == 'pretty':
     3074        dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2]))
     3075    elif yaxv[0] == 'Nfix':
     3076        dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2]))
     3077    elif yaxv[0] == 'Vfix':
     3078        dimyt0 = np.arange(0,dyx,yaxv[2])
     3079
     3080    dimxl0 = []
     3081    for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1]))
     3082    dimyl0 = []
     3083    for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1]))
     3084
     3085    dimxT0 = 'x'
     3086    dimyT0 = 'y'
     3087
     3088    if mapv is not None:
     3089        pixkind = 'data'
     3090    else:
     3091        # No following data values
     3092        dimxt0 = np.arange(len(dimxt0),dtype=np.float)/(len(dimxt0))
     3093        dimyt0 = np.arange(len(dimyt0),dtype=np.float)/(len(dimyt0))
     3094        pixkind = 'fixpixel'
     3095
     3096# No transformation
     3097#    if reva is not None:
     3098#        extravals, xval, yval, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT =            \
     3099#          transform(extravals, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0, \
     3100#          dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0)
     3101#    else:
     3102#        dimxv = dimxv0
     3103#        dimyv = dimyv0
     3104#        dimxt = dimxt0
     3105#        dimyt = dimyt0
     3106#        dimxl = dimxl0
     3107#        dimyl = dimyl0
     3108#        dimxT = dimxT0
     3109#        dimyT = dimyT0
     3110
     3111    dimxv = dimxv0
     3112    dimyv = dimyv0
     3113    dimxt = dimxt0
     3114    dimyt = dimyt0
     3115    dimxl = dimxl0
     3116    dimyl = dimyl0
     3117    dimxT = dimxT0
     3118    dimyT = dimyT0
     3119
    30543120# Canging line kinds every 7 pts (end of standard colors)
    30553121    ptkinds=['.','x','o','*','+','8','>','D','h','p','s']
     
    31283194        plt.pcolormesh(x, y, extravals, cmap=plt.get_cmap(extrapar[3]),              \
    31293195          vmin=extrapar[1], vmax=extrapar[2])
    3130         cbar = plt.colorbar()
    3131         cbar.set_label(extrapar[0].replace('_','\_') +'('+ units_lunits(extrapar[4])+\
     3196        if extrapar[5] == 'horizontal':
     3197            cbar = plt.colorbar(format=extrapar[4],orientation=extrapar[5])
     3198            # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib
     3199            ticklabels= cbar.ax.get_xticklabels()
     3200            Nticks = len(ticklabels)
     3201            ticklabs = []
     3202            for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text())
     3203            cbar.ax.set_xticklabels(ticklabs,rotation=90)
     3204        else:
     3205            cbar = plt.colorbar(format=extrapar[4],orientation=extrapar[5])
     3206
     3207        cbar.set_label(gen.latex_text(extrapar[0]) +'('+ units_lunits(extrapar[6]) + \
    31323208          ')')
    31333209
     
    31393215
    31403216        if figk[0:8] == 'labelled':
     3217            if len(figk.split(',')) != 3:
     3218                print errormsg
     3219                print '  ' + fname + ": 'labelled' requires two additional values !!"
     3220                print "    'labelled',[txtsize],[txtcolor]"
     3221                quit(-1)
    31413222            txtsize=int(figk.split(',')[1])
    31423223            txtcol=figk.split(',')[2]
     
    31503231        plt.plot(xval, yval, '.', color=ptcol)
    31513232
    3152     graphtit = vtit.replace('_','\_').replace('&','\&')
    3153 
    3154     plt.title(graphtit.replace('|', ' '))
     3233    graphtit = gen.latex_text(vtit.replace('|',' '))
     3234
     3235    plt.title(graphtit)
    31553236   
    3156     output_kind(kfig, figname, True)
     3237    output_kind(kfig, figname, ifclose)
    31573238
    31583239    return
Note: See TracChangeset for help on using the changeset viewer.