Changeset f20af73 in flex_extract.git for source/python/mods


Ignore:
Timestamp:
Mar 8, 2019, 10:05:20 AM (5 years ago)
Author:
Anne Philipp <anne.philipp@…>
Branches:
master, ctbto, dev
Children:
82c2959
Parents:
b4a4777
Message:

added CDS API support for ERA5 instead of ECMWFAPI / refactored setup of CONTROL parameter because for local version it wanted to use not installed ECMWF_ENV file.

Location:
source/python/mods
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • source/python/mods/checks.py

    r5551626 rf20af73  
    2727import sys
    2828import _config
    29 import exceptions
    30 from tools import my_error, silent_remove
     29try:
     30    import exceptions
     31except ImportError:
     32    import builtins as exceptions
     33from .tools import my_error, silent_remove
    3134from datetime import datetime
    3235import numpy as np
     
    296299            step = ['{:0>3}'.format(i) for i in ilist]
    297300        elif 'to' in step.lower() and 'by' not in step.lower():
    298             my_error(mailfail, step + ':\n' +
     301            my_error(step + ':\n' +
    299302                     'if "to" is used in steps parameter, '
    300303                     'please use "by" as well')
  • source/python/mods/get_mars_data.py

    r45b99e6 rf20af73  
    6767    inspect.getfile(inspect.currentframe()))) + '/../')
    6868import _config
    69 from tools import (my_error, normal_exit, get_cmdline_args,
     69from .tools import (setup_controldata, my_error, normal_exit, get_cmdline_args,
    7070                   read_ecenv, make_dir)
    7171from classes.EcFlexpart import EcFlexpart
     
    7474
    7575try:
    76     ecapi = True
     76    ec_api = True
    7777    import ecmwfapi
    7878except ImportError:
    79     ecapi = False
     79    ec_api = False
     80
     81try:
     82    cds_api = True
     83    import cdsapi
     84except ImportError:
     85    cds_api = False
    8086# ------------------------------------------------------------------------------
    8187# FUNCTION
     
    95101    '''
    96102
    97     args = get_cmdline_args()
    98     c = ControlFile(args.controlfile)
    99 
    100     env_parameter = read_ecenv(_config.PATH_ECMWF_ENV)
    101     c.assign_args_to_control(args)
    102     c.assign_envs_to_control(env_parameter)
    103     c.check_conditions(args.queue)
    104 
     103    c, _, _, _ = setup_controldata()
    105104    get_mars_data(c)
    106     normal_exit(c.mailops, c.queue, 'Done!')
     105    normal_exit('Retrieving MARS data: Done!')
    107106
    108107    return
     
    125124
    126125    '''
    127     c.ecapi = ecapi
     126    c.ec_api = ec_api
     127    c.cds_api = cds_api
    128128
    129129    if not os.path.exists(c.inputdir):
     
    182182
    183183def mk_server(c):
    184     '''Creates server connection if ECMWF WebAPI is available.
     184    '''Creates a server connection with available python API.
     185
     186    Which API is used depends on availability and the dataset to be retrieved.
     187    The CDS API is used for ERA5 dataset no matter if the user is a member or
     188    a public user. ECMWF WebAPI is used for all other available datasets.
    185189
    186190    Parameters
     
    192196    Return
    193197    ------
    194     server : ECMWFDataServer or ECMWFService
    195         Connection to ECMWF server via python interface ECMWF WebAPI.
    196 
    197     '''
    198     if c.ecapi:
     198    server : ECMWFDataServer, ECMWFService or Client
     199        Connection to ECMWF server via python interface ECMWF WebAPI or CDS API.
     200
     201    '''
     202    if cds_api and (c.marsclass.upper() == 'EA'):
     203        server = cdsapi.Client()
     204        c.ec_api = False
     205    elif c.ec_api:
    199206        if c.public:
    200207            server = ecmwfapi.ECMWFDataServer()
    201208        else:
    202209            server = ecmwfapi.ECMWFService("mars")
     210        c.cds_api = False
    203211    else:
    204212        server = False
    205213
    206     print('Using ECMWF WebAPI: ' + str(c.ecapi))
     214    print('Using ECMWF WebAPI: ' + str(c.ec_api))
     215    print('Using CDS API: ' + str(c.cds_api))
    207216
    208217    return server
     
    353362            flexpart.retrieve(server, dates, c.public, c.request, c.inputdir)
    354363        except IOError:
    355             my_error(c.mailfail, 'MARS request failed')
     364            my_error('MARS request failed')
    356365
    357366        day += delta_t
  • source/python/mods/prepare_flexpart.py

    re811e1a rf20af73  
    7171    inspect.getfile(inspect.currentframe()))) + '/../')
    7272import _config
    73 from checks import check_ppid
     73from .checks import check_ppid
    7474from classes.UioFiles import UioFiles
    7575from classes.ControlFile import ControlFile
    76 from tools import clean_up, get_cmdline_args, read_ecenv, make_dir
     76from .tools import (setup_controldata, clean_up, get_cmdline_args,
     77                   read_ecenv, make_dir)
    7778from classes.EcFlexpart import EcFlexpart
    78 
    79 ecapi = 'ecmwf' not in socket.gethostname()
    80 try:
    81     if ecapi:
    82         import ecmwfapi
    83 except ImportError:
    84     ecapi = False
    8579
    8680# ------------------------------------------------------------------------------
     
    10195    '''
    10296
    103     args = get_cmdline_args()
    104     c = ControlFile(args.controlfile)
    105 
    106     env_parameter = read_ecenv(_config.PATH_ECMWF_ENV)
    107     c.assign_args_to_control(args)
    108     c.assign_envs_to_control(env_parameter)
    109     c.check_conditions(args.queue)
    110 
    111     prepare_flexpart(args.ppid, c)
     97    c, ppid, _, _ = setup_controldata()
     98    prepare_flexpart(ppid, c)
     99    normal_exit('Preparing FLEXPART output files: Done!')
    112100
    113101    return
     
    136124    '''
    137125    check_ppid(c, ppid)
    138 
    139     c.ecapi = ecapi
    140126
    141127    # create the start and end date
  • source/python/mods/tools.py

    r8778c5a rf20af73  
    6565import subprocess
    6666import traceback
    67 import exceptions
     67try:
     68    import exceptions
     69except ImportError:
     70    import builtins as exceptions
    6871from datetime import datetime
    6972from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
     73
     74
    7075
    7176# ------------------------------------------------------------------------------
    7277# METHODS
    7378# ------------------------------------------------------------------------------
     79
     80def setup_controldata():
     81    '''Collects, stores and checks controlling arguments from command line,
     82    CONTROL file and ECMWF_ENV file.
     83
     84    Parameters
     85    ----------
     86
     87    Return
     88    ------
     89    c : ControlFile
     90        Contains all the parameters of CONTROL file and
     91        command line.
     92
     93    ppid : str
     94        Parent process id.
     95
     96    queue : str
     97        Name of queue for submission to ECMWF (e.g. ecgate or cca )
     98
     99    job_template : str
     100        Name of the job template file for submission to ECMWF server.
     101    '''
     102    import _config
     103    from classes.ControlFile import ControlFile
     104
     105    args = get_cmdline_args()
     106    c = ControlFile(args.controlfile)
     107    c.assign_args_to_control(args)
     108    if os.path.isfile(_config.PATH_ECMWF_ENV):
     109        env_parameter = read_ecenv(_config.PATH_ECMWF_ENV)
     110        c.assign_envs_to_control(env_parameter)
     111    c.check_conditions(args.queue)
     112
     113    return c, args.ppid, args.queue, args.job_template
    74114
    75115def none_or_str(value):
     
    259299    print("... clean inputdir!")
    260300
    261     cleanlist = glob.glob(os.path.join(c.inputdir, "*"))
     301    cleanlist = [file for file in glob.glob(os.path.join(c.inputdir, "*"))
     302                 if not os.path.basename(file).startswith(c.prefix)]
    262303
    263304    if cleanlist:
    264305        for element in cleanlist:
    265             if c.prefix not in element:
    266                 silent_remove(element)
    267             if c.ecapi is False and (c.ectrans == 1 or c.ecstorage == 1):
    268                 silent_remove(element)
     306            silent_remove(element)
    269307        print("... done!")
    270308    else:
     
    274312
    275313
    276 def my_error(users, message='ERROR'):
     314def my_error(message='ERROR'):
    277315    '''Prints a specified error message which can be passed to the function
    278316    before exiting the program.
     
    280318    Parameters
    281319    ----------
    282     user : list of str
    283         Contains all email addresses which should be notified.
    284         It might also contain just the ecmwf user name which wil trigger
    285         mailing to the associated email address for this user.
    286 
    287320    message : str, optional
    288321        Error message. Default value is "ERROR".
     
    464497    else:
    465498        for data in fdata:
    466             if data[0] != '!':
    467                 table128[data[0:3]] = data[59:64].strip()
     499            if data != '' and data[0] != '!':
     500                table128[data[0:3]] = data[59:65].strip()
    468501
    469502    return table128
     
    508541
    509542    return ipar
     543
     544def to_param_id_with_tablenumber(pars, table):
     545    '''Transform parameter names to parameter ids and add table id.
     546
     547    Conversion with ECMWF grib table 128.
     548
     549    Parameters
     550    ----------
     551    pars : str
     552        Addpar argument from CONTROL file in the format of
     553        parameter names instead of ids. The parameter short
     554        names are sepearted with "/" and they are passed as
     555        one single string.
     556
     557    table : dict
     558        Contains the ECMWF grib table 128 information.
     559        The key is the parameter number and the value is the
     560        short name of the parameter.
     561
     562    Return
     563    ------
     564    spar : str
     565        List of addpar parameters from CONTROL file transformed to
     566        parameter ids in the format of integer.
     567    '''
     568    if not pars:
     569        return []
     570    if not isinstance(pars, str):
     571        pars=str(pars)
     572
     573    cpar = pars.upper().split('/')
     574    spar = []
     575    for par in cpar:
     576        for k, v in table.iteritems():
     577            if par == k or par == v:
     578                spar.append(k + '.128')
     579                break
     580        else:
     581            print('\n\n\t\tWarning: par ' + par + ' not found in table 128\n\n')
     582
     583    return '/'.join(spar)
    510584
    511585def get_list_as_string(list_obj, concatenate_sign=', '):
Note: See TracChangeset for help on using the changeset viewer.
hosted by ZAMG