Changeset 1937 in lmdz_wrf for trunk


Ignore:
Timestamp:
Jul 17, 2018, 3:02:28 AM (6 years ago)
Author:
lfita
Message:

Adding:

  • `draw_multi_SkewT': creation of a SkewT-logP diagram with multiple lines using matplotlib's API example
Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/drawing.py

    r1931 r1937  
    1717import sys
    1818from cStringIO import StringIO
     19import numpy.ma as ma
    1920
    2021## e.g. # drawing.py -f /media/data2/etudes/WRF_LMDZ/WL_HyMeX/IIphase/medic950116/wlmdza/wrfout/wrfout_d01_1995-01-13_00:00:00 -o create_movie -S 'draw_2D_shad#Time@WRFTimes@10@95@191@1#tas:East_West|-1,North_South|-1,Time|2:longitude:latitude:Summer:270.,300.:tas|at|t=0:pdf:None:None' -v T2
     
    5859# movie_2D_shad -f '../PY/wrfout_d01_1995-01-01_00:00:00' -S 'tas:west_east|-1,south_north|-1,Time|-1:XLONG:XLAT:auto:rainbow,auto,auto:Srange,Srange:png:None:cyl,l:Time,Times:WRFdate,$%d^{%H}$:15:mp4' -v T2
    5960## e.g. # drawing.py -o draw_SkewT -f UWyoming_snd_87576.nc -S 'time|0:auto:auto:Sounding!at!Ezeiza!airport!on!3rd!July!1998:png:yes' -v ta,tda,pres
     61## e.g. # drawing.py -o draw_multi_SkewT -f '/home/lluis/estudios/ChemGBsAs/tests/199807/obs/snd/UWyoming_snd_87576.nc:pres|-1,time|0:ta,pres;/home/lluis/estudios/ChemGBsAs/tests/199807/obs/snd/UWyoming_snd_87576.nc:pres|-1,time|0:tda,pres' -S 'auto:auto:multilines!ta,tda!#6464FF,#FF6464!-!,!2:0,auto:Sounding!at!Ezeiza!airport!on!3rd!July!1998:png:yes'
    6062
    6163#######
     
    8284# draw_lines_time: Function to draw different lines at the same time from different files with times
    8385# draw_multi_2D_shad: plotting multiple 2D fields with same projection with shading and sharing colorbar
     86# draw_multi_SkewT: creation of a SkewT-logP diagram with multiple lines using matplotlib's API example
    8487# draw_Neighbourghood_evol: Function to draw the temporal evolution of a neighbourghood around a point
    8588# draw_points: Function to plot a series of points
     
    114117  'draw_2D_shad_line_time', 'draw_bar', 'draw_bar_line', 'draw_bar_line_time',       \
    115118  'draw_bar_time', 'draw_barbs', 'draw_basins', 'draw_cycle', 'draw_ensembles_time', \
    116   'draw_2lines', 'draw_2lines_time', 'draw_multi_2D_shad', 'draw_lines',             \
    117   'draw_lines_time',                                                                 \
     119  'draw_2lines', 'draw_2lines_time', 'draw_multi_2D_shad', 'draw_multi_SkewT',       \
     120  'draw_lines', 'draw_lines_time',                                                   \
    118121  'draw_Neighbourghood_evol',                                                        \
    119122  'draw_points', 'draw_points_lonlat',                                               \
     
    89138916        print errormsg
    89148917        print '  ' +fname+ ": requires 3 name of variables as '[tavarn],[tdavarn]" + \
    8915           ",[tavarn]' !!"
     8918          ",[presvarn]' !!"
    89168919        print "    variables provided: '" + varname + "' "
    89178920        quit(-1)
     
    89368939            print ' ' + fname + ": file '" + ncfile + "' does not have variable '" + \
    89378940              varn + "' !!"
    8938             print '    available ones:', onc.variables-keys()
     8941            print '    available ones:', onc.variables.keys()
    89398942            quit(-1)
    89408943
     
    89668969#varn='ta,tda,pres'
    89678970#draw_SkewT(filen, values, varn)
     8971
     8972def draw_multi_SkewT(ncfiles, values):
     8973    """ creation of a SkewT-logP diagram with multiple lines using matplotlib's API example
     8974      https://matplotlib.org/examples/api/skewt.html (skewt.py, included as external python)
     8975    draw_SkewT(ncfile, values, varn)
     8976      ncfiles = ';' list of [filen]:[dimvals]:[varn],[presvarn] file and variables to use
     8977        from each file
     8978        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the
     8979          variable a given value is required:
     8980            * [integer]: which value of the dimension
     8981            * -1: all along the dimension
     8982            * -9: last value of the dimension
     8983            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
     8984            * NOTE, no dim name all the dimension size
     8985        [varn]: name of the variable to plot [C]
     8986        [presvarn]: name of the variable with the pressures of [varn] [Pa]
     8987      values = [taminv],[tamaxv]:[presminv],[presmaxv]:[kindgraph]:[legvals]:[figt]:
     8988        [kindfig]:[close]
     8989        [taminv],[tamaxv]: minimum and maximum of temperatures to plot [C]
     8990          ('auto' for -50,50)
     8991        [presminv],[presmaxv]: minimum and maximum of pressures to plot [hPa]
     8992          ('auto' for 100.,1020.)
     8993        [kindgraph]: kind of graphic to produce. To select from:
     8994          'multilines'![labels]![collines]![kindlines]![kindmarkers]![widthlines]
     8995            [labels] = ',' separated list of labels for each file ('None' for no
     8996              label)
     8997            [collines] = ',' separated list of colors ('#RRGGBB' values) of lines for
     8998              each file (1 value for all the lines the same)
     8999            [kindmarkers] = ';' separated list of marker types (matplolib values) for
     9000              each file (1 value for all the lines the same)
     9001            [kindlines] = ';' separated list of line types (matplolib values) of
     9002              lines for each file (1 value for all the lines the same)
     9003            [widthlines] = ';' separated list of line widths (matplolib values) of
     9004              lines for each file (1 value for all the lines the same)
     9005        [legvals]=[loclegend],[fonstsize] values for the legend
     9006          [locleg]: location of the legend (0, automatic)
     9007            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
     9008            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
     9009            9: 'upper center', 10: 'center'
     9010          [fontsize]: font size for the legend ('auto' for 12)
     9011        [figt]: title of figure ('!' for spaces)
     9012        [kindfig]: kind of graphical output (ps, png, pdf)
     9013        [close]: wether figure should be closed or not
     9014    """
     9015    fname = 'draw_SkewT'
     9016
     9017    if values == 'h':
     9018        print fname + '_____________________________________________________________'
     9019        print draw_SkewT.__doc__
     9020        quit()
     9021
     9022    availgraph = ['multilines']
     9023
     9024    expectargs = '[taminv],[tamaxv]:[presminv],[presmaxv]:[figt]:[kindgraph]:' +     \
     9025      '[legvals]:[kindfig]:[close]'
     9026 
     9027    drw.check_arguments(fname,values,expectargs,':')
     9028
     9029    if values.split(':')[0] != 'auto':
     9030        tanx = gen.str_list_k(values.split(':')[1], ',', 'np.float')
     9031    else:
     9032        tanx = [-50.,50.]
     9033    if values.split(':')[1] != 'auto':
     9034        presnx = gen.str_list_k(values.split(':')[2], ',', 'np.float')
     9035    else:
     9036        presnx = [100.,1020.]
     9037    kindgraph = values.split(':')[2]
     9038    legv = drw.legend_values(values.split(':')[3], ',')
     9039    figt = values.split(':')[4].replace('!',' ')
     9040    kindfig = values.split(':')[5]
     9041    close = gen.Str_Bool(values.split(':')[6])
     9042
     9043    filevals = ncfiles.split(';')
     9044    Nfiles = len(filevals)
     9045
     9046    # Getting graphic parameters
     9047    kindgraphv = kindgraph.split('!')
     9048    kgraphS = kindgraphv[0]
     9049    kgraphv = {}
     9050    if kgraphS == 'multilines':
     9051        kgraphv['labels'] = kindgraphv[1].split(',')
     9052        kgraphv['collines'] = gen.str_list_rep(kindgraphv[2], ',', Nfiles)
     9053        kgraphv['kindlines'] = gen.str_list_rep(kindgraphv[3], ',', Nfiles)
     9054        kgraphv['kindmarkers'] = gen.str_list_rep(kindgraphv[4], ',', Nfiles)
     9055        kgraphv['widthlines'] = gen.str_list_rep(kindgraphv[5], ',', Nfiles)
     9056    else:
     9057        print errormsg
     9058        print '  ' + fname + ": graphic type '" + kindgraphv[0] + "' not ready !!"
     9059        print '    available ones:', availgraph
     9060        quit(-1)
     9061
     9062    vavals = {}
     9063    presvals = {}
     9064    ifile = 0
     9065    # Getting values to plot
     9066    for fileval in filevals:
     9067        ncfile = fileval.split(':')[0]
     9068        dimvals= fileval.split(':')[1].replace('|',':')
     9069        varname = fileval.split(':')[2]
     9070
     9071        # Variables
     9072        varns = varname.split(',')
     9073        if len(varns) != 2:
     9074            print errormsg
     9075            print '  ' +fname+ ": requires 2 name of variables as '[varn]," +      \
     9076              "[presvarn]' !!"
     9077            print "    variables provided: '" + varname + "' "
     9078            quit(-1)
     9079
     9080        onc = NetCDFFile(ncfile, 'r')
     9081        for varn in varns:
     9082            if not onc.variables.has_key(varn):
     9083                print errormsg
     9084                print ' ' + fname + ": file '" + ncfile + "' does not have " +       \
     9085                  "variable '" + varn + "' !!"
     9086                print '    available ones:', onc.variables.keys()
     9087                quit(-1)
     9088
     9089        ov = onc.variables[varns[0]]
     9090        opres = onc.variables[varns[1]]
     9091
     9092        # Getting values
     9093        vals, valdims = drw.slice_variable(ov, dimvals.replace(',','|'))
     9094        pvals, presdims = drw.slice_variable(opres, dimvals.replace(',','|'))
     9095
     9096        # Expected masked values
     9097        if type(vals) != type(gen.mamat):
     9098            vavals[ifile] = ma.masked_array(vals)
     9099        else:
     9100            vavals[ifile] = vals
     9101        if type(presvals) != type(gen.mamat):
     9102            presvals[ifile] = ma.masked_array(pvals)
     9103        else:
     9104            presvals[ifile] = pvals
     9105        ifile = ifile + 1
     9106
     9107    drw.plot_multi_SkewT(vavals, presvals, tanx, presnx, kgraphS, kgraphv, legv,     \
     9108      figt, kindfig, close)
     9109
     9110    onc.close()
     9111
     9112    return
     9113
     9114#filen='/home/lluis/estudios/ChemGBsAs/tests/199807/obs/snd/UWyoming_snd_87576.nc:pres|-1,time|0:ta,pres;' + \
     9115#  '/home/lluis/estudios/ChemGBsAs/tests/199807/obs/snd/UWyoming_snd_87576.nc:pres|-1,time|0:tda,pres'
     9116#values='auto:auto:multilines!ta,tda!#6464FF,#FF6464!-!,!2:0,auto:Sounding!at!Ezeiza!airport!on!3rd!July!1998:png:yes'
     9117#draw_multi_SkewT(filen, values)
    89689118
    89699119#quit()
     
    89909140  'draw_2D_shad_line', 'draw_2D_shad_line_time', 'draw_2lines', 'draw_2lines_time',  \
    89919141  'draw_bar', 'draw_bar_line', 'draw_bar_line_time', 'draw_bar_time',                \
    8992   'draw_cycle', 'draw_ensembles_time', 'draw_multi_2D_shad', 'draw_lines',           \
     9142  'draw_cycle', 'draw_ensembles_time', 'draw_multi_2D_shad', 'draw_multi_SkewT',     \
     9143  'draw_lines',                                                                      \
    89939144  'draw_lines_time', 'draw_points', 'draw_Taylor', 'draw_time_lag',                  \
    89949145  'draw_topo_geogrid_boxes',                                                         \
     
    90809231    elif oper == 'draw_multi_2D_shad':
    90819232        draw_multi_2D_shad(opts.ncfile, opts.values)
     9233    elif oper == 'draw_multi_SkewT':
     9234        draw_multi_SkewT(opts.ncfile, opts.values)
    90829235    elif oper == 'draw_points':
    90839236        draw_points(opts.ncfile, opts.values)
  • trunk/tools/drawing_tools.py

    r1936 r1937  
    18081808    """ Function to determine the values for the legend
    18091809      legstring= char separated list of [locleg][char][fontsize]:
    1810           [locleg]: location of the legend (0, autmoatic)
     1810          [locleg]: location of the legend (0, automatic)
    18111811            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
    18121812            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
     
    1149711497def plot_SkewT(ta, tda, pres, taxtrm, presxtrm, figtitle, kfig, close):
    1149811498    """ Function to plot a SkewT-logP diagram using matplotlib's API example 
    11499       ta: air temperature [K]
    11500       tda: dew point air temperature [K]
     11499      ta: air temperature [C]
     11500      tda: dew point air temperature [C]
    1150111501      pres: pessures for ta and tda [Pa]
    1150211502      figtitle: title of figure
     
    1158111581
    1158211582    return
     11583
     11584def plot_multi_SkewT(tvals, press, taxtrm, presxtrm, kindgS, kindgv, legv, figtitle,
     11585  kfig, close):
     11586    """ Function to plot a SkewT-logP diagram with multiple data using matplotlib's
     11587      API example
     11588      tvals: dictionary with multiple air temperatures [C]
     11589      press: dictionary with multiple pessures for ta and tda [Pa]
     11590      [kindgS]: kind of graphic to produce. To select from:
     11591          'multilines': multiple lines
     11592      [kindgv]: dictionary with values for the given [kindgS]
     11593        * For 'multilines':
     11594          'labels' = list of labels for each line
     11595          'collines' = list of colors ('#RRGGBB' values) for each line
     11596          'kindmarkers' = list of marker types for each line
     11597          'kindlines' = list of line types (matplolib values) of lines
     11598          'widthlines' = list of line widths
     11599      [legv] = [[locleg], [fontsize]] list with the values for the legend
     11600          [locleg]: location of the legend (0, automatic)
     11601            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
     11602            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
     11603            9: 'upper center', 10: 'center'
     11604          [fontsize]: font size for the legend ('auto' for 12)
     11605      figtitle: title of figure
     11606      kfig: kind of graphical output (jpg, pdf, png)
     11607      close: whether figure should be closed or not
     11608    """
     11609    import skewt
     11610
     11611    fname = 'plot_SkewT'
     11612   
     11613    # Create a new figure. The dimensions here give a good aspect ratio
     11614    fig = plt.figure(figsize=(6.5875, 6.2125))
     11615    ax = fig.add_subplot(111, projection='skewx')
     11616
     11617    plt.grid(True)
     11618
     11619    # Quantity of dryadiabats
     11620    xmax = taxtrm[1]
     11621    xmin = taxtrm[0]
     11622    print 'len:', np.arange(xmin,xmax,10.)
     11623    if len(np.arange(xmin,xmax,10.)) < 10: xfrqtk = 10.
     11624    else: xfrqtk = 20.
     11625
     11626    # Including dry adiabats
     11627    ddt = int((xmax+xfrqtk-xmin)/xfrqtk)
     11628    for itt in range(ddt):
     11629        dryt = thetapotct(xmin+itt*xfrqtk, pmin=10000.)
     11630        ax.semilogy(dryt[:,1], dryt[:,0]/100., color='#FFCCCC', linewidth=0.75)
     11631
     11632    # Including moist- adiabats
     11633    #for itt in range(ddt):
     11634    #    moist = ethetapotct(xmin+itt*xfrqtk, pmin=10000.)
     11635    #    if xmin+itt*xfrqtk == 10.: print moist[:,1], moist[:,0]/100.
     11636    #    ax.semilogy(moist[:,1], moist[:,0]/100., color='#CCFFCC', linewidth=0.75)   
     11637
     11638    # An example of a slanted line at constant X
     11639    l = ax.axvline(0, color='C0')
     11640
     11641    Nlines = len(kindgv['labels'])
     11642
     11643    for iline in range(Nlines):
     11644        ta = tvals[iline]
     11645        pres = press[iline]
     11646
     11647        # line characteristics
     11648        lline = kindgv['labels'][iline]
     11649        cline = kindgv['collines'][iline]
     11650        kmark = kindgv['kindmarkers'][iline]
     11651        kline = kindgv['kindlines'][iline]
     11652        wline = kindgv['widthlines'][iline]
     11653
     11654        # Checking for variable consistency
     11655        if len(ta.shape) != 1:
     11656            print errormsg
     11657            print '  ' + fname + ": values of 'T[" + str(iline) + "]' must have " +  \
     11658              "1D-rank!!"
     11659            print '    passed shape:', ta.shape
     11660            quit(-1)
     11661        if len(pres.shape) != 1:
     11662            print errormsg
     11663            print '  ' +fname+ ": values of 'pres[" + str(iline) + "]' must have " + \
     11664              "1D-rank!!"
     11665            print '    passed shape:', pres.shape
     11666            quit(-1)
     11667
     11668        # Plot the data using normal plotting functions, in this case using
     11669        # log scaling in Y, as dictated by the typical meteorological plot
     11670        tamask = ta.mask
     11671
     11672        if lline != 'None':
     11673            ax.semilogy(ta.compressed(), pres[~tamask], kline, color=cline,          \
     11674              linewidth=wline, marker=kmark, label=lline)
     11675        else:
     11676            ax.semilogy(ta.compressed(), pres[~tamask], kline, color=cline,          \
     11677              linewidth=wline, marker=kmark)
     11678
     11679    # Disables the log-formatting that comes with semilogy
     11680    ax.yaxis.set_major_formatter(ScalarFormatter())
     11681    ax.yaxis.set_minor_formatter(NullFormatter())
     11682    ax.set_yticks(np.linspace(100, 1000, 10))
     11683    ax.set_ylim(presxtrm[1], presxtrm[0])
     11684
     11685    ax.xaxis.set_major_locator(MultipleLocator(10))
     11686    ax.set_xlim(taxtrm[0], taxtrm[1])
     11687
     11688    # Indices
     11689    #plt.annotate('CAPE: ' + str(stvals['CAPE']), xy=(0.98,0.97),                         \
     11690    #  xycoords='axes fraction', ha="right", backgroundcolor='#DDDDDD')
     11691    #plt.annotate('CI: '+ str(stvals['CI']), xy=(0.98,0.93), xycoords='axes fraction',    \
     11692    #  ha='right', backgroundcolor='#DDDDDD')
     11693
     11694    plt.legend(loc=legv[0], prop={'size':legv[1]})
     11695
     11696    ax.set_title(gen.latex_text(figtitle))
     11697
     11698    figname = 'multi_SkewT'
     11699    output_kind(kfig, figname, close)
     11700
     11701    return
Note: See TracChangeset for help on using the changeset viewer.