source: flex_extract.git/python/getMARSdata.py @ 51f9853

ctbtodev
Last change on this file since 51f9853 was 51f9853, checked in by anphi <anne.philipp@…>, 6 years ago

added request parameter for writing mars requests into csv file

  • Property mode set to 100755
File size: 5.6 KB
Line 
1#!/usr/bin/env python
2#
3# This software is licensed under the terms of the Apache Licence Version 2.0
4# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
5#
6# Functionality provided: Prepare input 3D-wind fields in hybrid coordinates + surface fields for FLEXPART runs
7#
8# Creation: October  2014 - Anne Fouilloux - University of Oslo
9# Extension November 2015 - Leopold Haimberger - University of Vienna for:
10# - using the WebAPI also for general MARS retrievals
11# - job submission on ecgate and cca
12# - job templates suitable for twice daily operational dissemination
13# - dividing retrievals of longer periods into digestable chunks
14# - retrieve also longer term forecasts, not only analyses and short term forecast data
15# - conversion into GRIB2
16# - conversion into .fp format for faster execution of FLEXPART
17#
18#
19# Further documentation may be obtained from www.flexpart.eu
20#
21# Requirements:
22# in addition to a standard python 2.6 or 2.7 installation the following packages need to be installed
23# ECMWF WebMARS, gribAPI with python enabled, emoslib, ecaccess web toolkit, all available from https://software.ecmwf.int/
24# dateutils
25# matplotlib (optional, for debugging)
26#
27# Get MARS GRIB fields from ECMWF for FLEXPART
28#
29
30#import socket
31
32#hostname=socket.gethostname()
33#ecapi= 'ecmwf' not in hostname
34try:
35    ecapi=True
36    import ecmwfapi
37except ImportError:
38    ecapi=False
39
40import calendar
41import shutil
42import datetime
43import time
44import os,glob,sys,inspect
45#from string import strip
46from argparse import ArgumentParser,ArgumentDefaultsHelpFormatter
47# add path to submit.py to pythonpath so that python finds its buddies
48localpythonpath=os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
49if localpythonpath not in sys.path:
50    sys.path.append(localpythonpath)
51
52from FlexpartTools import MARSretrieval, EIFlexpart, silentremove, \
53     Control,myerror,normalexit, interpret_args_and_control
54
55
56def getMARSdata(args,c):
57
58    if not os.path.exists(c.inputdir):
59        os.makedirs(c.inputdir)
60    print "start date %s "%(c.start_date)
61    print "end date %s "%(c.end_date)
62   
63    if c.request == '0' or c.request == '2':
64        print("Retrieving EC data!")
65    elif c.request == '1':
66        print("Printing mars requests!")
67
68    if ecapi:
69        if int(c.public):
70            server = ecmwfapi.ECMWFDataServer()
71        else:
72            server = ecmwfapi.ECMWFService("mars")
73    else:
74        server = False
75
76    c.ecapi=ecapi
77    print 'ecapi:',c.ecapi
78# Retrieve ERA interim data for running flexpart
79
80    syear=int(c.start_date[:4])
81    smonth=int(c.start_date[4:6])
82    sday=int(c.start_date[6:])
83    start = datetime.date( year = syear, month = smonth, day = sday )
84    startm1=start- datetime.timedelta(days=1)
85    if c.basetime=='00':
86        start=startm1
87    eyear=int(c.end_date[:4])
88    emonth=int(c.end_date[4:6])
89    eday=int(c.end_date[6:])
90
91    end = datetime.date( year = eyear, month = emonth, day = eday )
92    if c.basetime=='00' or c.basetime=='12':
93        endp1=end+ datetime.timedelta(days=1)
94    else:
95        endp1=end+ datetime.timedelta(days=2)
96
97    datechunk=datetime.timedelta(days=int(c.date_chunk))
98    if c.request == '0' or c.request == '2':
99        print 'removing content of '+c.inputdir
100        tobecleaned=glob.glob(c.inputdir+'/*_acc_*.'+str(os.getppid())+'.*.grb')
101        for f in tobecleaned:
102            os.remove(f)
103
104    times=None
105    if c.maxstep<=24:
106        day=startm1
107        while day<endp1:
108            # we need to retrieve MARS data for this period (maximum one month)
109            flexpart = EIFlexpart(c,fluxes=True)
110            if day+datechunk-datetime.timedelta(days=1)<endp1:
111                dates= day.strftime("%Y%m%d") + "/to/" + (day+datechunk-datetime.timedelta(days=1)).strftime("%Y%m%d")
112            else:
113                dates= day.strftime("%Y%m%d") + "/to/" + end.strftime("%Y%m%d")
114
115            print "retrieve " + dates + " in dir " + c.inputdir
116            try:
117                flexpart.retrieve(server, c.public, dates, c.request, times, c.inputdir)
118            except IOError:
119                myerror(c,'MARS request failed')
120
121            day+=datechunk
122    else:
123        day=start
124        while day<=end:
125            # we need to retrieve MARS data for this period (maximum one month)
126            flexpart = EIFlexpart(c,fluxes=True)
127            if day+datechunk-datetime.timedelta(days=1)<end:
128                dates= day.strftime("%Y%m%d") + "/to/" + (day+datechunk-datetime.timedelta(days=1)).strftime("%Y%m%d")
129            else:
130                dates= day.strftime("%Y%m%d") + "/to/" + end.strftime("%Y%m%d")
131
132            print "retrieve " + dates + " in dir " + c.inputdir
133            flexpart.retrieve(server, c.public, dates, c.request, times, c.inputdir)
134            day+=datechunk
135
136
137    if c.request == '0' or c.request == '2':
138        print 'removing content of '+c.inputdir
139        tobecleaned=glob.glob(c.inputdir+'/*__*.'+str(os.getppid())+'.*.grb')
140        for f in tobecleaned:
141            os.remove(f)
142           
143    day=start
144    times=None
145    while day<=end:
146
147            # we need to retrieve MARS data for this period (maximum one month)
148        flexpart = EIFlexpart(c)
149        if day+datechunk-datetime.timedelta(days=1)<end:
150            dates= day.strftime("%Y%m%d") + "/to/" + (day+datechunk-datetime.timedelta(days=1)).strftime("%Y%m%d")
151        else:
152            dates= day.strftime("%Y%m%d") + "/to/" + end.strftime("%Y%m%d")
153        print "retrieve " + dates + " in dir " + c.inputdir
154
155        flexpart.retrieve(server, c.public, dates, c.request, times, c.inputdir)
156        day+=datechunk
157
158
159if __name__ == "__main__":
160
161    args,c=interpret_args_and_control()
162    getMARSdata(args,c)
163    normalexit(c)
Note: See TracBrowser for help on using the repository browser.
hosted by ZAMG