source: flex_extract.git/python/plot_retrieved.py @ efdb01a

ctbtodev
Last change on this file since efdb01a was efdb01a, checked in by Anne Philipp <anne.philipp@…>, 6 years ago

whole bunch of modifications due to new structure of ECMWFDATA, added basics of documentation, minor programming corrections

  • Property mode set to 100755
File size: 10.5 KB
Line 
1#!/usr/bin/env python
2# This software is licensed under the terms of the Apache Licence Version 2.0
3# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4#
5# Functionality provided: Simple tool for creating maps and time series of retrieved fields.
6#
7# Requirements:
8# in addition to a standard python 2.6 or 2.7 installation the following packages need to be installed
9# ECMWF WebMARS, gribAPI with python enabled, emoslib, ecaccess web toolkit, all available from https://software.ecmwf.int/
10# dateutils
11# matplotlib (optional, for debugging)
12
13import datetime
14import time
15import os,inspect,sys,glob
16import socket
17# add path to submit.py to pythonpath so that python finds its buddies
18localpythonpath=os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
19if localpythonpath not in sys.path:
20    sys.path.append(localpythonpath)
21
22from matplotlib.pylab import *
23import matplotlib.patches as mpatches
24from mpl_toolkits.basemap import Basemap,addcyclic
25import matplotlib.colors as mcolors
26from matplotlib.font_manager import FontProperties
27from matplotlib.patches import Polygon
28import matplotlib.cm as cmx
29import matplotlib.colors as colors
30from argparse import ArgumentParser,ArgumentDefaultsHelpFormatter
31
32from Tools import interpret_args_and_control, silentremove, product
33from Control import Control
34from GribTools import GribTools
35from gribapi import *
36from rasotools.utils import stats
37
38def plot_retrieved(args,c):
39
40    start = datetime.datetime.strptime(c.start_date,'%Y%m%d%H')
41    end = datetime.datetime.strptime(c.end_date,'%Y%m%d%H')
42
43    c.paramIds=asarray(c.paramIds,dtype='int')
44    c.levels=asarray(c.levels,dtype='int')
45    c.area=asarray(c.area)
46
47    index_keys=["date","time","step"]
48    indexfile=c.inputdir+"/date_time_stepRange.idx"
49    silentremove(indexfile)
50    files=glob.glob(c.inputdir+'/'+c.prefix+'*')
51    grib=GribTools(files)
52    iid=grib.index(index_keys=index_keys, index_file = indexfile)
53
54    gdict=dict(Ni = 360, Nj = 181,  iScansNegatively = 0,  jScansPositively = 0,
55               jPointsAreConsecutive = 0,  alternativeRowScanning = 0,
56               latitudeOfFirstGridPointInDegrees = 90,
57               longitudeOfFirstGridPointInDegrees = 181,
58               latitudeOfLastGridPointInDegrees = -90,
59               longitudeOfLastGridPointInDegrees = 180,
60               iDirectionIncrementInDegrees = 1,
61               jDirectionIncrementInDegrees = 1
62               )
63
64    index_vals = []
65    for key in index_keys:
66        key_vals = grib_index_get(iid,key)
67        print key_vals
68
69        index_vals.append(key_vals)
70
71    fdict=dict()
72    fmeta=dict()
73    fstamp=dict()
74    for p in c.paramIds:
75        for l in c.levels:
76            key='{:0>3}_{:0>3}'.format(p,l)
77            fdict[key]=[]
78            fmeta[key]=[]
79            fstamp[key]=[]
80    for prod in product(*index_vals):
81        for i in range(len(index_keys)):
82            grib_index_select(iid,index_keys[i],prod[i])
83
84        gid = grib_new_from_index(iid)
85#        if gid is not None:
86
87        while(gid is not None):
88            date = grib_get(gid, 'date')
89            fdate= datetime.datetime(date/10000,mod(date,10000)/100,mod(date,100))
90            gtime = grib_get(gid, 'time')
91            step = grib_get(gid, 'step')
92            fdatetime=fdate+datetime.timedelta(hours=gtime/100)
93#            if fdatetime<start or fdatetime>end:
94#                break
95            gtype = grib_get(gid, 'type')
96            paramId = grib_get(gid, 'paramId')
97            parameterName = grib_get(gid, 'parameterName')
98            level=grib_get(gid,'level')
99            if step>=c.start_step and step <=c.end_step and fdatetime>=start and fdatetime<=end and paramId in c.paramIds and level in c.levels:
100                key='{:0>3}_{:0>3}'.format(paramId,level)
101                print key
102                fdatetimestep=fdatetime+datetime.timedelta(hours=step)
103                if len(fstamp)==0:
104                    fstamp[key].append(fdatetimestamp)
105                    fmeta[key].append((paramId,parameterName,gtype,fdatetime,gtime,step,level))
106                    fdict[key].append(flipud(reshape(grib_get_values(gid),[gdict['Nj'],gdict['Ni']])))
107                else:
108                    i=0
109                    inserted=False
110                    for i in range(len(fstamp[key])):
111                        if fdatetimestep<fstamp[key][i]:
112                            fstamp[key][i:i]=[fdatetimestep]
113                            fmeta[key][i:i]=[(paramId,parameterName,gtype,fdatetime,gtime,step,level)]
114                            fdict[key][i:i]=[flipud(reshape(grib_get_values(gid),[gdict['Nj'],gdict['Ni']]))]
115                            inserted=True
116                            break
117                    if not inserted:
118                        fstamp[key].append(fdatetimestep)
119                        fmeta[key].append((paramId,parameterName,gtype,fdatetime,gtime,step,level))
120                        fdict[key].append(flipud(reshape(grib_get_values(gid),[gdict['Nj'],gdict['Ni']])))
121
122
123            grib_release(gid)
124            gid = grib_new_from_index(iid)
125
126    for k in fdict.keys():
127        fml=fmeta[k]
128        fdl=fdict[k]
129
130        for fd,fm in zip(fdl,fml):
131            ftitle=fm[1]+' {} '.format(fm[-1])+datetime.datetime.strftime(fm[3],'%Y%m%d%H')+' '+stats(fd)
132            pname='_'.join(fm[1].split())+'_{}_'.format(fm[-1])+datetime.datetime.strftime(fm[3],'%Y%m%d%H')+'.{:0>3}'.format(fm[5])
133            plotmap(fd, fm,gdict,ftitle,pname+'.eps')
134
135    for k in fdict.keys():
136        fml=fmeta[k]
137        fdl=fdict[k]
138        fsl=fstamp[k]
139        if fdl:
140            fm=fml[0]
141            fd=fdl[0]
142            ftitle=fm[1]+' {} '.format(fm[-1])+datetime.datetime.strftime(fm[3],'%Y%m%d%H')+' '+stats(fd)
143            pname='_'.join(fm[1].split())+'_{}_'.format(fm[-1])+datetime.datetime.strftime(fm[3],'%Y%m%d%H')+'.{:0>3}'.format(fm[5])
144            lat=-20
145            lon=20
146            plottimeseries(fdl,fml,fsl,lat,lon, gdict, ftitle, pname+'.eps')
147
148def plottimeseries(flist,fmetalist,ftimestamps,lat,lon,gdict,ftitle,filename):
149    t1=time.time()
150    latindex=(lat+90)*180/(gdict['Nj']-1)
151    lonindex=(lon+179)*360/gdict['Ni']
152    farr=asarray(flist)
153    ts=farr[:,latindex,lonindex]
154    f=plt.figure(figsize=(12,6.7))
155    plt.plot(ftimestamps,ts)
156    plt.title(ftitle)
157    savefig(c.outputdir+'/'+filename)
158    print 'created ',c.outputdir+'/'+filename
159    plt.close(f)
160    print time.time()-t1,'s'
161
162def plotmap(flist,fmetalist,gdict,ftitle,filename):
163    t1=time.time()
164    f=plt.figure(figsize=(12,6.7))
165    mbaxes = f.add_axes([0.05, 0.15, 0.8, 0.7])
166    m =Basemap(llcrnrlon=-180.,llcrnrlat=-90.,urcrnrlon=180,urcrnrlat=90.)
167    #if bw==0 :
168        #fill_color=rgb(0.6,0.8,1)
169    #else:
170        #fill_color=rgb(0.85,0.85,0.85)
171
172    lw=0.3
173    m.drawmapboundary()
174    parallels = arange(-90.,91,90.)
175    # labels = [left,right,top,bottom]
176    m.drawparallels(parallels,labels=[True,True,True,True],linewidth=lw)
177    meridians = arange(-180.,181.,60.)
178    m.drawmeridians(meridians,labels=[True,True,True,True],linewidth=lw)
179    m.drawcoastlines(linewidth=lw)
180    xleft=gdict['longitudeOfFirstGridPointInDegrees']
181    if xleft>180.0:
182        xleft-=360.
183    x=linspace(xleft,gdict['longitudeOfLastGridPointInDegrees'],gdict['Ni'])
184    y=linspace(gdict['latitudeOfLastGridPointInDegrees'],gdict['latitudeOfFirstGridPointInDegrees'],gdict['Nj'])
185    xx, yy = m(*meshgrid(x,y))
186
187    s=m.contourf(xx,yy, flist)
188    title(ftitle,y=1.1)
189    cbaxes = f.add_axes([0.9, 0.2, 0.04, 0.6])
190    cb=colorbar(cax=cbaxes)
191
192    savefig(c.outputdir+'/'+filename)
193    print 'created ',c.outputdir+'/'+filename
194    plt.close(f)
195    print time.time()-t1,'s'
196
197
198def interpret_plotargs(*args,**kwargs):
199
200    parser = ArgumentParser(description='Retrieve FLEXPART input from ECMWF MARS archive',
201                            formatter_class=ArgumentDefaultsHelpFormatter)
202
203# the most important arguments
204    parser.add_argument("--start_date", dest="start_date",
205                        help="start date YYYYMMDD")
206    parser.add_argument( "--end_date", dest="end_date",
207                         help="end_date YYYYMMDD")
208
209    parser.add_argument("--start_step", dest="start_step",
210                        help="start step in hours")
211    parser.add_argument( "--end_step", dest="end_step",
212                         help="end_step in hours")
213
214# some arguments that override the default in the control file
215    parser.add_argument("--levelist", dest="levelist",help="Vertical levels to be retrieved, e.g. 30/to/60")
216    parser.add_argument("--area", dest="area", help="area defined as north/west/south/east")
217    parser.add_argument("--paramIds", dest="paramIds", help="parameter IDs")
218    parser.add_argument("--prefix", dest="prefix",default='EN', help="output file name prefix")
219
220# set the working directories
221    parser.add_argument("--inputdir", dest="inputdir",default=None,
222                        help="root directory for storing intermediate files")
223    parser.add_argument("--outputdir", dest="outputdir",default=None,
224                        help="root directory for storing output files")
225    parser.add_argument("--flexpart_root_scripts", dest="flexpart_root_scripts",
226                        help="FLEXPART root directory (to find grib2flexpart and COMMAND file)\n\
227                              Normally ECMWFDATA resides in the scripts directory of the FLEXPART distribution")
228
229    parser.add_argument("--controlfile", dest="controlfile",default='CONTROL.temp',
230                        help="file with control parameters")
231    args = parser.parse_args()
232
233    try:
234        c=Control(args.controlfile)
235    except IOError:
236        try:
237            c=Control(localpythonpath+args.controlfile)
238
239        except:
240            print 'Could not read control file "'+args.controlfile+'"'
241            print 'Either it does not exist or its syntax is wrong.'
242            print 'Try "'+sys.argv[0].split('/')[-1]+' -h" to print usage information'
243            exit(1)
244
245    if args.levelist:
246        c.levels=args.levelist.split('/')
247    else:
248        c.levels=[0]
249    if args.area:
250        c.area=args.area.split('/')
251    else:
252        c.area='[0,0]'
253
254    c.paramIds=args.paramIds.split('/')
255    if args.start_step:
256        c.start_step=int(args.start_step)
257    else:
258        c.start_step=0
259    if args.end_step:
260        c.end_step=int(args.end_step)
261    else:
262        c.end_step=0
263
264    c.start_date=args.start_date
265    c.end_date=args.end_date
266    c.prefix=args.prefix
267    c.inputdir=args.inputdir
268    if args.outputdir:
269        c.outputdir=args.outputdir
270    else:
271        c.outputdir=c.inputdir
272
273        return args,c
274
275if __name__ == "__main__":
276
277    args,c=interpret_plotargs()
278    plot_retrieved(args,c)
Note: See TracBrowser for help on using the repository browser.
hosted by ZAMG