Changeset 1454 in lmdz_wrf


Ignore:
Timestamp:
Feb 20, 2017, 4:44:18 PM (8 years ago)
Author:
lfita
Message:

Improving `draw_vals_trajectories'

Location:
trunk/tools
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/drawing.py

    r1449 r1454  
    3434## e.g. # drawing.py -o draw_WindRose -S 'lon|7;lat|2:linepoint;multicoltime;time;auto;auto;auto;auto;exct,5,d;%m/%d;date!([DD]/[MM]):November!ERA-I!daily!mean!wind!at!850!hPa:png:cardinals:False:WindRose:True' -v u,v -f reg1_daymean_mon11_lev850_kmh.nc
    3535## e.g. # drawing.py -o draw_Taylor -f 'file0.nc@var,file1.nc@var,file2.nc@var,file3.nc@var' -S '$10.\sin(0.05t2\pi)$:x:8:k,b,r,g,#FFBB00:$10.25\sin(0.025+0.05t2\pi)$,$10.25\sin(0.025+0.05125t2\pi)$,$10.5\sin(0.05+0.05t2\pi)$,$10.\sin(0.05+0.0525t2\pi)$:legend,0,8:norm:sinus!Taylor!diagram:png:yes:True' -v reffile.nc,var
     36## e.g. # drawing.py -o draw_timeSeries -f ~/PY/ERAI_pl199501_131-132.nc -S 'lon|240,lat|120,time|-1,lev|0:Srange,Srange:ua:date|($[MM]^{[DD]}$):exct,15,d:$%m^{%d}$:January|1995|ERA-Interim|x-wind|at|i=240,|j=120,|k=0:ua:0|12:png:r:-:2:x:2:20:yes' -v var131,time
     37## e.g. # drawing.py -o draw_trajectories -f 'medic950116/control/trajectory.dat@-1@etudes/domains/WL_HyMeX_HighRes_C/geo_em.d01.nc#XLONG_M#XLAT_M@t-step|3600.|19950115000000,medic950116/wlmdza/trajectory.dat@-1@etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M@t-step|3600.|19950115000000,medic950116/wlmdzb/trajectory.dat@-1@etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M@t-step|3600.|19950115000000,medic950116/wlmdzb_cyc/trajectory.dat@-1@etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M@t-step|3600.|19950115000000' -S 'spaghetti_date@-@None@1@o@1@$%d^{%H}$@8@6@4@4|$WRF_{CRM}$,$LMDZ_{AR4.0}$,$LMDZ_{NPv3.1}$,$LMDZ_{NPv3.1b}$|15,28,26,39|medicane trajectories|png|cyl,i|0@8|yes' -v 'medic950116/obs/trajectory.dat,satellite,-1,0.9999998779E+03,t-step|1800.|19950115000000@auto'
     38
    3639
    3740## 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
     
    33323335      draw_timeSeries(filen, values, variable):
    33333336        filen= name of the file
    3334         values= [gvarname]:[timetit]:[tkind]:[timefmt]:[title]:[legvals]:[gkind]:[colorlines]:[pointtype]:[pointfreq]
     3337        values= [dimvalues]:[sminv],[smaxv]:[gvarname]:[timetit]:[tkind]:[timefmt]:[title]:[leglabs]:[legvals]:
     3338          [gkind]:[colorlines]:[typelines]:[widthlines]:[pointtype]:[pointfreq]:[figclose]
     3339        [dimvalues]= ',' separated list of [dimname]|[slice] no given dimension takes all values
     3340          [dimname]: name of dimension
     3341          [slice]: value to take for the given dimension
     3342            * [integer]: which value of the dimension
     3343            * -1: all along the dimension
     3344            * [beg]@[end]@[freq] slice from [beg] to [end] every [freq]
     3345            * -9: last value of the dimension
     3346       [sminv],[smaxv]: minimum and maximum value for the lines or one value for each extreme:
     3347          'Srange': for full range
     3348          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
     3349          'Saroundminmax@val': for min*val,max*val
     3350          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
     3351            percentile_(100-val)-median)
     3352          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
     3353          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
     3354          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
     3355             percentile_(100-val)-median)
    33353356        [gvarname]: name of the variable to appear in the graph
    33363357        [timetit]: title of the time axis (assumed x-axis, '|' for spaces)
     
    33413362              'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
    33423363              'l': milisecond
    3343         [timefmt]: format of the time labels
     3364        [timefmt]: format of the time labels (C-like)
    33443365        [title]: title of the graphic ('|' for spaces)
    3345         [legvals]=[locleg]|[fontsize]:
     3366        [leglabs]: ',' separated list of labels for the lines
     3367        [legvals]=[locleg]|[fontsize]: legend values
    33463368          [locleg]: location of the legend (0, autmoatic)
    33473369            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
     
    33503372          [fontsize]: font size for the legend (auto for 12)
    33513373        [gkind]: kind of graphical output
    3352         [colorlines]: ',' list of colors for the lines, None for automatic, single
     3374        [colorlines]: ',' list of colors for the lines, 'None' for automatic, single
    33533375          value all the same
    3354         [pointtype]: ',' list of type of points for the lines, None for automatic, single
     3376        [typelines]: ',' list of types for the lines, 'None' for automatic, single
     3377          value all the same
     3378        [widthlines]: ',' list of width for the lines, 'None' for automatic, single
     3379          value all the same
     3380        [pointtype]: ',' list of type of points for the lines, 'None' for automatic, single
     3381          value all the same
     3382        [pointsizee]: ',' list of size of points for the lines, 'None' for automatic, single
    33553383          value all the same
    33563384        [pointfreq]: frequency of point plotting, 'all' for all time steps
     3385        [figclose]: whether figure should be closed or not
    33573386      variables= [varname],[timename] names of variable and variable with times
    3358       draw_timeSeries('wrfout_d01_1979-12-01_00:00:00_bottom_top_B6-E6-I1_south_north_B3-E3-I1_west_east_B26-E26-I1.nc', 'dt_con:time|($[DD]^{[HH]}$):exct,12,h:$%d^{%H}$:time|evolution|at|-1|6|3|26:1:pdf', 'LDQCON,time')
    33593387    """
    33603388
     
    33663394        quit()
    33673395
    3368     expectargs = '[gvarname]:[timetit]:[tkind]:[timefmt]:[title]:' +                 \
    3369       '[locleg]:[gkind]:[colorlines]:[pointtype]:[pointfreq]'
     3396    expectargs= '[dimvalues]:[sminv],[smaxv]:[gvarname]:[timetit]:[tkind]:' +        \
     3397      '[timefmt]:[title]:[leglabs]:[legvals]:[gkind]:[colorlines]:[typelines]:' +    \
     3398      '[widthlines]:[pointtype]:[pointsize]:[pointfreq]:[figclose]'
    33703399 
    33713400    drw.check_arguments(fname,values,expectargs,':')
    33723401
    3373     gvarname = values.split(':')[0]
    3374     timetit = values.split(':')[1].replace('|',' ')
    3375     tkind = values.split(':')[2]
    3376     timefmt = values.split(':')[3]
    3377     title = values.split(':')[4].replace('|',' ')
    3378     locleg = int(values.split(':')[5])
    3379     gkind = values.split(':')[6]
    3380     colorlines = values.split(':')[7]
    3381     pointtype = values.split(':')[8]
    3382     pointfreq0 = values.split(':')[9]
     3402    dimvalues = values.split(':')[0]
     3403    sminmaxv = values.split(':')[1]
     3404    gvarname = gen.latex_text(values.split(':')[2])
     3405    timetit = values.split(':')[3].replace('|',' ')
     3406    tkind = values.split(':')[4]
     3407    timefmt = values.split(':')[5]
     3408    title = gen.latex_text(values.split(':')[6].replace('|',' '))
     3409    leglabs = gen.str_list(values.split(':')[7], ',')
     3410    legvals = values.split(':')[8]
     3411    gkind = values.split(':')[9]
     3412    colorlines = values.split(':')[10]
     3413    typelines = values.split(':')[11]
     3414    widthlines = values.split(':')[12]
     3415    pointtype = values.split(':')[13]
     3416    pointsize = values.split(':')[14]
     3417    pointfreq0 = values.split(':')[15]
     3418    figclose = gen.Str_Bool(values.split(':')[16])
    33833419   
    33843420    ncobj = NetCDFFile(filen, 'r')
     
    34023438    timeobj = ncobj.variables[timevar]
    34033439
    3404     dimt = len(timeobj[:])
     3440    # Slicing variables
     3441    dictslice = {}
     3442    for dnv in dimvalues.split(','):
     3443        dimn = dnv.split('|')[0]
     3444        dimv = dnv.split('|')[1]
     3445        if dimv.find(',') != -1:
     3446            dictslice[dimn] = list(np.array(dimv.split('@'), dtype=int))
     3447        else:
     3448            dictslice[dimn] = int(dimv)
     3449
     3450    slicet, ddt = ncvar.SliceVarDict(timeobj, dictslice)
     3451    timevals = timeobj[tuple(slicet)]
     3452    dimt = len(timevals)
     3453
     3454    varattrs = varobj.ncattrs()
     3455    if not gen.searchInlist(varattrs,'units'):
     3456        print '  ' + fname + ": variable '" + variable + "' does not have units !!"
     3457        print "    using name in figure to search for them in 'variable_values.dat'"
     3458        varvals = drw.variables_values(gvarname)
     3459        gunits = varvals[5]
     3460        print "   getting units of '" + gvarname + "' as: '" + gunits + "'"
     3461    else:
     3462        gunits = varobj.getncattr('units')
     3463    tunits = timeobj.getncattr('units')
     3464
     3465    slicev, ddv = ncvar.SliceVarDict(varobj, dictslice)
     3466    varvalues = varobj[tuple(slicev)]
     3467    matvarvals = np.array(varvalues)
     3468    if len(matvarvals.shape) != 1:
     3469        print errormsg
     3470        print '  ' + fname + ': wrong rank of values to plot!!'
     3471        print '    resultant values to plot have a shape:', matvarvals.shape,        \
     3472          'it mast be of rank 1D'
     3473        print '    provided slice:', slicev
     3474        quit(-1)
     3475
    34053476    varvals = np.zeros((2,dimt), dtype=np.float)
    3406 
    3407     gunits = varobj.getncattr('units')
    3408     tunits = timeobj.getncattr('units')
    3409 
    3410     varvals[0,:], valpot, newgunits, Spot = drw.pot_values(varobj[:].flatten(), gunits)
     3477    varvals[0,:], valpot, newgunits, Spot = drw.pot_values(varvalues.flatten(), gunits)
    34113478    varvals[1,:] = timeobj[:]
     3479
     3480    # Min/max values in plot
     3481    line_nx = []
     3482    if sminmaxv.split(',')[0][0:1] != 'S':
     3483        line_nx.append(np.float(sminmaxv.split(',')[0]))
     3484    else:
     3485        line_nx.append(sminmaxv.split(',')[0])
     3486
     3487    if sminmaxv.split(',')[1][0:1] != 'S':
     3488        line_nx.append(np.float(sminmaxv.split(',')[1]))
     3489    else:
     3490        line_nx.append(sminmaxv.split(',')[1])
    34123491
    34133492    tseriesvals = []
    34143493    tseriesvals.append(varvals)
    34153494
    3416     if colorlines == 'None':
    3417         collines = None
    3418     else:
    3419         collines = colorlines.split(',')
    3420     if pointtype == 'None':
    3421         pttype = None
    3422     else:
    3423         pttype = pointtype.split(',')
     3495    collines = gen.str_list(colorlines, ',')
     3496    typlines = gen.str_list(typelines, ',')
     3497    wdthlines = gen.str_list(widthlines, ',')
     3498    pttype = gen.str_list(pointtype, ',')
     3499    ptsize = gen.str_list(pointsize, ',')
    34243500
    34253501    if pointfreq0 == 'all':
     
    34283504        pointfreq = int(pointfreq0)
    34293505
    3430     drw.plot_TimeSeries(tseriesvals, Spot + drw.units_lunits(gunits), tunits,        \
    3431       'TimeSeries', gvarname, timetit, tkind, timefmt, title,                        \
    3432       gvarname.replace('_','\_'), locleg, gkind, collines, pttype, pointfreq)
     3506    locleg, sizleg = drw.legend_values(legvals, '|')
     3507
     3508    drw.plot_TimeSeries(tseriesvals, line_nx, Spot + gunits, tunits, 'TimeSeries',   \
     3509      gvarname,timetit, tkind, timefmt, title, leglabs, locleg, sizleg, gkind,       \
     3510      collines, typlines, pttype, wdthlines, ptsize, pointfreq, figclose)
    34333511
    34343512    return
     
    34383516def draw_trajectories(trjfilens, values, observations):
    34393517    """ Function to draw different trajectories at the same time
    3440     draw_trajectories(trjfilens, values, observations):
    3441       trjfilens= [filen]@[Tint]@[map] ',' separated list of files with trajectories,
     3518      Trajectories are readed from ASCII files with a pair of i,j grid points for each position of the trajectory
     3519        i,j couples of trajectories for all files are referred to a netcdf file with a respective projection
     3520      A complemtary file for observations is also added separately
     3521      trjfilens= [filen]@[Tint]@[map]@[Ttrj] ',' separated list of ASCII files with trajectories,
    34423522         time intervals and reference maps (first one will be used to plot)
    3443         [filen]: name of the file to use (lines with '#', not readed) as:
     3523        [filen]: name of the file to use (lines with '#', not readed) with values as:
    34443524          [t-step] [x] [y]
    3445         [Tint]: interval of time as [Tbeg]@[Tend] or -1 for all the interval
    3446         [map]: [file]#[lonname]#[latname]
    3447           [file]; with the [lon],[lat] matrices
    3448           [lonname],[latname]; names of the longitudes and latitudes variables
    3449       values=[leglabels]|[lonlatlims]|[title]|[graphk]|[mapkind]
     3525        [Tint]: interval of time-steps to get from the file as [Tbeg]@[Tend] or -1 for all the interval
     3526        [map]: [file]#[lonname]#[latname] common projection data
     3527          [file]; netcdf file with the [lon],[lat] projection for the trajectory
     3528          [lonname],[latname]; names of the longitudes and latitudes variables in [file]
     3529        [Ttrj]|[val1]|[val2]|[...|[valN]]: kind of associated time values to the trajectory
     3530          't-step'|[dtime]|[idate]: each line corresponds to a consecutive time-step with the same deltatime
     3531             [dtime]: length of time-step in seconds
     3532             [idate]: date of the first time-step (in [YYYY][MM][DD][HH][MI][SS] format)
     3533          'CF-step'|[units]|[refdate]: each line corresponds to a consecutive CF time-step
     3534             [units]: any of standard temporal CF units: weeks, days, hours, minutes, seconds, ...
     3535             [refdate]: reference date of the CF time-units
     3536          'fulldate': each line provides the correspondance date (in [YYYY][MM][DD][HH][MI][SS] format)
     3537      values= [plotkind]|[leglabels]|[lonlatlims]|[title]|[graphk]|[mapkind]|[legvals]|[figclose]
     3538        [plotkind],[val1],[...,[valN]]: kind of plot to generate
     3539          'spaghetti'@[trjltype]@[trjlcol]@[trjlwdth]@[trjptyp]@[trjpsiz]: line-marker for each trajectory
     3540            [trjltype]: ',' list of type of lines for each trajectory (single value same for all, 'None' for auto)
     3541            [trjlcol]: ',' list of color of lines for each trajectory (single value same for all, 'None' for auto)
     3542            [trjlwdth]: ',' list of width of lines for each trajectory (single value same for all, 'None' for auto)
     3543            [trjptyp]: ',' list of type of points for each trajectory (single value same for all, 'None' for auto)
     3544            [trjpsiz]: ',' list of size of points for each trajectory (single value same for all, 'None' for auto)
     3545          'spaghetti_date'@[trjltype]@[trjlcol]@[trjlwdth]@[trjptyp]@[trjpsiz]@[datefmt]@[datefontsize]
     3546              @[datefreq]@[xoffset]@[yoffset]: line-marker
     3547              for each trajectory with a given date format at each point
     3548            [trjltype]: ',' list of type of lines for each trajectory (single value same for all, 'None' for auto)
     3549            [trjlcol]: ',' list of color of lines for each trajectory (single value same for all, 'None' for auto)
     3550            [trjlwdth]: ',' list of width of lines for each trajectory (single value same for all, 'None' for auto)
     3551            [trjptyp]: ',' list of type of points for each trajectory (single value same for all, 'None' for auto)
     3552            [trjpsiz]: ',' list of size of points for each trajectory (single value same for all, 'None' for auto)
     3553            [datefmt]: format of the date to show (C-like mixed with LaTeX commands)
     3554            [datefontsize]: font-size of the time-labels
     3555            [datefreq]: frequency of time-labels
     3556            [xoffset]: x-axis offset in pixels of the time-lables respect trajectory
     3557            [yoffset]: y-axis offset in pixels of the time-lables respect trajectory
    34503558        [leglabels]: ',' separated list of names for the legend
    34513559        [lonlatlims]: ',' list of limits of the map [lonmin, latmin, lonmax, latmax] or None
    34523560        [title]: title of the plot ('!' for spaces)
    3453         [graphk]: kind of the graphic
     3561        [graphk]: kind of output of the graphic (png, pdf, ...)
    34543562        [mapkind]: drawing coastaline ([proj],[res]) or None
    34553563          [proj]: projection
     
    34623570             * 'h', high
    34633571             * 'f', full
    3464       obsevations= [obsfile],[obsname],[Tint],[null]
     3572        [legvals]=[locleg]@[fontsize]: legend values
     3573          [locleg]: location of the legend (0, autmoatic)
     3574            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
     3575            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
     3576            9: 'upper center', 10: 'center'
     3577          [fontsize]: font size for the legend (auto for 12)
     3578        [figclose]: whether figure should be closed or not
     3579      observations= [obsfile],[obsname],[Tint],[null],[obstrjvals] ('None' for no observational/reference trajectory)
    34653580        [obsfile]: name fo the File with the observations as [t-step] [lat] [lon]
    34663581        [obsname]: name of the observations in the graph
    34673582        [Tint]: interval of time as [Tbeg]@[Tend] or -1 for all the interval
    34683583        [null]: null value for the observed trajectory
     3584        [obstrjvals] = [Ttrj]@[obsltype]@[obslcol]@[obslwdth]@[obsptyp]@[obspsiz] values for the observational/reference
     3585          trajectory in the plot
     3586             [Ttrj]|[val1]|[val2]|[...|[valN]]: kind of associated time values to the trajectory
     3587              't-step'|[dtime]|[idate]: each line corresponds to a consecutive time-step with the same deltatime
     3588                 [dtime]: length of time-step in seconds
     3589                 [idate]: date of the first time-step (in [YYYY][MM][DD][HH][MI][SS] format)
     3590              'CF-step'|[units]|[refdate]: each line corresponds to a consecutive CF time-step
     3591                 [units]: any of standard temporal CF units: weeks, days, hours, minutes, seconds, ...
     3592                 [refdate]: reference date of the CF time-units
     3593              'fulldate': each line provides the correspondance date (in [YYYY][MM][DD][HH][MI][SS] format)
     3594            [obsltype]: type of line for the observations/reference trajectory (single 'auto' for '-', 'k', 2, 'x', 2)
     3595            [obslcol]: color of line for the observations/reference trajectory
     3596            [obslwdth]: width of line for the observations/reference trajectory
     3597            [obsptyp]: type of point for the observations/reference trajectory
     3598            [obspsiz]: size of point for the observations/reference trajectory
    34693599    """
    3470 
     3600    import datetime as dt
    34713601    fname = 'draw_trajectories'
    34723602
     
    34763606        quit()
    34773607
    3478     expectargs = '[leglabels]|[lonlatlims]|[title]|[graphk]|[mapkind]'
    3479  
     3608    expectargs = '[plotkind]|[leglabels]|[lonlatlims]|[title]|[graphk]|[mapkind]|' + \
     3609      '[legvals]|[figclose]'
    34803610    drw.check_arguments(fname,values,expectargs,'|')
    34813611
     3612    expectargs = '[obsfile],[obsname],[Tint],[null],[obstrjvals]'
     3613    drw.check_arguments('obstraj',observations,expectargs,',')
     3614
    34823615    trjfiles = trjfilens.split(',')
    3483     leglabels = values.split('|')[0]
    3484     lonlatlims = values.split('|')[1]
    3485     title = values.split('|')[2].replace('!',' ')
    3486     graphk = values.split('|')[3]
    3487     mapkind = values.split('|')[4]
     3616    plotkind = values.split('|')[0]
     3617    leglabels = values.split('|')[1]
     3618    lonlatlims = values.split('|')[2]
     3619    title = gen.latex_text(values.split('|')[3].replace('!',' '))
     3620    graphk = values.split('|')[4]
     3621    mapkind = values.split('|')[5]
     3622    legvals = values.split('|')[6]
     3623    figclose = gen.Str_Bool(values.split('|')[7])
    34883624
    34893625    Nfiles = len(trjfiles)
     3626
     3627    # plot kind
     3628    plotkindv = plotkind.split('@')
     3629    if plotkindv[0] == 'spaghetti':
     3630        expectargs = 'spaghetti@[trjltype]@[trjlcol]@[trjlwdth]@[trjptyp]@[trjpsiz]'
     3631        drw.check_arguments(plotkindv[0],plotkind,expectargs,'@')
     3632
     3633        trjltype = gen.str_list(plotkindv[1], ',')
     3634        trjlcol = gen.str_list(plotkindv[2], ',')
     3635        trjlwdth = gen.str_list(plotkindv[3], ',')
     3636        trjptyp = gen.str_list(plotkindv[4], ',')
     3637        trjpsiz = gen.str_list(plotkindv[5], ',')
     3638    elif plotkindv[0] == 'spaghetti_date':
     3639        expectargs = 'spaghetti_date@[trjltype]@[trjlcol]@[trjlwdth]@[trjptyp]@' +   \
     3640          '[trjpsiz]@[datefmt]@[datefontsize]@[datefreq]@[xoffset]@[yoffset]'
     3641        drw.check_arguments(plotkindv[0],plotkind,expectargs,'@')
     3642
     3643        trjltype = gen.str_list(plotkindv[1], ',')
     3644        trjlcol = gen.str_list(plotkindv[2], ',')
     3645        trjlwdth = gen.str_list(plotkindv[3], ',')
     3646        trjptyp = gen.str_list(plotkindv[4], ',')
     3647        trjpsiz = gen.str_list(plotkindv[5], ',')
     3648        datefmt = gen.str_list(plotkindv[6], ',')
     3649        datefsize = gen.str_list(plotkindv[7], ',')
     3650        datefreq = int(plotkindv[8])
     3651        xoffset = int(plotkindv[9])
     3652        yoffset = int(plotkindv[10])
     3653    else:
     3654        print errormsg
     3655        print '  ' + fname + ": kind of plot '" + plotkindv[0] + "' not ready !!"
     3656        print '    accepted ones:', ['spaghetti', 'spaghetti_date']
     3657        quit(-1)
    34903658
    34913659# Getting trajectotries
    34923660##
    3493 
    34943661    lontrjvalues = []
    34953662    lattrjvalues = []
    3496 
    3497     print '  ' + fname
     3663    timetrjvalues = []
     3664
    34983665    ifn = 0
    34993666    for ifile in trjfiles:
     
    35013668        Tint = ifile.split('@')[1]
    35023669
    3503         print '    trajectory:',filen
     3670        if not os.path.isfile(filen):
     3671            print errormsg
     3672            print '  ' + fname + ": trajectory file '" + filen + "' does not exist !!"
     3673            quit(-1)
     3674
     3675        print '    ', ifn+1, "trajectory'" + filen + "'"
    35043676
    35053677        if Tint != '-1':
     
    35073679            Tend = ifile.split('@')[2]
    35083680            mapv = ifile.split('@')[3]
     3681            Tkind = ifile.split('@')[4]
    35093682        else:
    35103683            mapv = ifile.split('@')[2]
    3511 
    3512         if not os.path.isfile(filen):
    3513             print errormsg
    3514             print '  ' + fname + ": trajectory file '" + filen + "' does not exist !!"
    3515             quit(-1)
     3684            Tkind = ifile.split('@')[3]
    35163685
    35173686# Charging longitude and latitude values
     
    35363705        objfile.close()
    35373706
     3707        #Time-values
     3708        Tkindv = Tkind.split('|')
     3709        datesTtrj = []
     3710        if Tkindv[0] == 'CF-step':
     3711            tunits = Tkindv[1]
     3712            refdate = Tkindv[2]
     3713
     3714            if tunits == 'weeks': dtime = tunis*7.*24.*3600.
     3715            elif tunits == 'days': dtime = tunis*24.*3600.
     3716            elif tunits == 'hours': dtime = tunis*3600.
     3717            elif tunits == 'minutes': dtime = tunis*60.
     3718            elif tunits == 'seconds': dtime = tunis
     3719            else:
     3720                print erromsg
     3721                print ' '+ fname + ": time-units of CF time-trajectory '" + tunits + \
     3722                  "' not ready !!"
     3723                print '    available ones:', ['weeks', 'days', 'hours', 'minutes',   \
     3724                  'seconds']
     3725                quit(-1)
     3726            refdateT = gen.DateTimeStr_date(refdate)
     3727            for it in trjtimev:
     3728                datesTtrj.append(refdateT + dt.timedelta(seconds=it))
     3729        elif Tkindv[0] == 'fulldate':
     3730            for it in trjtimev:
     3731                datesTtrj.append(gen.DateTimeStr_date(it))           
     3732        elif Tkindv[0] == 't-step':
     3733            dtime = np.float(Tkindv[1])
     3734            idate = Tkindv[2]
     3735            print '  ' + fname + ': idate:', idate
     3736            refdateT = gen.DateTimeStr_date(idate)
     3737            for it in range(len(trjtimev)):
     3738                datesTtrj.append(refdateT + dt.timedelta(seconds=dtime*it))
     3739        else:
     3740            print errormsg
     3741            print '  ' +fname+ ": associated time kind of trajectory '" + Tkind[0] + \
     3742              "' not ready!!"
     3743            print '    accepted ones:', ['t-step', 'CF-step']
     3744
    35383745        if Tint != '-1':
    35393746            lontrjvalues.append(lonvals[trjyv[Tint:Tend+1], trjxv[Tint:Tend+1]])
    35403747            lattrjvalues.append(latvals[trjyv[Tint:Tend+1], trjxv[Tint:Tend+1]])
     3748            timetrjvalues.append(datesTtrj[Tint:Tend+1])
    35413749        else:
    35423750            lontrjvalues.append(lonvals[trjyv[:], trjxv[:]])
    35433751            lattrjvalues.append(latvals[trjyv[:], trjxv[:]])
     3752            timetrjvalues.append(datesTtrj[:])
    35443753
    35453754# lonlatlimits
     
    35753784        Tint = observations.split(',')[2]
    35763785        null = np.float(observations.split(',')[3])
    3577         print '    observational trajectory:',obsfile
     3786        obstrajvals = observations.split(',')[4]
    35783787
    35793788        if not os.path.isfile(obsfile):
     
    35823791              "' does not exist !!"
    35833792            quit(-1)
     3793
     3794        print '  ' + fname + ": observational trajectory in file: '" + obsfile + "'"
    35843795
    35853796        objfile = open(obsfile, 'r')
     
    35973808                    obstrjyv.append(lat)
    35983809                else:
    3599                     obstrjtimev.append(int(line.split(' ')[0]))
     3810                    obstrjtimev.append(None)
    36003811                    obstrjxv.append(None)
    36013812                    obstrjyv.append(None)
    36023813
    36033814        objfile.close()
     3815        #Time-values
     3816        Tkind = obstrajvals.split('@')[0]
     3817
     3818        Tkindv = Tkind.split('|')
     3819        datesTtrj = []
     3820        if Tkindv[0] == 'CF-step':
     3821            tunits = Tkindv[1]
     3822            refdate = Tkindv[2]
     3823
     3824            if tunits == 'weeks': dtime = tunis*7.*24.*3600.
     3825            elif tunits == 'days': dtime = tunis*24.*3600.
     3826            elif tunits == 'hours': dtime = tunis*3600.
     3827            elif tunits == 'minutes': dtime = tunis*60.
     3828            elif tunits == 'seconds': dtime = tunis
     3829            else:
     3830                print erromsg
     3831                print ' '+ fname + ": time-units of CF time-trajectory '" + tunits + \
     3832                  "' not ready !!"
     3833                print '    available ones:', ['weeks', 'days', 'hours', 'minutes',   \
     3834                  'seconds']
     3835                quit(-1)
     3836            refdateT = gen.DateTimeStr_date(refdate)
     3837            for it in obstrjtimev:
     3838                datesTtrj.append(refdateT + dt.timedelta(seconds=it))
     3839        elif Tkindv[0] == 'fulldate':
     3840            for it in obstrjtimev:
     3841                datesTtrj.append(gen.DateTimeStr_date(it))     
     3842        elif Tkindv[0] == 't-step':
     3843            dtime = np.float(Tkindv[1])
     3844            idate = Tkindv[2]
     3845            refdateT = gen.DateTimeStr_date(idate)
     3846            for it in range(len(obstrjtimev)):
     3847                datesTtrj.append(refdateT + dt.timedelta(seconds=dtime*it))
     3848        else:
     3849            print errormsg
     3850            print '  ' +fname+ ": associated time kind of trajectory '" + Tkindv[0]+ \
     3851              "' not ready!!"
     3852            print '    accepted ones:', ['t-step', 'CF-step']
     3853
     3854        # Parameters observational/reference trajectory
     3855        obslv = obstrajvals.split('@')[1:6]
     3856        if obslv[0] == 'auto':
     3857            obslt = '-'
     3858            obslc = 'k'
     3859            obslw = '2'
     3860            obspt = 'x'
     3861            obsps = '2'
     3862        else:
     3863            obslt = obslv[0]
     3864            obslc = obslv[1]
     3865            obslw = np.float(obslv[2])
     3866            obspt = obslv[3]
     3867            obsps = np.float(obslv[4])
    36043868
    36053869        if Tint != '-1':
     
    36083872            lontrjvalues.append(obstrjxv[Tint:Tend+1])
    36093873            lattrjvalues.append(obstrjyv[Tint:Tend+1])
     3874            timetrjvalues.append(datesTtrj[Tint:Tend+1])
    36103875        else:
    36113876            lontrjvalues.append(obstrjxv[:])
    36123877            lattrjvalues.append(obstrjyv[:])
    3613 
    3614     drw.plot_Trajectories(lontrjvalues, lattrjvalues, leglabels.split(','),          \
    3615       lonobj, latobj, lonlatlimsv, title, graphk, mapkindv, obsname)
     3878            timetrjvalues.append(datesTtrj[:])
     3879
     3880    locleg, sizleg = drw.legend_values(legvals, '@')
     3881
     3882    drw.plot_Trajectories(lontrjvalues, lattrjvalues, timetrjvalues, plotkindv,      \
     3883      leglabels.split(','), trjltype, trjlcol, trjlwdth, trjptyp, trjpsiz, lonobj,   \
     3884      latobj, [obslt, obslc, obslw, obspt, obsps], lonlatlimsv, title, graphk,       \
     3885      mapkindv, obsname, locleg, sizleg, figclose)
    36163886
    36173887    objnc.close()
     
    36233893      draw_vals_trajectories(ncfile, values, variable)
    36243894      ncfile= [ncfile] ',' list of files to use
    3625       values= [statisticskind]:[Tint]:[labels]@[legvals]:[gvarname]:[timetit]:[tkind]:[timefmt]:[title]:[gkind]
     3895      values= [statisticskind]:[sminv],[smaxv]:[Tint]:[labels]:[legvals]:[gvarname]:[timetit]:[tkind]:
     3896          [timefmt]:[title]:[gkind]:[colorlines]:[typelines]:[widthlines]:[pointtype]:[pointsizee]:[pointfreq]:[figclose]
    36263897        [statisticskind]=[statistics][kind]
    36273898          [statistics]: which statistics to use, from: 'center', 'min', 'max', 'mean',
     
    36293900          [kind]: 'box', 'circle' statistics taking the values from a box or a circle
    36303901            'trj': value following the trajectory
     3902        [sminv],[smaxv]: minimum and maximum value for the lines or one value for each extreme:
     3903          'Srange': for full range
     3904          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
     3905          'Saroundminmax@val': for min*val,max*val
     3906          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
     3907            percentile_(100-val)-median)
     3908          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
     3909          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
     3910          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
     3911             percentile_(100-val)-median)
    36313912        [Tint]: [Tbeg]@[Tend] or None, interval of time to plot or -1 for all the times
    3632         [labels]: ',' separated list of labels for the legend
     3913        [leglabels]: ',' separated list of labels for the legend
    36333914        [legvals]=[locleg]|[fontsize]:
    36343915          [locleg]: location of the legend (0, autmoatic)
     
    36483929        [title]: title of the graphic ('|' for spaces)
    36493930        [gkind]: kind of graphical output
     3931        [colorlines]: ',' list of colors for the lines, 'None' for automatic, single
     3932          value all the same
     3933        [typelines]: ',' list of types for the lines, 'None' for automatic, single
     3934          value all the same
     3935        [widthlines]: ',' list of width for the lines, 'None' for automatic, single
     3936          value all the same
     3937        [pointtype]: ',' list of type of points for the lines, 'None' for automatic, single
     3938          value all the same
     3939        [pointsizee]: ',' list of size of points for the lines, 'None' for automatic, single
     3940          value all the same
     3941        [pointfreq]: frequency of point plotting, 'all' for all time steps
     3942        [figclose]: whether figure should be close or not
    36503943      variable= variable to use
    36513944    """
     
    36573950        quit()
    36583951
     3952    expectargs = '[statisticskind]:[sminv],[smaxv]:[Tint]:[leglabels]:[legvals]:' +  \
     3953      '[gvarname]:[timetit]:[tkind]:[timefmt]:[title]:[gkind]:[colorlines]:' +       \
     3954      '[typelines]:[widthlines]:[pointtype]:[pointsizee]:[pointfreq]:[figclose]'
     3955    drw.check_arguments(fname,values,expectargs,':')
     3956
    36593957    sims = ncfile.split(',')
    36603958
    3661     if len(values.split(':')) != 9:
    3662         print errormsg
    3663         print '  ' + fname  + ': wrong number of values!', len(values.split(':')),   \
    3664           'given 9 needed!!'
    3665         print '    ',values.split(':')
    3666         quit(-1)
    3667 
    36683959    statisticskind = values.split(':')[0]
    3669     Tint = values.split(':')[1]
    3670     labels = values.split(':')[2]
    3671     gvarname = values.split(':')[3]
    3672     timetit = values.split(':')[4].replace('|',' ')
    3673     tkind = values.split(':')[5]
    3674     timefmt = values.split(':')[6]
    3675     title = values.split(':')[7].replace('|',' ')
    3676     gkind = values.split(':')[8]
    3677 
    3678     leglabels = labels.split('@')[0].split(',')
    3679     locleg = int(labels.split('@')[1])
     3960    sminmaxv = values.split(':')[1]
     3961    Tint = values.split(':')[2]
     3962    leglabels = values.split(':')[3].split(',')
     3963    legvals = values.split(':')[4]
     3964    gvarname = values.split(':')[5]
     3965    timetit = values.split(':')[6].replace('|',' ')
     3966    tkind = values.split(':')[7]
     3967    timefmt = values.split(':')[8]
     3968    title = values.split(':')[9].replace('|',' ')
     3969    gkind = values.split(':')[10]
     3970    colorlines = values.split(':')[11]
     3971    typelines = values.split(':')[12]
     3972    widthlines = values.split(':')[13]
     3973    pointtype = values.split(':')[14]
     3974    pointsize = values.split(':')[15]
     3975    pointfreq0 = values.split(':')[16]
     3976    figclose = gen.Str_Bool(values.split(':')[17])
    36803977
    36813978    Nsims = len(sims)
     
    37514048        trjobj.close()
    37524049
    3753     drw.plot_TimeSeries(vartimetrjv, drw.units_lunits(gunits), tunits,               \
    3754       'val_trajectories_' + statisticskind, gvarname, timetit, tkind, timefmt, title,\
    3755       leglabels, locleg, gkind)
     4050    # Min/max values in plot
     4051    line_nx = []
     4052    if sminmaxv.split(',')[0][0:1] != 'S':
     4053        line_nx.append(np.float(sminmaxv.split(',')[0]))
     4054    else:
     4055        line_nx.append(sminmaxv.split(',')[0])
     4056
     4057    if sminmaxv.split(',')[1][0:1] != 'S':
     4058        line_nx.append(np.float(sminmaxv.split(',')[1]))
     4059    else:
     4060        line_nx.append(sminmaxv.split(',')[1])
     4061
     4062    locleg, fsizeleg = drw.legend_values(legvals, '|')
     4063
     4064    collines = gen.str_list(colorlines, ',')
     4065    typlines = gen.str_list(typelines, ',')
     4066    wdthlines = gen.str_list(widthlines, ',')
     4067    pttype = gen.str_list(pointtype, ',')
     4068    ptsize = gen.str_list(pointsize, ',')
     4069
     4070    if pointfreq0 == 'all':
     4071        pointfreq = None
     4072    else:
     4073        pointfreq = int(pointfreq0)
     4074
     4075    figname = 'val_trajectories_' + statisticskind
     4076
     4077    drw.plot_TimeSeries(vartimetrjv, line_nx, gunits, tunits, figname, gvarname,     \
     4078      timetit, tkind, timefmt, title, leglabels, locleg, fsizeleg, gkind,            \
     4079      collines, typlines, pttype, wdthlines, ptsize, pointfreq, figclose)
     4080
     4081    return
    37564082
    37574083def variable_values(values):
  • trunk/tools/drawing_tools.py

    r1449 r1454  
    6262# lonlat_values:
    6363# date_CFtime:
    64 # pot_values:
     64# pot_values: Function to modify a seies of values by their potency of 10
    6565# CFtimes_plot:
    6666# color_lines:
     
    7575# plot_2D_shadow:
    7676# plot_2D_shadow_time: Plotting a 2D field with one of the axes being time
    77 # plot_Neighbourghood_evol:Plotting neighbourghood evolution# plot_Trajectories
     77# plot_Neighbourghood_evol:Plotting neighbourghood evolution
     78# plot_Trajectories
    7879# plot_2D_shadow_contour:
    7980# plot_2D_shadow_contour_time:
     
    21972198    fname = 'CFtimes_plot'
    21982199
    2199     if timev == 'h':
     2200    if type(timev) == type('S') and timev == 'h':
    22002201        print fname + '_____________________________________________________________'
    22012202        print CFtimes_plot.__doc__
     
    22832284
    22842285    firstT = timev[0]
     2286    secondT = timev[1]
    22852287    lastT = timev[dtv-1]
    22862288
    22872289# First and last times as datetime objects
    22882290    firstTdt = timeref_datetime(refdate, firstT, trefunits)
     2291    secondTdt = timeref_datetime(refdate, secondT, trefunits)
    22892292    lastTdt = timeref_datetime(refdate, lastT, trefunits)
     2293
     2294    # Difference between second and first time-step
     2295    dt12 = secondTdt - firstTdt
     2296    if searchInlist(dir(dt12), 'total_seconds'):
     2297        diff12 = dt12.total_seconds()
     2298    else:
     2299        diff12 = dt12.days*24.*3600. + dt12.seconds
    22902300
    22912301# First and last times as [year, mon, day, hour, minut, second] vectors
     
    25332543#        print it,':',timeoutv[it], timeoutS[it]
    25342544
    2535     if len(timeoutv) < 1 or len(timeoutS) < 1:
     2545    if len(timeoutv) <= 1 or len(timeoutS) <= 1:
    25362546        print errormsg
    2537         print '  ' + fname + ': no time values are generated!'
    2538         print '    values passed:',timev
     2547        print '  ' + fname + ": no `time-labels' values are generated !!"
     2548        print '    passed configuration does not conform time-data'
     2549        print '  input data:'
     2550        print '    number of values passed:', len(timev)
    25392551        print '    units:',units
    2540         print '    desired kind:',kind
     2552        print '  desired output:'
     2553        print '    kind of labels:',kind
    25412554        print '    format:',tfmt
    2542         print '    function values ___ __ _'
    2543         print '      reference date:',refdate
    2544         print '      first date:',firstTdt
    2545         print '      last date:',lastTdt
    2546         print '      increment:',basedt,trefunits
    2547 
     2555        print '  function values ___ __ _'
     2556        print '    time reference date:',refdate
     2557        print '    first date in input data:',firstTdt
     2558        print '    last date in input data:',lastTdt
     2559        print '    period in input data:', lastTdt - firstTdt
     2560        print '    time difference between first and second time-step:', dt12,       \
     2561          '==>', diff12, 'seconds'
     2562        print '  Provide new parameters in order to obtain time-labels'
    25482563        quit(-1)
    25492564
     
    26872702
    26882703    rangegrph = np.zeros((2), dtype=np.float)
     2704
    26892705# Changing limits of the colors
    26902706    if type(vrng[0]) == type('S') and vrng[0][0:1] == 'S':
     
    27422758            print '  ' + fname + ": range '" + vrng[0] + "' not ready!!!"
    27432759            quit(-1)
    2744         print '    ' + fname + ': modified shadow min,max:',rangegrph
     2760        print '    ' + fname + ': modified min,max:',rangegrph
    27452761    else:
    27462762        rangegrph[0] = np.float(vrng[0])
     
    28072823####### ###### ##### #### ### ## # END of GENERIC functions
    28082824
    2809 def plot_TimeSeries(valtimes, vunits, tunits, hfileout, vtit, ttit, tkind, tformat,  \
    2810   tit, linesn, lloc, kfig,coll,ptl,ptf):
     2825def plot_TimeSeries(valtimes, lnx, vunits, tunits, hfileout, vtit, ttit, tkind,      \
     2826  tformat, tit, linesn, lloc, lsiz, kfig, coll, typl, ptl, wdtl, ptz, ptf, fclose):
    28112827    """ Function to draw time-series
    28122828      valtimes= list of arrays to plot [vals1[1values, 1times], [...,valsM[Mvals,Mtimes]])
     2829      lnx: list with the minimum and maximum values
    28132830      vunits= units of the values
    28142831      tunits= units of the times
     
    28292846        5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
    28302847        9: 'upper center', 10: 'center'
    2831       kfig= type of figure: jpg, png, pds, ps
    2832       coll= ',' list of colors for the lines, None for automatic, single
     2848      lsiz= font size of the legend
     2849      kfig= type of figure: jpg, png, pdf, ps
     2850      coll= ',' list of colors for the lines, 'None' for automatic, single
    28332851          value all the same
    2834       ptl= ',' list of type of points for the lines, None for automatic, single
     2852      typl= ',' list of type for the lines, 'None' for automatic, single
     2853          value all the same
     2854      ptl= ',' list of type of points for the lines, 'None' for automatic, single
     2855          value all the same
     2856      wdtl= ',' list of width for the lines, 'None' for automatic, single
     2857          value all the same
     2858      ptz= ',' list of size of points for the lines, 'None' for automatic, single
    28352859          value all the same
    28362860      ptf= frequency of point plotting, 'all' for all time steps
     2861      fclose= whether figure has to be closed or not
    28372862    """
    28382863    fname = 'plot_TimeSeries'
     
    28442869
    28452870    Nlines = len(valtimes)
    2846 # Canging line kinds every 7 lines (end of standard colors)
    2847     Npts = len(pointkindsauto)
    2848     linekinds = []
    2849     pointkinds = []
    2850     if ptl is None:
    2851         if ptf is None:
    2852             for ptype in range(Npts):
    2853                 for ip in range(7):
    2854                     linekinds.append(pointkindsauto[ptype] + '-')
    2855         else:
    2856             for ptype in range(Npts):
    2857                 for ip in range(7):
    2858                     linekinds.append('-')
    2859                     pointkinds.append(pointkindsauto[ptype])
    2860     else:
    2861         if ptf is None:
    2862             if len(ptl) > 1:
    2863                for pt in ptl:
    2864                     linekinds.append(pt + '-')
    2865             else:
    2866                 for il in range(Nlines):
    2867                     linekinds.append(ptl+'-')
    2868         else:
    2869             if len(ptl) > 1:
    2870                for pt in ptl:
    2871                     linekinds.append('-')
    2872                     pointkinds.append(pt)
    2873             else:
    2874                 for il in range(Nlines):
    2875                     linekinds.append('-')
    2876                 pointkinds = ptl
     2871
     2872    # Lines' characteristics
     2873    cols, lins, pts, lws, pss = ColorsLinesPointsStyles(Nlines, coll, typl, ptl, wdtl, ptz, ptf)
    28772874
    28782875    Nvalues = []
    28792876    Ntimes = []
    28802877
     2878    totvals = []
    28812879    for il in range(Nlines):
    28822880        array = valtimes[il]
     2881        totvals = totvals + list(array[0,:])
    28832882
    28842883        if Nlines == 1:
     
    29112910            if vmax > ymax: ymax = vmax
    29122911
     2912    # Changing limits of the plot
     2913    vsend = graphic_range(lnx, np.array(totvals))
     2914
    29132915    dx = np.max(Ntimes)
    29142916    dy = np.min(Nvalues)
     
    29162918    plt.rc('text', usetex=True)
    29172919
    2918     print vtit
    29192920    if vtit == 'ps':
    29202921        plt.ylim(98000.,ymax)
    29212922    else:
    2922         plt.ylim(ymin,ymax)
     2923        plt.ylim(vsend[0],vsend[1])
    29232924
    29242925    plt.xlim(xmin,xmax)
    2925 #    print 'x lim:',xmin,xmax
    2926 #    print 'y lim:',ymin,ymax
    2927 
    2928     N7lines=0
     2926
    29292927    for il in range(Nlines):
    29302928        array = valtimes[il]
     
    29322930            array[0,:] = np.where(array[0,:] < 98000., None, array[0,:])
    29332931
    2934         if ptf is None:
    2935             if coll is None:
    2936                 if ptf is None:
    2937                     plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il])
    2938                 else:
    2939                     plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il])
    2940                     plt.plot(array[1,::ptf],array[0,::ptf], pointkinds[il],          \
    2941                       label=linesn[il])
    2942             else:
    2943                 if ptf is None:
    2944                     plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il], \
    2945                       color=coll[il])
    2946                 else:
    2947                     plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il], \
    2948                       color=coll[il])
    2949                     plt.plot(array[1,::ptf],array[0,::ptf], pointkinds[il],          \
    2950                       label=linesn[il], color=coll[il])
    2951         else:
    2952             if coll is None:
    2953                 if ptf is None:
    2954                     plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il])
    2955                 else:
    2956                     plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il])
    2957                     plt.plot(array[1,::ptf],array[0,::ptf], pointkinds[il],          \
    2958                       label=linesn[il])
    2959             else:
    2960                 if ptf is None:
    2961                     plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il], \
    2962                       color=coll[il])
    2963                 else:
    2964                     plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il], \
    2965                       color=coll[il])
    2966                     plt.plot(array[1,::ptf],array[0,::ptf], pointkinds[il],          \
    2967                       label=linesn[il], color=coll[il])
     2932#        plt.plot(array[1,:],array[0,:], lins[il], label=gen.latex_text(linesn[il]))
     2933#        plt.plot(array[1,::ptf],array[0,::ptf], pointkinds[il],          \
     2934#          label=gen.latex_text(linesn[il]))
     2935        plt.plot(array[1,:], array[0,:], lins[il], marker=pts[il], color=cols[il],   \
     2936          label=gen.latex_text(linesn[il]), linewidth=lws[il], markersize=pss[il],   \
     2937          markevery=ptf)
    29682938
    29692939    timevals = np.arange(xmin,xmax)*1.
     
    29782948#    plt.Axes.set_xticklabels(tlabels)
    29792949
    2980 
    2981     plt.legend(loc=lloc)
     2950    plt.legend(loc=lloc, prop={'size':lsiz})
    29822951    plt.xlabel(ttit)
    2983     plt.ylabel(vtit + " (" + vunits + ")")
    2984     plt.title(tit.replace('_','\_').replace('&','\&'))
     2952    plt.ylabel(gen.latex_text(vtit) + " (" + units_lunits(vunits) + ")")
     2953    plt.title(tit)
    29852954
    29862955    figname = hfileout + '_' + vtit
    29872956   
    2988     output_kind(kfig, figname, True)
     2957    output_kind(kfig, figname, fclose)
    29892958
    29902959    return
     
    32773246#            print iv,xval[iv],yval[iv],labels[iv],ptkinds[N7pts]
    32783247            plt.plot(xval[iv],yval[iv], ptk, markersize=pts,                         \
    3279               gen.latex_text(label=labels[iv]))
     3248              label=gen.latex_text(labels[iv]))
    32803249
    32813250        if figk[0:8] == 'labelled':
     
    35663535    return
    35673536
    3568 def plot_Trajectories(lonval, latval, linesn, olon, olat, lonlatLims, gtit, kfig,    \
    3569   mapv, obsname):
     3537def plot_Trajectories(lonval, latval, timeval, plotk, linesn, trjlt, trjlc, trjlw,   \
     3538  trjpt, trjps, olon, olat, obstrjv, lonlatLims, gtit, kfig, mapv, obsname, lleg,    \
     3539  sleg, close):
    35703540    """ plotting Trajectories
    35713541      [lon/latval]= lon,lat values to plot (as list of vectors)
    3572       linesn: name of the lines
     3542      timeval= time values to plot (if required, as list of vectors)
     3543      plotk= kind of plot: 'spaghetti', 'spaghetti_date'
     3544      linesn= name of the lines
     3545      trjlt= ',' list of type of lines for each trajectory (single value for all trajetories with the same)
     3546      trjlc= ',' list of color of lines for each trajectory (single value for all trajetories with the same)
     3547      trjlw= ',' list of width of lines for each trajectory (single value for all trajetories with the same)
     3548      trjpt= ',' list of type of points for each trajectory (single value for all trajetories with the same)
     3549      trjps= ',' list of size of points for each trajectory (single value for all trajetories with the same)
    35733550      o[lon/lat]= object with the longitudes and the latitudes of the map to plot
     3551      obstrjv: values for the line of the observations/trajectory
    35743552      lonlatLims: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax]
    35753553      gtit= title of the graph
     
    35883566      obsname= name of the observations in graph (can be None for without).
    35893567        Observational trajectory would be the last one
     3568      lleg= location of the legend
     3569      sleg= fontsize of the legend
     3570      close= whether figure should be closed or not
    35903571    """
    35913572    fname = 'plot_Trajectories'
     
    35963577        quit()
    35973578
    3598 # Canging line kinds every 7 lines (end of standard colors)
    3599     linekinds=['.-','x-','o-']
    3600 
    36013579    Ntraj = len(lonval)
    3602 
    36033580    if obsname is not None:
    36043581        Ntraj = Ntraj - 1
    36053582
    3606     N7lines = 0
     3583    if Ntraj != len(linesn):
     3584        print errormsg
     3585        print '  '+fname+': number of trajectories:', Ntraj, 'and number of labels:',\
     3586          len(linesn), 'differ !!'
     3587        print '    provided labels:', linesn
     3588        quit(-1)
     3589
     3590    cols, lins, pts, lws, pss = ColorsLinesPointsStyles(Ntraj, trjlc, trjlt, trjpt,  \
     3591      trjlw, trjps, 'all')
    36073592
    36083593    plt.rc('text', usetex=True)
     
    36353620        dy = lon0.shape[0]
    36363621
    3637         nlon = lon0[0,0]
    3638         xlon = lon0[dy-1,dx-1]
    3639         nlat = lat0[0,0]
    3640         xlat = lat0[dy-1,dx-1]
     3622        nlon = np.min(lon0)
     3623        xlon = np.max(lon0)
     3624        nlat = np.min(lat0)
     3625        xlat = np.max(lat0)
    36413626
    36423627        lon2 = lon0[dy/2,dx/2]
     
    36773662#            print '  ' + fname + ': shapes of lon/lat objects', olon.shape,          \
    36783663#              'not ready!!!'
    3679 
    3680         for il in range(Ntraj):
    3681             plt.plot(lonval[il], latval[il], linekinds[N7lines], label= linesn[il])
    3682             if il == 6: N7lines = N7lines + 1
    36833664
    36843665        m.drawcoastlines()
     
    37143695            plt.ylim(np.min(olat[:]),np.max(olat[:]))
    37153696
    3716         for il in range(Ntraj):
    3717             plt.plot(lonval[il], latval[il], linekinds[N7lines], label= linesn[il])
    3718             if il == 6: N7lines = N7lines + 1
    3719 
    37203697        plt.xlabel('x-axis')
    37213698        plt.ylabel('y-axis')
    37223699
     3700    if plotk[0] == 'spaghetti':
     3701        for il in range(Ntraj):
     3702            plt.plot(lonval[il], latval[il], lins[il], marker=pts[il],               \
     3703              color=cols[il], label=gen.latex_text(linesn[il]), linewidth=lws[il],   \
     3704              markersize=pss[il])
     3705    elif plotk[0] == 'spaghetti_date':
     3706        ofs = np.array(plotk[9:11], dtype=int)
     3707        for il in range(Ntraj):
     3708            plt.plot(lonval[il], latval[il], lins[il], marker=pts[il],               \
     3709              color=cols[il], label=gen.latex_text(linesn[il]), linewidth=lws[il],   \
     3710              markersize=pss[il])
     3711            lvals = lonval[il]
     3712            Lvals = latval[il]
     3713            tvals = timeval[il]
     3714            Nvals = len(tvals)
     3715            for it in range(0,Nvals,int(plotk[8])):
     3716                if tvals[it] is not None:
     3717                    plt.annotate(gen.latex_text(tvals[it].strftime(plotk[6])),       \
     3718                      xy=(lvals[it],Lvals[it]), color=cols[il], fontsize=plotk[7],   \
     3719                      horizontalalignment="center", xytext=(ofs[0],ofs[1]),          \
     3720                      textcoords='offset pixels')
     3721
     3722    if obsname is not None:
     3723        il = Ntraj
     3724        if plotk[0] == 'spaghetti':
     3725            plt.plot(lonval[il], latval[il], linestyle=obstrjv[0],                   \
     3726              marker=obstrjv[3], color=obstrjv[1], label=gen.latex_text(obsname),    \
     3727              linewidth=obstrjv[2], markersize=obstrjv[4])
     3728        elif plotk[0] == 'spaghetti_date':
     3729            plt.plot(lonval[il], latval[il], linestyle=obstrjv[0],                   \
     3730              marker=obstrjv[3], color=obstrjv[1], label=gen.latex_text(obsname),    \
     3731              linewidth=obstrjv[2], markersize=obstrjv[4])
     3732
     3733            lvals = lonval[il]
     3734            Lvals = latval[il]
     3735            tvals = timeval[il]
     3736            Nvals = len(tvals)
     3737            for it in range(0,Nvals,int(plotk[8])):
     3738                if lvals[it] is not None and tvals[it] is not None:
     3739                    plt.annotate(gen.latex_text(tvals[it].strftime(plotk[6])),       \
     3740                      xy=(lvals[it],Lvals[it]), color=obstrjv[1], fontsize=plotk[7], \
     3741                      horizontalalignment="center", xytext=(ofs[0],ofs[1]),          \
     3742                      textcoords='offset pixels')
     3743 
     3744    if plotk[0] == 'spaghetti_date':
     3745        Tlab = gen.timefmt_timelab(plotk[6])
     3746        plt.annotate('time labels as ' + gen.latex_text(Tlab), xy=(0.75,0.05),       \
     3747          color='k', xycoords='figure fraction')
     3748    plt.title(gtit)
     3749    plt.legend(loc=lleg, prop={'size':sleg})
     3750   
    37233751    figname = 'trajectories'
    3724     graphtit = gtit
    3725 
    3726     if obsname is not None:
    3727         plt.plot(lonval[Ntraj], latval[Ntraj], linestyle='-', color='k',             \
    3728           linewidth=3, label= obsname)
    3729 
    3730     plt.title(graphtit.replace('_','\_').replace('&','\&'))
    3731     plt.legend()
    3732    
    3733     output_kind(kfig, figname, True)
     3752    output_kind(kfig, figname, close)
    37343753
    37353754    return
  • trunk/tools/generic_tools.py

    r1444 r1454  
    6262#   i,j-quads within which the curve lays (-1, no value for the given quad [2x2 points around]) and provide
    6363#   the weights of the quad to perform a distance-weighted mean at the given curve point
     64# DateTimeStr_date: Function to transform a string date-time ([YYYY][MM][DD][HH][MI][SS] format) to a date object
     65# datetimeStr_datetime: Function to transform a string date-time ([YYYY]-[MM]-[DD]_[HH]:[MI]:[SS] format) to a date object
    6466# dictionary_key: Function to provide the first key in a dictionay with a given value
    6567# dictionary_key_list: Function to provide the first key in a dictionary of lists with a given value
     
    123125# timestep_conform: Function to provide the time-step in seconds which conforms 1 temporal unit and the resultant number
    124126#   of time-steps for a whole period is multiple of a given number
     127# timefmt_timelab: Function to transform from C-like time format to general one
    125128# unitsdsDate: Function to know how many units of time are from a given pair of dates
    126129# vals_around: Function to provide the 3x3 values around a given j,i point
     
    25572560def timeStr_time(StringDate):
    25582561  """ Function to transform a string date ([HH]:[MI]:[SS] format) to a time object
    2559   >>> datetimeStr_datetime('04:32:54')
     2562  >>> timeStr_datetime('04:32:54')
    25602563  04:32:54
    25612564  """
     
    25692572
    25702573  return newtime
     2574
     2575def DateTimeStr_date(StringDate):
     2576    """ Function to transform a string date-time ([YYYY][MM][DD][HH][MI][SS] format) to a date object
     2577    >>> DateTimeStr_date('19760217083205')
     2578    1976-02-17 08:32:05
     2579    """
     2580    import datetime as dt
     2581
     2582    yr = int(StringDate[0:4])
     2583    mo = int(StringDate[4:6])
     2584    da = int(StringDate[6:8])
     2585    ho = int(StringDate[8:10])
     2586    mi = int(StringDate[10:12])
     2587    se = int(StringDate[12:14])
     2588
     2589    if yr == 0:
     2590      print warnmsg
     2591      print '     ' + fname + ': 0 reference year!! changing to 1'
     2592      yr = 1
     2593    newdate = dt.datetime(yr, mo, da, ho, mi, se)
     2594
     2595    return newdate
    25712596
    25722597def timeref_datetime(refd, timeval, tu):
     
    1131411339    return uwindtestv, vwindtestv, twindtestv
    1131511340
     11341def timefmt_timelab(timefmt):
     11342    """ Function to transform from C-like time format to general one
     11343      timefmt= C-like instruction for time
     11344      %y as [YY], %Y as [YYYY], %m as [MM], %d as [DD], %h as [HH], %M as [MI], %S as [SS]
     11345    >>> timefmt_timelab('$%d^{%H}$')
     11346    $[DD]^{[HH]}$
     11347    """
     11348    fname = 'timefmt_timelab'
     11349
     11350    # Dictionary wtth the equivalencies
     11351    dictchanges = {'%y': '[YY]', '%Y': '[YYYY]', '%m': '[MM]', '%d': '[DD]',         \
     11352      '%H': '[HH]', '%M': '[MI]', '%S': '[SS]'}
     11353    timelab = timefmt
     11354    for chg in dictchanges.keys():
     11355        newv = dictchanges[chg]
     11356        timelab = timelab.replace(chg, newv)
     11357
     11358    if timelab.find('%') != -1:
     11359        print warnsmg
     11360        print '  '+fname+": unsuccesfull substitution of all C-like values from '" + \
     11361          timefmt + "' !!"
     11362
     11363    return timelab
     11364
    1131611365#quit()
Note: See TracChangeset for help on using the changeset viewer.