source: flex_extract.git/Source/Python/Mods/get_mars_data.py @ a676cf7

dev
Last change on this file since a676cf7 was a676cf7, checked in by Anne Tipka <anne.tipka@…>, 18 months ago

modifications and adjustments to dates and times for correctly retrieving analysis and forecast data in operational mode

  • Property mode set to 100755
File size: 11.6 KB
Line 
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3#*******************************************************************************
4# @Author: Anne Fouilloux (University of Oslo)
5#
6# @Date: October 2014
7#
8# @Change History:
9#
10#    November 2015 - Leopold Haimberger (University of Vienna):
11#        - moved the getEIdata program into a function "get_mars_data"
12#        - moved the AgurmentParser into a separate function
13#        - adapted the function for use in flex_extract
14#        - renamed source file to get_mars_data
15#
16#    February 2018 - Anne Philipp (University of Vienna):
17#        - applied PEP8 style guide
18#        - added structured documentation
19#        - minor changes in programming style for consistence
20#        - added function main and moved function calls vom __main__ there
21#          (necessary for better documentation with docstrings for later
22#          online documentation)
23#        - use of UIFiles class for file selection and deletion
24#        - separated get_mars_data function into several smaller pieces:
25#          write_reqheader, mk_server, mk_dates, remove_old, do_retrievment
26#
27# @License:
28#    (C) Copyright 2014-2020.
29#    Anne Philipp, Leopold Haimberger
30#
31#    SPDX-License-Identifier: CC-BY-4.0
32#
33#    This work is licensed under the Creative Commons Attribution 4.0
34#    International License. To view a copy of this license, visit
35#    http://creativecommons.org/licenses/by/4.0/ or send a letter to
36#    Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
37#*******************************************************************************
38'''This script extracts MARS data from ECMWF.
39
40At first, the necessary parameters from command line and CONTROL files are
41extracted. They define the data set to be extracted from MARS.
42
43This file can also be imported as a module and contains the following
44functions:
45
46    * main            - the main function of the script
47    * get_mars_data   - overall control of ECMWF data retrievment
48    * write_reqheader - writes the header into the mars_request file
49    * mk_server       - creates the server connection to ECMWF servers
50    * mk_dates        - defines the start and end date
51    * remove_old      - deletes old retrieved grib files
52    * do_retrieval    - creates individual retrievals
53
54Type get_mars_data.py --help
55to get information about command line parameters.
56Read the documentation for usage instructions.
57'''
58# ------------------------------------------------------------------------------
59# MODULES
60# ------------------------------------------------------------------------------
61from __future__ import print_function
62
63import os
64import sys
65import inspect
66from datetime import datetime, timedelta
67
68# software-specific classes and modules from flex_extract
69# add path to local main Python path for flex_extract to get full access
70sys.path.append(os.path.dirname(os.path.abspath(
71    inspect.getfile(inspect.currentframe()))) + '/../')
72# pylint: disable=wrong-import-position
73import _config
74from Mods.tools import (setup_controldata, my_error, normal_exit, make_dir)
75from Classes.EcFlexpart import EcFlexpart
76from Classes.UioFiles import UioFiles
77from Classes.MarsRetrieval import MarsRetrieval
78# pylint: enable=wrong-import-position
79# pylint: disable=invalid-name
80try:
81    ec_api = True
82    import ecmwfapi
83except ImportError:
84    ec_api = False
85
86try:
87    cds_api = True
88    import cdsapi
89except ImportError:
90    cds_api = False
91# pylint: enable=invalid-name
92# ------------------------------------------------------------------------------
93# FUNCTION
94# ------------------------------------------------------------------------------
95def main():
96    '''Controls the program to retrieve data from MARS.
97
98    This is done if called directly from command line.
99    Then, arguments and control file are taken as input.
100
101    Parameters
102    ----------
103
104    Return
105    ------
106
107    '''
108
109    c, _, _, _ = setup_controldata()
110    get_mars_data(c)
111    normal_exit('Retrieving MARS data: Done!')
112
113    return
114
115def get_mars_data(c):
116    '''Retrieves the ECMWF data required for a FLEXPART simulation.
117
118    Start and end dates for retrieval period are set. Retrievals
119    are divided into shorter periods if necessary and if datechunk parameter
120    is set.
121
122    Parameters
123    ----------
124    c : ControlFile
125        Contains all the parameters of CONTROL file and
126        command line.
127
128    Return
129    ------
130
131    '''
132    c.ec_api = ec_api
133    c.cds_api = cds_api
134
135    if not os.path.exists(c.inputdir):
136        make_dir(c.inputdir)
137
138    if c.request == 0:
139        print("Retrieving ECMWF data!")
140    else:
141        if c.request == 1:
142            print("Printing MARS requests!")
143        elif c.request == 2:
144            print("Retrieving ECMWF data and printing MARS request!")
145        write_reqheader(os.path.join(c.inputdir, _config.FILE_MARS_REQUESTS))
146
147    print("start date %s " % (c.start_date))
148    print("end date %s " % (c.end_date))
149
150    if c.public:
151        server = mk_server(c)
152    else:
153        server = False
154
155    # if data are to be retrieved, clean up any old grib files
156    if c.request == 0 or c.request == 2:
157        remove_old('*grb', c.inputdir)
158
159    # --------------  flux data ------------------------------------------------
160    start, end, datechunk = mk_dates(c, fluxes=True)
161    do_retrievement(c, server, start, end, datechunk, fluxes=True)
162   
163    # --------------  non flux data --------------------------------------------
164    start, end, datechunk = mk_dates(c, fluxes=False)
165    do_retrievement(c, server, start, end, datechunk, fluxes=False)
166
167    return
168
169def write_reqheader(marsfile):
170    '''Writes header with column names into MARS request file.
171
172    Parameters
173    ----------
174    marsfile : str
175        Path to the MARS request file.
176
177    Return
178    ------
179
180    '''
181    MR = MarsRetrieval(None, None)
182    attrs = vars(MR).copy()
183    del attrs['server']
184    del attrs['public']
185    with open(marsfile, 'w') as f:
186        f.write('request_number' + ', ')
187        f.write(', '.join(str(key) for key in sorted(attrs.keys())))
188        f.write('\n')
189
190    return
191
192def mk_server(c):
193    '''Creates a server connection with available Python API.
194
195    The API selected depends on availability and the data set to be retrieved.
196    The CDS API is used for ERA5 data, no matter whether the user is a
197    member-state or a public user.
198    ECMWF WebAPI is used for all other available datasets.
199
200    Parameters
201    ----------
202    c : ControlFile
203        Contains all the parameters of CONTROL file and
204        command line.
205
206    Return
207    ------
208    server : ECMWFDataServer, ECMWFService or Client
209        Connection to ECMWF server via python interface ECMWF WebAPI or CDS API.
210
211    '''
212    if cds_api and (c.marsclass.upper() == 'EA'):
213        server = cdsapi.Client()
214        c.ec_api = False
215    elif c.ec_api:
216        if c.public:
217            server = ecmwfapi.ECMWFDataServer()
218        else:
219            server = ecmwfapi.ECMWFService("mars")
220        c.cds_api = False
221    else:
222        server = False
223
224    print('Using ECMWF WebAPI: ' + str(c.ec_api))
225    print('Using CDS API: ' + str(c.cds_api))
226
227    return server
228
229
230def check_dates_for_nonflux_fc_times(types, times):
231    '''Checks if the time 18UTC corresponds to forecast field.
232
233    Parameters
234    ----------
235    types : list of str
236        List of field types.
237
238    times : list of str or str
239        The time in hours of the field.
240
241    Return
242    ------
243    True or False
244
245    '''
246    for ty, ti in zip(types, times):
247        if ty.upper() == 'FC' and int(ti) == 18:
248            return True
249    return False
250
251
252def mk_dates(c, fluxes):
253    '''Prepares start and end date depending on flux or non-flux type of data.
254
255    If forecasts for a maximum of one day (24 h) are to be retrieved, then
256    collect accumulation data (flux data) with additional days in the
257    beginning and at the end (needed for complete disaggregation of
258    original period)
259
260    If forecast data for more than +24 h are to be retrieved, then
261    collect accumulation data (flux data) with the exact start and end date
262    (disaggregation will be done for the exact time period with
263    boundary conditions)
264
265    Since for basetime the extraction contains the 12 hours upfront,
266    if basetime is 0, the starting date has to be the day before
267
268    Parameters
269    ----------
270    c : ControlFile
271        Contains all the parameters of CONTROL file and
272        command line.
273
274    fluxes : boolean, optional
275        Decides if the flux parameter settings are stored or
276        the rest of the parameter list.
277        Default value is False.
278
279    Return
280    ------
281    start : datetime
282        The start date of the retrieving data set.
283
284    end : datetime
285        The end date of the retrieving data set.
286
287    chunk : datetime
288        Time period in days for one single mars retrieval.
289
290    '''
291    start = datetime.strptime(c.start_date, '%Y%m%d')
292    end = datetime.strptime(c.end_date, '%Y%m%d')
293    chunk = timedelta(days=int(c.date_chunk))
294
295    if c.basetime == 0 and not fluxes and not c.purefc:  # non-fluxes
296        start = start - timedelta(days=1)
297
298    if c.purefc and fluxes and c.maxstep < 24:
299        start = start - timedelta(days=1)
300#        if not c.oper:
301#            end = end + timedelta(days=1)
302
303    if not c.purefc and fluxes:
304        start = start - timedelta(days=1)
305        if not c.oper:
306            end = end + timedelta(days=1)
307#        elif c.oper and c.basetime == 0:
308#            end = end - timedelta(days=1)
309
310    # if we have non-flux forecast data starting at 18 UTC
311    # we need to start retrieving data one day in advance
312    if not fluxes and check_dates_for_nonflux_fc_times(c.type, c.time):
313        start = start - timedelta(days=1)
314
315    return start, end, chunk
316
317def remove_old(pattern, inputdir):
318    '''Deletes old retrieval files from current input directory
319    matching the pattern.
320
321    Parameters
322    ----------
323    pattern : str
324        The substring pattern which identifies the files to be deleted.
325
326    inputdir : str, optional
327        Path to the directory where the retrieved data are stored.
328
329    Return
330    ------
331
332    '''
333    print('... removing old files in ' + inputdir)
334
335    tobecleaned = UioFiles(inputdir, pattern)
336    tobecleaned.delete_files()
337
338    return
339
340
341def do_retrievement(c, server, start, end, delta_t, fluxes=False):
342    '''Divides the total retrieval period into smaller chunks and
343    retrieves the data from MARS.
344
345    Parameters
346    ----------
347    c : ControlFile
348        Contains all the parameters of CONTROL file and
349        command line.
350
351    server : ECMWFService or ECMWFDataServer
352            The server connection to ECMWF.
353
354    start : datetime
355        The start date of the retrieval.
356
357    end : datetime
358        The end date of the retrieval.
359
360    delta_t : datetime
361        Delta_t + 1 is the maximum time period of a single retrieval.
362
363    fluxes : boolean, optional
364        Decides if the flux parameters are to be retrieved or
365        the rest of the parameter list.
366        Default value is False.
367
368    Return
369    ------
370
371    '''
372
373    # since actual day also counts as one day,
374    # we only need to add datechunk - 1 days to retrieval for a period
375    delta_t_m1 = delta_t - timedelta(days=1)
376
377    day = start
378    while day <= end:
379        flexpart = EcFlexpart(c, fluxes)
380        tmpday = day + delta_t_m1
381        if tmpday < end:
382            dates = day.strftime("%Y%m%d") + "/to/" + \
383                    tmpday.strftime("%Y%m%d")
384        else:
385            dates = day.strftime("%Y%m%d") + "/to/" + \
386                    end.strftime("%Y%m%d")
387
388        print("... retrieve " + dates + " in dir " + c.inputdir)
389
390        try:
391            flexpart.retrieve(server, dates, c.public, c.purefc, c.request, c.inputdir)
392        except IOError:
393            my_error('MARS request failed')
394
395        day += delta_t
396
397    return
398
399if __name__ == "__main__":
400    main()
Note: See TracBrowser for help on using the repository browser.
hosted by ZAMG