Changeset 1553 in lmdz_wrf for trunk/tools/drawing.py


Ignore:
Timestamp:
May 2, 2017, 7:07:24 PM (8 years ago)
Author:
lfita
Message:

Adding `draw_time_lag': Function to plot a time-lag figure with multiple sources (x, previous values; y, future values)

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/drawing.py

    r1550 r1553  
    4949## e.g. # drawing.py -o draw_bar_line -f 'Forcing_rainstats_OKstomate_CRUNCEP_spinup_SESA_norm_meanstd_stat2.nc;time_counter,0@12@1;time_counter;rainnorm;bar:Forcing_rainstats_OKstomate_CRUNCEP_spinup_SESA_norm_meanstd_stat2.nc;time_counter,12@24@1;time_counter;rainnorm;bar:Forcing_rainstats_OKstomate_CRUNCEP_spinup_SACZ_norm_meanstd_stat2.nc;time_counter,0@12@1;time_counter;rainnorm;line:Forcing_rainstats_OKstomate_CRUNCEP_spinup_SACZ_norm_meanstd_stat2.nc;time_counter,12@24@1;time_counter;rainnorm;line' -S 'Stringlist,%s,January@Feburary@March@April@May@June@July@August@September@October@November@December@Jan@Feb@Mar@Apr@May@Jun@Jul@Aug@Sept@Oct@Nov@Dec,25,pretty,auto,auto,auto:time!since!1958-01-01:pr:x:-4.,4.:seconds:1:$SESA_{1958}$,$SESA_{1959}$,$SACZ_{1958}$,$SACZ_{1959}$:#AA0000,#0000AA:1000000.:#00AA00,#AAAA00:-.:,:2.:2.:all:normalized!evolution!of!precipitation!with!CRU-NCEP!forcing:0|10:png:bar-line_rain_CRU-NCEP_norm:yes'
    5050## e.g. # drawing.py -o draw_bar_line_time -f 'Forcing_rainstats_OKstomate_SESA_DJFmean_norm_meanstd_stat2.nc;time_centered,-1;time_centered;rainnorm;bar:Forcing_rainstats_OKstomate_SACZ_DJFmean_norm_meanstd_stat2.nc;time_centered,-1;time_centered;rainnorm;bar:DiPolo_evapstats_OKstomate_SESA_DJFmean_stat2.nc;time_centered,-1;time_centered;evap_stats;line:DiPolo_evapnustats_OKstomate_SESA_DJFmean_stat2.nc;time_centered,-1;time_centered;evapnu_stats;line:DiPolo_evspsblvegstats_OKstomate_SESA_DJFmean_stat2.nc;time_centered,-1;time_centered;evspsblveg_stats;line:DiPolo_transpirstats_OKstomate_SESA_DJFmean_stat2.nc;time_centered,-1;time_centered;transpir_stats;line:DiPolo_evapstats_OKstomate_SACZ_DJFmean_stat2.nc;time_centered,-1;time_centered;evap_stats;line:DiPolo_evapnustats_OKstomate_SACZ_DJFmean_stat2.nc;time_centered,-1;time_centered;evapnu_stats;line:DiPolo_evspsblvegstats_OKstomate_SACZ_DJFmean_stat2.nc;time_centered,-1;time_centered;evspsblveg_stats;line:DiPolo_transpirstats_OKstomate_SACZ_DJFmean_stat2.nc;time_centered,-1;time_centered;transpir_stats;line' -S 'auto;pr;y;None;1;year|seconds!since!1958-01-01!00:00:00|exct,5,y|%Y;SESA,SACZ,SESA!evap,evapnu,evspblveg,transpir,SACZ!evap,None,None,None;#AA0000,#0000AA;10000000.;#AAAA00,#00AAAA,#AA00AA,#AAAAAA,#AAAA00,#00AAAA,#AA00AA,#AAAAAA;-,-,-,-,--,--,--,--;,;2.;2.;all;normalized!evolution!of!DJFmean!with!WFD3!forcing;0|10;png;bar_time_rain_CRU-NCEP_DJFmean_norm;yes'
     51## e.g. # drawing.py -o draw_time_lag -f 'Forcing_rainstats_OKstomate_SESA_norm_meanstd_stat2.nc;time_centered,-1;time_counter;rainnorm%DiPolo_evapstats_SESA_norm_meanstd_OKstomate.nc;time_counter,-1|stats,2;time_counter;evapnorm:Forcing_rainstats_OKstomate_SACZ_norm_meanstd_stat2.nc;time_centered,-1;time_counter;rainnorm%DiPolo_evapstats_SACZ_norm_meanstd_OKstomate.nc;time_counter,-1|stats,2;time_counter;evapnorm' -S 'auto;centered;pr;1;evap;1;-5,5;-2,2;year|seconds!since!1958-01-01!00:00:00|exct,5,y|%Y;SESA,SACZ;simplepts,1,#AA0000@#0000AA,x,2.;1-month!time-lag!at!SACZ!between!pr!&!evap!normalized!by!mean/stddev;0|12;png;mon1_timelag_pr-evap_SACZ;yes'
     52
    5153#######
    5254# create_movie: Function to create a movie assuming ImageMagick installed!
     
    7274# draw_points: Function to plot a series of points
    7375# draw_points_lonlat: Function to plot a series of lon/lat points
    74 # draw_ptZvals: Function to plot a given list of points by their Z value and a colorbar
     76# draw_ptZvals: Function to plot a given list of points by their Z value and a colorbar
     77# draw_time_lag: Function to plot a time-lag figure with multiple sources (x, previous values; y, future values)
    7578# draw_timeSeries: Function to draw a time-series
    7679# draw_topo_geogrid: plotting geo_em.d[nn].nc topography from WPS files
     
    102105  'draw_points', 'draw_points_lonlat',                                               \
    103106  'draw_ptZvals', 'draw_river_desc', 'draw_subbasin', 'draw_Taylor',                 \
    104   'draw_timeSeries', 'draw_topo_geogrid',                                            \
     107  'draw_time_lag', 'draw_timeSeries', 'draw_topo_geogrid',                           \
    105108  'draw_topo_geogrid_boxes', 'draw_trajectories', 'draw_vals_trajectories',          \
    106109  'draw_vectors',  'draw_vertical_levels', 'list_graphics', 'draw_WindRose',         \
     
    65946597        [yunits]: units of the y-label
    65956598        [aval]: which acis should be used for the values ('x' or 'y')
    6596         [rangevals]: Range of the axis with the values (singel 'None' for 'auto','auto')
     6599        [rangevals]: Range of the axis with the values (single 'None' for 'auto','auto')
    65976600         [vmin],[vmax]: minimum and maximum values
    65986601           'auto': the computed minimumm or maximum of the values 
     
    68106813        [yunits]: units of the y-label
    68116814        [aval]: which acis should be used for the values ('x' or 'y')
    6812         [rangevals]: Range of the axis with the values (singel 'None' for 'auto','auto')
     6815        [rangevals]: Range of the axis with the values (single 'None' for 'auto','auto')
    68136816         [vmin],[vmax]: minimum and maximum values
    68146817           'auto': the computed minimumm or maximum of the values 
     
    70237026        [yunits]: units of the y-label
    70247027        [aval]: which acis should be used for the values ('x' or 'y')
    7025         [rangevals]: Range of the axis with the values (singel 'None' for 'auto','auto')
     7028        [rangevals]: Range of the axis with the values (single 'None' for 'auto','auto')
    70267029         [vmin],[vmax]: minimum and maximum values
    70277030           'auto': the computed minimumm or maximum of the values 
     
    72497252    return
    72507253
     7254def draw_time_lag(ncfile, values):
     7255    """ Function to plot a time-lag figure with multiple sources (x, previous values; y, future values)
     7256      ncfile = ':' list of couples ('%' formed) [prefilen];[predslice];[pretvarn];[prevarn]%[futfilen];
     7257          [futdslice];[futtvarn];[futvarn]
     7258        'pre': values to act as previous values
     7259        'fut': values to act as future values
     7260
     7261        [filen]: name of the file
     7262        [dimslice]: '|' list of [dimn],[dimrange]
     7263          [dimn]: name of the dimension
     7264          [dimrange]: range for the slice
     7265            * [integer]: which value of the dimension
     7266            * -1: all along the dimension
     7267            * -9: last value of the dimension
     7268            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
     7269            * NOTE, no dim name all the dimension size
     7270        [tvarn]: name of the variable time
     7271        [yvarn]: name of the variable to use for the values
     7272      values = [dimxyfmt];[axeskind];[preaxislab];[preunits];[futaxislab];[futunits];[prerangevals];
     7273          [futrangevals];[timevals];[labels];[figlagkind];[graphtit];[legvalues];[kindfig];[fign];[close]
     7274        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each
     7275            axis (or single 'auto' for 'auto','auto')
     7276          [dxs]: style of x-axis ('auto' for 'pretty')
     7277            'Nfix', values computed at even 'Ndx'
     7278            'Stringlist', a given list of strings
     7279            'Vfix', values computed at even 'Ndx' increments
     7280            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
     7281          [dxf]: format of the labels at the x-axis
     7282          [Ndx]: Number of ticks at the x-axis (for 'Stringlist', '@' list of labels)
     7283          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
     7284          [dys]: style of y-axis ('auto' for 'pretty')
     7285          [dyf]: format of the labels at the y-axis
     7286          [Ndy]: Number of ticks at the y-axis
     7287          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
     7288        [axeskind]: type of axes to be plotted
     7289          'centered': crossed at 0,0 at the center of the figure
     7290          'box': around the figure
     7291        [preaxislab]: Label for the future-axis ('!' for spaces)
     7292        [preunits]: units of the future-label
     7293        [futaxislab]: Label for the future-axis ('!' for spaces)
     7294        [futunits]: units of the future-label
     7295        [prerangevals]: Range of the previous axis with the values (single 'None' for 'auto','auto')
     7296         [vmin],[vmax]: minimum and maximum values
     7297           'auto': the computed minimumm or maximum of the values 
     7298        [futrangevals]: Range of the future axis with the values (single 'None' for 'auto','auto')
     7299         [vmin],[vmax]: minimum and maximum values
     7300           'auto': the computed minimumm or maximum of the values 
     7301        [timevals]: [timen]|[units]|[kind]|[tfmt] time labels characteristics
     7302          [timen]; name of the time variable
     7303          [units]; units string according to CF conventions ([tunits] since
     7304            [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
     7305          [kind]; kind of output
     7306            'Nval': according to a given number of values as 'Nval',[Nval]
     7307            'exct': according to an exact time unit as 'exct',[tunit];
     7308              tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
     7309               'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
     7310               'l': milisecond
     7311          [tfmt]; desired format
     7312        [labels]: ',' list of labels for the legend ('None' for no-labels, '!' for spaces)
     7313        [figlagkind]=[kindname],[valueskind] kind of time-lag plot
     7314          'repeatPeriod',[Nlag],[period],[colorbar],[cbarfmt],[cbaror],[ltype],[lwidth],[mtype],[msize]:
     7315              time-lag for a given repeating sub-period, Line-conected points following a colorbar and time-values
     7316            [Nlag]: number of time steps as lag
     7317            [period]: period to be repeated allover the time-data
     7318            [colorbar]: name of the color bar to use ('auto' for rainbow)
     7319            [cbarfmt]: format of the numbers in the colorbar
     7320            [cbaror]: orientation of the colorbar ('auto' for vertical)
     7321            [ltype]: type of the lines (single value for the same, or 'auto')
     7322            [lsize]: width of the lines (single value for the same, or 'auto')
     7323            [mtype]: type of the markers (single value for the same, or 'auto')
     7324            [msize]: size of the markers (single value for the same, or 'auto')
     7325          'shadTline',[Nlag],[colorbar],[cbarfmt],[cbaror],[ltype],[lwidth],[mtype],[msize]: Line-conected
     7326              points following a colorbar and time-values
     7327            [Nlag]: number of time steps as lag
     7328            [colorbar]: name of the color bar to use ('auto' for rainbow)
     7329            [cbarfmt]: format of the numbers in the colorbar
     7330            [cbaror]: orientation of the colorbar ('auto' for vertical)
     7331            [ltype]: type of the lines (single value for the same, or 'auto')
     7332            [lsize]: width of the lines (single value for the same, or 'auto')
     7333            [mtype]: type of the markers (single value for the same, or 'auto')
     7334            [msize]: size of the markers (single value for the same, or 'auto')
     7335          'simplepts',[Nlag],[col],[type],[size]: Simple points assuming that values have all the same times
     7336            [Nlag]: number of time steps as lag
     7337            [col]: '@' list of colors of the points (single value for the same, or 'auto')
     7338            [type]:types of the points (single value for the same, or 'auto')
     7339            [size]: sizes of the points kind of lag-time figure (single value for the same, or 'auto')
     7340      labels= list of labels for legend (None for no legend, and 'None' for no specific label)
     7341        [graphtit]: title of the figure '!' for spaces
     7342        [legvalues]=[locleg]|[fontsize]:
     7343          [locleg]: location of the legend (0, autmoatic)
     7344            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
     7345            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
     7346            9: 'upper center', 10: 'center'
     7347          [fontsize]: font size for the legend (auto for 12)
     7348        [kindfig]: kind of output figure (png, pdf, ps)
     7349        [fign]: name of the figure (without extension)
     7350        [close]: whether figure should be close or not
     7351    """
     7352    fname = 'draw_time_lag'
     7353
     7354    if values == 'h':
     7355        print fname + '____________________________________________________________'
     7356        print draw_time_lag.__doc__
     7357        quit()
     7358
     7359    expectargs = '[dimxyfmt];[axeskind];[preaxislab];[preunits];[futaxislab];' +     \
     7360      '[futunits];[prerangevals];[futrangevals];[timevals];[labels];[figlagkind];' + \
     7361      '[graphtit];[legvalues];[kindfig];[fign];[close]'
     7362    drw.check_arguments(fname,values,expectargs,';')
     7363
     7364    dimxyfmt = values.split(';')[0]
     7365    axeskind = values.split(';')[1]
     7366    preaxislab = values.split(';')[2].replace('!',' ')
     7367    preunits = values.split(';')[3]
     7368    futaxislab = values.split(';')[4].replace('!',' ')
     7369    futunits = values.split(';')[5]
     7370    prerangevals = values.split(';')[6]
     7371    futrangevals = values.split(';')[7]
     7372    timevals = values.split(';')[8]
     7373    labels = gen.str_list(values.split(';')[9].replace('!', ' '), ',')
     7374    figlagkind = values.split(';')[10]
     7375    graphtit = values.split(';')[11].replace('!',' ')
     7376    legvalues = values.split(';')[12]
     7377    kindfig = values.split(';')[13]
     7378    fign = values.split(';')[14]
     7379    close = gen.Str_Bool(values.split(';')[15])
     7380
     7381    # files and values
     7382    filedvs = ncfile.split(':')
     7383    timevalues = []
     7384    prevalues = []
     7385    futvalues = []
     7386
     7387    # time-values
     7388    expectargs = '[timen]|[units]|[kind]|[tfmt]'
     7389    drw.check_arguments('timevals: '+fname,timevals,expectargs,'|')
     7390
     7391    timen = timevals.split('|')[0].replace('!',' ')
     7392    timeunit = timevals.split('|')[1].replace('!',' ')
     7393    timekind = timevals.split('|')[2]
     7394    timefmt = timevals.split('|')[3]
     7395
     7396    preminval = gen.fillValue
     7397    premaxval = -gen.fillValue
     7398    futminval = gen.fillValue
     7399    futmaxval = -gen.fillValue
     7400    mintval = gen.fillValue
     7401    maxtval = -gen.fillValue
     7402
     7403    for fdvprefut in filedvs:
     7404        prefutdv = fdvprefut.split('%')
     7405        ifile=0
     7406        for fdv in prefutdv:
     7407            filen = fdv.split(';')[0]
     7408            dimrange = fdv.split(';')[1]
     7409            tvarn = fdv.split(';')[2]
     7410            yvarn = fdv.split(';')[3]
     7411            futfdv = fdvprefut.split('%')[1]
     7412
     7413            if not os.path.isfile(filen):
     7414                print errormsg
     7415                print '  ' + fname + ': file "' + filen + '" does not exist !!'
     7416                quit(-1)
     7417
     7418            onc = NetCDFFile(filen, 'r')
     7419            if not onc.variables.has_key(tvarn):
     7420                print errormsg
     7421                print '  ' +fname+ ': file "' +filen+ "' does not have variable '" + \
     7422                  tvarn + "' for the time-values !!"
     7423                print '    available ones:', onc.variables.keys()
     7424                onc.close()
     7425                quit(-1)
     7426            if not onc.variables.has_key(yvarn):
     7427                print errormsg
     7428                print '  ' +fname+ ': file "' +filen+ "' does not have variable '" + \
     7429                  yvarn + "' for the y-values !!"
     7430                print '    available ones:', onc.variables.keys()
     7431                onc.close()
     7432                quit(-1)
     7433
     7434            otvar = onc.variables[tvarn]
     7435            oyvar = onc.variables[yvarn]
     7436            tvs, tdims = ncvar.slice_variable(otvar, dimrange.replace(',',':'))
     7437            yvs, ydims = ncvar.slice_variable(oyvar, dimrange.replace(',',':'))
     7438            tunitsvar = otvar.units
     7439
     7440            if len(tvs.shape) != 1:
     7441                print errormsg
     7442                print '  ' +fname+ ': provided slice:', dimrange, "for variable '" + \
     7443                  tvarn + "' does not provide a rank-1 value !!"
     7444                print '    resultant shape:', tvs.shape, 'dimensions:',tdims,'fix it!!'
     7445                quit(-1)
     7446            if len(yvs.shape) != 1:
     7447                print errormsg
     7448                print '  ' +fname+ ': provided slice:', dimrange, "for variable '" + \
     7449                  yvarn + "' does not provide a rank-1 value !!"
     7450                print '    resultant shape:',yvs.shape, 'dimensions:',ydims,'fix it!!'
     7451                quit(-1)
     7452   
     7453            uvd = timeunit
     7454            tunitsec = timeunit.split(' ')
     7455            if len(tunitsec) == 4:
     7456                refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10] +      \
     7457                  tunitsec[3][0:2] + tunitsec[3][3:5] + tunitsec[3][6:8]
     7458            else:
     7459                refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10] +      \
     7460                  '000000'
     7461            tunitsval = tunitsec[0]
     7462            # Referring all times to the same reference time!
     7463            reftvals = gen.coincident_CFtimes(tvs, timeunit, tunitsvar)
     7464     
     7465            onc.close()
     7466
     7467            reftn = reftvals.min()
     7468            reftx = reftvals.max()
     7469            if reftn < mintval: mintval = reftn
     7470            if reftx > maxtval: maxtval = reftx
     7471
     7472            if ifile == 0:
     7473                timevalues.append(reftvals)
     7474                prevalues.append(yvs)
     7475                pren = yvs.min()
     7476                prex = yvs.max()
     7477                if pren < preminval: preminval = pren
     7478                if prex > premaxval: premaxval = prex
     7479            else:
     7480                timevalues.append(reftvals)
     7481                futvalues.append(yvs)
     7482                futn = yvs.min()
     7483                futx = yvs.max()
     7484                if futn < futminval: futminval = futn
     7485                if futx > futmaxval: futmaxval = futx
     7486            ifile = ifile + 1
     7487
     7488    # Times
     7489    if figlagkind[0:12] == 'repeatPeriod':
     7490        per=int(figlagkind.split(',')[2])
     7491        dtvals = (maxtval - mintval)/10/per
     7492    else:
     7493        dtvals = (maxtval - mintval)/10
     7494    dti = mintval
     7495    dte = maxtval
     7496    tvalsticks = np.arange(dti, dte+dtvals, dtvals)
     7497
     7498    dtiS = drw.datetimeStr_conversion(str(dti) + ',' + timeunit, 'cfTime',           \
     7499     'Y/m/d H-M-S')
     7500    dteS = drw.datetimeStr_conversion(str(dte) + ',' + timeunit, 'cfTime',           \
     7501     'Y/m/d H-M-S')
     7502
     7503    print '  ' + fname + ': plotting from: ' + dtiS + ' to ' + dteS
     7504
     7505    timepos, timelabels = drw.CFtimes_plot(tvalsticks, timeunit, timekind, timefmt)
     7506
     7507    # ranges
     7508    if prerangevals == 'None':
     7509        valmin = preminval
     7510        valmax = premaxval
     7511    else:
     7512        if prerangevals.split(',')[0] != 'auto':
     7513            valmin = np.float(prerangevals.split(',')[0])
     7514        else:
     7515            valmin = preminval
     7516        if prerangevals.split(',')[1] != 'auto':
     7517            valmax = np.float(prerangevals.split(',')[1])
     7518        else:
     7519            valmax = premaxval
     7520    prerng = [valmin, valmax]
     7521
     7522    if futrangevals == 'None':
     7523        valmin = futminval
     7524        valmax = futmaxval
     7525    else:
     7526        if futrangevals.split(',')[0] != 'auto':
     7527            valmin = np.float(futrangevals.split(',')[0])
     7528        else:
     7529            valmin = futminval
     7530        if futrangevals.split(',')[1] != 'auto':
     7531            valmax = np.float(futrangevals.split(',')[1])
     7532        else:
     7533            valmax = futmaxval
     7534    futrng = [valmin, valmax]
     7535
     7536    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
     7537    xaxis = [xstyl, xaxf, Nxax, xaxor]
     7538    yaxis = [ystyl, yaxf, Nyax, yaxor]
     7539
     7540    # Legend
     7541    legloc, legsiz = drw.legend_values(legvalues,'|')
     7542
     7543    drw.plot_time_lag(prevalues, futvalues, timevalues, xaxis, yaxis, axeskind,      \
     7544      preaxislab, futaxislab, preunits, futunits, prerng, futrng, figlagkind, labels,\
     7545      timen, timepos, timelabels, graphtit, legloc, legsiz, kindfig, fign, close)
     7546
     7547    return
    72517548
    72527549#quit()
     
    72737570  'draw_2D_shad_line', 'draw_2D_shad_line_time', 'draw_2lines', 'draw_2lines_time',  \
    72747571  'draw_bar', 'draw_bar_line', 'draw_bar_line_time', 'draw_bar_time', 'draw_lines',  \
    7275   'draw_lines_time', 'draw_points', 'draw_Taylor', 'draw_topo_geogrid_boxes',        \
     7572  'draw_lines_time', 'draw_points', 'draw_Taylor', 'draw_time_lag',                  \
     7573  'draw_topo_geogrid_boxes',                                                         \
    72767574  'draw_trajectories', 'draw_vals_trajectories', 'variable_values']
    72777575
     
    73627660    elif oper == 'draw_Taylor':
    73637661        draw_Taylor(opts.ncfile, opts.values, opts.varname)
     7662    elif oper == 'draw_time_lag':
     7663        draw_time_lag(opts.ncfile, opts.values)
    73647664    elif oper == 'draw_timeSeries':
    73657665        draw_timeSeries(opts.ncfile, opts.values, opts.varname)
Note: See TracChangeset for help on using the changeset viewer.