1 | #!/usr/bin/env python |
---|
2 | # -*- coding: utf-8 -*- |
---|
3 | #************************************************************************ |
---|
4 | # TODO AP |
---|
5 | # - |
---|
6 | #************************************************************************ |
---|
7 | #******************************************************************************* |
---|
8 | # @Author: Anne Fouilloux (University of Oslo) |
---|
9 | # |
---|
10 | # @Date: October 2014 |
---|
11 | # |
---|
12 | # @Change History: |
---|
13 | # |
---|
14 | # November 2015 - Leopold Haimberger (University of Vienna): |
---|
15 | # - optimized displayInfo |
---|
16 | # - optimized dataRetrieve and seperate between python and shell |
---|
17 | # script call |
---|
18 | # |
---|
19 | # February 2018 - Anne Philipp (University of Vienna): |
---|
20 | # - applied PEP8 style guide |
---|
21 | # - added documentation |
---|
22 | # - applied some minor modifications in programming style/structure |
---|
23 | # |
---|
24 | # @License: |
---|
25 | # (C) Copyright 2015-2018. |
---|
26 | # |
---|
27 | # This software is licensed under the terms of the Apache Licence Version 2.0 |
---|
28 | # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. |
---|
29 | # |
---|
30 | # @Class Description: |
---|
31 | # A MARS revtrieval has a specific syntax with a selection of keywords and |
---|
32 | # their corresponding values. This class provides the necessary functions |
---|
33 | # by displaying the selected parameters and their values and the actual |
---|
34 | # retrievement of the data through a mars request or a Python web api |
---|
35 | # interface. The initialization already expects all the keyword values. |
---|
36 | # |
---|
37 | # @Class Content: |
---|
38 | # - __init__ |
---|
39 | # - displayInfo |
---|
40 | # - dataRetrieve |
---|
41 | # |
---|
42 | #******************************************************************************* |
---|
43 | |
---|
44 | # ------------------------------------------------------------------------------ |
---|
45 | # MODULES |
---|
46 | # ------------------------------------------------------------------------------ |
---|
47 | import subprocess |
---|
48 | import os |
---|
49 | |
---|
50 | ecapi = True |
---|
51 | try: |
---|
52 | import ecmwfapi |
---|
53 | except ImportError: |
---|
54 | ecapi = False |
---|
55 | |
---|
56 | # ------------------------------------------------------------------------------ |
---|
57 | # CLASS |
---|
58 | # ------------------------------------------------------------------------------ |
---|
59 | class MARSretrieval: |
---|
60 | ''' |
---|
61 | Class for submitting MARS retrievals. |
---|
62 | |
---|
63 | A description of MARS keywords/arguments and examples of their |
---|
64 | values can be found here: |
---|
65 | https://software.ecmwf.int/wiki/display/UDOC/\ |
---|
66 | Identification+keywords#Identificationkeywords-class |
---|
67 | |
---|
68 | ''' |
---|
69 | |
---|
70 | def __init__(self, server, marsclass = "ei", type = "", levtype = "", |
---|
71 | levelist = "", repres = "", date = "", resol = "", stream = "", |
---|
72 | area = "", time = "", step = "", expver = "1", number = "", |
---|
73 | accuracy = "", grid = "", gaussian = "", target = "", |
---|
74 | param = ""): |
---|
75 | ''' |
---|
76 | @Description: |
---|
77 | Initialises the instance of the MARSretrieval class and |
---|
78 | defines and assigns a set of the necessary retrieval parameters |
---|
79 | for the FLEXPART input data. |
---|
80 | A description of MARS keywords/arguments, their dependencies |
---|
81 | on each other and examples of their values can be found here: |
---|
82 | |
---|
83 | https://software.ecmwf.int/wiki/display/UDOC/MARS+keywords |
---|
84 | |
---|
85 | @Input: |
---|
86 | self: instance of MARSretrieval |
---|
87 | For description see class documentation. |
---|
88 | |
---|
89 | server: instance of ECMWFService (from ECMWF Web-API) |
---|
90 | This is the connection to the ECMWF data servers. |
---|
91 | It is needed for the pythonic access of ECMWF data. |
---|
92 | |
---|
93 | marsclass: string, optional |
---|
94 | Characterisation of dataset. E.g. EI (ERA-Interim), |
---|
95 | E4 (ERA40), OD (Operational archive), ea (ERA5). |
---|
96 | Default is the ERA-Interim dataset "ei". |
---|
97 | |
---|
98 | type: string, optional |
---|
99 | Determines the type of fields to be retrieved. |
---|
100 | Selects between observations, images or fields. |
---|
101 | Examples for fields: Analysis (an), Forecast (fc), |
---|
102 | Perturbed Forecast (pf), Control Forecast (cf) and so on. |
---|
103 | Default is an empty string. |
---|
104 | |
---|
105 | levtype: string, optional |
---|
106 | Denotes type of level. Has a direct implication on valid |
---|
107 | levelist values! |
---|
108 | E.g. model level (ml), pressure level (pl), surface (sfc), |
---|
109 | potential vorticity (pv), potential temperature (pt) |
---|
110 | and depth (dp). |
---|
111 | Default is an empty string. |
---|
112 | |
---|
113 | levelist: string, optional |
---|
114 | Specifies the required levels. It has to have a valid |
---|
115 | correspondence to the selected levtype. |
---|
116 | Examples: model level: 1/to/137, pressure levels: 500/to/1000 |
---|
117 | Default is an empty string. |
---|
118 | |
---|
119 | repres: string, optional |
---|
120 | Selects the representation of the archived data. |
---|
121 | E.g. sh - spherical harmonics, gg - Gaussian grid, |
---|
122 | ll - latitude/longitude, ... |
---|
123 | Default is an empty string. |
---|
124 | |
---|
125 | date: string, optional |
---|
126 | Specifies the Analysis date, the Forecast base date or |
---|
127 | Observations date. Valid formats are: |
---|
128 | Absolute as YYYY-MM-DD or YYYYMMDD. |
---|
129 | Default is an empty string. |
---|
130 | |
---|
131 | resol: string, optional |
---|
132 | Specifies the desired triangular truncation of retrieved data, |
---|
133 | before carrying out any other selected post-processing. |
---|
134 | The default is automatic truncation (auto), by which the lowest |
---|
135 | resolution compatible with the value specified in grid is |
---|
136 | automatically selected for the retrieval. |
---|
137 | Users wanting to perform post-processing from full spectral |
---|
138 | resolution should specify Archived Value (av). |
---|
139 | The following are examples of existing resolutions found in |
---|
140 | the archive: 63, 106, 159, 213, 255, 319, 399, 511, 799 or 1279. |
---|
141 | This keyword has no meaning/effect if the archived data is |
---|
142 | not in spherical harmonics representation. |
---|
143 | The best selection can be found here: |
---|
144 | https://software.ecmwf.int/wiki/display/UDOC/\ |
---|
145 | Retrieve#Retrieve-Truncationbeforeinterpolation |
---|
146 | Default is an empty string. |
---|
147 | |
---|
148 | stream: string, optional |
---|
149 | Identifies the forecasting system used to generate the data. |
---|
150 | E.g. oper (Atmospheric model), enfo (Ensemble forecats), ... |
---|
151 | Default is an empty string. |
---|
152 | |
---|
153 | area: string, optional |
---|
154 | Specifies the desired sub-area of data to be extracted. |
---|
155 | Areas can be defined to wrap around the globe. |
---|
156 | |
---|
157 | Latitude values must be given as signed numbers, with: |
---|
158 | north latitudes (i.e. north of the equator) |
---|
159 | being positive (e.g: 40.5) |
---|
160 | south latitutes (i.e. south of the equator) |
---|
161 | being negative (e.g: -50.5) |
---|
162 | Longtitude values must be given as signed numbers, with: |
---|
163 | east longitudes (i.e. east of the 0 degree meridian) |
---|
164 | being positive (e.g: 35.0) |
---|
165 | west longitudes (i.e. west of the 0 degree meridian) |
---|
166 | being negative (e.g: -20.5) |
---|
167 | |
---|
168 | E.g.: North/West/South/East |
---|
169 | Default is an empty string. |
---|
170 | |
---|
171 | time: string, optional |
---|
172 | Specifies the time of the data in hours and minutes. |
---|
173 | Valid values depend on the type of data: Analysis time, |
---|
174 | Forecast base time or First guess verification time |
---|
175 | (all usually at synoptic hours: 00, 06, 12 and 18 ). |
---|
176 | Observation time (any combination in hours and minutes is valid, |
---|
177 | subject to data availability in the archive). |
---|
178 | The syntax is HHMM or HH:MM. If MM is omitted it defaults to 00. |
---|
179 | Default is an empty string. |
---|
180 | |
---|
181 | step: string, optional |
---|
182 | Specifies the forecast time step from forecast base time. |
---|
183 | Valid values are hours (HH) from forecast base time. It also |
---|
184 | specifies the length of the forecast which verifies at |
---|
185 | First Guess time. |
---|
186 | E.g. 1/3/6-hourly |
---|
187 | Default is an empty string. |
---|
188 | |
---|
189 | expver: string, optional |
---|
190 | The version of the dataset. Each experiment is assigned a |
---|
191 | unique code (version). Production data is assigned 1 or 2, |
---|
192 | and experimental data in Operations 11, 12 ,... |
---|
193 | Research or Member State's experiments have a four letter |
---|
194 | experiment identifier. |
---|
195 | Default is "1". |
---|
196 | |
---|
197 | number: string, optional |
---|
198 | Selects the member in ensemble forecast run. (Only then it |
---|
199 | is necessary.) It has a different meaning depending on |
---|
200 | the type of data. |
---|
201 | E.g. Perturbed Forecasts: specifies the Ensemble forecast member |
---|
202 | Default is an empty string. |
---|
203 | |
---|
204 | accuracy: string, optional |
---|
205 | Specifies the number of bits per value to be used in the |
---|
206 | generated GRIB coded fields. |
---|
207 | A positive integer may be given to specify the preferred number |
---|
208 | of bits per packed value. This must not be greater than the |
---|
209 | number of bits normally used for a Fortran integer on the |
---|
210 | processor handling the request (typically 32 or 64 bit). |
---|
211 | Within a compute request the accuracy of the original fields |
---|
212 | can be passed to the result field by specifying accuracy=av. |
---|
213 | Default is an empty string. |
---|
214 | |
---|
215 | grid: string, optional |
---|
216 | Specifies the output grid which can be either a Gaussian grid |
---|
217 | or a Latitude/Longitude grid. MARS requests specifying |
---|
218 | grid=av will return the archived model grid. |
---|
219 | |
---|
220 | Lat/Lon grid: The grid spacing needs to be an integer |
---|
221 | fraction of 90 degrees e.g. grid = 0.5/0.5 |
---|
222 | |
---|
223 | Gaussian grid: specified by a letter denoting the type of |
---|
224 | Gaussian grid followed by an integer (the grid number) |
---|
225 | representing the number of lines between the Pole and Equator, |
---|
226 | e.g. |
---|
227 | grid = F160 - full (or regular) Gaussian grid with |
---|
228 | 160 latitude lines between the pole and equator |
---|
229 | grid = N320 - ECMWF original reduced Gaussian grid with |
---|
230 | 320 latitude lines between the pole and equator, |
---|
231 | see Reduced Gaussian Grids for grid numbers used at ECMWF |
---|
232 | grid = O640 - ECMWF octahedral (reduced) Gaussian grid with |
---|
233 | 640 latitude lines between the pole and equator |
---|
234 | Default is an empty string. |
---|
235 | |
---|
236 | gaussian: string, optional |
---|
237 | This parameter is deprecated and should no longer be used. |
---|
238 | Specifies the desired type of Gaussian grid for the output. |
---|
239 | Valid Gaussian grids are quasi-regular (reduced) or regular. |
---|
240 | Keyword gaussian can only be specified together with |
---|
241 | keyword grid. Gaussian without grid has no effect. |
---|
242 | Default is an empty string. |
---|
243 | |
---|
244 | target: string, optional |
---|
245 | Specifies a file into which data is to be written after |
---|
246 | retrieval or manipulation. Path names should always be |
---|
247 | enclosed in double quotes. The MARS client supports automatic |
---|
248 | generation of multiple target files using MARS keywords |
---|
249 | enclosed in square brackets [ ]. If the environment variable |
---|
250 | MARS_MULTITARGET_STRICT_FORMAT is set to 1 before calling mars, |
---|
251 | the keyword values will be used in the filename as shown by |
---|
252 | the ecCodes GRIB tool grib_ls -m, e.g. with |
---|
253 | MARS_MULTITARGET_STRICT_FORMAT set to 1 the keywords time, |
---|
254 | expver and param will be formatted as 0600, 0001 and 129.128 |
---|
255 | rather than 600, 1 and 129. |
---|
256 | Default is an empty string. |
---|
257 | |
---|
258 | param: string, optional |
---|
259 | Specifies the meteorological parameter. |
---|
260 | The list of meteorological parameters in MARS is extensive. |
---|
261 | Their availability is directly related to their meteorological |
---|
262 | meaning and, therefore, the rest of directives specified |
---|
263 | in the MARS request. |
---|
264 | Meteorological parameters can be specified by their |
---|
265 | GRIB code (param=130), their mnemonic (param=t) or |
---|
266 | full name (param=temperature). |
---|
267 | The list of parameter should be seperated by a "/"-sign. |
---|
268 | E.g. 130/131/133 |
---|
269 | Default is an empty string. |
---|
270 | |
---|
271 | @Return: |
---|
272 | <nothing> |
---|
273 | ''' |
---|
274 | |
---|
275 | self.server = server |
---|
276 | self.marsclass = marsclass |
---|
277 | self.type = type |
---|
278 | self.levtype = levtype |
---|
279 | self.levelist = levelist |
---|
280 | self.repres = repres |
---|
281 | self.date = date |
---|
282 | self.resol = resol |
---|
283 | self.stream = stream |
---|
284 | self.area = area |
---|
285 | self.time = time |
---|
286 | self.step = step |
---|
287 | self.expver = expver |
---|
288 | self.number = number |
---|
289 | self.accuracy = accuracy |
---|
290 | self.grid = grid |
---|
291 | self.gaussian = gaussian |
---|
292 | self.target = target |
---|
293 | self.param = param |
---|
294 | |
---|
295 | return |
---|
296 | |
---|
297 | |
---|
298 | def displayInfo(self): |
---|
299 | ''' |
---|
300 | @Description: |
---|
301 | Prints all class attributes and their values. |
---|
302 | |
---|
303 | @Input: |
---|
304 | self: instance of MARSretrieval |
---|
305 | For description see class documentation. |
---|
306 | |
---|
307 | @Return: |
---|
308 | <nothing> |
---|
309 | ''' |
---|
310 | # Get all class attributes and their values as a dictionary |
---|
311 | attrs = vars(self) |
---|
312 | |
---|
313 | # iterate through all attributes and print them |
---|
314 | # with their corresponding values |
---|
315 | for item in attrs.items(): |
---|
316 | if item[0] in ('server'): |
---|
317 | pass |
---|
318 | else: |
---|
319 | print(item[0] + ': ' + str(item[1])) |
---|
320 | |
---|
321 | return |
---|
322 | |
---|
323 | def dataRetrieve(self): |
---|
324 | ''' |
---|
325 | @Description: |
---|
326 | Submits a MARS retrieval. Depending on the existence of |
---|
327 | ECMWF Web-API it is submitted via Python or a |
---|
328 | subprocess in the Shell. The parameter for the mars retrieval |
---|
329 | are taken from the defined class attributes. |
---|
330 | |
---|
331 | @Input: |
---|
332 | self: instance of MARSretrieval |
---|
333 | For description see class documentation. |
---|
334 | |
---|
335 | @Return: |
---|
336 | <nothing> |
---|
337 | ''' |
---|
338 | # Get all class attributes and their values as a dictionary |
---|
339 | attrs = vars(self) |
---|
340 | |
---|
341 | # convert the dictionary of attributes into a comma |
---|
342 | # seperated list of attributes with their values |
---|
343 | # needed for the retrieval call |
---|
344 | s = 'ret' |
---|
345 | for k, v in attrs.iteritems(): |
---|
346 | if k in ('server'): |
---|
347 | continue |
---|
348 | if k == 'marsclass': |
---|
349 | k = 'class' |
---|
350 | if v == '': |
---|
351 | continue |
---|
352 | if k.lower() == 'target': |
---|
353 | target = v |
---|
354 | else: |
---|
355 | s = s + ',' + k + '=' + str(v) |
---|
356 | |
---|
357 | # MARS request via Python script |
---|
358 | if self.server is not False: |
---|
359 | try: |
---|
360 | self.server.execute(s, target) |
---|
361 | except: |
---|
362 | print('MARS Request failed, \ |
---|
363 | have you already registered at apps.ecmwf.int?') |
---|
364 | raise IOError |
---|
365 | if os.stat(target).st_size == 0: |
---|
366 | print('MARS Request returned no data - please check request') |
---|
367 | raise IOError |
---|
368 | # MARS request via extra process in shell |
---|
369 | else: |
---|
370 | s += ',target = "' + target + '"' |
---|
371 | p = subprocess.Popen(['mars'], stdin=subprocess.PIPE, |
---|
372 | stdout=subprocess.PIPE, |
---|
373 | stderr=subprocess.PIPE, bufsize=1) |
---|
374 | pout = p.communicate(input=s)[0] |
---|
375 | print(pout.decode()) |
---|
376 | |
---|
377 | if 'Some errors reported' in pout.decode(): |
---|
378 | print('MARS Request failed - please check request') |
---|
379 | raise IOError |
---|
380 | |
---|
381 | if os.stat(target).st_size == 0: |
---|
382 | print('MARS Request returned no data - please check request') |
---|
383 | raise IOError |
---|
384 | |
---|
385 | return |
---|