Changeset 81c180c in flex_extract.git for Source


Ignore:
Timestamp:
Jul 20, 2022, 3:55:51 PM (22 months ago)
Author:
Anne Tipka <anne.tipka@…>
Branches:
dev
Children:
4f24798
Parents:
6857073 (diff), 7896304 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch current master branch from CTBTO's gitlab repo into dev branch from flexpart.eu repo

Location:
Source/Python
Files:
6 edited

Legend:

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

    r0a75335 r75db9b0  
    2121#   June 2020 - Anne Philipp
    2222#        - update default makefile to None
     23#   August 2020 - Leopold Haimberger
     24#        - added a class parameter for system installation path
    2325#
    2426# @License:
     
    404406        self.exedir = _config.PATH_FORTRAN_SRC
    405407        self.installdir = None
     408        self.sysinstalldir = None
    406409        self.makefile = None
    407410        self.destination = None
  • Source/Python/Mods/tools.py

    rf61e1df r75db9b0  
    2222#          put_file_to_ecserver, submit_job_to_ecserver, get_informations,
    2323#          get_dimensions, execute_subprocess, none_or_int, none_or_str
     24#
     25#    August 2020 - Leopold Haimberger (University of Vienna)
     26#        - added function to check if a specific string is in a file
     27#        - added function to overwrite lines in a file which contain specific string
    2428#
    2529# @License:
     
    249253                        type=none_or_str, default=None,
    250254                        help='The name of the ECMWF server name where the'
    251                         'job script is to be submitted ' 
     255                        'job script is to be submitted '
    252256                        '(e.g. ecgate | cca | ccb)')
    253257
     
    624628    '''Creates a directory.
    625629
    626     If the directory already exists, an information is printed and the creation 
     630    If the directory already exists, an information is printed and the creation
    627631    skipped. The program stops only if there is another problem.
    628632
     
    856860    ----------
    857861    cmd_list : list of str
    858         A list of the components for the command line execution. 
    859         They will be concatenated with blank space for the command 
     862        A list of the components for the command line execution.
     863        They will be concatenated with blank space for the command
    860864        to be submitted, like ['mv', file1, file2] for mv file1 file2.
    861865
     
    910914
    911915    return start_period, end_period
     916
     917
     918def check_for_string_in_file(filepath, search_string):
     919    """
     920    Search for a specific string in a file and return True if
     921    the string was found.
     922
     923    Parameters
     924    ----------
     925    filepath : str
     926        The full file path which is to be examined.
     927
     928    search_string : str
     929        The string which is looked up for in the file.
     930
     931    Return
     932    ------
     933    Boolean :
     934        True : String was found
     935        False : String was not found
     936    """
     937    with open(filepath, 'r') as fio:
     938        for line in fio:
     939            if search_string in line:
     940                return True
     941    return False
     942
     943
     944def overwrite_lines_in_file(filepath, search_string, sub_string):
     945    """
     946    Overwrites lines which contain the given search string with the
     947    substitution string.
     948
     949    Parameters
     950    ----------
     951    search_string : str
     952        The string which is looked up for in the file.
     953
     954    sub_string : str
     955        The string which overwrites the search string.
     956
     957    Return
     958    ------
     959    """
     960    with open(filepath, 'r') as fio:
     961        data = fio.readlines()
     962
     963    with open(filepath, 'w') as fio:
     964        for line in data:
     965            if search_string in line:
     966                fio.write(sub_string)
     967            else:
     968                fio.write(line)
     969
     970    return
     971
  • Source/Python/_config.py

    r0a75335 r75db9b0  
    99#      June 2020 - Anne Philipp
    1010#         - changed template filenames to .template
     11#      August 2020 - Leopold Haimberger
     12#         - added another target for installation
     13#         - added filename which will contain paths for system version     
     14#         - checks if software runs in normal local mode or system local mode
     15#           and defines paths to user directory and executable paths   
    1116#
    1217# @License:
     
    3843# ------------------------------------------------------------------------------
    3944
    40 _VERSION_STR = '7.1.2'
     45_VERSION_STR = '7.1.2_ctbto'
    4146
    4247FLAG_ON_ECMWFSERVER = 'ecgb' in platform.node()
     
    4449QUEUES_LIST = ['ecgate', 'cca', 'ccb']
    4550
    46 INSTALL_TARGETS = ['local', 'ecgate', 'cca', 'ccb']
     51INSTALL_TARGETS = ['local', 'syslocal', 'ecgate', 'cca', 'ccb']
    4752
    4853CDS_DATASET_ML = 'reanalysis-era5-complete'
     
    7075FILE_GRIB_INDEX = 'date_time_stepRange.idx'
    7176FILE_GRIBTABLE = 'ecmwf_grib1_table_128'
     77FILE_SYS_CONFIG = '.setup.rc'
    7278
    7379# ------------------------------------------------------------------------------
     
    7985
    8086# ------------------------------------------------------------------------------
    81 PATHES
     87LOAD ENVIRONMENT VARIABLES FOR SYS VERSION; IF NECESSARRY
    8288# ------------------------------------------------------------------------------
    8389
     
    8995if PATH_LOCAL_PYTHON not in sys.path:
    9096    sys.path.append(PATH_LOCAL_PYTHON)
     97
     98# ------------------------------------------------------------------------------
     99#  PATHES
     100# ------------------------------------------------------------------------------
     101
    91102PATH_FLEXEXTRACT_DIR = os.path.normpath(os.path.dirname(os.path.abspath(
    92103    inspect.getfile(inspect.currentframe()))) + '/../../')
     104if not os.path.isdir(os.path.join(PATH_FLEXEXTRACT_DIR,'Run')):
     105    # if it does not exist, we have a system installation in place
     106    # we need to have a sys and user path
     107    # configure correct system path
     108    PATH_SYSTEM_DIR = os.path.join(PATH_FLEXEXTRACT_DIR, FLEXEXTRACT_DIRNAME)
     109    # configure correct user path
     110    PATH_FLEXEXTRACT_DIR = os.environ.get('FLEXEXTRACT_USER_DIR')
     111else:
     112    PATH_SYSTEM_DIR = PATH_FLEXEXTRACT_DIR
     113
    93114PATH_RUN_DIR = os.path.join(PATH_FLEXEXTRACT_DIR, 'Run')
    94 PATH_SOURCES = os.path.join(PATH_FLEXEXTRACT_DIR, 'Source')
     115PATH_SOURCES = os.path.join(PATH_SYSTEM_DIR, 'Source')
    95116PATH_TEMPLATES = os.path.join(PATH_FLEXEXTRACT_DIR, 'Templates')
    96117PATH_ECMWF_ENV = os.path.join(PATH_RUN_DIR, FILE_USER_ENVVARS)
    97118PATH_GRIBTABLE = os.path.join(PATH_TEMPLATES, FILE_GRIBTABLE)
    98119PATH_JOBSCRIPTS = os.path.join(PATH_RUN_DIR, 'Jobscripts')
    99 PATH_FORTRAN_SRC = os.path.join(PATH_SOURCES, 'Fortran')
     120if os.path.isdir(os.path.join(PATH_SYSTEM_DIR,'Fortran')):
     121    PATH_FORTRAN_SRC = PATH_SYSTEM_DIR
     122else:
     123    PATH_FORTRAN_SRC = os.path.join(PATH_SOURCES, 'Fortran')
    100124PATH_PYTHONTEST_SRC = os.path.join(PATH_SOURCES, 'Pythontest')
    101125PATH_INPUT_DIR = os.path.join(PATH_RUN_DIR, INPUT_DIRNAME_DEFAULT)
  • Source/Python/install.py

    r8028176 r75db9b0  
    1919#    June 2020 - Anne Philipp
    2020#        - renamed "convert" functions to "fortran" functions
    21 #        - reconfigured mk_tarball to select *.template files instead 
     21#        - reconfigured mk_tarball to select *.template files instead
    2222#          of *.nl and *.temp
    2323#        - added check for makefile settings
     24#    August 2020 - Leopold Haimberger
     25#        - added a new installation section for system installation (if-else block)
     26#        - read new argument from command line
     27#        - write .setup.rc for a system installation into Run directory
     28#        - copy executables to system path and user files to user path
    2429#
    2530# @License:
     
    7580import subprocess
    7681import tarfile
     82import shutil
    7783from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
    7884
     
    8288from Classes.UioFiles import UioFiles
    8389from Mods.tools import (make_dir, put_file_to_ecserver, submit_job_to_ecserver,
    84                         silent_remove, execute_subprocess, none_or_str)
     90                        silent_remove, execute_subprocess, none_or_str,
     91                        overwrite_lines_in_file, check_for_string_in_file)
    8592
    8693# ------------------------------------------------------------------------------
     
    103110    check_install_conditions(c)
    104111
    105     if c.install_target.lower() != 'local': # ecgate or cca
     112    if c.install_target.lower() not in ['local', 'syslocal']: # ecgate or cca
    106113        install_via_gateway(c)
    107114    else: # local
    108115        install_local(c)
    109116
     117    print("SUCCESS: INSTALLATION FINISHED!")
     118
    110119    return
    111120
     
    128137    parser.add_argument('--target', dest='install_target',
    129138                        type=none_or_str, default=None,
    130                         help="Valid targets: local | ecgate | cca , \
     139                        help="Valid targets: syslocal | local | ecgate | cca , \
    131140                        the latter two are at ECMWF")
    132141    parser.add_argument("--makefile", dest="makefile",
     
    150159    parser.add_argument("--installdir", dest="installdir",
    151160                        type=none_or_str, default=None,
    152                         help='Root directory of the '
     161                        help='Root (user) directory of the '
    153162                        'flex_extract installation')
     163    parser.add_argument("--sysinstalldir", dest="sysinstalldir",
     164                        type=none_or_str, default=None,
     165                        help='System installation path; where '
     166                        'executables are stored.')
    154167
    155168    # arguments for job submission to ECMWF, only needed by submit.py
     
    228241                            _config.FLEXEXTRACT_DIRNAME + '.tar')
    229242
    230     if c.installdir == _config.PATH_FLEXEXTRACT_DIR:
    231         print('WARNING: installdir has not been specified')
    232         print('flex_extract will be installed in here by compiling the ' +
    233               'Fortran source in ' + _config.PATH_FORTRAN_SRC)
    234         os.chdir(_config.PATH_FORTRAN_SRC)
    235     else: # creates the target working directory for flex_extract
    236         c.installdir = os.path.expandvars(os.path.expanduser(
    237             c.installdir))
    238         if os.path.abspath(_config.PATH_FLEXEXTRACT_DIR) != \
    239            os.path.abspath(c.installdir):
     243    c.installdir = os.path.abspath(os.path.expandvars(os.path.expanduser(
     244                c.installdir)))
     245    c.sysinstalldir = os.path.abspath(os.path.expandvars(os.path.expanduser(
     246        c.sysinstalldir)))
     247
     248    # this is standard installation into a single directory
     249    if c.install_target == 'local':
     250
     251        # installation into the current directory
     252        if os.path.abspath(_config.PATH_FLEXEXTRACT_DIR) == c.installdir:
     253            print('WARNING: installdir has not been specified')
     254            print('flex_extract will be installed in current dir by compiling the ' +
     255                  'Fortran source in ' + _config.PATH_FORTRAN_SRC)
     256            os.chdir(_config.PATH_FORTRAN_SRC)
     257        # installation into a different path
     258        elif os.path.abspath(_config.PATH_FLEXEXTRACT_DIR) != c.installdir :
     259
     260            # creates the target working directory for flex_extract
    240261            mk_tarball(tar_file, c.install_target)
    241262            make_dir(os.path.join(c.installdir,
     
    248269                                  _config.PATH_REL_FORTRAN_SRC))
    249270
    250     # Create Fortran executable
    251     print('Install ' +  _config.FLEXEXTRACT_DIRNAME + ' software at ' +
    252           c.install_target + ' in directory ' +
    253           os.path.abspath(c.installdir) + '\n')
    254 
    255     del_fortran_build('.')
    256     mk_fortran_build('.', c.makefile)
     271        # Create Fortran executable
     272        print('Install ' +  _config.FLEXEXTRACT_DIRNAME + ' software at ' +
     273              c.install_target + ' in directory ' + c.installdir + '\n')
     274
     275        del_fortran_build('.')
     276        mk_fortran_build('.', c.makefile)
     277        os.chdir('../../')
     278        # make sure that the correct calling of submit.py script is in run_local.sh
     279        overwrite_lines_in_file('Run/run_local.sh',
     280                                'pyscript=', 'pyscript=../Source/Python/submit.py\n')
     281
     282    # this is system installation were executables and user files are separated
     283    elif c.install_target == 'syslocal':
     284        if os.path.abspath(_config.PATH_FLEXEXTRACT_DIR) == c.sysinstalldir :
     285            sys.exit('ERROR: System installation path is equal to user '
     286                     'installation path.\n Please change either the system '
     287                     'installation path or use installation target "local".')
     288        if os.path.abspath(_config.PATH_FLEXEXTRACT_DIR) == c.installdir :
     289            print('Flex_extract will be installed in current directory!')
     290        else: # install user part in different dir
     291            print('Flex_extract will be installed in ' + c.installdir )
     292
     293            c.installdir = os.path.join(c.installdir,_config.FLEXEXTRACT_DIRNAME)
     294            if os.path.isdir(c.installdir):
     295                shutil.rmtree(c.installdir)
     296
     297            # copy all files except Python and Fortranfiles to this dir
     298            shutil.copytree(_config.PATH_FLEXEXTRACT_DIR,
     299                            c.installdir, symlinks=True)
     300            shutil.rmtree(os.path.join(c.installdir,'Source'))
     301            shutil.rmtree(os.path.join(c.installdir,'.git'))
     302            for x in UioFiles(c.installdir, '*~').files:
     303                silent_remove(x)
     304
     305            os.remove(os.path.join(c.installdir,'setup.sh'))
     306            os.remove(os.path.join(c.installdir,'setup_local.sh'))
     307
     308        # configure run_local script correctly
     309        # check if source of system config file is already in run_local.sh,
     310        # if not, add it
     311        if not check_for_string_in_file(os.path.join(c.installdir,'Run/run_local.sh'),
     312                                 'source .setup.rc'):
     313            overwrite_lines_in_file(os.path.join(c.installdir,'Run/run_local.sh'),
     314                                    '# PATH TO SUBMISSION SCRIPT',
     315                                    '# PATH TO SUBMISSION SCRIPT\nsource '+_config.FILE_SYS_CONFIG+'\n')
     316        # make sure that the correct calling of submit.py script is in run_local.sh
     317        overwrite_lines_in_file(os.path.join(c.installdir,'Run/run_local.sh'),
     318                                'pyscript=', 'pyscript=submit.py\n')
     319
     320        # change permission for file to executable
     321        execute_subprocess(['chmod', '0775',
     322                            os.path.join(os.path.abspath(c.installdir),'Run/run_local.sh')])
     323
     324
     325        # create systemdir
     326        c.sysinstalldir = os.path.join(c.sysinstalldir,_config.FLEXEXTRACT_DIRNAME)
     327        if os.path.isdir(c.sysinstalldir):
     328            shutil.rmtree(c.sysinstalldir)
     329
     330        # create setup file for running flex_extract with system installation
     331        with open(os.path.join(os.path.abspath(c.installdir),'Run/.setup.rc'),'w') as fio:
     332            fio.write('#!/bin/bash \n')
     333            fio.write('export FLEXEXTRACT_USER_DIR='+os.path.abspath(c.installdir)+'\n')
     334            fio.write('export PATH='+os.path.abspath(c.sysinstalldir)+'/Python:${PATH}\n')
     335            fio.write('export PATH='+os.path.abspath(c.sysinstalldir)+':${PATH}\n')
     336
     337        # copy all Python and Fortranfiles to this dir
     338        shutil.copytree(_config.PATH_SOURCES, c.sysinstalldir, symlinks=True)
     339
     340        os.chdir(os.path.join(c.sysinstalldir,'Fortran'))
     341        # Create Fortran executable
     342        print('Install ' +  _config.FLEXEXTRACT_DIRNAME + ' software as ' +
     343              c.install_target + ' in directory ' +
     344              os.path.abspath(c.sysinstalldir) + '\n')
     345
     346        del_fortran_build('.')
     347        mk_fortran_build('.', c.makefile)
     348
     349        outfile = [x for x in UioFiles('.','*.out').files]
     350        test=os.path.join(c.sysinstalldir,'calc_etadot')
     351        if len(outfile) != 1:
     352            print('WARNING: Multiple executables for Fortran code are available!')
     353        # move executable one dir up and delete Fortran dir
     354        os.chdir('..')
     355        shutil.move(outfile[0], os.path.join(c.sysinstalldir,'calc_etadot'))
     356        shutil.rmtree(os.path.join(os.path.abspath(c.sysinstalldir),'Fortran'))
    257357
    258358    os.chdir(_config.PATH_FLEXEXTRACT_DIR)
     
    289389        sys.exit(1)
    290390
    291     if c.install_target and c.install_target != 'local':
     391    if c.install_target and c.install_target not in ['local', 'syslocal']:
    292392        if not c.ecgid or not c.ecuid:
    293393            print('Please enter your ECMWF user id and group id '
     
    305405        if not c.installdir:
    306406            c.installdir = '${HOME}'
    307     else: # local
     407    elif c.install_target == 'local':
    308408        if not c.installdir:
    309409            c.installdir = _config.PATH_FLEXEXTRACT_DIR
     410    elif c.install_target == 'syslocal':
     411        if not c.installdir:
     412            c.installdir = _config.PATH_FLEXEXTRACT_DIR
     413        if not c.sysinstalldir:
     414            print('ERROR: System installation was selected but '
     415                  'no system installation path was defined.')
     416            sys.exit()
    310417
    311418    if not c.makefile:
     
    323430        else:
    324431            pass
    325        
     432
    326433    return
    327434
     
    715822        print(e)
    716823    else:
    717         execute_subprocess(['ls', '-l', 
     824        execute_subprocess(['ls', '-l',
    718825                            os.path.join(src_path, _config.FORTRAN_EXECUTABLE)],
    719826                           error_msg='FORTRAN EXECUTABLE COULD NOT BE FOUND!')
  • Source/Python/submit.py

    ra916e8f r47be2684  
    114114    else:
    115115        submit(job_template, c, queue)
    116         exit_message = 'FLEX_EXTRACT JOB SCRIPT IS SUBMITED!'
     116        exit_message = 'FLEX_EXTRACT JOB SCRIPT IS SUBMITTED!'
    117117
    118118    normal_exit(exit_message)
  • Source/Python/Classes/MarsRetrieval.py

    r0a75335 r6857073  
    505505            newattrs['year'] = date.year
    506506            newattrs['month'] = date.month
    507             newattrs['day'] =  date.day                 
     507            newattrs['day'] =  date.day         
     508 
     509        # need to correct the time appearance for CDS surface field retrievals
     510        if attrs['type'] == 'FC': # for EA5 only flux fields are retrieved as FC type
     511            # need to convert fc start times 06/18 to usual AN times
     512            # since the surface fields can only be accessed through their validity time
     513            start, end, step = map(int,attrs['step'].split('/')[::2])
     514            newattrs['time'] = [ "{0:0=2d}".format(s) for s in range(0,24,step) ]
     515        elif '/' in attrs['time']: # we expect a list of times separated by /
     516            newattrs['time'] = attrs['time'].split('/')
     517        elif isinstance(attrs['time'], str): # we expect a single time here
     518            newattrs['time'] = [ attrs['time'] ]
    508519       
    509520        newattrs['product_type'] = 'reanalysis'
     
    511522        newattrs['grid'] = list(map(float,attrs['grid'].split('/')))
    512523        newattrs['param'] = attrs['param'].split('/')       
    513         newattrs['time'] = list(map(str,range(0,24,3)))
     524        if '/' in attrs['step']:
     525            sstep = int(attrs['step'].split('/')[4])
     526            newattrs['time'] = list(map(str,range(0,24,sstep)))             
     527        elif '160.128' in attrs['param']:
     528            newattrs['time'] = attrs['time']
    514529        newattrs['format'] = 'grib'
    515530               
Note: See TracChangeset for help on using the changeset viewer.
hosted by ZAMG