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

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

commented out the WRF parts since they are still under construction and added License SPDX tags

  • Property mode set to 100755
File size: 11.0 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 seperate function
13#        - adatpted the function for the use in flex_extract
14#        - renamed 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#        - seperated 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-2019.
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 servers.
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_retrievement - 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()))) + '/../')
72import _config
73from Mods.tools import (setup_controldata, my_error, normal_exit, get_cmdline_args,
74                   read_ecenv, make_dir)
75from Classes.EcFlexpart import EcFlexpart
76from Classes.UioFiles import UioFiles
77from Classes.MarsRetrieval import MarsRetrieval
78
79try:
80    ec_api = True
81    import ecmwfapi
82except ImportError:
83    ec_api = False
84
85try:
86    cds_api = True
87    import cdsapi
88except ImportError:
89    cds_api = False
90# ------------------------------------------------------------------------------
91# FUNCTION
92# ------------------------------------------------------------------------------
93def main():
94    '''Controls the program to get data out of mars.
95
96    This is done if it is called directly from command line.
97    Then it also takes program call arguments and control file input.
98
99    Parameters
100    ----------
101
102    Return
103    ------
104
105    '''
106
107    c, _, _, _ = setup_controldata()
108    get_mars_data(c)
109    normal_exit('Retrieving MARS data: Done!')
110
111    return
112
113def get_mars_data(c):
114    '''Retrieves the EC data needed for a FLEXPART simulation.
115
116    Start and end dates for retrieval period is set. Retrievals
117    are divided into smaller periods if necessary and datechunk parameter
118    is set.
119
120    Parameters
121    ----------
122    c : ControlFile
123        Contains all the parameters of CONTROL file and
124        command line.
125
126    Return
127    ------
128
129    '''
130    c.ec_api = ec_api
131    c.cds_api = cds_api
132
133    if not os.path.exists(c.inputdir):
134        make_dir(c.inputdir)
135
136    if c.request == 0:
137        print("Retrieving EC data!")
138    else:
139        if c.request == 1:
140            print("Printing mars requests!")
141        elif c.request == 2:
142            print("Retrieving EC data and printing mars request!")
143        write_reqheader(os.path.join(c.inputdir, _config.FILE_MARS_REQUESTS))
144
145    print("start date %s " % (c.start_date))
146    print("end date %s " % (c.end_date))
147
148    server = mk_server(c)
149
150    # if data are to be retrieved, clean up any old grib files
151    if c.request == 0 or c.request == 2:
152        remove_old('*grb', c.inputdir)
153
154    # --------------  flux data ------------------------------------------------
155    start, end, datechunk = mk_dates(c, fluxes=True)
156    do_retrievement(c, server, start, end, datechunk, fluxes=True)
157
158    # --------------  non flux data --------------------------------------------
159    start, end, datechunk = mk_dates(c, fluxes=False)
160    do_retrievement(c, server, start, end, datechunk, fluxes=False)
161
162    return
163
164def write_reqheader(marsfile):
165    '''Writes header with column names into mars request file.
166
167    Parameters
168    ----------
169    marsfile : str
170        Path to the mars request file.
171
172    Return
173    ------
174
175    '''
176    MR = MarsRetrieval(None, None)
177    attrs = vars(MR).copy()
178    del attrs['server']
179    del attrs['public']
180    with open(marsfile, 'w') as f:
181        f.write('request_number' + ', ')
182        f.write(', '.join(str(key) for key in sorted(attrs.keys())))
183        f.write('\n')
184
185    return
186
187def mk_server(c):
188    '''Creates a server connection with available python API.
189
190    Which API is used depends on availability and the dataset to be retrieved.
191    The CDS API is used for ERA5 dataset no matter if the user is a member or
192    a public user. ECMWF WebAPI is used for all other available datasets.
193
194    Parameters
195    ----------
196    c : ControlFile
197        Contains all the parameters of CONTROL file and
198        command line.
199
200    Return
201    ------
202    server : ECMWFDataServer, ECMWFService or Client
203        Connection to ECMWF server via python interface ECMWF WebAPI or CDS API.
204
205    '''
206    if cds_api and (c.marsclass.upper() == 'EA'):
207        server = cdsapi.Client()
208        c.ec_api = False
209    elif c.ec_api:
210        if c.public:
211            server = ecmwfapi.ECMWFDataServer()
212        else:
213            server = ecmwfapi.ECMWFService("mars")
214        c.cds_api = False
215    else:
216        server = False
217
218    print('Using ECMWF WebAPI: ' + str(c.ec_api))
219    print('Using CDS API: ' + str(c.cds_api))
220
221    return server
222
223
224def check_dates_for_nonflux_fc_times(types, times):
225    '''
226    '''
227    for ty, ti in zip(types,times):
228        if ty.upper() == 'FC' and int(ti) == 18:
229            return True
230    return False
231
232
233def mk_dates(c, fluxes):
234    '''Prepares start and end date depending on flux or non flux data.
235
236    If forecast for maximum one day (upto 24h) are to be retrieved, then
237    collect accumulation data (flux data) with additional days in the
238    beginning and at the end (used for complete disaggregation of
239    original period)
240
241    If forecast data longer than 24h are to be retrieved, then
242    collect accumulation data (flux data) with the exact start and end date
243    (disaggregation will be done for the exact time period with
244    boundary conditions)
245
246    Since for basetime the extraction contains the 12 hours upfront,
247    if basetime is 0, the starting date has to be the day before and
248
249    Parameters
250    ----------
251    c : ControlFile
252        Contains all the parameters of CONTROL file and
253        command line.
254
255    fluxes : boolean, optional
256        Decides if the flux parameter settings are stored or
257        the rest of the parameter list.
258        Default value is False.
259
260    Return
261    ------
262    start : datetime
263        The start date of the retrieving data set.
264
265    end : datetime
266        The end date of the retrieving data set.
267
268    chunk : datetime
269        Time period in days for one single mars retrieval.
270
271    '''
272    start = datetime.strptime(c.start_date, '%Y%m%d')
273    end = datetime.strptime(c.end_date, '%Y%m%d')
274    chunk = timedelta(days=int(c.date_chunk))
275
276    if c.basetime == 0:
277        start = start - timedelta(days=1)
278
279    if c.purefc and fluxes and c.maxstep < 24:
280        start = start - timedelta(days=1)
281        end = end + timedelta(days=1)
282
283    if not c.purefc and fluxes and not c.basetime == 0:
284        start = start - timedelta(days=1)
285        end = end + timedelta(days=1)
286
287    # if we have non-flux forecast data starting at 18 UTC
288    # we need to start retrieving data one day in advance
289    if not fluxes and check_dates_for_nonflux_fc_times(c.type, c.time):
290        start = start - timedelta(days=1)
291
292    return start, end, chunk
293
294def remove_old(pattern, inputdir):
295    '''Deletes old retrieval files from current input directory
296    matching the pattern.
297
298    Parameters
299    ----------
300    pattern : str
301        The sub string pattern which identifies the files to be deleted.
302
303    inputdir : str, optional
304        Path to the directory where the retrieved data is stored.
305
306    Return
307    ------
308
309    '''
310    print('... removing old content of ' + inputdir)
311
312    tobecleaned = UioFiles(inputdir, pattern)
313    tobecleaned.delete_files()
314
315    return
316
317
318def do_retrievement(c, server, start, end, delta_t, fluxes=False):
319    '''Divides the complete retrieval period in smaller chunks and
320    retrieves the data from MARS.
321
322    Parameters
323    ----------
324    c : ControlFile
325        Contains all the parameters of CONTROL file and
326        command line.
327
328    server : ECMWFService or ECMWFDataServer
329            The server connection to ECMWF.
330
331    start : datetime
332        The start date of the retrieval.
333
334    end : datetime
335        The end date of the retrieval.
336
337    delta_t : datetime
338        Delta_t + 1 is the maximal time period of a single
339        retrieval.
340
341    fluxes : boolean, optional
342        Decides if the flux parameters are to be retrieved or
343        the rest of the parameter list.
344        Default value is False.
345
346    Return
347    ------
348
349    '''
350
351    # since actual day also counts as one day,
352    # we only need to add datechunk - 1 days to retrieval
353    # for a period
354    delta_t_m1 = delta_t - timedelta(days=1)
355
356    day = start
357    while day <= end:
358        flexpart = EcFlexpart(c, fluxes)
359        tmpday = day + delta_t_m1
360        if tmpday < end:
361            dates = day.strftime("%Y%m%d") + "/to/" + \
362                    tmpday.strftime("%Y%m%d")
363        else:
364            dates = day.strftime("%Y%m%d") + "/to/" + \
365                    end.strftime("%Y%m%d")
366
367        print("... retrieve " + dates + " in dir " + c.inputdir)
368
369        try:
370            flexpart.retrieve(server, dates, c.public, c.request, c.inputdir)
371        except IOError:
372            my_error('MARS request failed')
373
374        day += delta_t
375
376    return
377
378if __name__ == "__main__":
379    main()
Note: See TracBrowser for help on using the repository browser.
hosted by ZAMG