Changeset 1874 in lmdz_wrf


Ignore:
Timestamp:
Mar 27, 2018, 9:57:55 PM (7 years ago)
Author:
lfita
Message:

Adding:

  • `movie_2D_shad': creation of a movie with shading
Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/drawing.py

    r1873 r1874  
    5656## e.g. # drawing.py -o draw_cycle -f 'Forcing_tairstats_OKstomate_CRUNCEP_spinup_SESA.nc;time_counter,-1|stats,2;time_centered;tair_stats' -S 'auto;y;centered;tair;K;None;12,3;lines,rainbow,horizontal,auto,-,2.;1,3,5@Sep/Nov,Jan/Jul,Mar/May;year|seconds!since!1958-01-01!00:00:00|exct,5,y|%Y;SESA;year-evolution!of!CRUNCEP!tair!forcing!at!SESA;0|10;png;cycle_tair_CRUNCEP_spinup_SESA;yes'
    5757## e.g. # drawing.py -o draw_multi_2D_shad -f '../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|0;../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|1;../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|2;../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|3' -S 'tas:XLONG:XLAT:auto:rainbow,auto,auto:Srange,Srange:png:None:cyl,l:0!UTC,1!UTC,2!UTC,3!UTC:2:2:tas!at!2001-11-11:True'
    58 
     58# 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
    5959
    6060#######
     
    9999# draw_vertical_levels: plotting vertical levels distribution
    100100# draw_WindRose: Function to plot a wind rose (from where the dinw blows)
     101# movie_2D_shad: creation of a movie with shading
    101102
    102103mainn = 'drawing.py'
     
    119120  'draw_topo_geogrid_boxes', 'draw_trajectories', 'draw_vals_trajectories',          \
    120121  'draw_vectors',  'draw_vertical_levels', 'list_graphics', 'draw_WindRose',         \
    121   'variable_values']
     122  'movie_2D_shad', 'variable_values']
    122123
    123124def draw_2D_shad(ncfile, values, varn, axfig=None, fig=None):
     
    84608461        [globaltitle]: global title of the figure ('!' for spaces)
    84618462        [close]: Whether figure should be finished or not
    8462       valules= 'rh:z|-1,x|-1:z|-1,x|-1:lat:pressure:BuPu:0.,100.:rh:pdf:flip@y:None'
    8463       varn=
    84648463    """
    84658464
     
    85968595    return
    85978596#python drawing.py -o draw_multi_2D_shad -f '../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|0;../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|1;../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|2;../PY/wrfout_d01_1995-01-01_00:00:00@T2@west_east|-1,south_north|-1,Time|3' -S 'tas:XLONG:XLAT:auto:rainbow,auto,auto:Srange,Srange:png:None:cyl,l:0!UTC,1!UTC,2!UTC,3!UTC:2:2:tas!at!2001-11-11:True'
     8597
     8598def movie_2D_shad(ncfile, values, varn, axfig=None, fig=None):
     8599    """ creation of a movie with shading
     8600    movie_2D_shad(ncfile, values, varn)
     8601      ncfile= file to use
     8602      values=[vnamefs]:[dimvals]:[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]:[sminv],[smaxv]:[figt]:
     8603       [kindfig]:[reverse]:[mapv]:[moviedim]:[fps]:[kmov]
     8604        [vnamefs]: Name in the figure of the variable to be shaded
     8605        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the
     8606          variable a given value is required:
     8607            * [integer]: which value of the dimension
     8608            * -1: all along the dimension
     8609            * -9: last value of the dimension
     8610            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
     8611            * NOTE, no dim name all the dimension size
     8612        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)
     8613        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
     8614          [dxs]: style of x-axis ('auto' for 'pretty')
     8615            'Nfix', values computed at even 'Ndx'
     8616            'Vfix', values computed at even 'Ndx' increments
     8617            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
     8618          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
     8619          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
     8620          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
     8621          [dys]: style of y-axis ('auto' for 'pretty')
     8622          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
     8623          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
     8624          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
     8625        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
     8626          [colorbarn]: name of the color bar
     8627          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
     8628          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
     8629        [smin/axv]: minimum and maximum value for the shading or:
     8630          'Srange': for full range
     8631          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
     8632          'Saroundminmax@val': for min*val,max*val
     8633          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
     8634            percentile_(100-val)-median)
     8635          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
     8636          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
     8637          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
     8638             percentile_(100-val)-median)
     8639        [kindfig]: kind of figure
     8640        [reverse]: Transformation of the values
     8641          * 'transpose': reverse the axes (x-->y, y-->x)
     8642          * 'flip'@[x/y]: flip the axis x or y
     8643        [mapv]: map characteristics: [proj],[res]
     8644          see full documentation: http://matplotlib.org/basemap/
     8645          [proj]: projection
     8646            * 'cyl', cilindric
     8647            * 'lcc', lambert conformal
     8648          [res]: resolution:
     8649            * 'c', crude
     8650            * 'l', low
     8651            * 'i', intermediate
     8652            * 'h', high
     8653            * 'f', full
     8654        [movievals] = [moviedim],[movivar] way to get values for the movie
     8655          [moviedime]: name of the dimension to get the movie (following outcome from [dimvals])
     8656          [movievar]: name of the variable to get the values
     8657        [framelabels]: values for the production of the labels of each frame
     8658          * 'varVal',[HeadTit],[TailTit],[fmt]: Following direct values from variable as:
     8659            [HeadTit] + ' ' + [varValue] + ' ' + [TailTit]
     8660              [HeadTit]: Head of title ('!', for spaces)
     8661              [TailTit]: title of title ('!', for spaces)
     8662              [fmt]: format of the values of the variable in the title (C-like)
     8663          * 'listtit',[Ftitles]: Providing manually title for each frame
     8664              [Ftitle]: '@' separated list of titles ('!', for titles)
     8665          * 'CFdate',[datefmt]: Just title with the date (assuming CF-time compilant variable)
     8666              [tfmt]: format of the date (C-like)
     8667          * 'WRFdate',[datefmt]: Just title with the date (assuming WRF time variable)
     8668              [tfmt]: format of the date (C-like)
     8669        [fps]: frames per second of the output movie
     8670        [kmov]: kind of movie (mp4, ....)
     8671      varn= [varsn] name of the variable to plot with shading
     8672    """
     8673    fname = 'movie_2D_shad'
     8674    if values == 'h':
     8675        print fname + '_____________________________________________________________'
     8676        print movie_2D_shad.__doc__
     8677        quit()
     8678
     8679    expectargs = '[vnamefs]:[dimvals]:[dimxvn]:[dimyvn]:[dimxyf]:[colbarvals]:' +    \
     8680      '[sminv],[smaxv]:[kindfig]:[reverse]:[mapv]:[movidime]:[framelabels]:[fps]' +  \
     8681      ':[kmov]'
     8682 
     8683    drw.check_arguments(fname,values,expectargs,':')
     8684
     8685    vnamesfig = values.split(':')[0]
     8686    dimvals= values.split(':')[1].replace('|',':')
     8687    vdimxn = values.split(':')[2]
     8688    vdimyn = values.split(':')[3]
     8689    dimxyf = values.split(':')[4]
     8690    colorbarvals = values.split(':')[5]
     8691    shadminmax = values.split(':')[6]
     8692    figkind = values.split(':')[7]
     8693    revals = values.split(':')[8]
     8694    mapvalue = values.split(':')[9]
     8695    movievals = values.split(':')[10].split(',')
     8696    framelabelS = values.split(':')[11]
     8697    fps = int(values.split(':')[12])
     8698    kmov = values.split(':')[13]
     8699
     8700    ncfiles = ncfile
     8701   
     8702    if not os.path.isfile(ncfiles):
     8703        print errormsg
     8704        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
     8705        quit(-1)   
     8706
     8707    objsf = NetCDFFile(ncfiles, 'r')
     8708   
     8709    varns = varn.split(',')[0]
     8710
     8711    if  not objsf.variables.has_key(varns):
     8712        print errormsg
     8713        print '  ' + fname + ': shading file "' + ncfiles +                          \
     8714          '" does not have variable "' +  varns + '" !!'
     8715        varns = sorted(objsf.variables.keys())
     8716        print '    available ones:', varns
     8717        quit(-1)
     8718
     8719# Variables' values
     8720    objvars = objsf.variables[varns]
     8721
     8722    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
     8723    dimnamesv = [vdimxn, vdimyn]
     8724
     8725    # Movie variable
     8726    moviedim = movievals[0]
     8727    movievar = movievals[1]
     8728    idd = 0
     8729    for dn in objvars.dimensions:
     8730        if dn == moviedim:
     8731            NumDimT = idd
     8732        break
     8733        idd = idd + 1
     8734
     8735    if drw.searchInlist(objvars.ncattrs(),'units'):
     8736        varunits = objvars.getncattr('units')
     8737    else:
     8738        print warnmsg
     8739        print '  ' + fname + ": variable '" + varn + "' without units!!"
     8740        varunits = '-'
     8741
     8742    if  not objsf.variables.has_key(vdimxn):
     8743        print errormsg
     8744        print '  ' + fname + ': shading file "' + ncfiles +                          \
     8745          '" does not have dimension variable "' +  vdimxn + '" !!'
     8746        quit(-1)
     8747    if  not objsf.variables.has_key(vdimyn):
     8748        print errormsg
     8749        print '  ' + fname + ': shading file "' + ncfiles +                          \
     8750          '" does not have dimension variable "' +  vdimyn + '" !!'
     8751        quit(-1)
     8752
     8753    objdimx = objsf.variables[vdimxn]
     8754    objdimy = objsf.variables[vdimyn]
     8755    if drw.searchInlist(objdimx.ncattrs(),'units'):
     8756        odimxu = objdimx.getncattr('units')
     8757    else:
     8758        print warnmsg
     8759        print '  ' + fname + ": variable dimension '" + vdimxn + "' without units!!"
     8760        odimxu = '-'
     8761
     8762    if drw.searchInlist(objdimy.ncattrs(),'units'):
     8763        odimyu = objdimy.getncattr('units')
     8764    else:
     8765        print warnmsg
     8766        print '  ' + fname + ": variable dimension '" + vdimyn + "' without units!!"
     8767        odimyu = '-'
     8768
     8769    odimxv, odimyv = drw.dxdy_lonlatDIMS(objdimx[:], objdimy[:], objdimx.dimensions,     \
     8770      objdimy.dimensions, dimvals.replace(':','|').split(','))
     8771
     8772    shading_nx = []
     8773    if shadminmax.split(',')[0][0:1] != 'S':
     8774            shading_nx.append(np.float(shadminmax.split(',')[0]))
     8775    else:
     8776        shading_nx.append(shadminmax.split(',')[0])
     8777
     8778    if shadminmax.split(',')[1][0:1] != 'S':
     8779        shading_nx.append(np.float(shadminmax.split(',')[1]))
     8780    else:
     8781        shading_nx.append(shadminmax.split(',')[1])
     8782
     8783    if mapvalue == 'None': mapvalue = None
     8784
     8785    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
     8786    colormapv = [colbarn, fmtcolbar, colbaror]
     8787
     8788    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyf,',')
     8789    xaxis = [xstyl, xaxf, Nxax, xaxor]
     8790    yaxis = [ystyl, yaxf, Nyax, yaxor]
     8791
     8792    if revals == 'None':
     8793        revals = None
     8794
     8795    if not objsf.variables.has_key(movievar):
     8796        oncvars = objsf.variables.keys()
     8797        oncvars.sort()
     8798        print errormsg
     8799        print '  ' + fname + ": file '" + ncfile + "' does not have variable '" +    \
     8800          movievar + "' to get from the values for the frames!!"
     8801        print '    available ones:', oncvars
     8802        quit(-1)
     8803    omovievar = objsf.variables[movievar]
     8804    movievarv, dimsmov = drw.slice_variable(omovievar, dimvals.replace(',','|'))
     8805
     8806    # Labels for frames
     8807    framelabels = []
     8808    if framelabelS[0:6] == 'varVal':
     8809        HeadTit = framelabelS.split(',')[1]
     8810        TailTit = framelabelS.split(',')[2]
     8811        fmt = framelabelS.split(',')[3]
     8812
     8813        if len(movievarv.shape) != 1:
     8814            print errormsg
     8815            print '  ' + fname + ": for frame labels type 'varVal' is required a " + \
     8816              " rank 1 variable !!"
     8817            print "    variable '" + movievar + "' shape:", vn.shape
     8818            quit(-1)
     8819        dimt = movievarv.shape[0]
     8820        for it in range(dimt):
     8821            framelabels.append(gen.latex_tex(HeadTit) + ' ' +                        \
     8822              '{}'.format(movievarv[it]) + ' ' + gen.latex_tex(TailTit))
     8823
     8824    elif framelabelS[0:7] == 'listtit':
     8825        frameS = framelabelS.split(',')[1].split('@')
     8826        dimt = len(frameS)
     8827        for it in range(dimt):
     8828            framelabels.append(gen.latex_tex(frameS[it].replace('!', ' ')))
     8829
     8830    elif framelabelS[0:6] == 'CFdate':
     8831        import datetime as dt
     8832        tfmt = framelabelS.split(',')[1]
     8833        if len(movievarv.shape) != 1:
     8834            print errormsg
     8835            print '  ' + fname + ": for frame labels type 'CFdate' is required a " + \
     8836              " rank 1 variable !!"
     8837            print "    variable '" + movievar + "' shape:", movievarv.shape
     8838            quit(-1)
     8839        tunits = omovievar.getncattr('units')
     8840        tcalendar = omovievar.getncattr('calendar')
     8841        datesv = gen.netCDFdatetime_realdatetime(tunits, tcalendar, movievarv[:])
     8842        dimt = omovievar.shape[0]
     8843        for it in range(dimt):
     8844            dateV = dt.datetime(datesv[it][0], datesv[it][1], datesv[it][2],         \
     8845              datesv[it][3], datesv[it][4], datesv[it][5])
     8846            framelabels.append(dateV.strftime(tfmt))
     8847
     8848    elif framelabelS[0:7] == 'WRFdate':
     8849        import datetime as dt
     8850        tfmt = framelabelS.split(',')[1]
     8851        if len(movievarv.shape) != 2:
     8852            print errormsg
     8853            print '  ' + fname + ": for frame labels type 'WRFtime' is required a "+ \
     8854              " rank 2 variable !!"
     8855            print "    variable '" + movievar + "' shape:", movievarv.shape
     8856            quit(-1)
     8857        timev, tunits = ncvar.compute_WRFtime(movievarv[:])
     8858        datesv = gen.netCDFdatetime_realdatetime(tunits, 'standard', timev)
     8859        dimt = omovievar.shape[0]
     8860        for it in range(dimt):
     8861            dateV = dt.datetime(datesv[it][0], datesv[it][1], datesv[it][2],         \
     8862              datesv[it][3], datesv[it][4], datesv[it][5])
     8863            framelabels.append(dateV.strftime(tfmt))
     8864
     8865    drw.movie_2D_shadow(valshad, NumDimT, vnamesfig, odimxv, odimyv, odimxu, odimyu, \
     8866      xaxis, yaxis, dimnamesv, colormapv, shading_nx, varunits, framelabels,         \
     8867      figkind, revals, mapvalue, fps, kmov)
     8868
     8869    return
     8870
     8871#python drawing.py -o 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
    85988872
    85998873#quit()
     
    87489022    elif oper == 'draw_WindRose':
    87499023        draw_WindRose(opts.ncfile, opts.values, opts.varname)
     9024    elif oper == 'movie_2D_shad':
     9025        movie_2D_shad(opts.ncfile, opts.values, opts.varname)
    87509026    elif oper == 'variable_values':
    87519027        variable_values(opts.values)
  • trunk/tools/drawing_tools.py

    r1873 r1874  
    117117# check_arguments:
    118118# Str_Bool:
     119# movie_2D_shadow: Plot of a 2D field with shadow
     120# multi_plot_2D_shadow: plot of multiple 2D shadowing variables sharing colorbar
    119121# pixelgrid: Function to provide the kind of grid distribution for a plot
    120122# plot_points:
     
    1109811100    return
    1109911101
     11102def movie_2D_shadow(varsv, dimT, vnames, dimxv, dimyv, dimxu, dimyu, xaxv, yaxv,     \
     11103  dimn, cbarv, vs, uts, ltit, kfig, reva, mapv, framesec, kmov):
     11104    """ Plot of a 2D field with shadow
     11105      varsv= 3D values to plot each frame with shading
     11106      dimT= number of the dimension to be used as time-loop
     11107      vnames= variable names for the figure
     11108      dim[x/y]v = values at the axes of x and y
     11109      dim[x/y]u = units at the axes of x and y
     11110      xaxv= list with the x-axis paramteres [style, format, number and orientation]
     11111      yaxv= list with the y-axis paramteres [style, format, number and orientation]
     11112      dimn= dimension names to plot
     11113      cbarv= list with the parameters of the color bar [colorbar, cbarfmt, cbaror]
     11114        colorbar: name of the color bar to use
     11115        cbarfmt: format of the numbers in the colorbar
     11116        cbaror: orientation of the colorbar
     11117      vs= minmum and maximum values to plot in shadow or:
     11118        'Srange': for full range
     11119        'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
     11120        'Saroundminmax@val': for min*val,max*val
     11121        'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
     11122          percentile_(100-val)-median)
     11123        'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
     11124        'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
     11125        'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
     11126           percentile_(100-val)-median)
     11127      uts= units of the variable to shadow
     11128      ltit= list of titles for each frame
     11129      kfig= kind of figure (jpg, pdf, png)
     11130      reva= ('|' for combination)
     11131        * 'transpose': reverse the axes (x-->y, y-->x)
     11132        * 'flip'@[x/y]: flip the axis x or y
     11133      mapv= map characteristics: [proj],[res]
     11134        see full documentation: http://matplotlib.org/basemap/
     11135        [proj]: projection
     11136          * 'cyl', cilindric
     11137          * 'lcc', lambert conformal
     11138        [res]: resolution:
     11139          * 'c', crude
     11140          * 'l', low
     11141          * 'i', intermediate
     11142          * 'h', high
     11143          * 'f', full
     11144      fremessec= frames per second of the output movie
     11145      kmov= kind of movie putput (mp4)
     11146    """
     11147    import matplotlib.animation as manimation
     11148    fname = 'movie_2D_shadow'
     11149
     11150    ofile = "movie_2D_shadow." + kmov
     11151
     11152    if type(varsv) == type('S') and varsv == 'h':
     11153        print fname + '_____________________________________________________________'
     11154        print movie_2D_shadow.__doc__
     11155        quit()
     11156
     11157    if len(varsv.shape) != 3:
     11158        print errormsg
     11159        print '  ' + fname + ': wrong variable shadow rank:', varsv.shape,           \
     11160          'is has to be 3D!!'
     11161        quit(-1)
     11162
     11163
     11164    # Getting the right lon values for plotting
     11165    if mapv is not None:
     11166        dimxv = np.where(dimxv > 180., dimxv-360., dimxv)
     11167
     11168    # Axis ticks
     11169    # Usually axis > x must be the lon, thus...
     11170    dimxv0 = dimxv.copy()
     11171    dimyv0 = dimyv.copy()
     11172
     11173    dxn = dimxv.min()
     11174    dxx = dimxv.max()
     11175    dyn = dimyv.min()
     11176    dyx = dimyv.max()
     11177
     11178    if xaxv[0] == 'pretty':
     11179        dimxt0 = np.array(gen.pretty_int(dxn,dxx,xaxv[2]))
     11180    elif xaxv[0] == 'Nfix':
     11181        dimxt0 = np.arange(dxn,dxx,(dxx-dxn)/(1.*xaxv[2]))
     11182    elif xaxv[0] == 'Vfix':
     11183        dimxt0 = np.arange(0,dxx,xaxv[2])
     11184    if yaxv[0] == 'pretty':
     11185        dimyt0 = np.array(gen.pretty_int(dyn,dyx,yaxv[2]))
     11186    elif yaxv[0] == 'Nfix':
     11187        dimyt0 = np.arange(dyn,dyx,(dyx-dyn)/(1.*yaxv[2]))
     11188    elif yaxv[0] == 'Vfix':
     11189        dimyt0 = np.arange(0,dyx,yaxv[2])
     11190
     11191    dimxl0 = []
     11192    for i in range(len(dimxt0)): dimxl0.append('{:{style}}'.format(dimxt0[i], style=xaxv[1]))
     11193    dimyl0 = []
     11194    for i in range(len(dimyt0)): dimyl0.append('{:{style}}'.format(dimyt0[i], style=yaxv[1]))
     11195
     11196    dimxT0 = variables_values(dimn[0])[0] + ' (' + units_lunits(dimxu) + ')'
     11197    dimyT0 = variables_values(dimn[1])[0] + ' (' + units_lunits(dimyu) + ')'
     11198
     11199    if mapv is not None:
     11200        pixkind = 'data'
     11201    else:
     11202        # No following data values
     11203        dimxt0 = np.arange(len(dimxt0),dtype=np.float)/(len(dimxt0))
     11204        dimyt0 = np.arange(len(dimyt0),dtype=np.float)/(len(dimyt0))
     11205        pixkind = 'fixpixel'
     11206
     11207    if reva is not None:
     11208        varsv, dimxv, dimyv, dimxt, dimyt, dimxl, dimyl, dimxT, dimyT =              \
     11209          transform(varsv, reva, dxv=dimxv0, dyv=dimyv0, dxt=dimxt0, dyt=dimyt0,     \
     11210          dxl=dimxl0, dyl=dimyl0, dxtit=dimxT0, dytit=dimyT0)
     11211    else:
     11212        dimxv = dimxv0
     11213        dimyv = dimyv0
     11214        dimxt = dimxt0
     11215        dimyt = dimyt0
     11216        dimxl = dimxl0
     11217        dimyl = dimyl0
     11218        dimxT = dimxT0
     11219        dimyT = dimyT0
     11220
     11221    if len(dimxv[:].shape) == 3:
     11222        xdims = '1,2'
     11223    elif len(dimxv[:].shape) == 2:
     11224        xdims = '0,1'
     11225    elif len(dimxv[:].shape) == 1:
     11226        xdims = '0'
     11227
     11228    if len(dimyv[:].shape) == 3:
     11229        ydims = '1,2'
     11230    elif len(dimyv[:].shape) == 2:
     11231        ydims = '0,1'
     11232    elif len(dimyv[:].shape) == 1:
     11233        ydims = '0'
     11234
     11235#    lon0 = dimxv
     11236#    lat0 = dimyv
     11237    lon0, lat0 = dxdy_lonlat(dimxv,dimyv, xdims, ydims)
     11238
     11239    if not mapv is None:
     11240        map_proj=mapv.split(',')[0]
     11241        map_res=mapv.split(',')[1]
     11242
     11243        dx = lon0.shape[1]
     11244        dy = lat0.shape[0]
     11245
     11246        nlon = np.min(lon0)
     11247        xlon = np.max(lon0)
     11248        nlat = np.min(lat0)
     11249        xlat = np.max(lat0)
     11250
     11251        lon2 = lon0[dy/2,dx/2]
     11252        lat2 = lat0[dy/2,dx/2]
     11253
     11254        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
     11255          xlon, ',', xlat
     11256
     11257        if map_proj == 'cyl':
     11258            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
     11259              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
     11260        elif map_proj == 'lcc':
     11261            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
     11262              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
     11263        else:
     11264            print errormsg
     11265            print '  ' + fname + ": map projection '" + map_proj + "' not defined!!!"
     11266            print '    available: cyl, lcc'
     11267            quit(-1)
     11268 
     11269        x,y = m(lon0,lat0)
     11270
     11271    else:
     11272        # No following data values
     11273        x = (dimxv-np.min(dimxv))/(np.max(dimxv) - np.min(dimxv))
     11274        y = (dimyv-np.min(dimyv))/(np.max(dimyv) - np.min(dimyv))
     11275
     11276# Changing limits of the colors
     11277    vsend = graphic_range(vs,varsv)
     11278
     11279    # FROM: https://matplotlib.org/examples/animation/moviewriter.html
     11280    FFMpegWriter = manimation.writers['ffmpeg']
     11281    cmt = vnames
     11282    metadata = dict(title=cmt, artist='Matplotlib', comment='PyNCplot')
     11283    writer = FFMpegWriter(fps=framesec, metadata=metadata)
     11284
     11285    fig = plt.figure()
     11286    plt.rc('text', usetex=True)
     11287
     11288    dimt = varsv.shape[dimT]
     11289
     11290    with writer.saving(fig, ofile, dimt):
     11291        for it in range(dimt):
     11292            slicev = []
     11293            for idn in range(3):
     11294                if idn == dimT: slicev.append(it)
     11295                else: slicev.append(slice(0,varsv.shape[idn]))
     11296            vv = varsv[tuple(slicev)]
     11297
     11298            plt.pcolormesh(x, y, vv, cmap=plt.get_cmap(cbarv[0]), vmin=vsend[0], vmax=vsend[1])
     11299            if cbarv[2] == 'horizontal':
     11300                cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2])
     11301                # From: http://stackoverflow.com/questions/32050030/rotation-of-colorbar-tick-labels-in-matplotlib
     11302                ticklabels= cbar.ax.get_xticklabels()
     11303                Nticks = len(ticklabels)
     11304                ticklabs = []
     11305                for itick in range(Nticks): ticklabs.append(ticklabels[itick].get_text())
     11306                cbar.ax.set_xticklabels(ticklabs,rotation=90)
     11307            else:
     11308                cbar = plt.colorbar(format=cbarv[1],orientation=cbarv[2])
     11309       
     11310            if not mapv is None:
     11311                if cbarv[0] == 'gist_gray':
     11312                    m.drawcoastlines(color="red")
     11313                else:
     11314                    m.drawcoastlines()
     11315   
     11316                meridians = gen.pretty_int(nlon,xlon,xaxv[2])
     11317                m.drawmeridians(meridians,labels=[True,False,False,True])
     11318                parallels = gen.pretty_int(nlat,xlat,yaxv[2])
     11319                m.drawparallels(parallels,labels=[False,True,True,False])
     11320   
     11321                plt.xlabel('W-E')
     11322                plt.ylabel('S-N')
     11323            else:
     11324                plt.xlabel(dimxT)
     11325                plt.ylabel(dimyT)
     11326
     11327            plt.axis([x.min(), x.max(), y.min(), y.max()])
     11328
     11329            if mapv is None:
     11330                plt.xticks(dimxt, dimxl, rotation=xaxv[3])
     11331                plt.yticks(dimyt, dimyl, rotation=yaxv[3])
     11332
     11333            # units labels
     11334            cbar.set_label(gen.latex_text(vnames) + ' (' + units_lunits(uts) + ')')
     11335
     11336            graphtit = gen.latex_text(ltit[it])
     11337            plt.title(gen.latex_text(graphtit))
     11338
     11339            #figname = '2D_shadow_frame' + str(it).zfill(int(np.log10(dimt))+1)
     11340            #output_kind(kfig, figname, True)
     11341
     11342            writer.grab_frame()
     11343            plt.clf()
     11344            plt.cla()
     11345   
     11346
     11347    print fname + ": successful creation of movie '" + ofile + "' !!"
     11348
     11349    return
     11350
     11351
Note: See TracChangeset for help on using the changeset viewer.