Changeset da1b788 in flex_extract.git for Source


Ignore:
Timestamp:
Mar 6, 2020, 1:34:52 PM (4 years ago)
Author:
anphi <anne.philipp@…>
Branches:
master, ctbto, dev
Children:
5868d74
Parents:
f7b9666 (diff), 4d68c4a (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 'feature/makefiles' into dev

Solved merge conflict in makefile_fast and corrected executable name and LIB var name to eccodes

Location:
Source
Files:
1 added
1 deleted
24 edited

Legend:

Unmodified
Added
Removed
  • Source/Fortran/makefile_cray

    rdfa7dbd r4d68c4a  
    11###############################################################################
    22#
    3 # Top level Makefile for ECMWFDATA7.0 software
     3# Makefile for flex_extract, Fortran code to calculate etadot
     4# Makefile created using by mkmf 19.3.0
    45#
    5 # Last modified:  December 1, 2015
     6# Copyright: Leopold Haimberger, Petra Seibert
     7# SPDX-License-Identifier: GPL-2.0
     8#
     9# Version for a machine with eccodes and emoslib installed on standard paths
     10# with optimisation
    611#
    712###############################################################################
    813
    914
    10 .SUFFIXES: .o .c .c~ .f .f~ .F90 .f90 .f90~ .f95 .f95~ .F .F~ .y .y~ .l .l~ \
    11            .s .s~ .sh .sh~ .h .h~ .C .C~ .a
     15EXE      =  calc_etadot
    1216
    13 OPT     =
    14 DEBUG   = -g
    15 LIB     =  $(GRIB_API_LIBS) $(EMOSLIB)
     17LIB     =  $(ECCODES_LIB) $(EMOSLIB)   
     18INC = -I. -I$(ECCODES_INCLUDE_DIR)
    1619
    17 FC=ftn  $(F90FLAGS)
    18 F90C=ftn    $(F90FLAGS)
     20FC = ftn
    1921
    20 FFLAGS =  $(OPT) -I. -r8 -I$(GRIB_API_INCLUDE_DIR)
    21 F90FLAGS =  $(OPT) -I. -r8 -I$(GRIB_API_INCLUDE_DIR)
    22 
    23 LDFLAGS =  $(OPT)
    24 
    25 BINDIR  =      .
    26 
     22OPT = -O3
     23FFLAGS =  -s real64  $(OPT) $(LIB) $(INC)
     24LDFLAGS =  $(OPT) -fopenmp
    2725EXE     =      calc_etadot
    2826
    29 
    3027.f.o:
    31         $(F90C) -c $(F90FLAGS) $(DEBUG) $*.f
    32 .f90.o:
    33         $(F90C) -c $(F90FLAGS) $(DEBUG) $*.f90
     28SRC = ./rwgrib2.f90 ./calc_etadot.f90 ./ftrafo.f90 ./grphreal.f90 ./posnam.f90 ./phgrreal.f90
     29OBJ = rwgrib2.o calc_etadot.o ftrafo.o grphreal.o posnam.o phgrreal.o
     30MOD = ftrafo.mod  grtoph.mod    phtogr.mod  rwgrib2.mod
    3431
    3532all:    ${EXE}
    3633
    37 clean:
    38         rm *.o *.mod ${EXE}
     34ftrafo.o: ./ftrafo.f90 phgrreal.o
     35        $(FC)  $(FFLAGS)  -c    ./ftrafo.f90
     36grphreal.o: ./grphreal.f90 phgrreal.o
     37        $(FC)  $(FFLAGS)  -c    ./grphreal.f90
     38phgrreal.o: ./phgrreal.f90
     39        $(FC)  $(FFLAGS)  -c    ./phgrreal.f90
     40posnam.o: ./posnam.f90
     41        $(FC)  $(FFLAGS)  -c    ./posnam.f90
     42calc_etadot.o: ./calc_etadot.f90 phgrreal.o grphreal.o ftrafo.o rwgrib2.o
     43        $(FC)  $(FFLAGS)  -c    ./calc_etadot.f90
     44rwgrib2.o: ./rwgrib2.f90
     45        $(FC)  $(FFLAGS)  -c    ./rwgrib2.f90
    3946
    40 phgrreal.o: phgrreal.f
    41         $(F90C) -c -g -O3 phgrreal.f
     47clean:
     48        -rm -f $(OBJ) ${EXE} $(MOD) calc_etadot
    4249
    43 grphreal.o: grphreal.f
    44         $(F90C) -c -g -O3 grphreal.f
    45 
    46 ftrafo.o: ftrafo.f
    47         $(F90C) -c -g -O3 ftrafo.f
    48 
    49 $(BINDIR)/${EXE}:       phgrreal.o grphreal.o ftrafo.o rwgrib2.o  posnam.o calc_etadot.o
    50         $(F90C) $(DEBUG) $(OPT) -o $(BINDIR)/${EXE} ftrafo.o phgrreal.o grphreal.o rwgrib2.o posnam.o calc_etadot.o ${LIB}
    51 
    52 
    53 ###############################################################################
    54 #
    55 # End of the Makefile
    56 #
    57 ###############################################################################
     50${EXE}: $(OBJ)
     51        $(FC) $(OBJ) -o ${EXE}  $(LDFLAGS)
  • Source/Fortran/makefile_debug

    rdfa7dbd r7cd1586  
    77# SPDX-License-Identifier: GPL-2.0
    88#
    9 # Version for a machine with grib_api and emoslib installed on standard paths
     9# Version for a machine with eccodes and emoslib installed on standard paths
    1010# full debugging
    1111#
     
    1515EXE      =  calc_etadot_debug.out
    1616
    17 GRIB_API_LIB=  -Bstatic -lgrib_api_f90 -lgrib_api -Bdynamic -lm -ljasper
     17GRIB_API_LIB=  -Bstatic -leccodes_f90 -leccodes -Bdynamic -lm -ljasper
    1818EMOSLIB=-lemosR64
    1919LIB =  $(GRIB_API_LIB) $(EMOSLIB)
    2020
    21 GRIB_API_INCLUDE_DIR=/usr/include
    22 INC = -I. -I$(GRIB_API_INCLUDE_DIR)
     21ECCODES_INCLUDE_DIR=/usr/lib/x86_64-linux-gnu/fortran/gfortran-mod-15
     22INC = -I. -I$(ECCODES_INCLUDE_DIR)
    2323
    2424FC = gfortran
     
    4747        $(FC)  $(FFLAGS)  -c    ./rwgrib2.f90
    4848
    49 clean: -rm -f $(OBJ) ${EXE} $(MOD)
     49clean:
     50        -rm -f $(OBJ) ${EXE} $(MOD) calc_etadot
    5051
    5152${EXE}: $(OBJ)
    5253        $(FC) $(OBJ) -o ${EXE}  $(LDFLAGS)
     54        ln -sf ${EXE} calc_etadot
  • Source/Fortran/makefile_ecgate

    rdfa7dbd r1610f73  
    11###############################################################################
    22#
    3 # Top level Makefile for ECMWFDATA7.0 software
     3# Makefile for flex_extract, Fortran code to calculate etadot
     4# Makefile created using by mkmf 19.3.0
    45#
    5 # Last modified:  December 1, 2015
     6# Copyright: Leopold Haimberger, Petra Seibert
     7# SPDX-License-Identifier: GPL-2.0
     8#
     9# Version for a machine with eccodes and emoslib installed on standard paths
     10# with optimisation
    611#
    712###############################################################################
    813
    914
    10 .SUFFIXES: .o .c .c~ .f .f~ .F90 .f90 .f90~ .f95 .f95~ .F .F~ .y .y~ .l .l~ \
    11            .s .s~ .sh .sh~ .h .h~ .C .C~ .a
     15EXE      =  calc_etadot_fast.out
    1216
    13 OPT     = -O3
    14 DEBUG   = -g
    1517LIB     =  $(ECCODES_LIB) $(EMOSLIB)   
     18INC = -I. -I$(ECCODES_INCLUDE_DIR)
    1619
    17 FC=gfortran   -m64 -fdefault-real-8 -fcray-pointer -fno-second-underscore  -ffixed-line-length-132 -fopenmp  -fconvert=big-endian 
    18 F90C=gfortran   -m64 -fdefault-real-8 -fcray-pointer -fno-second-underscore  -ffixed-line-length-132 -fopenmp  -fconvert=big-endian
     20FC=gfortran 
    1921
    20 FFLAGS =  $(OPT) -I. -I$(ECCODES_INCLUDE_DIR)
     22OPT = -O3 -march=native
     23FFLAGS =   $(OPT) $(LIB) $(INC) -fdefault-real-8 -fopenmp -fconvert=big-endian
     24LDFLAGS =  $(OPT) $(LIB) -fopenmp
     25SRC = ./rwgrib2.f90 ./calc_etadot.f90 ./ftrafo.f90 ./grphreal.f90 ./posnam.f90 ./phgrreal.f90
     26OBJ = rwgrib2.o calc_etadot.o ftrafo.o grphreal.o posnam.o phgrreal.o
     27MOD = ftrafo.mod  grtoph.mod    phtogr.mod  rwgrib2.mod
    2128
    22 F90FLAGS =  $(OPT) -I. -I$(ECCODES_INCLUDE_DIR)
     29all: ${EXE}
     30ftrafo.o: ./ftrafo.f90 phgrreal.o
     31        $(FC)  $(FFLAGS)  -c    ./ftrafo.f90
     32grphreal.o: ./grphreal.f90 phgrreal.o
     33        $(FC)  $(FFLAGS)  -c    ./grphreal.f90
     34phgrreal.o: ./phgrreal.f90
     35        $(FC)  $(FFLAGS)  -c    ./phgrreal.f90
     36posnam.o: ./posnam.f90
     37        $(FC)  $(FFLAGS)  -c    ./posnam.f90
     38calc_etadot.o: ./calc_etadot.f90 phgrreal.o grphreal.o ftrafo.o rwgrib2.o
     39        $(FC)  $(FFLAGS)  -c    ./calc_etadot.f90
     40rwgrib2.o: ./rwgrib2.f90
     41        $(FC)  $(FFLAGS)  -c    ./rwgrib2.f90
    2342
    24 LDFLAGS =  $(OPT)
     43clean:
     44        -rm -f $(OBJ) ${EXE} $(MOD) calc_etadot
    2545
    26 BINDIR  =      .
    27 
    28 EXE     =      calc_etadot
    29 
    30 
    31 .f.o:
    32         $(F90C) -c $(F90FLAGS) $(DEBUG) $*.f
    33 .f90.o:
    34         $(F90C) -c $(F90FLAGS) $(DEBUG) $*.f90
    35 
    36 all:    ${EXE}
    37 
    38 clean:
    39         rm *.o *.mod ${EXE}
    40 
    41 phgrreal.o: phgrreal.f
    42         $(F90C) -c -g -O3 -fopenmp phgrreal.f
    43 
    44 grphreal.o: grphreal.f
    45         $(F90C) -c -g -O3 -fopenmp grphreal.f
    46 
    47 ftrafo.o: ftrafo.f
    48         $(F90C) -c -g -O3 -fopenmp ftrafo.f
    49 
    50 $(BINDIR)/${EXE}:       phgrreal.o grphreal.o ftrafo.o rwgrib2.o  posnam.o calc_etadot.o
    51         $(F90C) $(DEBUG) $(OPT) -o $(BINDIR)/${EXE} ftrafo.o phgrreal.o grphreal.o rwgrib2.o posnam.o calc_etadot.o ${LIB}
    52 
    53 
    54 ###############################################################################
    55 #
    56 # End of the Makefile
    57 #
    58 ###############################################################################
     46${EXE}: $(OBJ)
     47        $(FC) $(OBJ) -o ${EXE}  $(LDFLAGS)
     48        ln -sf ${EXE} calc_etadot
  • Source/Fortran/makefile_fast

    rdeb7d17 rda1b788  
    77# SPDX-License-Identifier: GPL-2.0
    88#
    9 # Version for a machine with grib_api and emoslib installed on standard paths
    10 # full debugging
     9# Version for a machine with eccodes and emoslib installed on standard paths
     10# with optimisation
    1111#
    1212###############################################################################
    1313
    1414
    15 EXE      =  calc_etadot
     15EXE      =  calc_etadot_fast.out
    1616
    17 #GRIB_API_LIB=  -Bstatic -lgrib_api_f90 -lgrib_api -Bdynamic -lm -ljasper
    18 ECCODES_LIB= -L/usr/local/lib -leccodes_f90 -leccodes -lm
     17ECCODES_LIB =  -Bstatic -leccodes_f90 -leccodes -Bdynamic -lm -ljasper
    1918EMOSLIB=-lemosR64
    2019LIB =  $(ECCODES_LIB) $(EMOSLIB)
    2120
    22 ECCODES_INCLUDE_DIR=/usr/local/include
     21ECCODES_INCLUDE_DIR=/usr/lib/x86_64-linux-gnu/fortran/gfortran-mod-15
    2322INC = -I. -I$(ECCODES_INCLUDE_DIR)
    2423
     
    4948
    5049clean:
    51         -rm -f $(OBJ) ${EXE} $(MOD)
     50        -rm -f $(OBJ) ${EXE} $(MOD) calc_etadot
    5251
    5352${EXE}: $(OBJ)
    5453        $(FC) $(OBJ) -o ${EXE}  $(LDFLAGS)
     54        ln -sf ${EXE} calc_etadot
  • Source/Python/Classes/ControlFile.py

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

    rc77630a r53d3b2a  
    5353#pylint: disable=consider-using-enumerate
    5454# this is not useful in this case
     55#pylint: disable=unsubscriptable-object
     56# this error is a bug
     57#pylint: disable=ungrouped-imports
     58# not necessary that we group the imports
    5559# ------------------------------------------------------------------------------
    5660# MODULES
     
    6266import glob
    6367import shutil
    64 import subprocess
    6568from datetime import datetime, timedelta
    6669
    6770# software specific classes and modules from flex_extract
     71#pylint: disable=wrong-import-position
    6872sys.path.append('../')
    6973import _config
    7074from Classes.GribUtil import GribUtil
    7175from Mods.tools import (init128, to_param_id, silent_remove, product,
    72                         my_error, make_dir, get_informations, get_dimensions,
     76                        my_error, get_informations, get_dimensions,
    7377                        execute_subprocess, to_param_id_with_tablenumber,
    7478                        generate_retrieval_period_boundary)
     
    7680from Classes.UioFiles import UioFiles
    7781import Mods.disaggregation as disaggregation
    78 
     82#pylint: enable=wrong-import-position
    7983# ------------------------------------------------------------------------------
    8084# CLASS
     
    317321
    318322        '''
     323        if self.purefc:
     324            # need to retrieve forecasts for step 000 in case of pure forecast
     325            steps = '{}/to/{}/by/{}'.format(0, self.accmaxstep, self.dtime)
     326        else:
     327            steps = '{}/to/{}/by/{}'.format(self.dtime,
     328                                            self.accmaxstep,
     329                                            self.dtime)
     330
    319331        self.types[str(self.acctype)] = {'times': str(self.acctime),
    320                                          'steps': '{}/to/{}/by/{}'.format(
    321                                              self.dtime,
    322                                              self.accmaxstep,
    323                                              self.dtime)}
     332                                         'steps': steps}
    324333        return
    325334
     
    401410        else:  # GAUSS and ETA
    402411            print('Warning: Collecting etadot and parameters for gaussian grid '
    403                            'is a very costly parameter combination, '
    404                            'use this combination only for debugging!')
     412                  'is a very costly parameter combination, '
     413                  'use this combination only for debugging!')
    405414            self.params['GG__SL'] = ['Q', 'ML', '1',
    406415                                     '{}'.format((int(self.resol) + 1) // 2)]
     
    415424
    416425        # ADDITIONAL FIELDS FOR FLEXPART-WRF MODEL (IF QUESTIONED)
    417         # -----------------------------------------------------------------------
     426        # ----------------------------------------------------------------------
    418427        if wrf:
    419428            # @WRF
     
    710719                    retr_param_dict['date'] = self.dates.split('/')[0]
    711720                    retr_param_dict['target'] = self._mk_targetname('',
    712                                             pk, retr_param_dict['date'])
     721                                                                    pk,
     722                                                                    retr_param_dict['date'])
    713723                elif pk == 'OG_OROLSM__SL' and oro:
    714724                    continue
     
    752762                        if 'acc' in pk:
    753763                            startdate = retr_param_dict['date'].split('/')[0]
    754                             enddate = datetime.strftime(elimit - t24h,'%Y%m%d')
     764                            enddate = datetime.strftime(elimit - t24h, '%Y%m%d')
    755765                            retr_param_dict['date'] = '/'.join([startdate,
    756766                                                                'to',
     
    776786
    777787                    elif self.basetime == 0:
    778                         retr_param_dict['date'] = \
    779                             datetime.strftime(elimit - t24h, '%Y%m%d')
     788#                        retr_param_dict['date'] = \
     789#                            datetime.strftime(elimit - t24h, '%Y%m%d')
    780790
    781791                        timesave = ''.join(retr_param_dict['time'])
    782792
    783                         if ('/' in retr_param_dict['time'] and
    784                             pk != 'OG_OROLSM__SL' and
    785                             'acc' not in pk ) :
     793                        if all(['/' in retr_param_dict['time'],
     794                                pk != 'OG_OROLSM__SL',
     795                                'acc' not in pk]):
    786796                            times = retr_param_dict['time'].split('/')
    787797                            steps = retr_param_dict['step'].split('/')
     
    794804                                    retr_param_dict['time'] = times[0]
    795805
    796                         if (pk != 'OG_OROLSM__SL' and
    797                             int(retr_param_dict['step'].split('/')[0]) == 0 and
    798                             int(timesave.split('/')[0]) == 0):
     806                        if all([pk != 'OG_OROLSM__SL',
     807                                int(retr_param_dict['step'].split('/')[0]) == 0,
     808                                int(timesave.split('/')[0]) == 0]):
    799809
    800810                            retr_param_dict['date'] = \
     
    810820                    else:
    811821                        raise ValueError('ERROR: Basetime has an invalid value '
    812                                                  '-> {}'.format(str(basetime)))
     822                                         '-> {}'.format(str(self.basetime)))
    813823
    814824        if request == 0 or request == 2:
     
    860870
    861871            stream = namelist_template.generate(
    862                 maxl = str(maxl),
    863                 maxb = str(maxb),
    864                 mlevel = str(self.level),
    865                 mlevelist = str(self.levelist),
    866                 mnauf = str(self.resol),
    867                 metapar = '77',
    868                 rlo0 = str(area[1]),
    869                 rlo1 = str(area[3]),
    870                 rla0 = str(area[2]),
    871                 rla1 = str(area[0]),
    872                 momega = str(c.omega),
    873                 momegadiff = str(c.omegadiff),
    874                 mgauss = str(c.gauss),
    875                 msmooth = str(c.smooth),
    876                 meta = str(c.eta),
    877                 metadiff = str(c.etadiff),
    878                 mdpdeta = str(c.dpdeta)
     872                maxl=str(maxl),
     873                maxb=str(maxb),
     874                mlevel=str(self.level),
     875                mlevelist=str(self.levelist),
     876                mnauf=str(self.resol),
     877                metapar='77',
     878                rlo0=str(area[1]),
     879                rlo1=str(area[3]),
     880                rla0=str(area[2]),
     881                rla1=str(area[0]),
     882                momega=str(c.omega),
     883                momegadiff=str(c.omegadiff),
     884                mgauss=str(c.gauss),
     885                msmooth=str(c.smooth),
     886                meta=str(c.eta),
     887                metadiff=str(c.etadiff),
     888                mdpdeta=str(c.dpdeta)
    879889            )
    880890        except UndefinedError as e:
     
    928938        '''
    929939        import numpy as np
    930         from eccodes import (codes_index_select, codes_new_from_index, codes_get,
     940        from eccodes import (codes_index_select, codes_get,
    931941                             codes_get_values, codes_set_values, codes_set,
    932942                             codes_write, codes_release, codes_new_from_index,
     
    10531063            step = codes_get(gid, 'step') # integer
    10541064            ctime = '{:0>2}'.format(time)
    1055             cstep = '{:0>3}'.format(step)
    10561065
    10571066            t_date = datetime.strptime(cdate + ctime, '%Y%m%d%H')
     
    11321141                    deac_vals[parId].append(
    11331142                        (orig_vals[parId][-1] - orig_vals[parId][-2]) /
    1134                          int(c.dtime))
     1143                        int(c.dtime))
    11351144
    11361145                # store precipitation if new disaggregation method is selected
     
    13321341            for inum in range(maxnum):
    13331342                for ix in range(ni*nj):
    1334                     lsp_new_np[inum,ix,:] = disaggregation.IA3(lsp_np[inum,ix,:])[:-1]
    1335                     cp_new_np[inum,ix,:] = disaggregation.IA3(cp_np[inum,ix,:])[:-1]
     1343                    lsp_new_np[inum, ix, :] = disaggregation.IA3(lsp_np[inum, ix, :])[:-1]
     1344                    cp_new_np[inum, ix, :] = disaggregation.IA3(cp_np[inum, ix, :])[:-1]
    13361345        else:
    13371346            for ix in range(ni*nj):
    1338                 lsp_new_np[0,ix,:] = disaggregation.IA3(lsp_np[ix,:])[:-1]
    1339                 cp_new_np[0,ix,:] = disaggregation.IA3(cp_np[ix,:])[:-1]
     1347                lsp_new_np[0, ix, :] = disaggregation.IA3(lsp_np[ix, :])[:-1]
     1348                cp_new_np[0, ix, :] = disaggregation.IA3(cp_np[ix, :])[:-1]
    13401349
    13411350        # write to grib files (full/orig times to flux file and inbetween
     
    14021411            # write original time step to flux file as usual
    14031412            fluxfile = GribUtil(os.path.join(c.inputdir, fluxfilename))
    1404             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1413            fluxfile.set_keys(tmpfile, filemode='ab',
    14051414                              wherekeynames=['paramId'], wherekeyvalues=[142],
    1406                               keynames=['perturbationNumber','date','time','stepRange','values'],
     1415                              keynames=['perturbationNumber', 'date', 'time',
     1416                                        'stepRange', 'values'],
    14071417                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
    1408                                          date.hour*100, 0, lsp_new_np[inumb,:,it]],
     1418                                         date.hour*100, 0, lsp_new_np[inumb, :, it]],
    14091419                             )
    1410             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1420            fluxfile.set_keys(tmpfile, filemode='ab',
    14111421                              wherekeynames=['paramId'], wherekeyvalues=[143],
    1412                               keynames=['perturbationNumber','date','time','stepRange','values'],
    1413                               keyvalues=[inumb,int(date.strftime('%Y%m%d')),
    1414                                          date.hour*100, 0, cp_new_np[inumb,:,it]]
     1422                              keynames=['perturbationNumber', 'date', 'time',
     1423                                        'stepRange', 'values'],
     1424                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1425                                         date.hour*100, 0, cp_new_np[inumb, :, it]]
    14151426                             )
    14161427
    14171428            # rr for first subgrid point is identified by step = 1
    1418             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1429            fluxfile.set_keys(tmpfile, filemode='ab',
    14191430                              wherekeynames=['paramId'], wherekeyvalues=[142],
    1420                               keynames=['perturbationNumber','date','time','stepRange','values'],
    1421                               keyvalues=[inumb,int(date.strftime('%Y%m%d')),
    1422                                          date.hour*100, '1', lsp_new_np[inumb,:,it+1]]
    1423                               )
    1424             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1431                              keynames=['perturbationNumber', 'date', 'time',
     1432                                        'stepRange', 'values'],
     1433                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1434                                         date.hour*100, '1', lsp_new_np[inumb, :, it+1]]
     1435                             )
     1436            fluxfile.set_keys(tmpfile, filemode='ab',
    14251437                              wherekeynames=['paramId'], wherekeyvalues=[143],
    1426                               keynames=['perturbationNumber','date','time','stepRange','values'],
    1427                               keyvalues=[inumb,int(date.strftime('%Y%m%d')),
    1428                                          date.hour*100, '1', cp_new_np[inumb,:,it+1]]
    1429                               )
     1438                              keynames=['perturbationNumber', 'date', 'time',
     1439                                        'stepRange', 'values'],
     1440                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1441                                         date.hour*100, '1', cp_new_np[inumb, :, it+1]]
     1442                             )
    14301443
    14311444            # rr for second subgrid point is identified by step = 2
    1432             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1445            fluxfile.set_keys(tmpfile, filemode='ab',
    14331446                              wherekeynames=['paramId'], wherekeyvalues=[142],
    1434                               keynames=['perturbationNumber','date','time','stepRange','values'],
    1435                               keyvalues=[inumb,int(date.strftime('%Y%m%d')),
    1436                                          date.hour*100, '2', lsp_new_np[inumb,:,it+2]]
    1437                               )
    1438             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1447                              keynames=['perturbationNumber', 'date', 'time',
     1448                                        'stepRange', 'values'],
     1449                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1450                                         date.hour*100, '2', lsp_new_np[inumb, :, it+2]]
     1451                             )
     1452            fluxfile.set_keys(tmpfile, filemode='ab',
    14391453                              wherekeynames=['paramId'], wherekeyvalues=[143],
    1440                               keynames=['perturbationNumber','date','time','stepRange','values'],
    1441                               keyvalues=[inumb,int(date.strftime('%Y%m%d')),
    1442                                          date.hour*100, '2', cp_new_np[inumb,:,it+2]]
    1443                               )
     1454                              keynames=['perturbationNumber', 'date', 'time',
     1455                                        'stepRange', 'values'],
     1456                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1457                                         date.hour*100, '2', cp_new_np[inumb, :, it+2]]
     1458                             )
    14441459
    14451460            it = it + 3 # jump to next original time step in rr fields
     
    14631478        '''
    14641479
    1465         gribfile = GribUtil(os.path.join(inputdir,'rr_grib_dummy.grb'))
     1480        gribfile = GribUtil(os.path.join(inputdir, 'rr_grib_dummy.grb'))
    14661481
    14671482        gribfile.copy_dummy_msg(ifile, keynames=['paramId'],
    1468                       keyvalues=[142], filemode='wb')
     1483                                keyvalues=[142], filemode='wb')
    14691484
    14701485        gribfile.copy_dummy_msg(ifile, keynames=['paramId'],
    1471                       keyvalues=[143], filemode='ab')
     1486                                keyvalues=[143], filemode='ab')
    14721487
    14731488        return
     
    15011516
    15021517        '''
    1503         from eccodes import (codes_index_select, codes_new_from_index, codes_get,
     1518        from eccodes import (codes_index_select, codes_get,
    15041519                             codes_get_values, codes_set_values, codes_set,
    15051520                             codes_write, codes_release, codes_new_from_index,
     
    15831598            cdate_hour = datetime.strftime(timestamp, '%Y%m%d%H')
    15841599
     1600            # if basetime is used, adapt start/end date period
     1601            if c.basetime is not None:
     1602                time_delta = timedelta(hours=12-int(c.dtime))
     1603                start_period = datetime.strptime(c.end_date + str(c.basetime),
     1604                                               '%Y%m%d%H') - time_delta
     1605                end_period = datetime.strptime(c.end_date + str(c.basetime),
     1606                                             '%Y%m%d%H')
     1607
    15851608            # skip all temporary times
    15861609            # which are outside the retrieval period
     
    15891612                continue
    15901613
    1591             # if the timestamp is out of basetime start/end date period,
    1592             # skip this specific product
    1593             if c.basetime is not None:
    1594                 time_delta = timedelta(hours=12-int(c.dtime))
    1595                 start_time = datetime.strptime(c.end_date + str(c.basetime),
    1596                                                 '%Y%m%d%H') - time_delta
    1597                 end_time = datetime.strptime(c.end_date + str(c.basetime),
    1598                                              '%Y%m%d%H')
    1599                 if timestamp < start_time or timestamp > end_time:
    1600                     continue
    16011614
    16021615            # @WRF
     
    16201633                paramId = codes_get(gid, 'paramId')
    16211634                gridtype = codes_get(gid, 'gridType')
    1622                 levtype = codes_get(gid, 'typeOfLevel')
    16231635                if paramId == 77: # ETADOT
    16241636                    codes_write(gid, fdict['21'])
     
    17041716            # Fortran program creates file fort.15 (with u,v,etadot,t,sp,q)
    17051717            execute_subprocess([os.path.join(c.exedir,
    1706                                 _config.FORTRAN_EXECUTABLE)],
     1718                                             _config.FORTRAN_EXECUTABLE)],
    17071719                               error_msg='FORTRAN PROGRAM FAILED!')#shell=True)
    17081720
     
    17331745            # to the outputfile (final GRIB input files for FLEXPART)
    17341746            orolsm = os.path.basename(glob.glob(c.inputdir +
    1735                                         '/OG_OROLSM__SL.*.' + c.ppid + '*')[0])
     1747                                                '/OG_OROLSM__SL.*.' +
     1748                                                c.ppid +
     1749                                                '*')[0])
    17361750            fluxfile = 'flux' + cdate[0:2] + suffix
    17371751            if not c.cwc:
     
    17831797        '''
    17841798        from eccodes import (codes_grib_new_from_file, codes_get_array,
    1785                              codes_set_array, codes_release, codes_set_values,
    1786                              codes_set, codes_write, codes_release)
     1799                             codes_set_array, codes_release,
     1800                             codes_set, codes_write)
    17871801
    17881802        # max number
     
    17901804
    17911805        # get a list of all prepared output files with control forecast (CF)
    1792         CF_filelist = UioFiles(path, prefix + '*.N000')
    1793         CF_filelist.files = sorted(CF_filelist.files)
    1794 
    1795         for cffile in CF_filelist.files:
     1806        cf_filelist = UioFiles(path, prefix + '*.N000')
     1807        cf_filelist.files = sorted(cf_filelist.files)
     1808
     1809        for cffile in cf_filelist.files:
    17961810            with open(cffile, 'rb') as f:
    1797                 cfvalues=[]
     1811                cfvalues = []
    17981812                while True:
    17991813                    fid = codes_grib_new_from_file(f)
     
    19001914
    19011915        return
    1902 
  • Source/Python/Classes/GribUtil.py

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

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

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

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

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

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

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

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

    rc77630a rd1bfa24  
    6969import subprocess
    7070import traceback
     71# pylint: disable=unused-import
    7172try:
    7273    import exceptions
    7374except ImportError:
    7475    import builtins as exceptions
     76# pylint: enable=unused-import
    7577from datetime import datetime, timedelta
    7678from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
     
    268270        and destination for ECMWF server environments.
    269271    '''
    270     envs= {}
     272    envs = {}
    271273    try:
    272274        with open(filepath, 'r') as f:
     
    279281
    280282        sys.exit('\n... Error occured while trying to read ECMWF_ENV '
    281                      'file: ' + str(filepath))
     283                 'file: ' + str(filepath))
    282284
    283285    return envs
     
    302304    print("... clean inputdir!")
    303305
    304     cleanlist = [file for file in glob.glob(os.path.join(c.inputdir, "*"))
    305                  if not os.path.basename(file).startswith(c.prefix)]
     306    cleanlist = [filename for filename in
     307                 glob.glob(os.path.join(c.inputdir, "*"))
     308                 if not os.path.basename(filename).startswith(c.prefix)]
    306309
    307310    if cleanlist:
     
    371374                                 stderr=subprocess.PIPE,
    372375                                 bufsize=1)
    373             pout = p.communicate(input=message.encode() + '\n\n')[0]
     376            pout = p.communicate(input=message + '\n\n')[0]
    374377        except ValueError as e:
    375378            print('... ERROR: ' + str(e))
     
    415418    https://software.ecmwf.int/wiki/display/GRIB/index.py; 2018-03-16
    416419
     420    It was released under the following license:
     421    https://confluence.ecmwf.int/display/ECC/License
     422
    417423    Example
    418424    -------
     
    531537        return []
    532538    if not isinstance(pars, str):
    533         pars=str(pars)
     539        pars = str(pars)
    534540
    535541    cpar = pars.upper().split('/')
     
    575581        return []
    576582    if not isinstance(pars, str):
    577         pars=str(pars)
     583        pars = str(pars)
    578584
    579585    cpar = pars.upper().split('/')
     
    768774
    769775        # information needed from grib message
    770         keys = [
    771                 'Ni',
     776        keys = ['Ni',
    772777                'Nj',
    773778                'latitudeOfFirstGridPointInDegrees',
     
    783788        for key in keys:
    784789            # Get the value of the key in a grib message.
    785             data[key] = codes_get(gid,key)
    786             print("%s = %s" % (key,data[key]))
     790            data[key] = codes_get(gid, key)
     791            print("%s = %s" % (key, data[key]))
    787792
    788793        # Free the memory for the message referred as gribid.
  • Source/Python/_config.py

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

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

    r44174de r0f89116  
    6464import os
    6565import sys
    66 import subprocess
    67 import inspect
    68 import collections
    6966from datetime import datetime, timedelta
    7067
    7168# software specific classes and modules from flex_extract
    7269import _config
    73 from Mods.tools import (setup_controldata, normal_exit, get_cmdline_args,
    74                          submit_job_to_ecserver, read_ecenv)
     70from Mods.tools import (setup_controldata, normal_exit,
     71                        submit_job_to_ecserver)
    7572from Mods.get_mars_data import get_mars_data
    7673from Mods.prepare_flexpart import prepare_flexpart
    77 from Classes.ControlFile import ControlFile
     74#from Classes.ControlFile import ControlFile
    7875
    7976
  • Source/Pythontest/TestInput.py

    rba99230 r76c37a9  
    1 #!/usr/bin/env python
     1#!/usr/bin/env python3
    22# -*- coding: utf-8 -*-
    33
     
    66import pytest
    77
    8 sys.path.append('../python')
    9 from classes.ControlFile import ControlFile
    10 from mods.tools import get_cmdline_arguments
     8sys.path.append('../Python')
     9from Classes.ControlFile import ControlFile
     10from Mods.tools import get_cmdline_args
    1111
    1212
     
    2121    # 2. check of parameter
    2222
    23     def __init__(self):
     23    @classmethod
     24    def setup_class(self):
    2425        # Default values for ArgumentParser
    2526        self.args = {'start_date':None,
     
    3637                     'job_template':'job.temp',
    3738                     'queue':None,
    38                      'controlfile':'CONTROL.temp',
     39                     'controlfile':'CONTROL.test',
    3940                     'debug':0,
    4041                     }
     
    4344        sys.argv = ['dummy.py', '--start_date=20180101']
    4445
    45         self.args = tools.get_commandline_arguments()
     46        self.args = get_cmdline_args()
    4647
    47         self.c = ControlFile('TestData/CONTROL.temp')
     48        self.c = ControlFile('../../Testing/Regression/Unit/Testfiles/CONTROL.test')
    4849
    4950        self.c.assign_args_to_control(self.args)
     
    5758                    '--step=0/to/11/BY/3', '--area=20./20./0./90.']
    5859
    59         arguments = tools.get_cmdline_arguments()
     60        arguments = get_cmdline_args()
    6061
    6162        args_exp = {'start_date':'20180101',
     
    7273                    'job_template':'job.temp',
    7374                    'queue':None,
    74                     'controlfile':'CONTROL.temp',
     75                    'controlfile':'CONTROL.test',
    7576                    'debug':1,
    7677                    }
     
    8990                    'area': None,
    9091                    'basetime': None,
    91                     'controlfile': 'CONTROL.temp',
     92                    'controlfile': 'CONTROL.test',
    9293                    'cwc': 0,
    9394                    'date_chunk': 3,
     
    158159
    159160        return
     161
     162    @classmethod
     163    def teardown_class(self):
     164 
     165        return
  • Source/Pythontest/TestInstall.py

    rba99230 r76c37a9  
    1 #!/usr/bin/env python
     1#!/usr/bin/env python3
    22# -*- coding: utf-8 -*-
    33
     
    1111import shutil
    1212from genshi.template import TemplateLoader
    13 from genshi.template.eval import  UndefinedError
    14 from exceptions import OSError
     13from genshi.template.eval import UndefinedError
     14
     15try:
     16    import exceptions
     17except ImportError:
     18    import builtins
    1519import pytest
    1620from mock import patch
    1721
    18 sys.path.append('../python')
     22sys.path.append('../Python')
    1923import _config
    20 import _config_test
     24from . import _config_test
    2125from install import (mk_tarball, un_tarball, mk_env_vars, mk_compilejob,
    2226                     mk_job_template)
    2327
    24 from mods.tools import make_dir, silent_remove
     28from Mods.tools import make_dir, silent_remove
    2529
    2630#    - main
     
    4448
    4549        # un tar the test tarballs from shell script
    46         subprocess.check_output([os.path.join(self.testinstalldir,
    47                                               'un_install_tar.sh')])
     50#        subprocess.check_output([os.path.join(self.testinstalldir,
     51#                                            'un_install_tar.sh')])
    4852
    4953
     
    5660        tarballname = _config.FLEXEXTRACT_DIRNAME + '_localtest.tar'
    5761
    58         with pytest.raises(SystemExit):
    59             mk_tarball(ecd + tarballname, 'local')
    6062        with pytest.raises(SystemExit):
    6163            mk_tarball(ecd + tarballname, 'local')
     
    7880
    7981        # remove test tar file from flex_extract directory
    80         os.remove(ecd + tarballname)
     82        #os.remove(ecd + tarballname)
    8183
    8284        # test if comparison filelist is equal to the
     
    310312        test_dir = os.path.join(self.testinstalldir,
    311313                                _config.FLEXEXTRACT_DIRNAME + '_local')
    312         shutil.rmtree(test_dir)
     314#        shutil.rmtree(test_dir)
    313315        test_dir = os.path.join(self.testinstalldir,
    314316                                _config.FLEXEXTRACT_DIRNAME + '_ecgate')
    315         shutil.rmtree(test_dir)
     317#        shutil.rmtree(test_dir)
    316318
    317319        test_dir = os.path.join(self.testinstalldir,
    318320                                'test_local')
    319         shutil.rmtree(test_dir)
     321#        shutil.rmtree(test_dir)
    320322        test_dir = os.path.join(self.testinstalldir,
    321323                                'test_ecgate')
    322         shutil.rmtree(test_dir)
     324#        shutil.rmtree(test_dir)
    323325
    324326        tar_file = os.path.join(self.testinstalldir,
    325327                     _config.FLEXEXTRACT_DIRNAME + '_local.tar')
    326         os.remove(tar_file)
     328#        os.remove(tar_file)
    327329        tar_file = os.path.join(self.testinstalldir,
    328330                                _config.FLEXEXTRACT_DIRNAME + '_ecgate.tar')
    329         os.remove(tar_file)
     331#        os.remove(tar_file)
    330332        pass
  • Source/Pythontest/TestTools.py

    rba99230 r76c37a9  
    77import sys
    88import errno
    9 from exceptions import OSError
     9#from exceptions import OSError
    1010import subprocess
    1111import pipes
     12
     13try:
     14    import exceptions
     15except ImportError:
     16    import builtins
     17
    1218import pytest
    1319from mock import patch, call
     
    1622
    1723import _config
    18 import _config_test
    19 from classes.ControlFile import ControlFile
    20 from mods.tools import (none_or_str, none_or_int, get_cmdline_arguments,
     24from . import _config_test
     25from Classes.ControlFile import ControlFile
     26from Mods.tools import (none_or_str, none_or_int, get_cmdline_args,
    2127                        read_ecenv, clean_up, my_error, send_mail,
    2228                        normal_exit, product, silent_remove,
     
    2531
    2632class TestTools(object):
    27     '''
    28     '''
     33    """Test the tools module."""
    2934
    3035    def setup_method(self):
     
    4853        sys.argv = ['dummy.py', '--wrong=1']
    4954        with pytest.raises(SystemExit):
    50             results = get_cmdline_arguments()
     55            results = get_cmdline_args()
    5156
    5257    def test_default_get_cmdline_arguments(self):
    53         cmd_dict_control = {'start_date':None,
    54                             'end_date':None,
    55                             'date_chunk':None,
    56                             'basetime':None,
    57                             'step':None,
    58                             'levelist':None,
    59                             'area':None,
    60                             'inputdir':None,
    61                             'outputdir':None,
    62                             'flexpart_root_scripts':None,
    63                             'ppid':None,
    64                             'job_template':'job.temp',
    65                             'queue':None,
    66                             'controlfile':'CONTROL.temp',
    67                             'debug':None,
    68                             'public':None,
    69                             'request':None}
     58        cmd_dict_control = {'start_date': None,
     59                            'end_date': None,
     60                            'date_chunk': None,
     61                            'basetime': None,
     62                            'step': None,
     63                            'levelist': None,
     64                            'area': None,
     65                            'inputdir': None,
     66                            'outputdir': None,
     67                            'job_template': None,
     68                            'job_chunk': None,
     69                            'ppid': None,
     70                            'job_template': 'job.temp',
     71                            'queue': None,
     72                            'controlfile': 'CONTROL_EA5',
     73                            'debug': None,
     74                            'public': None,
     75                            'request': None,
     76                            'oper': None,
     77                            'rrint': None}
    7078
    7179        sys.argv = ['dummy.py']
    7280
    73         results = get_cmdline_arguments()
     81        results = get_cmdline_args()
    7482
    7583        assert cmd_dict_control == vars(results)
    7684
    7785    def test_input_get_cmdline_arguments(self):
    78         cmd_dict_control = {'start_date':'20180101',
    79                             'end_date':'20180101',
    80                             'date_chunk':3,
    81                             'basetime':12,
    82                             'step':'1',
    83                             'levelist':'1/to/10',
    84                             'area':'50/10/60/20',
    85                             'inputdir':'../work',
    86                             'outputdir':None,
    87                             'flexpart_root_scripts':'../',
    88                             'ppid':1234,
    89                             'job_template':'job.sh',
    90                             'queue':'ecgate',
    91                             'controlfile':'CONTROL.WORK',
    92                             'debug':1,
    93                             'public':None,
    94                             'request':0}
     86        cmd_dict_control = {'start_date': '20180101',
     87                            'end_date': '20180101',
     88                            'date_chunk': 3,
     89                            'basetime': 12,
     90                            'step': '1',
     91                            'levelist': '1/to/10',
     92                            'area': '50/10/60/20',
     93                            'inputdir': '../work',
     94                            'outputdir': None,
     95                            'ppid': '1234',
     96                            'job_template': 'job.sh',
     97                            'queue': 'ecgate',
     98                            'controlfile': 'CONTROL.WORK',
     99                            'debug': 1,
     100                            'public': None,
     101                            'request': 0,
     102                            'rrint': 0,
     103                            'job_chunk': None,
     104                            'oper': 0}
    95105
    96106        sys.argv = ['dummy.py',
     
    104114                    '--inputdir=../work',
    105115                    '--outputdir=None',
    106                     '--flexpart_root_scripts=../',
    107116                    '--ppid=1234',
    108117                    '--job_template=job.sh',
     
    111120                    '--debug=1',
    112121                    '--public=None',
    113                     '--request=0']
    114 
    115         results = get_cmdline_arguments()
     122                    '--request=0',
     123                    '--rrint=0',
     124                    '--job_chunk=None',
     125                    '--oper=0']
     126
     127        results = get_cmdline_args()
    116128
    117129        assert cmd_dict_control == vars(results)
     
    121133        expected_sample = {'078': 'TCLW', '130': 'T', '034': 'SST'}
    122134        # check a sample of parameters which must have been read in
    123         assert all((k in table128 and table128[k]==v)
    124                    for k,v in expected_sample.iteritems())
    125 
    126     @patch('__builtin__.open', side_effect=[OSError(errno.EEXIST)])
     135        assert all((k in table128 and table128[k] == v)
     136                   for k, v in expected_sample.items())
     137
     138    @patch('builtins.open', side_effect=[OSError(errno.EEXIST)])
    127139    def test_fail_open_init128(self, mock_openfile):
    128140        with pytest.raises(SystemExit):
     
    145157
    146158    @patch('traceback.format_stack', return_value='empty trace')
    147     @patch('mods.tools.send_mail', return_value=0)
     159    @patch('Mods.tools.send_mail', return_value=0)
    148160    def test_success_my_error(self, mock_mail, mock_trace, capfd):
    149161        with pytest.raises(SystemExit):
    150             my_error(['any_user'], 'Failed!')
     162            my_error('Failed!')
    151163            out, err = capfd.readouterr()
    152164            assert out == "Failed!\n\nempty_trace\n"
     
    160172        send_mail(['${USER}', 'any_user'], 'ERROR', message='error mail')
    161173        out, err = capfd.readouterr()
    162         assert out == b'Email sent to user\nEmail sent to user\n'
     174        assert out == 'Email sent to user\nEmail sent to user\n'
    163175
    164176    @patch('subprocess.Popen')
     
    169181        send_mail(['any-user'], 'ERROR', message='error mail')
    170182        out, err = capfd.readouterr()
    171         assert out == b'Email sent to any_user\n'
     183        assert out == 'Email sent to any_user\n'
    172184
    173185    @patch('subprocess.Popen', side_effect=[ValueError, OSError])
     
    189201        assert envs_ref == envs
    190202
    191     @patch('__builtin__.open', side_effect=[OSError(errno.EPERM)])
     203    @patch('builtins.open', side_effect=[OSError(errno.EPERM)])
    192204    def test_fail_read_ecenv(self, mock_open):
    193205        with pytest.raises(SystemExit):
     
    195207
    196208    @patch('glob.glob', return_value=[])
    197     @patch('mods.tools.silent_remove')
     209    @patch('Mods.tools.silent_remove')
    198210    def test_empty_clean_up(self, mock_rm, mock_clean):
    199211        clean_up(self.c)
     
    203215    @patch('os.remove', return_value=0)
    204216    def test_success_clean_up(self, mock_rm, mock_glob):
    205         # ectrans=0; ecstorage=0; ecapi=None; prefix not in filename
    206         clean_up(self.c)
    207         mock_rm.assert_has_calls([call('any_file'), call('EIfile')])
    208         mock_rm.reset_mock()
    209 
    210         # ectrans=0; ecstorage=0; ecapi=False; prefix in filename
     217
    211218        self.c.prefix = 'EI'
    212219        self.c.ecapi = False
     
    215222        mock_rm.reset_mock()
    216223
    217         # ectrans=0; ecstorage=0; ecapi=True; prefix in filename
    218         self.c.prefix = 'EI'
    219         self.c.ecapi = True
    220         clean_up(self.c)
    221         mock_rm.assert_has_calls([call('any_file')])
    222         mock_rm.reset_mock()
    223 
    224         # ectrans=1; ecstorage=0; ecapi=True; prefix in filename
    225         self.c.prefix = 'EI'
    226         self.c.ecapi = True
    227         self.c.ectrans = 1
    228         clean_up(self.c)
    229         mock_rm.assert_has_calls([call('any_file')])
    230         mock_rm.reset_mock()
    231 
    232         # ectrans=1; ecstorage=0; ecapi=False; prefix in filename
    233         self.c.prefix = 'EI'
    234         self.c.ecapi = False
    235         self.c.ectrans = 1
    236         clean_up(self.c)
    237         mock_rm.assert_has_calls([call('any_file'), call('EIfile')])
    238         mock_rm.reset_mock()
    239 
    240         # ectrans=1; ecstorage=1; ecapi=False; prefix in filename
    241         self.c.prefix = 'EI'
    242         self.c.ecapi = False
    243         self.c.ectrans = 1
    244         self.c.ecstorage = 1
    245         clean_up(self.c)
    246         mock_rm.assert_has_calls([call('any_file'), call('EIfile')])
    247         mock_rm.reset_mock()
    248224
    249225    def test_default_normal_exit(self, capfd):
  • Source/Pythontest/TestUIOFiles.py

    rba99230 r76c37a9  
    55import sys
    66import pytest
     7from mock import patch
    78
    8 sys.path.append('../python')
    9 from classes.UioFiles import UioFiles
     9from . import _config_test
     10sys.path.append('../Python')
     11
     12from Classes.UioFiles import UioFiles
    1013
    1114
    1215class TestUioFiles():
    13     '''
    14     Test class to test the UIOFiles methods.
    15     '''
     16    """Test class to test the UIOFiles methods."""
     17
     18    @classmethod
     19    def setup_class(self):
     20        """Setup status"""
     21        self.testpath = os.path.join(_config_test.PATH_TEST_DIR, 'Dir')
     22        # Initialise and collect filenames
     23        self.files = UioFiles(self.testpath, '*.grb')
    1624
    1725    def test_listFiles(self):
    18         '''
    19         @Description:
    20             Test the listFiles method from class UIOFiles.
     26        """Test the listFiles method from class UIOFiles."""
     27        # set comparison information
     28        self.expected = ['FCGG__SL.20160410.40429.16424.grb',
     29                         'FCOG__ML.20160410.40429.16424.grb',
     30                         'FCSH__ML.20160410.40429.16424.grb',
     31                         'OG_OROLSM__SL.20160410.40429.16424.grb',
     32                         'FCOG_acc_SL.20160409.40429.16424.grb',
     33                         'FCOG__SL.20160410.40429.16424.grb',
     34                         'FCSH__SL.20160410.40429.16424.grb']
    2135
    22         @Input:
    23             self: instance of TestClass
    24                 Class to test the UIOFiles methods.
    25 
    26         @Return:
    27             <nothing>
    28         '''
    29         # set comparison information
    30         self.testpath = os.path.join(os.path.dirname(__file__), 'TestDir')
    31         self.expected = ['FCGG__SL.20160410.40429.16424.grb',
    32                              'FCOG__ML.20160410.40429.16424.grb',
    33                              'FCSH__ML.20160410.40429.16424.grb',
    34                              'OG_OROLSM__SL.20160410.40429.16424.grb',
    35                              'FCOG_acc_SL.20160409.40429.16424.grb',
    36                              'FCOG__SL.20160410.40429.16424.grb',
    37                              'FCSH__SL.20160410.40429.16424.grb']
    38 
    39         # Initialise and collect filenames
    40         files = UioFiles(self.testpath, '*.grb')
    4136        # get the basename to just check for equality of filenames
    42         filelist = [os.path.basename(f) for f in files.files]
     37        filelist = [os.path.basename(f) for f in self.files.files]
    4338        # comparison of expected filenames against the collected ones
    4439        assert sorted(self.expected) == sorted(filelist)
    4540
    46         return
    4741
     42    def test_delete_files(self):
     43        """Test if a file is deleted."""
     44        testfile = os.path.join(self.testpath, 'test.test')
     45        open(testfile, 'w').close()
     46        iofile = UioFiles(testfile, 'test.test')
     47        iofile.delete_files()
     48        assert [] == UioFiles(testfile, 'test.test').files
     49
     50
     51    def test_str_(self):
     52        """Test if list of file is correctly converted to string."""
     53        self.expected = "FCSH__SL.20160410.40429.16424.grb, "\
     54                        "FCSH__ML.20160410.40429.16424.grb, "\
     55                        "FCOG__SL.20160410.40429.16424.grb, "\
     56                        "FCOG__ML.20160410.40429.16424.grb, "\
     57                        "OG_OROLSM__SL.20160410.40429.16424.grb, "\
     58                        "FCGG__SL.20160410.40429.16424.grb, "\
     59                        "FCOG_acc_SL.20160409.40429.16424.grb"
     60        assert self.expected == self.files.__str__()
  • Source/Pythontest/_config_test.py

    rba99230 r76c37a9  
    1 #!/usr/bin/env python
     1#!/usr/bin/env python3
    22# -*- coding: utf-8 -*-
    33'''
     
    2727import sys
    2828
    29 sys.path.append('../python')
     29sys.path.append('../Python')
    3030import _config
    3131
     
    3838# DIRECTORY NAMES
    3939# ------------------------------------------------------------------------------
    40 TEST_DIR = 'test/Unit'
     40TEST_DIR = 'Testing/Regression/Unit'
    4141TESTFILES_DIR = 'Testfiles'
    4242TESTINSTALL_DIR = 'InstallTar'
  • Source/Pythontest/conftest.py

    rba99230 rd9abaac  
    22import pytest
    33
    4 sys.path.append('../python')
     4sys.path.append('../Python')
    55import _config
    66
     
    88#def prep_test_env():
    99#    testdir = _config.PATH_TEST_DIR
    10 print ''
     10print('')
Note: See TracChangeset for help on using the changeset viewer.
hosted by ZAMG