Changeset 25b14be in flex_extract.git for source/pythontest/TestInstallTar


Ignore:
Timestamp:
Sep 23, 2018, 11:40:28 AM (6 years ago)
Author:
Anne Philipp <anne.philipp@…>
Branches:
master, ctbto, dev
Children:
4971f63
Parents:
5d42acd
Message:

changed whole tree structure of flex_extract to have better overview

Location:
source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate
Files:
22 added
33 moved

Legend:

Unmodified
Added
Removed
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/run/control/CONTROL.worktest

    r2fb99de r25b14be  
     1DAY1 20100101
     2DAY2
    13DTIME 3
    24TYPE AN FC FC FC FC FC AN FC FC FC FC FC AN FC FC FC FC FC AN FC FC FC FC FC
     
    57CLASS EI
    68STREAM OPER
     9NUMBER OFF
    710EXPVER 1
    811GRID 5000 
     
    1114UPPER 40000
    1215RIGHT 10000
    13 LEVELIST 59/to/60
     16LEVEL 60
     17LEVELIST 58/to/60
    1418RESOL 63
    1519GAUSS 1
     20ACCURACY 16
     21OMEGA 0
     22OMEGADIFF 0
     23ETA 0
     24ETADIFF 0
     25DPDETA 1
     26SMOOTH 0
     27FORMAT GRIB1
    1628ADDPAR 186/187/188/235/139/39
    17 PREFIX EItest_
     29PREFIX EI
     30ECSTORAGE 0
    1831ECTRANS 1
     32ECFSDIR ectmp:/${USER}/econdemand/
     33MAILFAIL ${USER}
     34MAILOPS ${USER}
     35GRIB2FLEXPART 0
     36EOF
     37
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/_config.py

    r5d42acd r25b14be  
    3232# ------------------------------------------------------------------------------
    3333
    34 FLEXEXTRACT_DIRNAME = 'flex_extract_v' + _VERSION_STR
    3534FILE_MARS_REQUESTS = 'mars_requests.dat'
    3635FORTRAN_EXECUTABLE = 'CONVERT2'
     
    4443FILE_NAMELIST = 'fort.4'
    4544FILE_GRIB_INDEX = 'date_time_stepRange.idx'
     45FILE_GRIBTABLE = 'ecmwf_grib1_table_128'
     46
     47# ------------------------------------------------------------------------------
     48# DIRECTORY NAMES
     49# ------------------------------------------------------------------------------
     50
     51FLEXEXTRACT_DIRNAME = 'flex_extract_v' + _VERSION_STR
     52INPUT_DIRNAME_DEFAULT = 'workspace'
    4653
    4754# ------------------------------------------------------------------------------
     
    4956# ------------------------------------------------------------------------------
    5057
    51 # path to the flex_extract directory
    52 PATH_FLEXEXTRACT_DIR = os.path.normpath(os.path.dirname(os.path.abspath(
    53     inspect.getfile(inspect.currentframe()))) + '/../')
    54 
    5558# path to the local python source files
     59# first thing to get because the submitted python script starts in here
    5660PATH_LOCAL_PYTHON = os.path.dirname(os.path.abspath(
    5761    inspect.getfile(inspect.currentframe())))
    58 PATH_RELATIVE_PYTHON = os.path.relpath(PATH_LOCAL_PYTHON, PATH_FLEXEXTRACT_DIR)
    5962# add path to pythonpath
    6063if PATH_LOCAL_PYTHON not in sys.path:
    6164    sys.path.append(PATH_LOCAL_PYTHON)
    62 
    63 # path to the templates
    64 PATH_TEMPLATES = os.path.join(PATH_FLEXEXTRACT_DIR, '_templates')
    65 PATH_RELATIVE_TEMPLATES = os.path.relpath(PATH_TEMPLATES, PATH_FLEXEXTRACT_DIR)
    66 
    67 # path to the environment parameter file
    68 PATH_ECMWF_ENV = os.path.join(PATH_LOCAL_PYTHON, FILE_USER_ENVVARS)
    69 PATH_RELATIVE_ECMWF_ENV = os.path.relpath(PATH_ECMWF_ENV, PATH_FLEXEXTRACT_DIR)
    70 
    71 # path to gribtable
    72 PATH_GRIBTABLE = os.path.join(PATH_TEMPLATES, 'ecmwf_grib1_table_128')
    73 
    74 # path to run directory
     65PATH_FLEXEXTRACT_DIR = os.path.normpath(os.path.dirname(os.path.abspath(
     66    inspect.getfile(inspect.currentframe()))) + '/../../')
    7567PATH_RUN_DIR = os.path.join(PATH_FLEXEXTRACT_DIR, 'run')
    76 PATH_RELATIVE_RUN_DIR = os.path.relpath(PATH_RUN_DIR, PATH_FLEXEXTRACT_DIR)
    77 
    78 # path to directory where all control files are stored
     68PATH_SOURCES = os.path.join(PATH_FLEXEXTRACT_DIR, 'source')
     69PATH_TEMPLATES = os.path.join(PATH_FLEXEXTRACT_DIR, 'templates')
     70PATH_ECMWF_ENV = os.path.join(PATH_RUN_DIR, FILE_USER_ENVVARS)
     71PATH_GRIBTABLE = os.path.join(PATH_TEMPLATES, FILE_GRIBTABLE)
     72PATH_JOBSCRIPTS = os.path.join(PATH_RUN_DIR, 'jobscripts')
     73PATH_FORTRAN_SRC = os.path.join(PATH_SOURCES, 'fortran')
     74PATH_TEST_DIR = os.path.join(PATH_SOURCES, 'pythontest')
     75PATH_INPUT_DIR = os.path.join(PATH_RUN_DIR, INPUT_DIRNAME_DEFAULT)
    7976if os.getenv('CONTROL') and '/' in os.getenv('CONTROL'):
    8077    # this is only needed if remote version with job script is used!
     
    8481else:
    8582    PATH_CONTROLFILES = os.path.join(PATH_RUN_DIR, 'control')
    86     PATH_RELATIVE_CONTROLFILES = os.path.relpath(PATH_CONTROLFILES, PATH_FLEXEXTRACT_DIR)
    87 
    88 # path to directory where all job scripts are stored
    89 PATH_JOBSCRIPTS = os.path.join(PATH_RUN_DIR, 'jobscripts')
    90 PATH_RELATIVE_JOBSCRIPTS = os.path.relpath(PATH_JOBSCRIPTS, PATH_FLEXEXTRACT_DIR)
    91 
    92 # path to the fortran executable and the source code
    93 PATH_FORTRAN_SRC = os.path.join(PATH_FLEXEXTRACT_DIR, 'src')
    94 PATH_RELATIVE_FORTRAN_SRC = os.path.relpath(PATH_FORTRAN_SRC, PATH_FLEXEXTRACT_DIR)
    95 
    96 # path to the python testing directory
    97 PATH_TEST_DIR = os.path.join(PATH_LOCAL_PYTHON, 'pythontest')
    98 
     83#
     84# ------------------------------------------------------------------------------
     85#
     86# for making the installation tar ball the relative pathes to the
     87# flex_extract root directory are needed
     88PATH_REL_PYTHON = os.path.relpath(PATH_LOCAL_PYTHON, PATH_FLEXEXTRACT_DIR)
     89PATH_REL_CONTROLFILES = os.path.relpath(PATH_CONTROLFILES, PATH_FLEXEXTRACT_DIR)
     90PATH_REL_TEMPLATES = os.path.relpath(PATH_TEMPLATES, PATH_FLEXEXTRACT_DIR)
     91PATH_REL_ECMWF_ENV = os.path.relpath(PATH_ECMWF_ENV, PATH_FLEXEXTRACT_DIR)
     92PATH_REL_RUN_DIR = os.path.relpath(PATH_RUN_DIR, PATH_FLEXEXTRACT_DIR)
     93PATH_REL_JOBSCRIPTS = os.path.relpath(PATH_JOBSCRIPTS, PATH_FLEXEXTRACT_DIR)
     94PATH_REL_FORTRAN_SRC = os.path.relpath(PATH_FORTRAN_SRC, PATH_FLEXEXTRACT_DIR)
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/classes/ControlFile.py

    r2fb99de r25b14be  
    113113        self.stream = None
    114114        self.number = 'OFF'
    115         self.expver = None
     115        self.expver = '1'
    116116        self.grid = None
    117117        self.area = ''
     
    143143        self.ecstorage = 0
    144144        self.ectrans = 0
    145         self.inputdir = '../work'
     145        self.inputdir = _config.PATH_INPUT_DIR
    146146        self.outputdir = self.inputdir
    147         self.ecmwfdatadir = None
    148         self.exedir = None
     147        self.ecmwfdatadir = _config.PATH_FLEXEXTRACT_DIR
     148        self.exedir = _config.PATH_FORTRAN_SRC
    149149        self.flexpart_root_scripts = None
    150         self.makefile = None
     150        self.makefile = 'Makefile.gfortran'
    151151        self.destination = None
    152152        self.gateway = None
     
    157157        self.request = 0
    158158
     159        self.logicals = ['gauss', 'omega', 'omegadiff', 'eta', 'etadiff',
     160                         'dpdeta', 'cwc', 'wrf', 'grib2flexpart', 'ecstorage',
     161                         'ectrans', 'debug', 'request']
     162
    159163        self.__read_controlfile__()
    160164
     
    173177            <nothing>
    174178        '''
    175         from tools import my_error
     179        from mods.tools import my_error
    176180
    177181        # read whole CONTROL file
    178         with open(self.controlfile) as f:
     182        with open(os.path.join(_config.PATH_CONTROLFILES,
     183                               self.controlfile)) as f:
    179184            fdata = f.read().split('\n')
    180185
     
    226231                pass
    227232
    228         # script directory
    229         self.ecmwfdatadir = os.path.dirname(os.path.abspath(inspect.getfile(
    230             inspect.currentframe()))) + '/../'
    231 
    232         # Fortran source directory
    233         self.exedir = self.ecmwfdatadir + 'src/'
    234 
    235233        return
    236234
     
    314312        return
    315313
    316     def check_conditions(self):
     314    def check_conditions(self, queue):
    317315        '''
    318316        @Description:
     
    325323                Description see class documentation.
    326324
     325            queue: string
     326                Name of the queue if submitted to the ECMWF servers.
     327                Used to check if ecuid, ecgid, gateway and destination
     328                are set correctly and are not empty.
     329
    327330        @Return:
    328331            <nothing>
    329332        '''
    330         from tools import my_error
     333        from mods.tools import my_error
    331334        import numpy as np
    332335
     
    334337        # otherwise program is not allowed to run
    335338        if self.start_date is None:
    336             print 'start_date specified neither in command line nor ' + \
    337                   'in CONTROL file ' +  self.controlfile
    338             print 'Try "' + sys.argv[0].split('/')[-1] + \
    339                   ' -h" to print usage information'
     339            print('start_date specified neither in command line nor \
     340                   in CONTROL file ' +  self.controlfile)
     341            print('Try "' + sys.argv[0].split('/')[-1] +
     342                  ' -h" to print usage information')
    340343            sys.exit(1)
    341344
     
    345348
    346349        # assure consistency of levelist and level
    347         if self.levelist is None:
    348             if self.level is None:
    349                 print 'Warning: neither levelist nor level ' + \
    350                       'specified in CONTROL file'
    351                 sys.exit(1)
     350        if self.levelist is None and self.level is None:
     351            print('Warning: neither levelist nor level \
     352                               specified in CONTROL file')
     353            sys.exit(1)
     354        elif self.levelist is None and self.level:
     355            self.levelist = '1/to/' + self.level
     356        elif (self.levelist and self.level is None) or \
     357             (self.levelist[-1] != self.level[-1]):
     358            self.level = self.levelist.split('/')[-1]
     359        else:
     360            pass
     361
     362        # if area was provided (only from commandline)
     363        # decompose area into its 4 components
     364        if self.area:
     365            components = self.area.split('/')
     366            # convert float to integer coordinates
     367            if '.' in self.area:
     368                components = [str(int(float(item) * 1000))
     369                              for i, item in enumerate(components)]
     370            self.upper, self.left, self.lower, self.right = components
     371
     372        # prepare step list if "/" signs are found
     373        if '/' in self.step:
     374            steps = self.step.split('/')
     375            if 'to' in self.step.lower() and 'by' in self.step.lower():
     376                ilist = np.arange(int(steps[0]),
     377                                  int(steps[2]) + 1,
     378                                  int(steps[4]))
     379                self.step = ['{:0>3}'.format(i) for i in ilist]
     380            elif 'to' in self.step.lower() and 'by' not in self.step.lower():
     381                my_error(self.mailfail, self.step + ':\n' +
     382                         'if "to" is used in steps parameter, \
     383                         please use "by" as well')
    352384            else:
    353                 self.levelist = '1/to/' + self.level
    354         else:
    355             if 'to' in self.levelist.lower():
    356                 self.level = self.levelist.split('/')[2]
    357             else:
    358                 self.level = self.levelist.split('/')[-1]
    359 
    360         # if area was provided at command line
    361         # decompse area into its 4 components
    362         if self.area:
    363             afloat = '.' in self.area
    364             l = self.area.split('/')
    365             if afloat:
    366                 for i, item in enumerate(l):
    367                     item = str(int(float(item) * 1000))
    368             self.upper, self.left, self.lower, self.right = l
    369 
    370         # prepare step for correct usage
    371         if '/' in self.step:
    372             l = self.step.split('/')
    373             if 'to' in self.step.lower():
    374                 if 'by' in self.step.lower():
    375                     ilist = np.arange(int(l[0]), int(l[2]) + 1, int(l[4]))
    376                     self.step = ['{:0>3}'.format(i) for i in ilist]
    377                 else:
    378                     my_error(self.mailfail, self.step + ':\n' +
    379                              'if "to" is used, please use "by" as well')
    380             else:
    381                 self.step = l
     385                self.step = steps
    382386
    383387        # if maxstep wasn't provided
     
    411415                self.mailops = [self.mailops]
    412416
    413         if not self.gateway or not self.destination or \
     417        if queue in ['ecgate', 'cca'] and \
     418           not self.gateway or not self.destination or \
    414419           not self.ecuid or not self.ecgid:
    415             print '\nEnvironment variables GATWAY, DESTINATION, ECUID and ' + \
    416                   'ECGID were not set properly!'
    417             print 'Please check for excistence of file "ECMWF_ENV" in the ' + \
    418                   'python directory!'
     420            print('\nEnvironment variables GATEWAY, DESTINATION, ECUID and \
     421                   ECGID were not set properly!')
     422            print('Please check for existence of file "ECMWF_ENV" in the \
     423                   python directory!')
    419424            sys.exit(1)
    420425
    421426        if self.request != 0:
    422             marsfile = os.path.join(_config.PATH_RUN_DIR + os.path.sep +
     427            marsfile = os.path.join(self.inputdir,
    423428                                    _config.FILE_MARS_REQUESTS)
    424429            if os.path.isfile(marsfile):
    425430                os.remove(marsfile)
    426431
    427         # check logical variables for data type
     432        # check all logical variables for data type
    428433        # if its a string change to integer
    429         logicals = ['gauss', 'omega', 'omegadiff', 'eta', 'etadiff',
    430                     'dpdeta', 'cwc', 'wrf', 'grib2flexpart', 'ecstorage',
    431                     'ectrans', 'debug', 'request']
    432 
    433         for var in logicals:
     434        for var in self.logicals:
    434435            if not isinstance(getattr(self, var), int):
    435436                setattr(self, var, int(getattr(self, var)))
     
    481482        else: # local
    482483            if not self.flexpart_root_scripts:
    483                 self.flexpart_root_scripts = '../'
    484 
    485         if not self.makefile:
    486             self.makefile = 'Makefile.gfortran'
     484                self.flexpart_root_scripts = _config.PATH_FLEXEXTRACT_DIR
    487485
    488486        return
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/classes/EcFlexpart.py

    r2fb99de r25b14be  
    6161#
    6262# @Class Attributes:
    63 #    - dtime
    64 #    - basetime
    65 #    - server
    66 #    - marsclass
    67 #    - stream
    68 #    - resol
    69 #    - accuracy
    70 #    - number
    71 #    - expver
    72 #    - glevelist
    73 #    - area
    74 #    - grid
    75 #    - level
    76 #    - levelist
    77 #    - types
    78 #    - dates
    79 #    - area
    80 #    - gaussian
    81 #    - params
    82 #    - inputdir
    83 #    - outputfilelist
     63#
     64#  TODO
    8465#
    8566#*******************************************************************************
    8667#pylint: disable=unsupported-assignment-operation
    87 # this is disabled because its an error in pylint for this specific case
     68# this is disabled because for this specific case its an error in pylint
    8869#pylint: disable=consider-using-enumerate
    8970# this is not useful in this case
     
    10485import _config
    10586from GribTools import GribTools
    106 from tools import init128, to_param_id, silent_remove, product, my_error
     87from mods.tools import init128, to_param_id, silent_remove, product, my_error
    10788from MarsRetrieval import MarsRetrieval
    108 import disaggregation
     89import mods.disaggregation
    10990
    11091# ------------------------------------------------------------------------------
     
    205186        self.accuracy = c.accuracy
    206187        self.level = c.level
    207 
    208         if c.levelist:
    209             self.levelist = c.levelist
    210         else:
    211             self.levelist = '1/to/' + c.level
    212 
     188        self.expver = c.expver
     189        self.levelist = c.levelist
    213190        # for gaussian grid retrieval
    214191        self.glevelist = '1/to/' + c.level
     
    218195        else:
    219196            self.gaussian = ''
    220 
    221         if hasattr(c, 'expver') and c.expver:
    222             self.expver = c.expver
    223         else:
    224             self.expver = '1'
    225 
    226         if hasattr(c, 'number') and c.number:
    227             self.number = c.number
    228         else:
    229             self.number = '0'
    230197
    231198        if 'N' in c.grid:  # Gaussian output grid
     
    251218        # 4) Download also data for WRF
    252219
    253 
    254220        # Different grids need different retrievals
    255221        # SH = Spherical Harmonics, GG = Gaussian Grid,
     
    275241            self.params['OG__ML'] = ['T/Q', 'ML', self.levelist, self.grid]
    276242
    277             if c.gauss == '0' and c.eta == '1':
     243            #if c.gauss == '0' and c.eta == '1':
     244            if not c.gauss and c.eta:
    278245                # the simplest case
    279246                self.params['OG__ML'][0] += '/U/V/77'
    280             elif c.gauss == '0' and c.eta == '0':
     247            #elif c.gauss == '0' and c.eta == '0':
     248            elif not c.gauss and not c.eta:
    281249            # this is not recommended (inaccurate)
    282250                self.params['OG__ML'][0] += '/U/V'
    283             elif c.gauss == '1' and c.eta == '0':
     251            #elif c.gauss == '1' and c.eta == '0':
     252            elif c.gauss and not c.eta:
    284253                # this is needed for data before 2008, or for reanalysis data
    285254                self.params['GG__SL'] = ['Q', 'ML', '1', \
     
    287256                self.params['SH__ML'] = ['U/V/D', 'ML', self.glevelist, 'OFF']
    288257            else:
    289                 print('Warning: This is a very costly parameter combination, '
    290                       'use only for debugging!')
     258                print('Warning: This is a very costly parameter combination, \
     259                      use only for debugging!')
    291260                self.params['GG__SL'] = ['Q', 'ML', '1', \
    292261                                         '{}'.format((int(self.resol) + 1) / 2)]
     
    294263                                         '{}'.format((int(self.resol) + 1) / 2)]
    295264
    296             if hasattr(c, 'omega') and c.omega == '1':
     265            if c.omega:
    297266                self.params['OG__ML'][0] += '/W'
    298267
    299268            # add cloud water content if necessary
    300             if hasattr(c, 'cwc') and c.cwc == '1':
     269            if c.cwc:
    301270                self.params['OG__ML'][0] += '/CLWC/CIWC'
    302271
    303272            # add vorticity and geopotential height for WRF if necessary
    304             if hasattr(c, 'wrf') and c.wrf == '1':
     273            if c.wrf:
    305274                self.params['OG__ML'][0] += '/Z/VO'
    306275                if '/D' not in self.params['OG__ML'][0]:
     
    439408                    pass
    440409                if pk == 'OG_OROLSM__SL':
    441                     if oro is False:
     410                    if not oro:
    442411                        mfstream = 'OPER'
    443412                        mftype = 'AN'
     
    459428
    460429    # ------  on demand path  --------------------------------------------------
    461                 if self.basetime is None:
     430                if not self.basetime:
    462431                    MR = MarsRetrieval(self.server,
    463432                                       marsclass=self.marsclass,
     
    483452                        MR.data_retrieve()
    484453                    elif request == 1:
    485                         MR.print_info()
     454                        MR.print_info(self.inputdir)
    486455                    elif request == 2:
    487                         MR.print_info()
     456                        MR.print_info(self.inputdir)
    488457                        MR.display_info()
    489458                        MR.data_retrieve()
    490459                    else:
    491                         print 'Failure'
     460                        print('Failure')
    492461    # ------  operational path  ------------------------------------------------
    493462                else:
     
    717686        '''
    718687
    719         print '\n\nPostprocessing:\n Format: {}\n'.format(c.format)
    720 
    721         if c.ecapi is False:
     688        print('\n\nPostprocessing:\n Format: {}\n'.format(c.format))
     689
     690        if not c.ecapi:
    722691            print('ecstorage: {}\n ecfsdir: {}\n'.
    723692                  format(c.ecstorage, c.ecfsdir))
    724             if not hasattr(c, 'gateway'):
    725                 c.gateway = os.getenv('GATEWAY')
    726             if not hasattr(c, 'destination'):
    727                 c.destination = os.getenv('DESTINATION')
     693            #if not hasattr(c, 'gateway'):
     694            #    c.gateway = os.getenv('GATEWAY')
     695            #if not hasattr(c, 'destination'):
     696            #    c.destination = os.getenv('DESTINATION')
    728697            print('ectrans: {}\n gateway: {}\n destination: {}\n '
    729698                  .format(c.ectrans, c.gateway, c.destination))
    730699
    731         print 'Output filelist: \n'
    732         print self.outputfilelist
     700        print('Output filelist: \n')
     701        print(self.outputfilelist)
    733702
    734703        if c.format.lower() == 'grib2':
     
    739708                p = subprocess.check_call(['mv', ofile + '_2', ofile])
    740709
    741         if int(c.ectrans) == 1 and c.ecapi is False:
     710        if c.ectrans and not c.ecapi:
    742711            for ofile in self.outputfilelist:
    743712                p = subprocess.check_call(['ectrans', '-overwrite', '-gateway',
     
    746715                #print('ectrans:', p)
    747716
    748         if int(c.ecstorage) == 1 and c.ecapi is False:
     717        if c.ecstorage and not c.ecapi:
    749718            for ofile in self.outputfilelist:
    750719                p = subprocess.check_call(['ecp', '-o', ofile,
     
    757726        # prepare environment for the grib2flexpart run
    758727        # to convert grib to flexpart binary
    759         if c.grib2flexpart == '1':
     728        if c.grib2flexpart:
    760729
    761730            # generate AVAILABLE file
     
    873842
    874843        index_keys = ["date", "time", "step"]
    875         indexfile = c.inputdir + "/date_time_stepRange.idx"
     844        indexfile = os.path.join(c.inputdir, _config.FILE_GRIB_INDEX)
    876845        silent_remove(indexfile)
    877846        grib = GribTools(inputfiles.files)
     
    883852        for key in index_keys:
    884853            index_vals.append(grib_index_get(iid, key))
    885             print index_vals[-1]
     854            print(index_vals[-1])
    886855            # index_vals looks for example like:
    887856            # index_vals[0]: ('20171106', '20171107', '20171108') ; date
     
    893862
    894863        for prod in product(*index_vals):
     864            # e.g. prod = ('20170505', '0', '12')
     865            #             (  date    ,time, step)
     866            # per date e.g. time = 0, 1200
     867            # per time e.g. step = 3, 6, 9, 12
    895868            # flag for Fortran program CONVERT2 and file merging
    896869            convertFlag = False
    897             print 'current prod: ', prod
     870            print('current prod: ', prod)
    898871            # e.g. prod = ('20170505', '0', '12')
    899872            #             (  date    ,time, step)
     
    917890                # they are just valid for a single product
    918891                for k, f in fdict.iteritems():
    919                     silent_remove(c.inputdir + "/fort." + k)
    920                     fdict[k] = open(c.inputdir + '/fort.' + k, 'w')
     892                    fortfile = os.path.join(c.inputdir, 'fort.' + k)
     893                    silent_remove(fortfile)
     894                    fdict[k] = open(fortfile, 'w')
    921895
    922896                cdate = str(grib_get(gid, 'date'))
     
    946920                    if timestamp < slimit or timestamp > elimit:
    947921                        continue
     922            else:
     923                pass
    948924
    949925            try:
    950                 if c.wrf == '1':
    951                     if 'olddate' not in locals():
    952                         fwrf = open(c.outputdir + '/WRF' + cdate +
    953                                     '.{:0>2}'.format(time) + '.000.grb2', 'w')
     926                if c.wrf:
     927                    if 'olddate' not in locals() or cdate != olddate:
     928                        fwrf = open(os.path.join(c.outputdir,
     929                                    'WRF' + cdate + '.{:0>2}'.format(time) +
     930                                    '.000.grb2'), 'w')
    954931                        olddate = cdate[:]
    955                     else:
    956                         if cdate != olddate:
    957                             fwrf = open(c.outputdir + '/WRF' + cdate +
    958                                         '.{:0>2}'.format(time) + '.000.grb2',
    959                                         'w')
    960                             olddate = cdate[:]
    961932            except AttributeError:
    962933                pass
    963934
    964             # helper variable to remember which fields are already used.
     935            # helper variable to remember which fields were already used.
    965936            savedfields = []
    966937            while 1:
     
    973944                # Specific humidity (Q.grb) is used as a template only
    974945                # so we need the first we "meet"
    975                     with open(c.inputdir + '/fort.18', 'w') as fout:
     946                    with open(os.path.join(c.inputdir, 'fort.18'), 'w') as fout:
    976947                        grib_write(gid, fout)
    977948                elif paramId == 131 or paramId == 132:
     
    986957                    grib_write(gid, fdict['13'])
    987958                elif  paramId in [129, 138, 155] and levtype == 'hybrid' \
    988                         and c.wrf == '1':
     959                        and c.wrf:
    989960                    pass
    990961                elif paramId == 246 or paramId == 247:
     
    1006977                        savedfields.append(paramId)
    1007978                    else:
    1008                         print 'duplicate ' + str(paramId) + ' not written'
     979                        print('duplicate ' + str(paramId) + ' not written')
    1009980
    1010981                try:
    1011                     if c.wrf == '1':
    1012                         if levtype == 'hybrid': # model layer
    1013                             if paramId in [129, 130, 131, 132, 133, 138, 155]:
    1014                                 grib_write(gid, fwrf)
    1015                         else: # sfc layer
    1016                             if paramId in wrfpars:
    1017                                 grib_write(gid, fwrf)
     982                    if c.wrf:
     983                        # model layer
     984                        if levtype == 'hybrid' and \
     985                           paramId in [129, 130, 131, 132, 133, 138, 155]:
     986                            grib_write(gid, fwrf)
     987                        # sfc layer
     988                        elif paramId in wrfpars:
     989                            grib_write(gid, fwrf)
    1018990                except AttributeError:
    1019991                    pass
     
    10291001                pwd = os.getcwd()
    10301002                os.chdir(c.inputdir)
    1031                 if os.stat('fort.21').st_size == 0 and int(c.eta) == 1:
    1032                     print 'Parameter 77 (etadot) is missing, most likely it is \
    1033                            not available for this type or date/time\n'
    1034                     print 'Check parameters CLASS, TYPE, STREAM, START_DATE\n'
     1003                if os.stat('fort.21').st_size == 0 and c.eta:
     1004                    print('Parameter 77 (etadot) is missing, most likely it is \
     1005                           not available for this type or date/time\n')
     1006                    print('Check parameters CLASS, TYPE, STREAM, START_DATE\n')
    10351007                    my_error(c.mailfail, 'fort.21 is empty while parameter eta \
    10361008                             is set to 1 in CONTROL file')
     
    10381010                # create the corresponding output file fort.15
    10391011                # (generated by CONVERT2) + fort.16 (paramId 167 and 168)
    1040                 p = subprocess.check_call(
    1041                     [os.path.expandvars(os.path.expanduser(c.exedir)) +
    1042                      '/CONVERT2'], shell=True)
     1012                p = subprocess.check_call([os.path.join(c.exedir, 'CONVERT2')],
     1013                                          shell=True)
    10431014                os.chdir(pwd)
    10441015
    10451016                # create final output filename, e.g. EN13040500 (ENYYMMDDHH)
    1046                 fnout = c.inputdir + '/' + c.prefix
     1017                fnout = os.path.join(c.inputdir, c.prefix)
    10471018                if c.maxstep > 12:
    10481019                    suffix = cdate[2:8] + '.{:0>2}'.format(time/100) + \
     
    10511022                    suffix = cdateH[2:10]
    10521023                fnout += suffix
    1053                 print "outputfile = " + fnout
     1024                print("outputfile = " + fnout)
    10541025                self.outputfilelist.append(fnout) # needed for final processing
    10551026
     
    10591030                    c.inputdir + '/OG_OROLSM__SL.*.' + c.ppid + '*')[0])
    10601031                fluxfile = 'flux' + cdate[0:2] + suffix
    1061                 if c.cwc != '1':
     1032                if not c.cwc:
    10621033                    flist = ['fort.15', fluxfile, 'fort.16', orolsm]
    10631034                else:
     
    10661037                with open(fnout, 'wb') as fout:
    10671038                    for f in flist:
     1039                        shutil.copyfileobj(open(os.path.join(c.inputdir, f),
     1040                                                'rb'), fout)
     1041
     1042                if c.omega:
     1043                    with open(os.path.join(c.outputdir, 'OMEGA'), 'wb') as fout:
    10681044                        shutil.copyfileobj(
    1069                             open(c.inputdir + '/' + f, 'rb'), fout)
    1070 
    1071                 if c.omega == '1':
    1072                     with open(c.outputdir + '/OMEGA', 'wb') as fout:
    1073                         shutil.copyfileobj(
    1074                             open(c.inputdir + '/fort.25', 'rb'), fout)
    1075 
    1076         if hasattr(c, 'wrf') and c.wrf == '1':
     1045                            open(os.path.join(c.inputdir, 'fort.25'),
     1046                                 'rb'), fout)
     1047            else:
     1048                pass
     1049
     1050        if c.wrf:
    10771051            fwrf.close()
    10781052
     
    11171091        pars = to_param_id(self.params['OG_acc_SL'][0], table128)
    11181092        index_keys = ["date", "time", "step"]
    1119         indexfile = c.inputdir + "/date_time_stepRange.idx"
     1093        indexfile = os.path.join(c.inputdir, _config.FILE_GRIB_INDEX)
    11201094        silent_remove(indexfile)
    11211095        grib = GribTools(inputfiles.files)
     
    11271101        for key in index_keys:
    11281102            key_vals = grib_index_get(iid, key)
    1129             print key_vals
     1103            print(key_vals)
    11301104            # have to sort the steps for disaggregation,
    11311105            # therefore convert to int first
     
    11481122            stepsdict[str(p)] = []
    11491123
    1150         print 'maxstep: ', c.maxstep
     1124        print('maxstep: ', c.maxstep)
    11511125
    11521126        for prod in product(*index_vals):
     
    11551129            # per date e.g. time = 0, 1200
    11561130            # per time e.g. step = 3, 6, 9, 12
     1131            print('current prod: ', prod)
    11571132            for i in range(len(index_keys)):
    11581133                grib_index_select(iid, index_keys[i], prod[i])
    11591134
     1135            # get first id from current product
    11601136            gid = grib_new_from_index(iid)
     1137
     1138            # if there is data for this product combination
     1139            # prepare some date and time parameter before reading the data
    11611140            if gid is not None:
    11621141                cdate = grib_get(gid, 'date')
     
    11761155
    11771156            if c.maxstep > 12:
    1178                 fnout = c.inputdir + '/flux' + \
    1179                     sdate.strftime('%Y%m%d') + '.{:0>2}'.format(time/100) + \
    1180                     '.{:0>3}'.format(step-2*int(c.dtime))
    1181                 gnout = c.inputdir + '/flux' + \
    1182                     sdate.strftime('%Y%m%d') + '.{:0>2}'.format(time/100) + \
    1183                     '.{:0>3}'.format(step-int(c.dtime))
    1184                 hnout = c.inputdir + '/flux' + \
    1185                     sdate.strftime('%Y%m%d') + '.{:0>2}'.format(time/100) + \
    1186                     '.{:0>3}'.format(step)
    1187                 g = open(gnout, 'w')
    1188                 h = open(hnout, 'w')
     1157                fnout = os.path.join(c.inputdir, 'flux' +
     1158                                     sdate.strftime('%Y%m%d') +
     1159                                     '.{:0>2}'.format(time/100) +
     1160                                     '.{:0>3}'.format(step-2*int(c.dtime)))
     1161                gnout = os.path.join(c.inputdir, 'flux' +
     1162                                     sdate.strftime('%Y%m%d') +
     1163                                     '.{:0>2}'.format(time/100) +
     1164                                     '.{:0>3}'.format(step-int(c.dtime)))
     1165                hnout = os.path.join(c.inputdir, 'flux' +
     1166                                     sdate.strftime('%Y%m%d') +
     1167                                     '.{:0>2}'.format(time/100) +
     1168                                     '.{:0>3}'.format(step))
    11891169            else:
    1190                 fnout = c.inputdir + '/flux' + fdate.strftime('%Y%m%d%H')
    1191                 gnout = c.inputdir + '/flux' + (fdate +
    1192                                                 timedelta(hours=int(c.dtime))
    1193                                                ).strftime('%Y%m%d%H')
    1194                 hnout = c.inputdir + '/flux' + sdates.strftime('%Y%m%d%H')
    1195                 g = open(gnout, 'w')
    1196                 h = open(hnout, 'w')
    1197 
    1198             print "outputfile = " + fnout
    1199             f = open(fnout, 'w')
     1170                fnout = os.path.join(c.inputdir, 'flux' +
     1171                                     fdate.strftime('%Y%m%d%H'))
     1172                gnout = os.path.join(c.inputdir, 'flux' +
     1173                                     (fdate + timedelta(hours=int(c.dtime))).
     1174                                     strftime('%Y%m%d%H'))
     1175                hnout = os.path.join(c.inputdir, 'flux' +
     1176                                     sdates.strftime('%Y%m%d%H'))
     1177
     1178            print("outputfile = " + fnout)
     1179            f_handle = open(fnout, 'w')
     1180            g_handle = open(gnout, 'w')
     1181            h_handle = open(hnout, 'w')
    12001182
    12011183            # read message for message and store relevant data fields
     
    12581240                            grib_set(gid, 'date', fdate.year*10000 +
    12591241                                     fdate.month*100+fdate.day)
    1260                         grib_write(gid, f)
     1242                        grib_write(gid, f_handle)
    12611243
    12621244                        if c.basetime is not None:
     
    12851267                                     truedatetime.month * 100 +
    12861268                                     truedatetime.day)
    1287                             grib_write(gid, h)
     1269                            grib_write(gid, h_handle)
    12881270
    12891271                            #values = (svdp[1]+svdp[2])/2.
     
    13001282                                     truedatetime.day)
    13011283                            grib_set_values(gid, values)
    1302                             grib_write(gid, g)
     1284                            grib_write(gid, g_handle)
    13031285
    13041286                    grib_release(gid)
     
    13061288                    gid = grib_new_from_index(iid)
    13071289
    1308             f.close()
    1309             g.close()
    1310             h.close()
     1290            f_handle.close()
     1291            g_handle.close()
     1292            h_handle.close()
    13111293
    13121294        grib_index_release(iid)
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/classes/GribTools.py

    r2fb99de r25b14be  
    297297                Grib index id.
    298298        '''
    299         print "... index will be done"
     299        print("... index will be done")
    300300        iid = None
    301301
    302302        if os.path.exists(index_file):
    303303            iid = grib_index_read(index_file)
    304             print "Use existing index file: %s " % (index_file)
     304            print("Use existing index file: %s " % (index_file))
    305305        else:
    306306            for filename in self.filenames:
    307                 print "Inputfile: %s " % (filename)
     307                print("Inputfile: %s " % (filename))
    308308                if iid is None:
    309309                    iid = grib_index_new_from_file(filename, index_keys)
     
    314314                grib_index_write(iid, index_file)
    315315
    316         print '... index done'
     316        print('... index done')
    317317
    318318        return iid
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/classes/MarsRetrieval.py

    r2fb99de r25b14be  
    311311        '''
    312312        @Description:
    313             Prints all class attributes and their values.
     313            Prints all class attributes and their values to the
     314            standard output.
    314315
    315316        @Input:
     
    329330                pass
    330331            else:
    331                 print item[0] + ': ' + str(item[1])
     332                print(item[0] + ': ' + str(item[1]))
    332333
    333334        return
    334335
    335336
    336     def print_info(self):
    337         '''
     337    def print_info(self, inputdir):
     338        '''
     339        @Description:
     340            Prints all mars requests to an extra file for debugging and
     341            information.
     342
     343        @Input:
     344            self: instance of MarsRetrieval
     345                For description see class documentation.
     346
     347            inputdir: string
     348                The path where all data from the retrievals are stored.
     349
     350        @Return:
     351            <nothing>
    338352        '''
    339353        # Get all class attributes and their values as a dictionary
     
    341355
    342356        # open a file to store all requests to
    343         with open(os.path.join(_config.PATH_RUN_DIR + os.path.sep +
     357        with open(os.path.join(inputdir,
    344358                               _config.FILE_MARS_REQUESTS), 'a') as f:
    345359            f.write('mars\n')
     
    394408                self.server.execute(s, target)
    395409            except:
    396                 print('MARS Request failed, '
    397                       'have you already registered at apps.ecmwf.int?')
     410                print('MARS Request failed, \
     411                      have you already registered at apps.ecmwf.int?')
    398412                raise IOError
    399413            if os.stat(target).st_size == 0:
     
    407421                                 stderr=subprocess.PIPE, bufsize=1)
    408422            pout = p.communicate(input=s)[0]
    409             print pout.decode()
     423            print(pout.decode())
    410424
    411425            if 'Some errors reported' in pout.decode():
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/classes/UioFiles.py

    r54a8a01 r25b14be  
    5252# software specific module from flex_extract
    5353#import profiling
    54 from tools import silent_remove, get_list_as_string
     54from mods.tools import silent_remove, get_list_as_string
    5555
    5656# ------------------------------------------------------------------------------
     
    6060class UioFiles(object):
    6161    '''
    62     Class to manipulate files. At initialisation it has the attribute
    63     pattern which stores a regular expression pattern for the files associated
    64     with the instance of the class.
     62    Class to manipulate files. At initialisation it has the pattern
     63    which stores a regular expression pattern for the files, the path
     64    to the files and the files already.
    6565    '''
    6666    # --------------------------------------------------------------------------
     
    8888        self.path = path
    8989        self.pattern = pattern
    90         self.files = None
     90        self.files = []
    9191
    9292        self.__list_files__(self.path)
     
    9595
    9696    #@profiling.timefn
    97     def __list_files__(self, path, callid=0):
     97    def __list_files__(self, path):
    9898        '''
    9999        @Description:
     
    108108                Path to the files.
    109109
    110             callid: integer
    111                 Id which tells the function if its the first call
    112                 or a recursive call. Default and first call is 0.
    113                 Everything different from 0 is ment to be a recursive case.
    114 
    115110        @Return:
    116111            <nothing>
    117112        '''
    118 
    119         # initialize variable in first function call
    120         if callid == 0:
    121             self.files = []
    122 
    123113        # Get the absolute path
    124114        path = os.path.abspath(path)
    125115
    126         # get the file list of the path if its not a directory and
    127         # if it contains the pattern
    128         self.files.extend([os.path.join(path, k) for k in os.listdir(path)
    129                            if fnmatch.fnmatch(k, self.pattern)])
    130 
    131         # find possible sub-directories in the path
    132         subdirs = [s for s in os.listdir(path)
    133                    if os.path.isdir(os.path.join(path, s))]
    134 
    135         # do recursive calls for sub-direcorties
    136         if subdirs:
    137             for subdir in subdirs:
    138                 self.__list_files__(os.path.join(path, subdir), callid=1)
     116        # get all files in the dir and subdir as absolut path
     117        for root, dirnames, filenames in os.walk(path):
     118            for filename in fnmatch.filter(filenames, self.pattern):
     119                self.files.append(os.path.join(root, filename))
    139120
    140121        return
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/install.py

    r2fb99de r25b14be  
    1212#        - added documentation
    1313#        - moved install_args_and_control in here
     14#        - splitted code in smaller functions
     15#        - delete convert build files in here instead of compile job script
     16#        - changed static path names to Variables from config file
    1417#
    1518# @License:
     
    5558# software specific classes and modules from flex_extract
    5659import _config
    57 from ControlFile import ControlFile
    58 from UioFiles import UioFiles
    59 from tools import make_dir, put_file_to_ecserver, submit_job_to_ecserver
    60 
     60from classes.ControlFile import ControlFile
     61from classes.UioFiles import UioFiles
     62from mods.tools import make_dir, put_file_to_ecserver, submit_job_to_ecserver
    6163
    6264# ------------------------------------------------------------------------------
     
    7678    '''
    7779
    78     os.chdir(_config.PATH_LOCAL_PYTHON)
     80    #os.chdir(_config.PATH_LOCAL_PYTHON)
     81
    7982    args = get_install_cmdline_arguments()
    8083
     
    8285        c = ControlFile(args.controlfile)
    8386    except IOError:
    84         print 'Could not read CONTROL file "' + args.controlfile + '"'
    85         print 'Either it does not exist or its syntax is wrong.'
    86         print 'Try "' + sys.argv[0].split('/')[-1] + \
    87               ' -h" to print usage information'
     87        print('Could not read CONTROL file "' + args.controlfile + '"')
     88        print('Either it does not exist or its syntax is wrong.')
     89        print('Try "' + sys.argv[0].split('/')[-1] +
     90              ' -h" to print usage information')
    8891        exit(1)
    8992
     
    130133                        servers (to find grib2flexpart and COMMAND file)\n\
    131134                        Normally flex_extract resides in the scripts directory \
    132                         of the FLEXPART distribution, thus the:")
     135                        of the FLEXPART distribution.")
    133136
    134137    # arguments for job submission to ECMWF, only needed by submit.py
     
    171174    ecd = _config.PATH_FLEXEXTRACT_DIR
    172175    tarball_name = _config.FLEXEXTRACT_DIRNAME + '.tar'
    173     tar_file = os.path.join(ecd + os.path.sep + tarball_name)
     176    tar_file = os.path.join(ecd, tarball_name)
    174177
    175178    target_dirname = _config.FLEXEXTRACT_DIRNAME
     
    186189        mk_env_vars(c.ecuid, c.ecgid, c.gateway, c.destination)
    187190
    188         mk_tarball(tar_file)
     191        mk_tarball(tar_file, c.install_target)
    189192
    190193        put_file_to_ecserver(ecd, tarball_name, c.install_target,
     
    192195
    193196        submit_job_to_ecserver(c.install_target,
    194                                os.path.join(_config.PATH_JOBSCRIPTS +
    195                                             os.path.sep +
     197                               os.path.join(_config.PATH_REL_JOBSCRIPTS,
    196198                                            _config.FILE_INSTALL_COMPILEJOB))
    197199
     
    203205
    204206    else: #local
    205         if not c.flexpart_root_scripts or c.flexpart_root_scripts == '../':
    206             #install_dir = c.flexpart_root_scripts
     207        if c.flexpart_root_scripts == _config.PATH_FLEXEXTRACT_DIR :
    207208            print('WARNING: FLEXPART_ROOT_SCRIPTS has not been specified')
    208             print('There will be only the compilation of the Fortran program' +
    209                   ' in ' + _config.PATH_FORTRAN_SRC)
     209            print('flex_extract will be installed in here by compiling the ' +
     210                  'Fortran source in ' + _config.PATH_FORTRAN_SRC)
    210211            os.chdir(_config.PATH_FORTRAN_SRC)
    211212        else: # creates the target working directory for flex_extract
     
    213214                                        c.flexpart_root_scripts))
    214215            if os.path.abspath(ecd) != os.path.abspath(c.flexpart_root_scripts):
    215                 mk_tarball(tar_file)
    216                 make_dir(os.path.join(c.flexpart_root_scripts + os.path.sep +
     216                mk_tarball(tar_file, c.install_target)
     217                make_dir(os.path.join(c.flexpart_root_scripts,
    217218                                      target_dirname))
    218                 os.chdir(os.path.join(c.flexpart_root_scripts + os.path.sep +
     219                os.chdir(os.path.join(c.flexpart_root_scripts,
    219220                                      target_dirname))
    220221                un_tarball(tar_file)
    221                 os.chdir(os.path.join(c.flexpart_root_scripts + os.path.sep +
    222                                       target_dirname + os.path.sep +
    223                                       _config.PATH_RELATIVE_FORTRAN_SRC))
     222                os.chdir(os.path.join(c.flexpart_root_scripts,
     223                                      target_dirname,
     224                                      _config.PATH_REL_FORTRAN_SRC))
    224225
    225226        # Create Fortran executable - CONVERT2
     
    232233
    233234        os.chdir(ecd)
    234         if os.path.isfile(tar_file):
    235             os.remove(tar_file)
    236 
    237     return
    238 
    239 def mk_tarball(tarball_path):
     235#        if os.path.isfile(tar_file):
     236#            os.remove(tar_file)
     237
     238    return
     239
     240def mk_tarball(tarball_path, target):
    240241    '''
    241242    @Description:
     
    252253            relevant data for flex_extract.
    253254
     255        target: string
     256            The queue where the job is submitted to.
     257
    254258    @Return:
    255259        <nothing>
     
    266270
    267271    # get lists of the files to be added to the tar file
    268     ECMWF_ENV_FILE = [os.path.join(_config.PATH_RELATIVE_PYTHON +
    269                                    os.path.sep + _config.FILE_USER_ENVVARS)]
    270     pyfiles = [os.path.relpath(x,ecd)
    271                for x in glob(_config.PATH_LOCAL_PYTHON +
    272                              os.path.sep + '*py')]
    273     controlfiles = [os.path.relpath(x,ecd)
    274                     for x in glob(_config.PATH_CONTROLFILES +
    275                                   os.path.sep + 'CONTROL*')]
    276     tempfiles = [os.path.relpath(x,ecd)
    277                  for x in glob(_config.PATH_TEMPLATES)]
    278     ffiles = [os.path.relpath(x,ecd)
    279               for x in glob(_config.PATH_FORTRAN_SRC +
    280                             os.path.sep + '*.f*')]
    281     hfiles = [os.path.relpath(x,ecd)
    282               for x in glob(_config.PATH_FORTRAN_SRC +
    283                             os.path.sep + '*.h')]
    284     makefiles = [os.path.relpath(x,ecd)
    285                  for x in glob(_config.PATH_FORTRAN_SRC +
    286                                os.path.sep + 'Makefile*')]
     272    if target == 'local':
     273        ECMWF_ENV_FILE = []
     274    else:
     275        ECMWF_ENV_FILE = [_config.PATH_REL_ECMWF_ENV]
     276
     277    pyfiles = [os.path.relpath(x, ecd)
     278               for x in UioFiles(_config.PATH_LOCAL_PYTHON, '*py').files]
     279    controlfiles = [os.path.relpath(x, ecd)
     280                    for x in UioFiles(_config.PATH_CONTROLFILES,
     281                                      'CONTROL*').files]
     282    tempfiles = [os.path.relpath(x, ecd)
     283                 for x in UioFiles(_config.PATH_TEMPLATES , '*').files]
     284    ffiles = [os.path.relpath(x, ecd)
     285              for x in UioFiles(_config.PATH_FORTRAN_SRC, '*.f*').files]
     286    hfiles = [os.path.relpath(x, ecd)
     287              for x in UioFiles(_config.PATH_FORTRAN_SRC, '*.h').files]
     288    makefiles = [os.path.relpath(x, ecd)
     289                 for x in UioFiles(_config.PATH_FORTRAN_SRC, 'Makefile*').files]
    287290
    288291    # concatenate single lists to one for a better looping
     
    351354    '''
    352355
    353     with open(os.path.join(_config.PATH_LOCAL_PYTHON + os.path.sep +
    354                            _config.FILE_USER_ENVVARS), 'w') as fo:
     356    with open(_config.PATH_REL_ECMWF_ENV, 'w') as fo:
    355357        fo.write('ECUID ' + ecuid + '\n')
    356358        fo.write('ECGID ' + ecgid + '\n')
     
    389391    '''
    390392
    391     template = os.path.join(_config.PATH_TEMPLATES + os.path.sep +
     393    template = os.path.join(_config.PATH_REL_TEMPLATES,
    392394                            _config.TEMPFILE_INSTALL_COMPILEJOB)
    393395    with open(template) as f:
    394396        fdata = f.read().split('\n')
    395397
    396     compilejob = os.path.join(_config.PATH_JOBSCRIPTS + os.path.sep +
     398    compilejob = os.path.join(_config.PATH_REL_JOBSCRIPTS,
    397399                              _config.FILE_INSTALL_COMPILEJOB)
    398400    with open(compilejob, 'w') as fo:
     
    426428        Modifies the original job template file so that it is specified
    427429        for the user and the environment were it will be applied. Result
    428         is stored in a new file "job.temp" in the python directory.
     430        is stored in a new file.
    429431
    430432    @Input:
     
    449451        <nothing>
    450452    '''
    451     ec_python_rel_path = _config.FLEXEXTRACT_DIRNAME + '/' + \
    452                          _config.PATH_RELATIVE_PYTHON
    453 
    454     template = os.path.join(_config.PATH_TEMPLATES + os.path.sep +
     453    fp_root_path_to_python = os.path.join(fp_root, _config.FLEXEXTRACT_DIRNAME,
     454                         _config.PATH_REL_PYTHON)
     455
     456    template = os.path.join(_config.PATH_REL_TEMPLATES,
    455457                            _config.TEMPFILE_INSTALL_JOB)
    456458    with open(template) as f:
    457459        fdata = f.read().split('\n')
    458460
    459     jobfile_temp = os.path.join(_config.PATH_JOBSCRIPTS + os.path.sep +
     461    jobfile_temp = os.path.join(_config.PATH_REL_TEMPLATES,
    460462                                _config.TEMPFILE_JOB)
    461463    with open(jobfile_temp, 'w') as fo:
    462464        for data in fdata:
    463465            if '--workdir' in data:
    464                 data = '#SBATCH --workdir=/scratch/ms/' + ecgid + \
    465                         '/' + ecuid
     466                data = '#SBATCH --workdir=/scratch/ms/' + ecgid + '/' + ecuid
    466467            elif '##PBS -o' in data:
    467468                data = '##PBS -o /scratch/ms/' + ecgid + '/' + \
    468469                        ecuid + 'flex_ecmwf.$Jobname.$Job_ID.out'
    469470            elif  'export PATH=${PATH}:' in data:
    470                 data += fp_root + '/' + ec_python_rel_path
     471                data += fp_root_path_to_python
    471472
    472473            fo.write(data + '\n')
     
    516517        print('Using makefile: ' + makefile)
    517518        p = subprocess.Popen(['make', '-f',
    518                               os.path.join(src_path + os.path.sep + makefile)],
     519                              os.path.join(src_path, makefile)],
    519520                             stdin=subprocess.PIPE,
    520521                             stdout=subprocess.PIPE,
     
    537538    else:
    538539        subprocess.check_call(['ls', '-l',
    539                                os.path.join(src_path + os.path.sep +
     540                               os.path.join(src_path,
    540541                                            _config.FORTRAN_EXECUTABLE)])
    541542
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/mods/get_mars_data.py

    r2fb99de r25b14be  
    5757
    5858# software specific classes and modules from flex_extract
     59import _config
    5960from tools import my_error, normal_exit, get_cmdline_arguments, read_ecenv
    60 from EcFlexpart import EcFlexpart
    61 from UioFiles import UioFiles
    62 
    63 # add path to pythonpath so that python finds its buddies
    64 LOCAL_PYTHON_PATH = os.path.dirname(os.path.abspath(
    65     inspect.getfile(inspect.currentframe())))
    66 if LOCAL_PYTHON_PATH not in sys.path:
    67     sys.path.append(LOCAL_PYTHON_PATH)
    68 
     61from classes.EcFlexpart import EcFlexpart
     62from classes.UioFiles import UioFiles
    6963# ------------------------------------------------------------------------------
    7064# FUNCTION
     
    8983        c = ControlFile(args.controlfile)
    9084    except IOError:
    91         try:
    92             c = ControlFile(LOCAL_PYTHON_PATH + args.controlfile)
    93         except IOError:
    94             print 'Could not read CONTROL file "' + args.controlfile + '"'
    95             print 'Either it does not exist or its syntax is wrong.'
    96             print 'Try "' + sys.argv[0].split('/')[-1] + \
    97                   ' -h" to print usage information'
    98             sys.exit(1)
    99 
    100     env_parameter = read_ecenv(c.ecmwfdatadir + 'python/ECMWF_ENV')
     85        print('Could not read CONTROL file "' + args.controlfile + '"')
     86        print('Either it does not exist or its syntax is wrong.')
     87        print('Try "' + sys.argv[0].split('/')[-1] + \
     88              ' -h" to print usage information')
     89        sys.exit(1)
     90
     91    env_parameter = read_ecenv(_config.PATH_ECMWF_ENV)
    10192    c.assign_args_to_control(args, env_parameter)
    10293    c.assign_envs_to_control(env_parameter)
    103     c.check_conditions()
     94    c.check_conditions(args.queue)
    10495
    10596    get_mars_data(c)
     
    286277                    end.strftime("%Y%m%d")
    287278
    288 
    289279        print("... retrieve " + dates + " in dir " + c.inputdir)
    290280
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/mods/plot_retrieved.py

    r2fb99de r25b14be  
    5353
    5454# software specific classes and modules from flex_extract
    55 from ControlFile import ControlFile
    56 from UioFiles import UioFiles
    57 
    58 # add path to pythonpath so that python finds its buddies
    59 LOCAL_PYTHON_PATH = os.path.dirname(os.path.abspath(
    60     inspect.getfile(inspect.currentframe())))
    61 if LOCAL_PYTHON_PATH not in sys.path:
    62     sys.path.append(LOCAL_PYTHON_PATH)
     55import _config
     56from classes.ControlFile import ControlFile
     57from classes.UioFiles import UioFiles
    6358
    6459font = {'family': 'monospace', 'size': 12}
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/mods/prepare_flexpart.py

    r2fb99de r25b14be  
    5757import sys
    5858import socket
    59 import _config
    6059
    6160# software specific classes and modules from flex_extract
    62 from UioFiles import UioFiles
     61import _config
     62from classes.UioFiles import UioFiles
    6363from tools import clean_up, get_cmdline_arguments, read_ecenv
    64 from EcFlexpart import EcFlexpart
     64from classes.EcFlexpart import EcFlexpart
    6565
    6666ecapi = 'ecmwf' not in socket.gethostname()
     
    7070except ImportError:
    7171    ecapi = False
    72 
    73 # add path to pythonpath so that python finds its buddies
    74 LOCAL_PYTHON_PATH = os.path.dirname(os.path.abspath(
    75     inspect.getfile(inspect.currentframe())))
    76 if LOCAL_PYTHON_PATH not in sys.path:
    77     sys.path.append(LOCAL_PYTHON_PATH)
    78 
    7972
    8073# ------------------------------------------------------------------------------
     
    10093        c = ControlFile(args.controlfile)
    10194    except IOError:
    102         try:
    103             c = ControlFile(LOCAL_PYTHON_PATH + args.controlfile)
    104         except IOError:
    105             print 'Could not read CONTROL file "' + args.controlfile + '"'
    106             print 'Either it does not exist or its syntax is wrong.'
    107             print 'Try "' + sys.argv[0].split('/')[-1] + \
    108                   ' -h" to print usage information'
    109             sys.exit(1)
     95        print('Could not read CONTROL file "' + args.controlfile + '"')
     96        print('Either it does not exist or its syntax is wrong.')
     97        print('Try "' + sys.argv[0].split('/')[-1] + \
     98              ' -h" to print usage information')
     99        sys.exit(1)
    110100
    111     env_parameter = read_ecenv(c.ecmwfdatadir + 'python/ECMWF_ENV')
     101    env_parameter = read_ecenv(_config.PATH_ECMWF_ENV)
    112102    c.assign_args_to_control(args, env_parameter)
    113103    c.assign_envs_to_control(env_parameter)
    114     c.check_conditions()
     104    c.check_conditions(args.queue)
    115105    prepare_flexpart(args.ppid, c)
    116106
     
    170160        start = start - datetime.timedelta(days=1)
    171161
    172     print 'Prepare ' + start.strftime("%Y%m%d") + \
    173            "/to/" + end.strftime("%Y%m%d")
     162    print('Prepare ' + start.strftime("%Y%m%d") +
     163           "/to/" + end.strftime("%Y%m%d"))
    174164
    175165    # create output dir if necessary
     
    182172    # deaccumulate the flux data
    183173    flexpart = EcFlexpart(c, fluxes=True)
    184     flexpart.write_namelist(c, 'fort.4')
     174    flexpart.write_namelist(c, _config.FILE_NAMELIST)
    185175    flexpart.deacc_fluxes(inputfiles, c)
    186176
     
    197187    # otherwise delete temporary files
    198188    if int(c.debug) != 0:
    199         print '\nTemporary files left intact'
     189        print('\nTemporary files left intact')
    200190    else:
    201191        clean_up(c)
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/mods/profiling.py

    r2fb99de r25b14be  
    6666        result = fn(*args, **kwargs)
    6767        t2 = time.time()
    68         print "@timefn:" + fn.func_name + " took " + str(t2 - t1) + " seconds"
     68        print("@timefn:" + fn.func_name + " took " + str(t2 - t1) + " seconds")
    6969
    7070        return result
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/mods/tools.py

    r2fb99de r25b14be  
    140140    @Input:
    141141        filename: string
    142             Name of file where the ECMWV environment parameters are stored.
     142            Path to file where the ECMWV environment parameters are stored.
    143143
    144144    @Return:
    145145        envs: dict
     146            Contains the environment parameter ecuid, ecgid, gateway
     147            and destination for ECMWF server environments.
    146148    '''
    147149    envs= {}
    148     print filename
     150
    149151    with open(filename, 'r') as f:
    150152        for line in f:
     
    178180    '''
    179181
    180     print "clean_up"
     182    print("clean_up")
    181183
    182184    cleanlist = glob.glob(c.inputdir + "/*")
     
    187189            silent_remove(clist)
    188190
    189     print "Done"
     191    print("Done")
    190192
    191193    return
     
    211213    '''
    212214
    213     print message
     215    print(message)
    214216
    215217    # comment if user does not want email notification directly from python
     
    227229            pout = p.communicate(input=message + '\n\n' + trace)[0]
    228230        except ValueError as e:
    229             print 'ERROR: ', e
     231            print('ERROR: ', e)
    230232            sys.exit('Email could not be sent!')
    231233        else:
    232             print 'Email sent to ' + os.path.expandvars(user) + ' ' + \
    233                   pout.decode()
     234            print('Email sent to ' + os.path.expandvars(user) + ' ' +
     235                  pout.decode())
    234236
    235237    sys.exit(1)
     
    256258
    257259    '''
    258     print message
     260    print(message)
    259261
    260262    # comment if user does not want notification directly from python
     
    271273            pout = p.communicate(input=message+'\n\n')[0]
    272274        except ValueError as e:
    273             print 'ERROR: ', e
    274             print 'Email could not be sent!'
     275            print('ERROR: ', e)
     276            print('Email could not be sent!')
    275277        else:
    276             print 'Email sent to ' + os.path.expandvars(user) + ' ' + \
    277                   pout.decode()
     278            print('Email sent to ' + os.path.expandvars(user) + ' ' +
     279                  pout.decode())
    278280
    279281    return
     
    395397                break
    396398        else:
    397             print 'Warning: par ' + par + ' not found in table 128'
     399            print('Warning: par ' + par + ' not found in table 128')
    398400
    399401    return ipar
     
    441443            raise # re-raise exception if a different error occured
    442444        else:
    443             print 'WARNING: Directory {0} already exists!'.format(directory)
     445            print('WARNING: Directory {0} already exists!'.format(directory))
    444446
    445447    return
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/submit.py

    r2fb99de r25b14be  
    1616#        - added documentation
    1717#        - minor changes in programming style (for consistence)
     18#        - changed path names to variables from config file
     19#        - added option for writing mars requests to extra file
     20#          additionally,as option without submitting the mars jobs
    1821#
    1922# @License:
     
    4851# software specific classes and modules from flex_extract
    4952import _config
    50 from tools import normal_exit, get_cmdline_arguments, submit_job_to_ecserver, \
    51                   read_ecenv
    52 from get_mars_data import get_mars_data
    53 from prepare_flexpart import prepare_flexpart
    54 from ControlFile import ControlFile
     53from mods.tools import (normal_exit, get_cmdline_arguments,
     54                        submit_job_to_ecserver, read_ecenv)
     55from mods.get_mars_data import get_mars_data
     56from mods.prepare_flexpart import prepare_flexpart
     57from classes.ControlFile import ControlFile
    5558
    5659# ------------------------------------------------------------------------------
     
    7376    '''
    7477
    75     called_from_dir = os.getcwd()
    76 
    7778    args = get_cmdline_arguments()
    7879
     
    8081        c = ControlFile(args.controlfile)
    8182    except IOError:
    82         try:
    83             c = ControlFile(_config.PATH_LOCAL_PYTHON + args.controlfile)
    84         except IOError:
    85             print 'Could not read CONTROL file "' + args.controlfile + '"'
    86             print 'Either it does not exist or its syntax is wrong.'
    87             print 'Try "' + sys.argv[0].split('/')[-1] + \
    88                   ' -h" to print usage information'
    89             sys.exit(1)
    90 
    91     env_parameter = read_ecenv(c.ecmwfdatadir + 'python/ECMWF_ENV')
     83        print('Could not read CONTROL file "' + args.controlfile + '"')
     84        print('Either it does not exist or its syntax is wrong.')
     85        print('Try "' + sys.argv[0].split('/')[-1] + \
     86              ' -h" to print usage information')
     87        sys.exit(1)
     88
     89    env_parameter = read_ecenv(_config.PATH_ECMWF_ENV)
    9290    c.assign_args_to_control(args)
    9391    c.assign_envs_to_control(env_parameter)
    94     c.check_conditions()
     92    c.check_conditions(args.queue)
    9593
    9694    # on local side
    9795    # on ECMWF server this would also be the local side
     96    called_from_dir = os.getcwd()
    9897    if args.queue is None:
    9998        if c.inputdir[0] != '/':
     
    107106        else:
    108107            normal_exit(c.mailfail, 'PRINTING MARS_REQUESTS DONE!')
    109     # on ECMWF server
     108    # send files to ECMWF server and install there
    110109    else:
    111110        submit(args.job_template, c, args.queue)
     
    120119    @Input:
    121120        jtemplate: string
    122             Job template file for submission to ECMWF. It contains all necessary
     121            Job template file from sub-directory "_templates" for
     122            submission to ECMWF. It contains all necessary
    123123            module and variable settings for the ECMWF environment as well as
    124124            the job call and mail report instructions.
     
    146146
    147147    # read template file and get index for CONTROL input
    148     with open(jtemplate) as f:
     148    with open(os.path.join(_config.PATH_TEMPLATES, jtemplate)) as f:
    149149        lftext = f.read().split('\n')
    150150    insert_point = lftext.index('EOF')
     
    153153    # --------- create on demand job script ------------------------------------
    154154        if c.maxstep > 24:
    155             print '---- Pure forecast mode! ----'
     155            print('---- Pure forecast mode! ----')
    156156        else:
    157             print '---- On-demand mode! ----'
    158         job_file = jtemplate[:-4] + 'ksh'
     157            print('---- On-demand mode! ----')
     158        job_file = os.path.join(_config.PATH_JOBSCRIPTS,
     159                                jtemplate[:-4] + 'ksh')
    159160        clist = c.to_list()
    160161
     
    164165            f.write('\n'.join(lftextondemand))
    165166
    166         result_code = submit_job_to_ecserver(queue, job_file)
     167        submit_job_to_ecserver(queue, job_file)
    167168
    168169    else:
    169170    # --------- create operational job script ----------------------------------
    170         print '---- Operational mode! ----'
    171         job_file = jtemplate[:-5] + 'oper.ksh'
    172         #colist = []
     171        print('---- Operational mode! ----')
     172        job_file = os.path.join(_config.PATH_JOBSCRIPTS,
     173                                jtemplate[:-5] + 'oper.ksh')
    173174
    174175        if c.maxstep:
     
    190191            f.write('\n'.join(lftextoper))
    191192
    192         result_code = submit_job_to_ecserver(queue, job_file)
     193        submit_job_to_ecserver(queue, job_file)
    193194
    194195    # --------------------------------------------------------------------------
    195     print 'You should get an email with subject flex.hostname.pid'
     196    print('You should get an email with subject flex.hostname.pid')
    196197
    197198    return
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/templates/job.temp

    r5d42acd r25b14be  
    3333  module load grib_api/1.14.5
    3434  module load emos/437-r64
    35   export PATH=${PATH}:${HOME}/flex_extract_v7.1/python
     35  export PATH=${PATH}:${HOME}/flex_extract_v7.1/source/python
    3636  ;;
    3737  *cca*)
     
    4141  module load python
    4242  export SCRATCH=$TMPDIR
    43   export PATH=${PATH}:${HOME}/flex_extract_v7.1/python
     43  export PATH=${PATH}:${HOME}/flex_extract_v7.1/source/python
    4444  ;;
    4545esac
     
    4949cd python$$
    5050
    51 export CONTROL=$PWD/CONTROL
     51export CONTROL=CONTROL
    5252
    5353cat >$CONTROL<<EOF
Note: See TracChangeset for help on using the changeset viewer.
hosted by ZAMG