Changeset 0f89116 in flex_extract.git


Ignore:
Timestamp:
Dec 19, 2019, 8:07:12 PM (4 years ago)
Author:
Anne Philipp <anne.philipp@…>
Branches:
master, ctbto, dev
Children:
a73c0f6
Parents:
0d99607
Message:

diverse changes due to PEP8 style guide and eliminating grib2flexpart; removed unused parameter

Location:
Source/Python
Files:
14 edited

Legend:

Unmodified
Added
Removed
  • Source/Python/Classes/ControlFile.py

    r44174de r0f89116  
    3838
    3939import os
    40 import re
    4140import sys
    42 import inspect
    4341
    4442# software specific classes and modules from flex_extract
     43#pylint: disable=wrong-import-position
    4544sys.path.append('../')
    4645import _config
    47 from Mods.tools import my_error, silent_remove
     46from Mods.tools import my_error
    4847from Mods.checks import (check_grid, check_area, check_levels, check_purefc,
    4948                         check_step, check_mail, check_queue, check_pathes,
     
    5352                         check_logicals_type, check_len_type_time_step,
    5453                         check_addpar, check_job_chunk, check_number)
     54#pylint: enable=wrong-import-position
    5555
    5656# ------------------------------------------------------------------------------
     
    6565    from the MARS archive for driving FLEXPART are set in a CONTROL file.
    6666    Some specific parameters like the start and end dates can be overwritten
    67     by the command line parameters, but in generel all parameters needed
     67    by the command line parameters, but in generall all parameters needed
    6868    for a complete set of fields for FLEXPART can be set in the CONTROL file.
    6969
     
    238238        Default value is ['${USER}'].
    239239
    240     grib2flexpart : int 0
    241         Switch to select generation of preprocessed FLEXPART files ".fp".
    242         If it is selected, the program grib2flexpart will try
    243         to convert the flex_extract output files into ".fp" format.
    244 
    245240    ecstorage : int
    246241        Switch to select storage of FLEXPART ready output files
     
    334329        List of the names of logical switches which controls the flow
    335330        of the program. Default list is ['gauss', 'omega', 'omegadiff', 'eta',
    336         'etadiff', 'dpdeta', 'cwc', 'wrf', 'grib2flexpart', 'ecstorage',
     331        'etadiff', 'dpdeta', 'cwc', 'wrf', 'ecstorage',
    337332        'ectrans', 'debug', 'request', 'public', 'purefc', 'rrint', 'doubleelda']
    338333    '''
     
    400395        self.mailfail = ['${USER}']
    401396        self.mailops = ['${USER}']
    402         self.grib2flexpart = 0
    403397        self.ecstorage = 0
    404398        self.ectrans = 0
     
    425419
    426420        self.logicals = ['gauss', 'omega', 'omegadiff', 'eta', 'etadiff',
    427                          'dpdeta', 'cwc', 'wrf', 'grib2flexpart', 'ecstorage',
     421                         'dpdeta', 'cwc', 'wrf', 'ecstorage',
    428422                         'ectrans', 'debug', 'oper', 'request', 'public',
    429423                         'purefc', 'rrint', 'doubleelda']
     
    602596
    603597        self.outputdir, self.installdir = check_pathes(self.inputdir,
    604              self.outputdir, self.installdir, self.flexextractdir)
     598                                                       self.outputdir,
     599                                                       self.installdir,
     600                                                       self.flexextractdir)
    605601
    606602        self.start_date, self.end_date = check_dates(self.start_date,
     
    611607        self.levelist, self.level = check_levels(self.levelist, self.level)
    612608
    613         self.step = check_step(self.step, self.mailfail)
     609        self.step = check_step(self.step)
    614610
    615611        self.maxstep = check_maxstep(self.maxstep, self.step)
     
    649645        self.job_chunk = check_job_chunk(self.job_chunk)
    650646
    651         self.number = check_number(self.number, self.mailfail)
     647        self.number = check_number(self.number)
    652648
    653649        return
     
    695691
    696692        return sorted(l)
    697 
  • Source/Python/Classes/EcFlexpart.py

    rc77630a r0f89116  
    5353#pylint: disable=consider-using-enumerate
    5454# this is not useful in this case
     55#pylint: disable=unsubscriptable-object
     56# this error is a bug
     57#pylint: disable=ungrouped-imports
     58# not necessary that we group the imports
    5559# ------------------------------------------------------------------------------
    5660# MODULES
     
    6266import glob
    6367import shutil
    64 import subprocess
    6568from datetime import datetime, timedelta
    6669
    6770# software specific classes and modules from flex_extract
     71#pylint: disable=wrong-import-position
    6872sys.path.append('../')
    6973import _config
    7074from Classes.GribUtil import GribUtil
    7175from Mods.tools import (init128, to_param_id, silent_remove, product,
    72                         my_error, make_dir, get_informations, get_dimensions,
     76                        my_error, get_informations, get_dimensions,
    7377                        execute_subprocess, to_param_id_with_tablenumber,
    7478                        generate_retrieval_period_boundary)
     
    7680from Classes.UioFiles import UioFiles
    7781import Mods.disaggregation as disaggregation
    78 
     82#pylint: enable=wrong-import-position
    7983# ------------------------------------------------------------------------------
    8084# CLASS
     
    401405        else:  # GAUSS and ETA
    402406            print('Warning: Collecting etadot and parameters for gaussian grid '
    403                            'is a very costly parameter combination, '
    404                            'use this combination only for debugging!')
     407                  'is a very costly parameter combination, '
     408                  'use this combination only for debugging!')
    405409            self.params['GG__SL'] = ['Q', 'ML', '1',
    406410                                     '{}'.format((int(self.resol) + 1) // 2)]
     
    415419
    416420        # ADDITIONAL FIELDS FOR FLEXPART-WRF MODEL (IF QUESTIONED)
    417         # -----------------------------------------------------------------------
     421        # ----------------------------------------------------------------------
    418422        if wrf:
    419423            # @WRF
     
    710714                    retr_param_dict['date'] = self.dates.split('/')[0]
    711715                    retr_param_dict['target'] = self._mk_targetname('',
    712                                             pk, retr_param_dict['date'])
     716                                                                    pk,
     717                                                                    retr_param_dict['date'])
    713718                elif pk == 'OG_OROLSM__SL' and oro:
    714719                    continue
     
    752757                        if 'acc' in pk:
    753758                            startdate = retr_param_dict['date'].split('/')[0]
    754                             enddate = datetime.strftime(elimit - t24h,'%Y%m%d')
     759                            enddate = datetime.strftime(elimit - t24h, '%Y%m%d')
    755760                            retr_param_dict['date'] = '/'.join([startdate,
    756761                                                                'to',
     
    781786                        timesave = ''.join(retr_param_dict['time'])
    782787
    783                         if ('/' in retr_param_dict['time'] and
    784                             pk != 'OG_OROLSM__SL' and
    785                             'acc' not in pk ) :
     788                        if all(['/' in retr_param_dict['time'],
     789                                pk != 'OG_OROLSM__SL',
     790                                'acc' not in pk]):
    786791                            times = retr_param_dict['time'].split('/')
    787792                            steps = retr_param_dict['step'].split('/')
     
    794799                                    retr_param_dict['time'] = times[0]
    795800
    796                         if (pk != 'OG_OROLSM__SL' and
    797                             int(retr_param_dict['step'].split('/')[0]) == 0 and
    798                             int(timesave.split('/')[0]) == 0):
     801                        if all([pk != 'OG_OROLSM__SL',
     802                                int(retr_param_dict['step'].split('/')[0]) == 0,
     803                                int(timesave.split('/')[0]) == 0]):
    799804
    800805                            retr_param_dict['date'] = \
     
    810815                    else:
    811816                        raise ValueError('ERROR: Basetime has an invalid value '
    812                                                  '-> {}'.format(str(basetime)))
     817                                         '-> {}'.format(str(self.basetime)))
    813818
    814819        if request == 0 or request == 2:
     
    860865
    861866            stream = namelist_template.generate(
    862                 maxl = str(maxl),
    863                 maxb = str(maxb),
    864                 mlevel = str(self.level),
    865                 mlevelist = str(self.levelist),
    866                 mnauf = str(self.resol),
    867                 metapar = '77',
    868                 rlo0 = str(area[1]),
    869                 rlo1 = str(area[3]),
    870                 rla0 = str(area[2]),
    871                 rla1 = str(area[0]),
    872                 momega = str(c.omega),
    873                 momegadiff = str(c.omegadiff),
    874                 mgauss = str(c.gauss),
    875                 msmooth = str(c.smooth),
    876                 meta = str(c.eta),
    877                 metadiff = str(c.etadiff),
    878                 mdpdeta = str(c.dpdeta)
     867                maxl=str(maxl),
     868                maxb=str(maxb),
     869                mlevel=str(self.level),
     870                mlevelist=str(self.levelist),
     871                mnauf=str(self.resol),
     872                metapar='77',
     873                rlo0=str(area[1]),
     874                rlo1=str(area[3]),
     875                rla0=str(area[2]),
     876                rla1=str(area[0]),
     877                momega=str(c.omega),
     878                momegadiff=str(c.omegadiff),
     879                mgauss=str(c.gauss),
     880                msmooth=str(c.smooth),
     881                meta=str(c.eta),
     882                metadiff=str(c.etadiff),
     883                mdpdeta=str(c.dpdeta)
    879884            )
    880885        except UndefinedError as e:
     
    928933        '''
    929934        import numpy as np
    930         from eccodes import (codes_index_select, codes_new_from_index, codes_get,
     935        from eccodes import (codes_index_select, codes_get,
    931936                             codes_get_values, codes_set_values, codes_set,
    932937                             codes_write, codes_release, codes_new_from_index,
     
    10531058            step = codes_get(gid, 'step') # integer
    10541059            ctime = '{:0>2}'.format(time)
    1055             cstep = '{:0>3}'.format(step)
    10561060
    10571061            t_date = datetime.strptime(cdate + ctime, '%Y%m%d%H')
     
    11321136                    deac_vals[parId].append(
    11331137                        (orig_vals[parId][-1] - orig_vals[parId][-2]) /
    1134                          int(c.dtime))
     1138                        int(c.dtime))
    11351139
    11361140                # store precipitation if new disaggregation method is selected
     
    13321336            for inum in range(maxnum):
    13331337                for ix in range(ni*nj):
    1334                     lsp_new_np[inum,ix,:] = disaggregation.IA3(lsp_np[inum,ix,:])[:-1]
    1335                     cp_new_np[inum,ix,:] = disaggregation.IA3(cp_np[inum,ix,:])[:-1]
     1338                    lsp_new_np[inum, ix, :] = disaggregation.IA3(lsp_np[inum, ix, :])[:-1]
     1339                    cp_new_np[inum, ix, :] = disaggregation.IA3(cp_np[inum, ix, :])[:-1]
    13361340        else:
    13371341            for ix in range(ni*nj):
    1338                 lsp_new_np[0,ix,:] = disaggregation.IA3(lsp_np[ix,:])[:-1]
    1339                 cp_new_np[0,ix,:] = disaggregation.IA3(cp_np[ix,:])[:-1]
     1342                lsp_new_np[0, ix, :] = disaggregation.IA3(lsp_np[ix, :])[:-1]
     1343                cp_new_np[0, ix, :] = disaggregation.IA3(cp_np[ix, :])[:-1]
    13401344
    13411345        # write to grib files (full/orig times to flux file and inbetween
     
    14021406            # write original time step to flux file as usual
    14031407            fluxfile = GribUtil(os.path.join(c.inputdir, fluxfilename))
    1404             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1408            fluxfile.set_keys(tmpfile, filemode='ab',
    14051409                              wherekeynames=['paramId'], wherekeyvalues=[142],
    1406                               keynames=['perturbationNumber','date','time','stepRange','values'],
     1410                              keynames=['perturbationNumber', 'date', 'time',
     1411                                        'stepRange', 'values'],
    14071412                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
    1408                                          date.hour*100, 0, lsp_new_np[inumb,:,it]],
     1413                                         date.hour*100, 0, lsp_new_np[inumb, :, it]],
    14091414                             )
    1410             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1415            fluxfile.set_keys(tmpfile, filemode='ab',
    14111416                              wherekeynames=['paramId'], wherekeyvalues=[143],
    1412                               keynames=['perturbationNumber','date','time','stepRange','values'],
    1413                               keyvalues=[inumb,int(date.strftime('%Y%m%d')),
    1414                                          date.hour*100, 0, cp_new_np[inumb,:,it]]
     1417                              keynames=['perturbationNumber', 'date', 'time',
     1418                                        'stepRange', 'values'],
     1419                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1420                                         date.hour*100, 0, cp_new_np[inumb, :, it]]
    14151421                             )
    14161422
    14171423            # rr for first subgrid point is identified by step = 1
    1418             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1424            fluxfile.set_keys(tmpfile, filemode='ab',
    14191425                              wherekeynames=['paramId'], wherekeyvalues=[142],
    1420                               keynames=['perturbationNumber','date','time','stepRange','values'],
    1421                               keyvalues=[inumb,int(date.strftime('%Y%m%d')),
    1422                                          date.hour*100, '1', lsp_new_np[inumb,:,it+1]]
    1423                               )
    1424             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1426                              keynames=['perturbationNumber', 'date', 'time',
     1427                                        'stepRange', 'values'],
     1428                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1429                                         date.hour*100, '1', lsp_new_np[inumb, :, it+1]]
     1430                             )
     1431            fluxfile.set_keys(tmpfile, filemode='ab',
    14251432                              wherekeynames=['paramId'], wherekeyvalues=[143],
    1426                               keynames=['perturbationNumber','date','time','stepRange','values'],
    1427                               keyvalues=[inumb,int(date.strftime('%Y%m%d')),
    1428                                          date.hour*100, '1', cp_new_np[inumb,:,it+1]]
    1429                               )
     1433                              keynames=['perturbationNumber', 'date', 'time',
     1434                                        'stepRange', 'values'],
     1435                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1436                                         date.hour*100, '1', cp_new_np[inumb, :, it+1]]
     1437                             )
    14301438
    14311439            # rr for second subgrid point is identified by step = 2
    1432             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1440            fluxfile.set_keys(tmpfile, filemode='ab',
    14331441                              wherekeynames=['paramId'], wherekeyvalues=[142],
    1434                               keynames=['perturbationNumber','date','time','stepRange','values'],
    1435                               keyvalues=[inumb,int(date.strftime('%Y%m%d')),
    1436                                          date.hour*100, '2', lsp_new_np[inumb,:,it+2]]
    1437                               )
    1438             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1442                              keynames=['perturbationNumber', 'date', 'time',
     1443                                        'stepRange', 'values'],
     1444                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1445                                         date.hour*100, '2', lsp_new_np[inumb, :, it+2]]
     1446                             )
     1447            fluxfile.set_keys(tmpfile, filemode='ab',
    14391448                              wherekeynames=['paramId'], wherekeyvalues=[143],
    1440                               keynames=['perturbationNumber','date','time','stepRange','values'],
    1441                               keyvalues=[inumb,int(date.strftime('%Y%m%d')),
    1442                                          date.hour*100, '2', cp_new_np[inumb,:,it+2]]
    1443                               )
     1449                              keynames=['perturbationNumber', 'date', 'time',
     1450                                        'stepRange', 'values'],
     1451                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1452                                         date.hour*100, '2', cp_new_np[inumb, :, it+2]]
     1453                             )
    14441454
    14451455            it = it + 3 # jump to next original time step in rr fields
     
    14631473        '''
    14641474
    1465         gribfile = GribUtil(os.path.join(inputdir,'rr_grib_dummy.grb'))
     1475        gribfile = GribUtil(os.path.join(inputdir, 'rr_grib_dummy.grb'))
    14661476
    14671477        gribfile.copy_dummy_msg(ifile, keynames=['paramId'],
    1468                       keyvalues=[142], filemode='wb')
     1478                                keyvalues=[142], filemode='wb')
    14691479
    14701480        gribfile.copy_dummy_msg(ifile, keynames=['paramId'],
    1471                       keyvalues=[143], filemode='ab')
     1481                                keyvalues=[143], filemode='ab')
    14721482
    14731483        return
     
    15011511
    15021512        '''
    1503         from eccodes import (codes_index_select, codes_new_from_index, codes_get,
     1513        from eccodes import (codes_index_select, codes_get,
    15041514                             codes_get_values, codes_set_values, codes_set,
    15051515                             codes_write, codes_release, codes_new_from_index,
     
    15831593            cdate_hour = datetime.strftime(timestamp, '%Y%m%d%H')
    15841594
     1595            # if basetime is used, adapt start/end date period
     1596            if c.basetime is not None:
     1597                time_delta = timedelta(hours=12-int(c.dtime))
     1598                start_period = datetime.strptime(c.end_date + str(c.basetime),
     1599                                               '%Y%m%d%H') - time_delta
     1600                end_period = datetime.strptime(c.end_date + str(c.basetime),
     1601                                             '%Y%m%d%H')
     1602
    15851603            # skip all temporary times
    1586             # which are outside the retrieval period
     1604            # which are outside the retrieval period               
    15871605            if timestamp < start_period or \
    15881606               timestamp > end_period:
    15891607                continue
    1590 
    1591             # if the timestamp is out of basetime start/end date period,
    1592             # skip this specific product
    1593             if c.basetime is not None:
    1594                 time_delta = timedelta(hours=12-int(c.dtime))
    1595                 start_time = datetime.strptime(c.end_date + str(c.basetime),
    1596                                                 '%Y%m%d%H') - time_delta
    1597                 end_time = datetime.strptime(c.end_date + str(c.basetime),
    1598                                              '%Y%m%d%H')
    1599                 if timestamp < start_time or timestamp > end_time:
    1600                     continue
     1608               
    16011609
    16021610            # @WRF
     
    16201628                paramId = codes_get(gid, 'paramId')
    16211629                gridtype = codes_get(gid, 'gridType')
    1622                 levtype = codes_get(gid, 'typeOfLevel')
    16231630                if paramId == 77: # ETADOT
    16241631                    codes_write(gid, fdict['21'])
     
    17041711            # Fortran program creates file fort.15 (with u,v,etadot,t,sp,q)
    17051712            execute_subprocess([os.path.join(c.exedir,
    1706                                 _config.FORTRAN_EXECUTABLE)],
     1713                                             _config.FORTRAN_EXECUTABLE)],
    17071714                               error_msg='FORTRAN PROGRAM FAILED!')#shell=True)
    17081715
     
    17331740            # to the outputfile (final GRIB input files for FLEXPART)
    17341741            orolsm = os.path.basename(glob.glob(c.inputdir +
    1735                                         '/OG_OROLSM__SL.*.' + c.ppid + '*')[0])
     1742                                                '/OG_OROLSM__SL.*.' +
     1743                                                c.ppid +
     1744                                                '*')[0])
    17361745            fluxfile = 'flux' + cdate[0:2] + suffix
    17371746            if not c.cwc:
     
    17831792        '''
    17841793        from eccodes import (codes_grib_new_from_file, codes_get_array,
    1785                              codes_set_array, codes_release, codes_set_values,
    1786                              codes_set, codes_write, codes_release)
     1794                             codes_set_array, codes_release,
     1795                             codes_set, codes_write)
    17871796
    17881797        # max number
     
    17901799
    17911800        # get a list of all prepared output files with control forecast (CF)
    1792         CF_filelist = UioFiles(path, prefix + '*.N000')
    1793         CF_filelist.files = sorted(CF_filelist.files)
    1794 
    1795         for cffile in CF_filelist.files:
     1801        cf_filelist = UioFiles(path, prefix + '*.N000')
     1802        cf_filelist.files = sorted(cf_filelist.files)
     1803
     1804        for cffile in cf_filelist.files:
    17961805            with open(cffile, 'rb') as f:
    1797                 cfvalues=[]
     1806                cfvalues = []
    17981807                while True:
    17991808                    fid = codes_grib_new_from_file(f)
     
    19001909
    19011910        return
    1902 
  • Source/Python/Classes/GribUtil.py

    rc77630a r0f89116  
    6868
    6969
    70     def get_keys(self, keynames, wherekeynames=[], wherekeyvalues=[]):
     70    def get_keys(self, keynames, wherekeynames, wherekeyvalues):
    7171        '''Get keyvalues for a given list of keynames a where statement
    7272        can be given (list of key and list of values)
     
    7777            List of keynames.
    7878
    79         wherekeynames : :obj:`list` of :obj:`string`, optional
    80             Default value is an empty list.
    81 
    82         wherekeyvalues : :obj:`list` of :obj:`string`, optional
    83             Default value is an empty list.
     79        wherekeynames : :obj:`list` of :obj:`string`
     80            List of key names for indexing grib message parameter.
     81
     82        wherekeyvalues : :obj:`list` of :obj:`string`
     83            List of key values corresponding the key names.
    8484
    8585        Return
     
    122122
    123123
    124     def set_keys(self, fromfile, keynames, keyvalues, wherekeynames=[],
    125                  wherekeyvalues=[], strict=False, filemode='wb'):
     124    def set_keys(self, fromfile, keynames, keyvalues, wherekeynames,
     125                 wherekeyvalues, filemode='wb'):
    126126        '''Opens the file to read the grib messages and then write
    127127        the selected messages (with wherekeys) to a new output file.
     
    141141            Default is an empty list.
    142142
    143         wherekeynames : :obj:`list` of :obj:`string`, optional
     143        wherekeynames : :obj:`list` of :obj:`string`
    144144            List of keynames to select correct message.
    145             Default value is an empty list.
    146 
    147         wherekeyvalues : :obj:`list` of :obj:`string`, optional
     145
     146        wherekeyvalues : :obj:`list` of :obj:`string`
    148147            List of keyvalues for keynames to select correct message.
    149             Default value is an empty list.
    150 
    151         strict : :obj:`boolean`, optional
    152             Decides if everything from keynames and keyvalues
    153             is written out the grib file (False) or only those
    154             meeting the where statement (True). Default is False.
    155148
    156149        filemode : :obj:`string`, optional
     
    200193        return
    201194
    202     def copy_dummy_msg(self, filename_in, selectWhere=True,
    203                  keynames=[], keyvalues=[], filemode='wb'):
     195    def copy_dummy_msg(self, filename_in, keynames, keyvalues,
     196                       selectwhere=True, filemode='wb'):
    204197        '''Add the content of another input grib file to the objects file but
    205198        only messages corresponding to keys/values passed to the function.
     
    212205            Filename of the input file to read the grib messages from.
    213206
    214         selectWhere : :obj:`boolean`, optional
     207        selectwhere : :obj:`boolean`, optional
    215208            Decides if to copy the keynames and values equal to (True) or
    216209            different to (False) the keynames/keyvalues list passed to the
    217210            function. Default is True.
    218211
    219         keynames : :obj:`list` of :obj:`string`, optional
    220             List of keynames. Default is an empty list.
    221 
    222         keyvalues : :obj:`list` of :obj:`string`, optional
    223             List of keyvalues. Default is an empty list.
     212        keynames : :obj:`list` of :obj:`string`
     213            List of keynames.
     214
     215        keyvalues : :obj:`list` of :obj:`string`
     216            List of keyvalues.
    224217
    225218        filemode : :obj:`string`, optional
     
    254247                    raise Exception("Key was not defined")
    255248
    256                 if selectWhere:
     249                if selectwhere:
    257250                    select = (select and (str(keyvalues[i]) ==
    258251                                          str(codes_get(gid, key))))
     
    272265        return
    273266
    274     def index(self, index_keys=["mars"], index_file="my.idx"):
     267    def index(self, index_keys, index_file="my.idx"):
    275268        '''Create index file from a list of files if it does not exist or
    276269        read an index file.
     
    278271        Parameters
    279272        ----------
    280         index_keys: :obj:`list` of :obj:`string`, optional
     273        index_keys: :obj:`list` of :obj:`string`
    281274            Contains the list of key parameter names from
    282275            which the index is to be created.
    283             Default is a list with a single entry string "mars".
    284276
    285277        index_file: :obj:`string`, optional
  • Source/Python/Classes/MarsRetrieval.py

    rc77630a r0f89116  
    4242
    4343# software specific classes and modules from flex_extract
     44#pylint: disable=wrong-import-position
    4445sys.path.append('../')
    4546import _config
     47#pylint: disable=invalid-name
    4648try:
    4749    ec_api = True
     
    5557except ImportError:
    5658    cds_api = False
     59#pylint: enable=invalid-name
     60#pylint: enable=wrong-import-position
    5761# ------------------------------------------------------------------------------
    5862# CLASS
     
    510514                print('\n\nMARS Request failed!')
    511515                print(e)
    512                 tb = sys.exc_info()[2]
    513516                print(traceback.format_exc())
    514517                sys.exit()
  • Source/Python/Classes/UioFiles.py

    r44174de r0f89116  
    4242
    4343# software specific modules from flex_extract
     44#pylint: disable=wrong-import-position
    4445sys.path.append('../')
    4546from Mods.tools import silent_remove, get_list_as_string
     47#pylint: enable=wrong-import-position
    4648
    4749# ------------------------------------------------------------------------------
     
    5052
    5153class UioFiles(object):
    52     '''Collection of files matching a specific pattern.
     54    """Collection of files matching a specific pattern.
    5355
    5456    The pattern can contain regular expressions for the files.
     
    6264
    6365    pattern : str
    64         Regular expression pattern. For example: '\*.grb'
     66        Regular expression pattern. For example: '*.grb'
    6567
    6668    files : list of str
    6769        List of files matching the pattern in the path.
    68     '''
     70    """
    6971    # --------------------------------------------------------------------------
    7072    # CLASS METHODS
    7173    # --------------------------------------------------------------------------
    7274    def __init__(self, path, pattern):
    73         '''Assignes a specific pattern for these files.
     75        """Assignes a specific pattern for these files.
    7476
    7577        Parameters
     
    7981
    8082        pattern : str
    81             Regular expression pattern. For example: '\*.grb'
     83            Regular expression pattern. For example: '*.grb'
    8284
    8385        Return
    8486        ------
    8587
    86         '''
     88        """
    8789
    8890        self.path = path
     
    9698
    9799    def _list_files(self, path):
    98         '''Lists all files in the directory with the matching
     100        """Lists all files in the directory with the matching
    99101        regular expression pattern.
    100102
     
    107109        ------
    108110
    109         '''
     111        """
    110112        # Get the absolute path
    111113        path = os.path.abspath(path)
    112114
    113115        # get all files in the dir and subdir as absolut path
     116            # pylint: disable=W0612
    114117        for root, dirnames, filenames in os.walk(path):
    115118            for filename in fnmatch.filter(filenames, self.pattern):
     
    120123
    121124    def __str__(self):
    122         '''Converts the list of files into a single string.
     125        """Converts the list of files into a single string.
    123126        The entries are sepereated by "," sign.
    124127
     
    130133        files_string : str
    131134            The content of the list as a single string.
    132         '''
     135        """
    133136
    134137        filenames = [os.path.basename(f) for f in self.files]
     
    139142
    140143    def delete_files(self):
    141         '''Deletes the files.
     144        """Deletes the files.
    142145
    143146        Parameters
     
    147150        ------
    148151
    149         '''
     152        """
    150153
    151154        for old_file in self.files:
  • Source/Python/Mods/checks.py

    r44174de r0f89116  
    2929import os
    3030import sys
    31 
    32 import _config
     31from datetime import datetime
     32# pylint: disable=unused-import
    3333try:
    3434    import exceptions
    3535except ImportError:
    3636    import builtins as exceptions
    37 from datetime import datetime
     37# pylint: enable=unused-import
     38
     39# software specific classes and modules from flex_extract
     40import _config
    3841from Mods.tools import my_error, silent_remove
    3942# ------------------------------------------------------------------------------
     
    113116    return grid
    114117
    115 def check_area(grid, area, upper, lower, left , right):
     118def check_area(grid, area, upper, lower, left, right):
    116119    '''Defines the correct area string.
    117120
     
    158161
    159162    # determine area format
    160     if ((abs(float(upper) / 10000.) >= 0.01 or float(upper) / 1000. == 0. ) and
    161         (abs(float(lower) / 10000.) >= 0.01 or float(lower) / 1000. == 0. ) and
    162         (abs(float(left) / 10000.) >= 0.01 or float(left) / 1000. == 0. ) and
    163         (abs(float(right) / 10000.) >= 0.01 or float(right) / 1000. == 0.)):
     163    if all([(abs(float(upper) / 10000.) >= 0.01 or float(upper) / 1000. == 0.),
     164            (abs(float(lower) / 10000.) >= 0.01 or float(lower) / 1000. == 0.),
     165            (abs(float(left) / 10000.) >= 0.01 or float(left) / 1000. == 0.),
     166            (abs(float(right) / 10000.) >= 0.01 or float(right) / 1000. == 0.)]):
    164167        # area is defined in 1/1000 degrees; old format
    165168        area = '{}/{}/{}/{}'.format(float(upper) / 1000.,
     
    167170                                    float(lower) / 1000.,
    168171                                    float(right) / 1000.)
    169     elif (abs(float(upper) / 10000.) < 0.05 and
    170           abs(float(lower) / 10000.) < 0.05 and
    171           abs(float(left) / 10000.) < 0.05 and
    172           abs(float(right) / 10000.) < 0.05):
     172    elif all([abs(float(upper) / 10000.) < 0.05,
     173              abs(float(lower) / 10000.) < 0.05,
     174              abs(float(left) / 10000.) < 0.05,
     175              abs(float(right) / 10000.) < 0.05]):
    173176        # area is already in new format
    174177        area = '{}/{}/{}/{}'.format(float(upper),
     
    180183                         'formats (upper, lower, left, right): '
    181184                         '{}/{}/{}/{}'.format(str(upper), str(lower),
    182                                               str(left) , str(right)))
     185                                              str(left), str(right)))
    183186
    184187    return area
     
    281284
    282285
    283 def check_step(step, mailfail):
     286def check_step(step):
    284287    '''Checks on step format and convert into a list of steps.
    285288
     
    293296        Specifies the forecast time step from forecast base time.
    294297        Valid values are hours (HH) from forecast base time.
    295 
    296     mailfail : list of str
    297         Contains all email addresses which should be notified.
    298         It might also contain just the ecmwf user name which will trigger
    299         mailing to the associated email address for this user.
    300298
    301299    Return
     
    405403        Valid values are hours (HH) from forecast base time.
    406404    '''
    407     if not (len(ftype) == len(ftime) == len(steps)):
     405    if not len(ftype) == len(ftime) == len(steps):
    408406        raise ValueError('ERROR: The number of field types, times and steps '
    409407                         'are not the same! Please check the setting in the '
     
    553551                         'in CONTROL file.\n'
    554552                         'Try "{} -h" to print usage information'
    555                          .format(sys.argv[0].split('/')[-1]) )
     553                         .format(sys.argv[0].split('/')[-1]))
    556554
    557555    # retrieve just one day if end_date isn't set
     
    790788            accmaxstep = maxstep
    791789            print('... For pure forecast mode, the accumulated forecast must '
    792                           'have the same maxstep as the normal forecast fields!\n'
    793                           '\t\t Accmaxstep was set to maxstep!')
     790                  'have the same maxstep as the normal forecast fields!\n'
     791                  '\t\t Accmaxstep was set to maxstep!')
    794792    return accmaxstep
    795793
     
    851849
    852850
    853 def check_number(number, mailfail):
     851def check_number(number):
    854852    '''Check for correct string format of ensemble member numbers.
    855853
     
    858856    number : str
    859857        List of ensemble member forecast runs.
    860 
    861     mailfail : list of str
    862         Contains all email addresses which should be notified.
    863         It might also contain just the ecmwf user name which will trigger
    864         mailing to the associated email address for this user.
    865858
    866859    Return
  • Source/Python/Mods/disaggregation.py

    r44174de r0f89116  
    247247            # geometric mean, restricted such that non-negativity is guaranteed
    248248            # according to Eq. (25)
    249             fip1=min( 3.*g[i] , 3.*g[i+1] , np.sqrt(g[i+1]*g[i]) )
     249            fip1 = min(3. * g[i], 3. * g[i + 1], np.sqrt(g[i + 1] * g[i]))
    250250
    251251            # the function value at the first sub-grid point (fi1) is determined
     
    281281                # the monotonicity filter corrects the value at (fim1) by
    282282                # substituting (fim1) with (fmon), see Eq. (27), (28) and (29)
    283                 fmon = min(3.*g[i-2], \
    284                            3.*g[i-1], \
    285                            np.sqrt(max(0,(18./13.*g[i-2] - 5./13.*f[-7]) *
    286                                          (18./13.*g[i-1] - 5./13.*f[-1]))))
     283                fmon = min(3. * g[i - 2],
     284                           3. * g[i - 1],
     285                           np.sqrt(max(0, (18. / 13. * g[i - 2] - 5. / 13. * f[-7]) *
     286                                       (18. / 13. * g[i - 1] - 5. / 13. * f[-1]))))
    287287
    288288                # recomputation of the sub-grid interval values while the
     
    295295                f[-2] = f[-3]+(f[-1]-fmon)/3.
    296296
    297             f.extend([0.,0.,0.])
     297            f.extend([0., 0., 0.])
    298298
    299299        # otherwise the sub-grid values are calculated and added to the list
     
    306306            # geometric mean, restricted such that non-negativity is guaranteed
    307307            # according to Eq. (25)
    308             fip1 = min( 3.*g[i] , 3.*g[i+1] , np.sqrt(g[i+1]*g[i]) )
     308            fip1 = min(3. * g[i], 3. * g[i + 1], np.sqrt(g[i + 1] * g[i]))
    309309
    310310            # the function value at the first sub-grid point (fi1) is determined
     
    324324                # the monotonicity filter corrects the value at (fim1) by
    325325                # substituting (fim1) with fmon, see Eq. (27), (28) and (29)
    326                 fmon = min(3.*g[i-2], \
    327                            3.*g[i-1], \
    328                            np.sqrt(max(0,(18./13.*g[i-2] - 5./13.*f[-7]) *
    329                                          (18./13.*g[i-1] - 5./13.*f[-1]))))
     326                fmon = min(3. * g[i - 2],
     327                           3. * g[i - 1],
     328                           np.sqrt(max(0, (18. / 13. * g[i - 2] - 5. / 13. * f[-7]) *
     329                                       (18. / 13. * g[i - 1] - 5. / 13. * f[-1]))))
    330330
    331331                # recomputation of the sub-grid interval values while the
     
    358358            # the monotonicity filter corrects the value at (fim1) by
    359359            # substituting (fim1) with (fmon), see Eq. (27), (28) and (29)
    360             fmon = min(3.*g[-3], \
    361                        3.*g[-2], \
    362                        np.sqrt(max(0,(18./13.*g[-3] - 5./13.*f[-7]) *
    363                                      (18./13.*g[-2] - 5./13.*f[-1]))))
     360            fmon = min(3. * g[-3],
     361                       3. * g[-2],
     362                       np.sqrt(max(0, (18. / 13. * g[-3] - 5. / 13. * f[-7]) *
     363                                   (18. / 13. * g[-2] - 5. / 13. * f[-1]))))
    364364
    365365            # recomputation of the sub-grid interval values while the
     
    372372            f[-2] = f[-3]+(f[-1]-fmon)/3.
    373373
    374         f.extend([0.,0.,0.])
     374        f.extend([0., 0., 0.])
    375375
    376376    # otherwise the sub-grid values are calculated and added to the list
     
    397397            # the monotonicity filter corrects the value at (fim1) by
    398398            # substituting (fim1) with (fmon), see Eq. (27), (28) and (29)
    399             fmon = min(3.*g[-3], \
    400                        3.*g[-2], \
    401                        np.sqrt(max(0,(18./13.*g[-3] - 5./13.*f[-7]) *
    402                                      (18./13.*g[-2] - 5./13.*f[-1]))))
     399            fmon = min(3. * g[-3],
     400                       3. * g[-2],
     401                       np.sqrt(max(0, (18. / 13. * g[-3] - 5. / 13. * f[-7]) *
     402                                   (18. / 13. * g[-2] - 5. / 13. * f[-1]))))
    403403
    404404            # recomputation of the sub-grid interval values while the
  • Source/Python/Mods/get_mars_data.py

    r44174de r0f89116  
    7070sys.path.append(os.path.dirname(os.path.abspath(
    7171    inspect.getfile(inspect.currentframe()))) + '/../')
     72# pylint: disable=wrong-import-position
    7273import _config
    73 from Mods.tools import (setup_controldata, my_error, normal_exit, get_cmdline_args,
    74                    read_ecenv, make_dir)
     74from Mods.tools import (setup_controldata, my_error, normal_exit, make_dir)
    7575from Classes.EcFlexpart import EcFlexpart
    7676from Classes.UioFiles import UioFiles
    7777from Classes.MarsRetrieval import MarsRetrieval
    78 
     78# pylint: enable=wrong-import-position
     79# pylint: disable=invalid-name
    7980try:
    8081    ec_api = True
     
    8889except ImportError:
    8990    cds_api = False
     91# pylint: enable=invalid-name
    9092# ------------------------------------------------------------------------------
    9193# FUNCTION
     
    223225
    224226def check_dates_for_nonflux_fc_times(types, times):
    225     '''
    226     '''
    227     for ty, ti in zip(types,times):
     227    '''Checks if the time 18UTC corresponds to forecast field.
     228
     229    Parameters
     230    ----------
     231    types : list of str
     232        List of field types.
     233
     234    times : list of str or str
     235        The time in hours of the field.
     236
     237    Return
     238    ------
     239    True or False
     240
     241    '''
     242    for ty, ti in zip(types, times):
    228243        if ty.upper() == 'FC' and int(ti) == 18:
    229244            return True
     
    245260
    246261    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
     262    if basetime is 0, the starting date has to be the day before
    248263
    249264    Parameters
  • Source/Python/Mods/prepare_flexpart.py

    r44174de r0f89116  
    3838#    http://creativecommons.org/licenses/by/4.0/ or send a letter to
    3939#    Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
    40 #*******************************************************************************
     40# *******************************************************************************
     41# pylint: disable=ungrouped-imports
     42# not necessary that we group the imports
    4143'''This script prepares the final version of the grib files which are
    4244then used by FLEXPART.
     
    6870import inspect
    6971import sys
    70 import socket
    7172
    7273# software specific classes and modules from flex_extract
     
    7475sys.path.append(os.path.dirname(os.path.abspath(
    7576    inspect.getfile(inspect.currentframe()))) + '/../')
    76 import _config
     77# pylint: disable=wrong-import-position
     78#import _config
    7779from Mods.checks import check_ppid
    7880from Classes.UioFiles import UioFiles
    79 from Classes.ControlFile import ControlFile
    80 from Mods.tools import (setup_controldata, clean_up, get_cmdline_args,
    81                         read_ecenv, make_dir, normal_exit)
     81#from Classes.ControlFile import ControlFile
     82from Mods.tools import (setup_controldata, clean_up, make_dir, normal_exit)
    8283from Classes.EcFlexpart import EcFlexpart
     84# pylint: enable=wrong-import-position
    8385
    8486# ------------------------------------------------------------------------------
     
    146148
    147149    print('Prepare ' + start.strftime("%Y%m%d") +
    148            "/to/" + end.strftime("%Y%m%d"))
     150          '/to/' + end.strftime("%Y%m%d"))
    149151
    150152    # create output dir if necessary
     
    171173    flexpart.process_output(c)
    172174
    173     # make use of a possible conversion to a
    174     # specific flexpart binary format
    175     if c.grib2flexpart:
    176         flexpart.prepare_fp_files(c)
    177 
    178175    # check if in debugging mode, then store all files
    179176    # otherwise delete temporary files
  • Source/Python/Mods/profiling.py

    r8463d78 r0f89116  
    3737# FUNCTION
    3838# ------------------------------------------------------------------------------
    39 def timefn(fn):
     39def timefn(func):
    4040    '''
    4141    @Description:
    4242        Decorator function. It takes the inner function as an argument.
    4343    '''
    44     @wraps(fn)
     44    @wraps(func)
    4545    def measure_time(*args, **kwargs):
    4646        '''
     
    6565        '''
    6666
    67         t1 = time.time()
    68         result = fn(*args, **kwargs)
    69         t2 = time.time()
    70         print("@timefn:" + fn.__name__ + " took " + str(t2 - t1) + " seconds")
     67        time1 = time.time()
     68        result = func(*args, **kwargs)
     69        time2 = time.time()
     70        print("@timefn:" + func.__name__ + " took " +
     71              str(time2 - time1) + " seconds")
    7172
    7273        return result
  • Source/Python/Mods/tools.py

    rc77630a r0f89116  
    6969import subprocess
    7070import traceback
     71# pylint: disable=unused-import
    7172try:
    7273    import exceptions
    7374except ImportError:
    7475    import builtins as exceptions
     76# pylint: enable=unused-import
    7577from datetime import datetime, timedelta
    7678from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
     
    268270        and destination for ECMWF server environments.
    269271    '''
    270     envs= {}
     272    envs = {}
    271273    try:
    272274        with open(filepath, 'r') as f:
     
    279281
    280282        sys.exit('\n... Error occured while trying to read ECMWF_ENV '
    281                      'file: ' + str(filepath))
     283                 'file: ' + str(filepath))
    282284
    283285    return envs
     
    302304    print("... clean inputdir!")
    303305
    304     cleanlist = [file for file in glob.glob(os.path.join(c.inputdir, "*"))
    305                  if not os.path.basename(file).startswith(c.prefix)]
     306    cleanlist = [filename for filename in
     307                 glob.glob(os.path.join(c.inputdir, "*"))
     308                 if not os.path.basename(filename).startswith(c.prefix)]
    306309
    307310    if cleanlist:
     
    371374                                 stderr=subprocess.PIPE,
    372375                                 bufsize=1)
    373             pout = p.communicate(input=message.encode() + '\n\n')[0]
     376            pout = p.communicate(input=message + '\n\n')[0]
    374377        except ValueError as e:
    375378            print('... ERROR: ' + str(e))
     
    531534        return []
    532535    if not isinstance(pars, str):
    533         pars=str(pars)
     536        pars = str(pars)
    534537
    535538    cpar = pars.upper().split('/')
     
    575578        return []
    576579    if not isinstance(pars, str):
    577         pars=str(pars)
     580        pars = str(pars)
    578581
    579582    cpar = pars.upper().split('/')
     
    768771
    769772        # information needed from grib message
    770         keys = [
    771                 'Ni',
     773        keys = ['Ni',
    772774                'Nj',
    773775                'latitudeOfFirstGridPointInDegrees',
     
    783785        for key in keys:
    784786            # Get the value of the key in a grib message.
    785             data[key] = codes_get(gid,key)
    786             print("%s = %s" % (key,data[key]))
     787            data[key] = codes_get(gid, key)
     788            print("%s = %s" % (key, data[key]))
    787789
    788790        # Free the memory for the message referred as gribid.
  • Source/Python/_config.py

    r44174de r0f89116  
    5454
    5555FILE_MARS_REQUESTS = 'mars_requests.csv'
    56 FORTRAN_EXECUTABLE = 'CONVERT2'
     56FORTRAN_EXECUTABLE = 'calc_etadot'
    5757TEMPFILE_USER_ENVVARS = 'ECMWF_ENV.template'
    5858FILE_USER_ENVVARS = 'ECMWF_ENV'
     
    9797PATH_PYTHONTEST_SRC = os.path.join(PATH_SOURCES, 'Pythontest')
    9898PATH_INPUT_DIR = os.path.join(PATH_RUN_DIR, INPUT_DIRNAME_DEFAULT)
    99 PATH_TEST = os.path.join(PATH_FLEXEXTRACT_DIR, 'Test')
     99PATH_TEST = os.path.join(PATH_FLEXEXTRACT_DIR, 'Testing')
    100100if os.getenv('CONTROL'):
    101101    # this is only needed if (gateway) version with job script is used!
  • Source/Python/install.py

    r3a41083 r0f89116  
    6868import os
    6969import sys
    70 import glob
    7170import subprocess
    72 import inspect
    7371import tarfile
    7472from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
     
    179177
    180178    '''
    181     import tarfile
    182179
    183180    tarball_name = _config.FLEXEXTRACT_DIRNAME + '.tar'
    184181    tar_file = os.path.join(_config.PATH_FLEXEXTRACT_DIR, tarball_name)
    185182
    186     mk_compilejob(c.makefile, c.install_target, c.ecuid, c.ecgid,
    187                   c.installdir)
    188 
    189     mk_job_template(c.ecuid, c.ecgid, c.gateway,
    190                     c.destination, c.installdir)
     183    mk_compilejob(c.makefile, c.ecuid, c.ecgid, c.installdir)
     184
     185    mk_job_template(c.ecuid, c.ecgid, c.installdir)
    191186
    192187    mk_env_vars(c.ecuid, c.ecgid, c.gateway, c.destination)
     
    205200    print('Job compilation script has been submitted to ecgate for ' +
    206201          'installation in ' + c.installdir +
    207            '/' + _config.FLEXEXTRACT_DIRNAME)
     202          '/' + _config.FLEXEXTRACT_DIRNAME)
    208203    print('You should get an email with subject "flexcompile" within ' +
    209204          'the next few minutes!')
     
    224219
    225220    '''
    226     import tarfile
    227221
    228222    tar_file = os.path.join(_config.PATH_FLEXEXTRACT_DIR,
    229223                            _config.FLEXEXTRACT_DIRNAME + '.tar')
    230224
    231     if c.installdir == _config.PATH_FLEXEXTRACT_DIR :
     225    if c.installdir == _config.PATH_FLEXEXTRACT_DIR:
    232226        print('WARNING: installdir has not been specified')
    233227        print('flex_extract will be installed in here by compiling the ' +
     
    241235            mk_tarball(tar_file, c.install_target)
    242236            make_dir(os.path.join(c.installdir,
    243                                    _config.FLEXEXTRACT_DIRNAME))
     237                                  _config.FLEXEXTRACT_DIRNAME))
    244238            os.chdir(os.path.join(c.installdir,
    245                                    _config.FLEXEXTRACT_DIRNAME))
     239                                  _config.FLEXEXTRACT_DIRNAME))
    246240            un_tarball(tar_file)
    247241            os.chdir(os.path.join(c.installdir,
    248                                    _config.FLEXEXTRACT_DIRNAME,
     242                                  _config.FLEXEXTRACT_DIRNAME,
    249243                                  _config.PATH_REL_FORTRAN_SRC))
    250244
     
    286280        print('target: ', c.install_target)
    287281        print('please specify correct installation target ' +
    288               str(INSTALL_TARGETS))
     282              str(_config.INSTALL_TARGETS))
    289283        print('use -h or --help for help')
    290284        sys.exit(1)
     
    334328
    335329    '''
    336     from glob import glob
    337330
    338331    print('Create tarball ...')
     
    345338    # get lists of the files to be added to the tar file
    346339    if target == 'local':
    347         ECMWF_ENV_FILE = []
     340        ecmwf_env_file = []
    348341        runfile = [os.path.relpath(x, ecd)
    349342                   for x in UioFiles(_config.PATH_REL_RUN_DIR,
    350343                                     'run_local.sh').files]
    351344    else:
    352         ECMWF_ENV_FILE = [_config.PATH_REL_ECMWF_ENV]
     345        ecmwf_env_file = [_config.PATH_REL_ECMWF_ENV]
    353346        runfile = [os.path.relpath(x, ecd)
    354                        for x in UioFiles(_config.PATH_REL_RUN_DIR,
    355                                          'run.sh').files]
     347                   for x in UioFiles(_config.PATH_REL_RUN_DIR,
     348                                     'run.sh').files]
    356349
    357350    pyfiles = [os.path.relpath(x, ecd)
    358351               for x in UioFiles(_config.PATH_REL_PYTHON_SRC, '*py').files]
    359352    pytestfiles = [os.path.relpath(x, ecd)
    360                for x in UioFiles(_config.PATH_REL_PYTHONTEST_SRC, '*py').files]
     353                   for x in UioFiles(_config.PATH_REL_PYTHONTEST_SRC, '*py').files]
    361354    controlfiles = [os.path.relpath(x, ecd)
    362355                    for x in UioFiles(_config.PATH_REL_CONTROLFILES,
    363356                                      'CONTROL*').files]
    364357    testfiles = [os.path.relpath(x, ecd)
    365                  for x in UioFiles(_config.PATH_REL_TEST , '*').files]
     358                 for x in UioFiles(_config.PATH_REL_TEST, '*').files]
    366359    tempfiles = [os.path.relpath(x, ecd)
    367                  for x in UioFiles(_config.PATH_REL_TEMPLATES , '*.temp').files]
     360                 for x in UioFiles(_config.PATH_REL_TEMPLATES, '*.temp').files]
    368361    nlfiles = [os.path.relpath(x, ecd)
    369                  for x in UioFiles(_config.PATH_REL_TEMPLATES , '*.nl').files]
     362               for x in UioFiles(_config.PATH_REL_TEMPLATES, '*.nl').files]
    370363    gribtable = [os.path.relpath(x, ecd)
    371                  for x in UioFiles(_config.PATH_REL_TEMPLATES , '*grib*').files]
     364                 for x in UioFiles(_config.PATH_REL_TEMPLATES, '*grib*').files]
    372365    ffiles = [os.path.relpath(x, ecd)
    373               for x in UioFiles(_config.PATH_REL_FORTRAN_SRC, '*.f*').files]
     366              for x in UioFiles(_config.PATH_REL_FORTRAN_SRC, '*.f90').files]
    374367    hfiles = [os.path.relpath(x, ecd)
    375368              for x in UioFiles(_config.PATH_REL_FORTRAN_SRC, '*.h').files]
     
    380373    # concatenate single lists to one for a better looping
    381374    filelist = pyfiles + pytestfiles + controlfiles + tempfiles + nlfiles + \
    382                ffiles + gribtable + hfiles + makefiles + ECMWF_ENV_FILE + \
     375               ffiles + gribtable + hfiles + makefiles + ecmwf_env_file + \
    383376               runfile + jobdir + testfiles +\
    384377               ['CODE_OF_CONDUCT.md', 'LICENSE.md', 'README.md']
    385378
    386379    # create installation tar-file
    387     exclude_files = [".ksh"]
     380    exclude_files = [".ksh", ".tar"]
    388381    try:
    389382        with tarfile.open(tarball_path, "w:gz") as tar_handle:
    390             for file in filelist:
    391                 tar_handle.add(file, recursive=False,
     383            for filename in filelist:
     384                tar_handle.add(filename, recursive=False,
    392385                               filter=lambda tarinfo: None
    393                                       if os.path.splitext(tarinfo.name)[1]
    394                                          in exclude_files
    395                                       else tarinfo)
     386                               if os.path.splitext(tarinfo.name)[1]
     387                               in exclude_files
     388                               else tarinfo)
    396389    except tarfile.TarError as e:
     390        print('... ERROR: ' + str(e))
     391
    397392        sys.exit('\n... error occured while trying to create the tar-file ' +
    398                      str(tarball_path))
     393                 str(tarball_path))
    399394
    400395    return
     
    422417    except tarfile.TarError as e:
    423418        sys.exit('\n... error occured while trying to read tar-file ' +
    424                      str(tarball_path))
     419                 str(tarball_path))
    425420    except OSError as e:
    426421        print('... ERROR CODE: ' + str(e.errno))
     
    465460                                         cls=NewTextTemplate)
    466461
    467         stream = ecmwfvars_template.generate(user_name = ecuid,
    468                                              user_group = ecgid,
    469                                              gateway_name = gateway,
    470                                              destination_name = destination
    471                                              )
     462        stream = ecmwfvars_template.generate(user_name=ecuid,
     463                                             user_group=ecgid,
     464                                             gateway_name=gateway,
     465                                             destination_name=destination
     466                                            )
    472467    except UndefinedError as e:
    473468        print('... ERROR ' + str(e))
     
    494489    return
    495490
    496 def mk_compilejob(makefile, target, ecuid, ecgid, fp_root):
     491def mk_compilejob(makefile, ecuid, ecgid, fp_root):
    497492    '''Modifies the original job template file so that it is specified
    498493    for the user and the environment were it will be applied. Result
     
    505500        CONVERT2 program.
    506501
    507     target : str
    508         The target where the installation should be done, e.g. the queue.
    509 
    510502    ecuid : str
    511503        The user id on ECMWF server.
     
    535527
    536528        stream = compile_template.generate(
    537             usergroup = ecgid,
    538             username = ecuid,
    539             version_number = _config._VERSION_STR,
    540             fp_root_scripts = fp_root,
    541             makefile = makefile,
    542             fortran_program = _config.FORTRAN_EXECUTABLE
     529            usergroup=ecgid,
     530            username=ecuid,
     531            version_number=_config._VERSION_STR,
     532            fp_root_scripts=fp_root,
     533            makefile=makefile,
     534            fortran_program=_config.FORTRAN_EXECUTABLE
    543535        )
    544536    except UndefinedError as e:
     
    569561    return
    570562
    571 def mk_job_template(ecuid, ecgid, gateway, destination, fp_root):
     563def mk_job_template(ecuid, ecgid, fp_root):
    572564    '''Modifies the original job template file so that it is specified
    573565    for the user and the environment were it will be applied. Result
     
    581573    ecgid : str
    582574        The group id on ECMWF server.
    583 
    584     gateway : str
    585         The gateway server the user is using.
    586 
    587     destination : str
    588         The remote destination which is used to transfer files
    589         from ECMWF server to local gateway server.
    590575
    591576    fp_root : str
     
    615600
    616601        stream = compile_template.generate(
    617             usergroup = ecgid,
    618             username = ecuid,
    619             version_number = _config._VERSION_STR,
    620             fp_root_path = fp_root_path_to_python,
     602            usergroup=ecgid,
     603            username=ecuid,
     604            version_number=_config._VERSION_STR,
     605            fp_root_path=fp_root_path_to_python,
    621606        )
    622607    except UndefinedError as e:
     
    711696        print(e)
    712697    else:
    713         execute_subprocess(['ls', '-l', os.path.join(src_path,
    714                             _config.FORTRAN_EXECUTABLE)], error_msg=
    715                            'FORTRAN EXECUTABLE COULD NOT BE FOUND!')
     698        execute_subprocess(['ls', '-l',
     699                            os.path.join(src_path, _config.FORTRAN_EXECUTABLE)],
     700                           error_msg='FORTRAN EXECUTABLE COULD NOT BE FOUND!')
    716701
    717702    return
  • Source/Python/submit.py

    r44174de r0f89116  
    6464import os
    6565import sys
    66 import subprocess
    67 import inspect
    68 import collections
    6966from datetime import datetime, timedelta
    7067
    7168# software specific classes and modules from flex_extract
    7269import _config
    73 from Mods.tools import (setup_controldata, normal_exit, get_cmdline_args,
    74                          submit_job_to_ecserver, read_ecenv)
     70from Mods.tools import (setup_controldata, normal_exit,
     71                        submit_job_to_ecserver)
    7572from Mods.get_mars_data import get_mars_data
    7673from Mods.prepare_flexpart import prepare_flexpart
    77 from Classes.ControlFile import ControlFile
     74#from Classes.ControlFile import ControlFile
    7875
    7976
Note: See TracChangeset for help on using the changeset viewer.
hosted by ZAMG