- Timestamp:
- Mar 6, 2020, 1:34:52 PM (4 years ago)
- 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. - Location:
- Source
- Files:
-
- 1 added
- 1 deleted
- 24 edited
Legend:
- Unmodified
- Added
- Removed
-
Source/Fortran/makefile_cray
rdfa7dbd r4d68c4a 1 1 ############################################################################### 2 2 # 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 4 5 # 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 6 11 # 7 12 ############################################################################### 8 13 9 14 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 15 EXE = calc_etadot 12 16 13 OPT = 14 DEBUG = -g 15 LIB = $(GRIB_API_LIBS) $(EMOSLIB) 17 LIB = $(ECCODES_LIB) $(EMOSLIB) 18 INC = -I. -I$(ECCODES_INCLUDE_DIR) 16 19 17 FC=ftn $(F90FLAGS) 18 F90C=ftn $(F90FLAGS) 20 FC = ftn 19 21 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 22 OPT = -O3 23 FFLAGS = -s real64 $(OPT) $(LIB) $(INC) 24 LDFLAGS = $(OPT) -fopenmp 27 25 EXE = calc_etadot 28 26 29 30 27 .f.o: 31 $(F90C) -c $(F90FLAGS) $(DEBUG) $*.f 32 .f90.o: 33 $(F90C) -c $(F90FLAGS) $(DEBUG) $*.f90 28 SRC = ./rwgrib2.f90 ./calc_etadot.f90 ./ftrafo.f90 ./grphreal.f90 ./posnam.f90 ./phgrreal.f90 29 OBJ = rwgrib2.o calc_etadot.o ftrafo.o grphreal.o posnam.o phgrreal.o 30 MOD = ftrafo.mod grtoph.mod phtogr.mod rwgrib2.mod 34 31 35 32 all: ${EXE} 36 33 37 clean: 38 rm *.o *.mod ${EXE} 34 ftrafo.o: ./ftrafo.f90 phgrreal.o 35 $(FC) $(FFLAGS) -c ./ftrafo.f90 36 grphreal.o: ./grphreal.f90 phgrreal.o 37 $(FC) $(FFLAGS) -c ./grphreal.f90 38 phgrreal.o: ./phgrreal.f90 39 $(FC) $(FFLAGS) -c ./phgrreal.f90 40 posnam.o: ./posnam.f90 41 $(FC) $(FFLAGS) -c ./posnam.f90 42 calc_etadot.o: ./calc_etadot.f90 phgrreal.o grphreal.o ftrafo.o rwgrib2.o 43 $(FC) $(FFLAGS) -c ./calc_etadot.f90 44 rwgrib2.o: ./rwgrib2.f90 45 $(FC) $(FFLAGS) -c ./rwgrib2.f90 39 46 40 phgrreal.o: phgrreal.f 41 $(F90C) -c -g -O3 phgrreal.f47 clean: 48 -rm -f $(OBJ) ${EXE} $(MOD) calc_etadot 42 49 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 7 7 # SPDX-License-Identifier: GPL-2.0 8 8 # 9 # Version for a machine with grib_apiand emoslib installed on standard paths9 # Version for a machine with eccodes and emoslib installed on standard paths 10 10 # full debugging 11 11 # … … 15 15 EXE = calc_etadot_debug.out 16 16 17 GRIB_API_LIB= -Bstatic -l grib_api_f90 -lgrib_api-Bdynamic -lm -ljasper17 GRIB_API_LIB= -Bstatic -leccodes_f90 -leccodes -Bdynamic -lm -ljasper 18 18 EMOSLIB=-lemosR64 19 19 LIB = $(GRIB_API_LIB) $(EMOSLIB) 20 20 21 GRIB_API_INCLUDE_DIR=/usr/include 22 INC = -I. -I$( GRIB_API_INCLUDE_DIR)21 ECCODES_INCLUDE_DIR=/usr/lib/x86_64-linux-gnu/fortran/gfortran-mod-15 22 INC = -I. -I$(ECCODES_INCLUDE_DIR) 23 23 24 24 FC = gfortran … … 47 47 $(FC) $(FFLAGS) -c ./rwgrib2.f90 48 48 49 clean: -rm -f $(OBJ) ${EXE} $(MOD) 49 clean: 50 -rm -f $(OBJ) ${EXE} $(MOD) calc_etadot 50 51 51 52 ${EXE}: $(OBJ) 52 53 $(FC) $(OBJ) -o ${EXE} $(LDFLAGS) 54 ln -sf ${EXE} calc_etadot -
Source/Fortran/makefile_ecgate
rdfa7dbd r1610f73 1 1 ############################################################################### 2 2 # 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 4 5 # 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 6 11 # 7 12 ############################################################################### 8 13 9 14 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 15 EXE = calc_etadot_fast.out 12 16 13 OPT = -O314 DEBUG = -g15 17 LIB = $(ECCODES_LIB) $(EMOSLIB) 18 INC = -I. -I$(ECCODES_INCLUDE_DIR) 16 19 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 20 FC=gfortran 19 21 20 FFLAGS = $(OPT) -I. -I$(ECCODES_INCLUDE_DIR) 22 OPT = -O3 -march=native 23 FFLAGS = $(OPT) $(LIB) $(INC) -fdefault-real-8 -fopenmp -fconvert=big-endian 24 LDFLAGS = $(OPT) $(LIB) -fopenmp 25 SRC = ./rwgrib2.f90 ./calc_etadot.f90 ./ftrafo.f90 ./grphreal.f90 ./posnam.f90 ./phgrreal.f90 26 OBJ = rwgrib2.o calc_etadot.o ftrafo.o grphreal.o posnam.o phgrreal.o 27 MOD = ftrafo.mod grtoph.mod phtogr.mod rwgrib2.mod 21 28 22 F90FLAGS = $(OPT) -I. -I$(ECCODES_INCLUDE_DIR) 29 all: ${EXE} 30 ftrafo.o: ./ftrafo.f90 phgrreal.o 31 $(FC) $(FFLAGS) -c ./ftrafo.f90 32 grphreal.o: ./grphreal.f90 phgrreal.o 33 $(FC) $(FFLAGS) -c ./grphreal.f90 34 phgrreal.o: ./phgrreal.f90 35 $(FC) $(FFLAGS) -c ./phgrreal.f90 36 posnam.o: ./posnam.f90 37 $(FC) $(FFLAGS) -c ./posnam.f90 38 calc_etadot.o: ./calc_etadot.f90 phgrreal.o grphreal.o ftrafo.o rwgrib2.o 39 $(FC) $(FFLAGS) -c ./calc_etadot.f90 40 rwgrib2.o: ./rwgrib2.f90 41 $(FC) $(FFLAGS) -c ./rwgrib2.f90 23 42 24 LDFLAGS = $(OPT) 43 clean: 44 -rm -f $(OBJ) ${EXE} $(MOD) calc_etadot 25 45 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 7 7 # SPDX-License-Identifier: GPL-2.0 8 8 # 9 # Version for a machine with grib_apiand emoslib installed on standard paths10 # full debugging9 # Version for a machine with eccodes and emoslib installed on standard paths 10 # with optimisation 11 11 # 12 12 ############################################################################### 13 13 14 14 15 EXE = calc_etadot 15 EXE = calc_etadot_fast.out 16 16 17 #GRIB_API_LIB= -Bstatic -lgrib_api_f90 -lgrib_api -Bdynamic -lm -ljasper 18 ECCODES_LIB= -L/usr/local/lib -leccodes_f90 -leccodes -lm 17 ECCODES_LIB = -Bstatic -leccodes_f90 -leccodes -Bdynamic -lm -ljasper 19 18 EMOSLIB=-lemosR64 20 19 LIB = $(ECCODES_LIB) $(EMOSLIB) 21 20 22 ECCODES_INCLUDE_DIR=/usr/l ocal/include21 ECCODES_INCLUDE_DIR=/usr/lib/x86_64-linux-gnu/fortran/gfortran-mod-15 23 22 INC = -I. -I$(ECCODES_INCLUDE_DIR) 24 23 … … 49 48 50 49 clean: 51 -rm -f $(OBJ) ${EXE} $(MOD) 50 -rm -f $(OBJ) ${EXE} $(MOD) calc_etadot 52 51 53 52 ${EXE}: $(OBJ) 54 53 $(FC) $(OBJ) -o ${EXE} $(LDFLAGS) 54 ln -sf ${EXE} calc_etadot -
Source/Python/Classes/ControlFile.py
r44174de r0f89116 38 38 39 39 import os 40 import re41 40 import sys 42 import inspect43 41 44 42 # software specific classes and modules from flex_extract 43 #pylint: disable=wrong-import-position 45 44 sys.path.append('../') 46 45 import _config 47 from Mods.tools import my_error , silent_remove46 from Mods.tools import my_error 48 47 from Mods.checks import (check_grid, check_area, check_levels, check_purefc, 49 48 check_step, check_mail, check_queue, check_pathes, … … 53 52 check_logicals_type, check_len_type_time_step, 54 53 check_addpar, check_job_chunk, check_number) 54 #pylint: enable=wrong-import-position 55 55 56 56 # ------------------------------------------------------------------------------ … … 65 65 from the MARS archive for driving FLEXPART are set in a CONTROL file. 66 66 Some specific parameters like the start and end dates can be overwritten 67 by the command line parameters, but in gener el all parameters needed67 by the command line parameters, but in generall all parameters needed 68 68 for a complete set of fields for FLEXPART can be set in the CONTROL file. 69 69 … … 238 238 Default value is ['${USER}']. 239 239 240 grib2flexpart : int 0241 Switch to select generation of preprocessed FLEXPART files ".fp".242 If it is selected, the program grib2flexpart will try243 to convert the flex_extract output files into ".fp" format.244 245 240 ecstorage : int 246 241 Switch to select storage of FLEXPART ready output files … … 334 329 List of the names of logical switches which controls the flow 335 330 of the program. Default list is ['gauss', 'omega', 'omegadiff', 'eta', 336 'etadiff', 'dpdeta', 'cwc', 'wrf', ' grib2flexpart', 'ecstorage',331 'etadiff', 'dpdeta', 'cwc', 'wrf', 'ecstorage', 337 332 'ectrans', 'debug', 'request', 'public', 'purefc', 'rrint', 'doubleelda'] 338 333 ''' … … 400 395 self.mailfail = ['${USER}'] 401 396 self.mailops = ['${USER}'] 402 self.grib2flexpart = 0403 397 self.ecstorage = 0 404 398 self.ectrans = 0 … … 425 419 426 420 self.logicals = ['gauss', 'omega', 'omegadiff', 'eta', 'etadiff', 427 'dpdeta', 'cwc', 'wrf', ' grib2flexpart', 'ecstorage',421 'dpdeta', 'cwc', 'wrf', 'ecstorage', 428 422 'ectrans', 'debug', 'oper', 'request', 'public', 429 423 'purefc', 'rrint', 'doubleelda'] … … 602 596 603 597 self.outputdir, self.installdir = check_pathes(self.inputdir, 604 self.outputdir, self.installdir, self.flexextractdir) 598 self.outputdir, 599 self.installdir, 600 self.flexextractdir) 605 601 606 602 self.start_date, self.end_date = check_dates(self.start_date, … … 611 607 self.levelist, self.level = check_levels(self.levelist, self.level) 612 608 613 self.step = check_step(self.step , self.mailfail)609 self.step = check_step(self.step) 614 610 615 611 self.maxstep = check_maxstep(self.maxstep, self.step) … … 649 645 self.job_chunk = check_job_chunk(self.job_chunk) 650 646 651 self.number = check_number(self.number , self.mailfail)647 self.number = check_number(self.number) 652 648 653 649 return … … 695 691 696 692 return sorted(l) 697 -
Source/Python/Classes/EcFlexpart.py
rc77630a r53d3b2a 53 53 #pylint: disable=consider-using-enumerate 54 54 # 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 55 59 # ------------------------------------------------------------------------------ 56 60 # MODULES … … 62 66 import glob 63 67 import shutil 64 import subprocess65 68 from datetime import datetime, timedelta 66 69 67 70 # software specific classes and modules from flex_extract 71 #pylint: disable=wrong-import-position 68 72 sys.path.append('../') 69 73 import _config 70 74 from Classes.GribUtil import GribUtil 71 75 from 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, 73 77 execute_subprocess, to_param_id_with_tablenumber, 74 78 generate_retrieval_period_boundary) … … 76 80 from Classes.UioFiles import UioFiles 77 81 import Mods.disaggregation as disaggregation 78 82 #pylint: enable=wrong-import-position 79 83 # ------------------------------------------------------------------------------ 80 84 # CLASS … … 317 321 318 322 ''' 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 319 331 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} 324 333 return 325 334 … … 401 410 else: # GAUSS and ETA 402 411 print('Warning: Collecting etadot and parameters for gaussian grid ' 403 404 412 'is a very costly parameter combination, ' 413 'use this combination only for debugging!') 405 414 self.params['GG__SL'] = ['Q', 'ML', '1', 406 415 '{}'.format((int(self.resol) + 1) // 2)] … … 415 424 416 425 # ADDITIONAL FIELDS FOR FLEXPART-WRF MODEL (IF QUESTIONED) 417 # ---------------------------------------------------------------------- -426 # ---------------------------------------------------------------------- 418 427 if wrf: 419 428 # @WRF … … 710 719 retr_param_dict['date'] = self.dates.split('/')[0] 711 720 retr_param_dict['target'] = self._mk_targetname('', 712 pk, retr_param_dict['date']) 721 pk, 722 retr_param_dict['date']) 713 723 elif pk == 'OG_OROLSM__SL' and oro: 714 724 continue … … 752 762 if 'acc' in pk: 753 763 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') 755 765 retr_param_dict['date'] = '/'.join([startdate, 756 766 'to', … … 776 786 777 787 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') 780 790 781 791 timesave = ''.join(retr_param_dict['time']) 782 792 783 if ('/' in retr_param_dict['time'] and784 pk != 'OG_OROLSM__SL' and785 'acc' not in pk ):793 if all(['/' in retr_param_dict['time'], 794 pk != 'OG_OROLSM__SL', 795 'acc' not in pk]): 786 796 times = retr_param_dict['time'].split('/') 787 797 steps = retr_param_dict['step'].split('/') … … 794 804 retr_param_dict['time'] = times[0] 795 805 796 if (pk != 'OG_OROLSM__SL' and797 int(retr_param_dict['step'].split('/')[0]) == 0 and798 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]): 799 809 800 810 retr_param_dict['date'] = \ … … 810 820 else: 811 821 raise ValueError('ERROR: Basetime has an invalid value ' 812 '-> {}'.format(str(basetime)))822 '-> {}'.format(str(self.basetime))) 813 823 814 824 if request == 0 or request == 2: … … 860 870 861 871 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) 879 889 ) 880 890 except UndefinedError as e: … … 928 938 ''' 929 939 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, 931 941 codes_get_values, codes_set_values, codes_set, 932 942 codes_write, codes_release, codes_new_from_index, … … 1053 1063 step = codes_get(gid, 'step') # integer 1054 1064 ctime = '{:0>2}'.format(time) 1055 cstep = '{:0>3}'.format(step)1056 1065 1057 1066 t_date = datetime.strptime(cdate + ctime, '%Y%m%d%H') … … 1132 1141 deac_vals[parId].append( 1133 1142 (orig_vals[parId][-1] - orig_vals[parId][-2]) / 1134 1143 int(c.dtime)) 1135 1144 1136 1145 # store precipitation if new disaggregation method is selected … … 1332 1341 for inum in range(maxnum): 1333 1342 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] 1336 1345 else: 1337 1346 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] 1340 1349 1341 1350 # write to grib files (full/orig times to flux file and inbetween … … 1402 1411 # write original time step to flux file as usual 1403 1412 fluxfile = GribUtil(os.path.join(c.inputdir, fluxfilename)) 1404 fluxfile.set_keys(tmpfile, filemode='ab', strict=True,1413 fluxfile.set_keys(tmpfile, filemode='ab', 1405 1414 wherekeynames=['paramId'], wherekeyvalues=[142], 1406 keynames=['perturbationNumber','date','time','stepRange','values'], 1415 keynames=['perturbationNumber', 'date', 'time', 1416 'stepRange', 'values'], 1407 1417 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]], 1409 1419 ) 1410 fluxfile.set_keys(tmpfile, filemode='ab', strict=True,1420 fluxfile.set_keys(tmpfile, filemode='ab', 1411 1421 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]] 1415 1426 ) 1416 1427 1417 1428 # 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', 1419 1430 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', 1425 1437 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 ) 1430 1443 1431 1444 # 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', 1433 1446 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', 1439 1453 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 ) 1444 1459 1445 1460 it = it + 3 # jump to next original time step in rr fields … … 1463 1478 ''' 1464 1479 1465 gribfile = GribUtil(os.path.join(inputdir, 'rr_grib_dummy.grb'))1480 gribfile = GribUtil(os.path.join(inputdir, 'rr_grib_dummy.grb')) 1466 1481 1467 1482 gribfile.copy_dummy_msg(ifile, keynames=['paramId'], 1468 keyvalues=[142], filemode='wb')1483 keyvalues=[142], filemode='wb') 1469 1484 1470 1485 gribfile.copy_dummy_msg(ifile, keynames=['paramId'], 1471 keyvalues=[143], filemode='ab')1486 keyvalues=[143], filemode='ab') 1472 1487 1473 1488 return … … 1501 1516 1502 1517 ''' 1503 from eccodes import (codes_index_select, codes_ new_from_index, codes_get,1518 from eccodes import (codes_index_select, codes_get, 1504 1519 codes_get_values, codes_set_values, codes_set, 1505 1520 codes_write, codes_release, codes_new_from_index, … … 1583 1598 cdate_hour = datetime.strftime(timestamp, '%Y%m%d%H') 1584 1599 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 1585 1608 # skip all temporary times 1586 1609 # which are outside the retrieval period … … 1589 1612 continue 1590 1613 1591 # if the timestamp is out of basetime start/end date period,1592 # skip this specific product1593 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_delta1597 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 continue1601 1614 1602 1615 # @WRF … … 1620 1633 paramId = codes_get(gid, 'paramId') 1621 1634 gridtype = codes_get(gid, 'gridType') 1622 levtype = codes_get(gid, 'typeOfLevel')1623 1635 if paramId == 77: # ETADOT 1624 1636 codes_write(gid, fdict['21']) … … 1704 1716 # Fortran program creates file fort.15 (with u,v,etadot,t,sp,q) 1705 1717 execute_subprocess([os.path.join(c.exedir, 1706 _config.FORTRAN_EXECUTABLE)],1718 _config.FORTRAN_EXECUTABLE)], 1707 1719 error_msg='FORTRAN PROGRAM FAILED!')#shell=True) 1708 1720 … … 1733 1745 # to the outputfile (final GRIB input files for FLEXPART) 1734 1746 orolsm = os.path.basename(glob.glob(c.inputdir + 1735 '/OG_OROLSM__SL.*.' + c.ppid + '*')[0]) 1747 '/OG_OROLSM__SL.*.' + 1748 c.ppid + 1749 '*')[0]) 1736 1750 fluxfile = 'flux' + cdate[0:2] + suffix 1737 1751 if not c.cwc: … … 1783 1797 ''' 1784 1798 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) 1787 1801 1788 1802 # max number … … 1790 1804 1791 1805 # 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: 1796 1810 with open(cffile, 'rb') as f: 1797 cfvalues =[]1811 cfvalues = [] 1798 1812 while True: 1799 1813 fid = codes_grib_new_from_file(f) … … 1900 1914 1901 1915 return 1902 -
Source/Python/Classes/GribUtil.py
rc77630a r0f89116 68 68 69 69 70 def get_keys(self, keynames, wherekeynames =[], wherekeyvalues=[]):70 def get_keys(self, keynames, wherekeynames, wherekeyvalues): 71 71 '''Get keyvalues for a given list of keynames a where statement 72 72 can be given (list of key and list of values) … … 77 77 List of keynames. 78 78 79 wherekeynames : :obj:`list` of :obj:`string` , optional80 Default value is an empty list.81 82 wherekeyvalues : :obj:`list` of :obj:`string` , optional83 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. 84 84 85 85 Return … … 122 122 123 123 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'): 126 126 '''Opens the file to read the grib messages and then write 127 127 the selected messages (with wherekeys) to a new output file. … … 141 141 Default is an empty list. 142 142 143 wherekeynames : :obj:`list` of :obj:`string` , optional143 wherekeynames : :obj:`list` of :obj:`string` 144 144 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` 148 147 List of keyvalues for keynames to select correct message. 149 Default value is an empty list.150 151 strict : :obj:`boolean`, optional152 Decides if everything from keynames and keyvalues153 is written out the grib file (False) or only those154 meeting the where statement (True). Default is False.155 148 156 149 filemode : :obj:`string`, optional … … 200 193 return 201 194 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'): 204 197 '''Add the content of another input grib file to the objects file but 205 198 only messages corresponding to keys/values passed to the function. … … 212 205 Filename of the input file to read the grib messages from. 213 206 214 select Where : :obj:`boolean`, optional207 selectwhere : :obj:`boolean`, optional 215 208 Decides if to copy the keynames and values equal to (True) or 216 209 different to (False) the keynames/keyvalues list passed to the 217 210 function. Default is True. 218 211 219 keynames : :obj:`list` of :obj:`string` , optional220 List of keynames. Default is an empty list.221 222 keyvalues : :obj:`list` of :obj:`string` , optional223 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. 224 217 225 218 filemode : :obj:`string`, optional … … 254 247 raise Exception("Key was not defined") 255 248 256 if select Where:249 if selectwhere: 257 250 select = (select and (str(keyvalues[i]) == 258 251 str(codes_get(gid, key)))) … … 272 265 return 273 266 274 def index(self, index_keys =["mars"], index_file="my.idx"):267 def index(self, index_keys, index_file="my.idx"): 275 268 '''Create index file from a list of files if it does not exist or 276 269 read an index file. … … 278 271 Parameters 279 272 ---------- 280 index_keys: :obj:`list` of :obj:`string` , optional273 index_keys: :obj:`list` of :obj:`string` 281 274 Contains the list of key parameter names from 282 275 which the index is to be created. 283 Default is a list with a single entry string "mars".284 276 285 277 index_file: :obj:`string`, optional -
Source/Python/Classes/MarsRetrieval.py
rc77630a r0f89116 42 42 43 43 # software specific classes and modules from flex_extract 44 #pylint: disable=wrong-import-position 44 45 sys.path.append('../') 45 46 import _config 47 #pylint: disable=invalid-name 46 48 try: 47 49 ec_api = True … … 55 57 except ImportError: 56 58 cds_api = False 59 #pylint: enable=invalid-name 60 #pylint: enable=wrong-import-position 57 61 # ------------------------------------------------------------------------------ 58 62 # CLASS … … 510 514 print('\n\nMARS Request failed!') 511 515 print(e) 512 tb = sys.exc_info()[2]513 516 print(traceback.format_exc()) 514 517 sys.exit() -
Source/Python/Classes/UioFiles.py
r44174de rd9abaac 42 42 43 43 # software specific modules from flex_extract 44 #pylint: disable=wrong-import-position 44 45 sys.path.append('../') 45 46 from Mods.tools import silent_remove, get_list_as_string 47 #pylint: enable=wrong-import-position 46 48 47 49 # ------------------------------------------------------------------------------ … … 50 52 51 53 class UioFiles(object): 52 '''Collection of files matching a specific pattern.54 """Collection of files matching a specific pattern. 53 55 54 56 The pattern can contain regular expressions for the files. … … 62 64 63 65 pattern : str 64 Regular expression pattern. For example: ' \*.grb'66 Regular expression pattern. For example: '*.grb' 65 67 66 68 files : list of str 67 69 List of files matching the pattern in the path. 68 '''70 """ 69 71 # -------------------------------------------------------------------------- 70 72 # CLASS METHODS 71 73 # -------------------------------------------------------------------------- 72 74 def __init__(self, path, pattern): 73 '''Assignes a specific pattern for these files.75 """Assignes a specific pattern for these files. 74 76 75 77 Parameters … … 79 81 80 82 pattern : str 81 Regular expression pattern. For example: ' \*.grb'83 Regular expression pattern. For example: '*.grb' 82 84 83 85 Return 84 86 ------ 85 87 86 '''88 """ 87 89 88 90 self.path = path … … 96 98 97 99 def _list_files(self, path): 98 '''Lists all files in the directory with the matching100 """Lists all files in the directory with the matching 99 101 regular expression pattern. 100 102 … … 107 109 ------ 108 110 109 '''111 """ 110 112 # Get the absolute path 111 113 path = os.path.abspath(path) 112 114 113 115 # get all files in the dir and subdir as absolut path 116 # pylint: disable=W0612 114 117 for root, dirnames, filenames in os.walk(path): 115 118 for filename in fnmatch.filter(filenames, self.pattern): … … 120 123 121 124 def __str__(self): 122 '''Converts the list of files into a single string.125 """Converts the list of files into a single string. 123 126 The entries are sepereated by "," sign. 124 127 … … 130 133 files_string : str 131 134 The content of the list as a single string. 132 '''135 """ 133 136 134 137 filenames = [os.path.basename(f) for f in self.files] … … 139 142 140 143 def delete_files(self): 141 '''Deletes the files.144 """Deletes the files. 142 145 143 146 Parameters … … 147 150 ------ 148 151 149 '''152 """ 150 153 151 154 for old_file in self.files: -
Source/Python/Mods/checks.py
r44174de r0f89116 29 29 import os 30 30 import sys 31 32 import _config 31 from datetime import datetime 32 # pylint: disable=unused-import 33 33 try: 34 34 import exceptions 35 35 except ImportError: 36 36 import builtins as exceptions 37 from datetime import datetime 37 # pylint: enable=unused-import 38 39 # software specific classes and modules from flex_extract 40 import _config 38 41 from Mods.tools import my_error, silent_remove 39 42 # ------------------------------------------------------------------------------ … … 113 116 return grid 114 117 115 def check_area(grid, area, upper, lower, left 118 def check_area(grid, area, upper, lower, left, right): 116 119 '''Defines the correct area string. 117 120 … … 158 161 159 162 # determine area format 160 if ((abs(float(upper) / 10000.) >= 0.01 or float(upper) / 1000. == 0. ) and161 (abs(float(lower) / 10000.) >= 0.01 or float(lower) / 1000. == 0. ) and162 (abs(float(left) / 10000.) >= 0.01 or float(left) / 1000. == 0. ) and163 (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.)]): 164 167 # area is defined in 1/1000 degrees; old format 165 168 area = '{}/{}/{}/{}'.format(float(upper) / 1000., … … 167 170 float(lower) / 1000., 168 171 float(right) / 1000.) 169 elif (abs(float(upper) / 10000.) < 0.05 and170 abs(float(lower) / 10000.) < 0.05 and171 abs(float(left) / 10000.) < 0.05 and172 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]): 173 176 # area is already in new format 174 177 area = '{}/{}/{}/{}'.format(float(upper), … … 180 183 'formats (upper, lower, left, right): ' 181 184 '{}/{}/{}/{}'.format(str(upper), str(lower), 182 str(left) 185 str(left), str(right))) 183 186 184 187 return area … … 281 284 282 285 283 def check_step(step , mailfail):286 def check_step(step): 284 287 '''Checks on step format and convert into a list of steps. 285 288 … … 293 296 Specifies the forecast time step from forecast base time. 294 297 Valid values are hours (HH) from forecast base time. 295 296 mailfail : list of str297 Contains all email addresses which should be notified.298 It might also contain just the ecmwf user name which will trigger299 mailing to the associated email address for this user.300 298 301 299 Return … … 405 403 Valid values are hours (HH) from forecast base time. 406 404 ''' 407 if not (len(ftype) == len(ftime) == len(steps)):405 if not len(ftype) == len(ftime) == len(steps): 408 406 raise ValueError('ERROR: The number of field types, times and steps ' 409 407 'are not the same! Please check the setting in the ' … … 553 551 'in CONTROL file.\n' 554 552 'Try "{} -h" to print usage information' 555 .format(sys.argv[0].split('/')[-1]) 553 .format(sys.argv[0].split('/')[-1])) 556 554 557 555 # retrieve just one day if end_date isn't set … … 790 788 accmaxstep = maxstep 791 789 print('... For pure forecast mode, the accumulated forecast must ' 792 793 790 'have the same maxstep as the normal forecast fields!\n' 791 '\t\t Accmaxstep was set to maxstep!') 794 792 return accmaxstep 795 793 … … 851 849 852 850 853 def check_number(number , mailfail):851 def check_number(number): 854 852 '''Check for correct string format of ensemble member numbers. 855 853 … … 858 856 number : str 859 857 List of ensemble member forecast runs. 860 861 mailfail : list of str862 Contains all email addresses which should be notified.863 It might also contain just the ecmwf user name which will trigger864 mailing to the associated email address for this user.865 858 866 859 Return -
Source/Python/Mods/disaggregation.py
r44174de r0f89116 247 247 # geometric mean, restricted such that non-negativity is guaranteed 248 248 # 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])) 250 250 251 251 # the function value at the first sub-grid point (fi1) is determined … … 281 281 # the monotonicity filter corrects the value at (fim1) by 282 282 # 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])))) 287 287 288 288 # recomputation of the sub-grid interval values while the … … 295 295 f[-2] = f[-3]+(f[-1]-fmon)/3. 296 296 297 f.extend([0., 0.,0.])297 f.extend([0., 0., 0.]) 298 298 299 299 # otherwise the sub-grid values are calculated and added to the list … … 306 306 # geometric mean, restricted such that non-negativity is guaranteed 307 307 # 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])) 309 309 310 310 # the function value at the first sub-grid point (fi1) is determined … … 324 324 # the monotonicity filter corrects the value at (fim1) by 325 325 # 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])))) 330 330 331 331 # recomputation of the sub-grid interval values while the … … 358 358 # the monotonicity filter corrects the value at (fim1) by 359 359 # 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])))) 364 364 365 365 # recomputation of the sub-grid interval values while the … … 372 372 f[-2] = f[-3]+(f[-1]-fmon)/3. 373 373 374 f.extend([0., 0.,0.])374 f.extend([0., 0., 0.]) 375 375 376 376 # otherwise the sub-grid values are calculated and added to the list … … 397 397 # the monotonicity filter corrects the value at (fim1) by 398 398 # 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])))) 403 403 404 404 # recomputation of the sub-grid interval values while the -
Source/Python/Mods/get_mars_data.py
r44174de r0f89116 70 70 sys.path.append(os.path.dirname(os.path.abspath( 71 71 inspect.getfile(inspect.currentframe()))) + '/../') 72 # pylint: disable=wrong-import-position 72 73 import _config 73 from Mods.tools import (setup_controldata, my_error, normal_exit, get_cmdline_args, 74 read_ecenv, make_dir) 74 from Mods.tools import (setup_controldata, my_error, normal_exit, make_dir) 75 75 from Classes.EcFlexpart import EcFlexpart 76 76 from Classes.UioFiles import UioFiles 77 77 from Classes.MarsRetrieval import MarsRetrieval 78 78 # pylint: enable=wrong-import-position 79 # pylint: disable=invalid-name 79 80 try: 80 81 ec_api = True … … 88 89 except ImportError: 89 90 cds_api = False 91 # pylint: enable=invalid-name 90 92 # ------------------------------------------------------------------------------ 91 93 # FUNCTION … … 223 225 224 226 def 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): 228 243 if ty.upper() == 'FC' and int(ti) == 18: 229 244 return True … … 245 260 246 261 Since for basetime the extraction contains the 12 hours upfront, 247 if basetime is 0, the starting date has to be the day before and262 if basetime is 0, the starting date has to be the day before 248 263 249 264 Parameters -
Source/Python/Mods/prepare_flexpart.py
r44174de r0f89116 38 38 # http://creativecommons.org/licenses/by/4.0/ or send a letter to 39 39 # 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 41 43 '''This script prepares the final version of the grib files which are 42 44 then used by FLEXPART. … … 68 70 import inspect 69 71 import sys 70 import socket71 72 72 73 # software specific classes and modules from flex_extract … … 74 75 sys.path.append(os.path.dirname(os.path.abspath( 75 76 inspect.getfile(inspect.currentframe()))) + '/../') 76 import _config 77 # pylint: disable=wrong-import-position 78 #import _config 77 79 from Mods.checks import check_ppid 78 80 from 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 82 from Mods.tools import (setup_controldata, clean_up, make_dir, normal_exit) 82 83 from Classes.EcFlexpart import EcFlexpart 84 # pylint: enable=wrong-import-position 83 85 84 86 # ------------------------------------------------------------------------------ … … 146 148 147 149 print('Prepare ' + start.strftime("%Y%m%d") + 148 "/to/"+ end.strftime("%Y%m%d"))150 '/to/' + end.strftime("%Y%m%d")) 149 151 150 152 # create output dir if necessary … … 171 173 flexpart.process_output(c) 172 174 173 # make use of a possible conversion to a174 # specific flexpart binary format175 if c.grib2flexpart:176 flexpart.prepare_fp_files(c)177 178 175 # check if in debugging mode, then store all files 179 176 # otherwise delete temporary files -
Source/Python/Mods/profiling.py
r8463d78 r0f89116 37 37 # FUNCTION 38 38 # ------------------------------------------------------------------------------ 39 def timefn(f n):39 def timefn(func): 40 40 ''' 41 41 @Description: 42 42 Decorator function. It takes the inner function as an argument. 43 43 ''' 44 @wraps(f n)44 @wraps(func) 45 45 def measure_time(*args, **kwargs): 46 46 ''' … … 65 65 ''' 66 66 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") 71 72 72 73 return result -
Source/Python/Mods/tools.py
rc77630a rd1bfa24 69 69 import subprocess 70 70 import traceback 71 # pylint: disable=unused-import 71 72 try: 72 73 import exceptions 73 74 except ImportError: 74 75 import builtins as exceptions 76 # pylint: enable=unused-import 75 77 from datetime import datetime, timedelta 76 78 from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter … … 268 270 and destination for ECMWF server environments. 269 271 ''' 270 envs = {}272 envs = {} 271 273 try: 272 274 with open(filepath, 'r') as f: … … 279 281 280 282 sys.exit('\n... Error occured while trying to read ECMWF_ENV ' 281 283 'file: ' + str(filepath)) 282 284 283 285 return envs … … 302 304 print("... clean inputdir!") 303 305 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)] 306 309 307 310 if cleanlist: … … 371 374 stderr=subprocess.PIPE, 372 375 bufsize=1) 373 pout = p.communicate(input=message .encode()+ '\n\n')[0]376 pout = p.communicate(input=message + '\n\n')[0] 374 377 except ValueError as e: 375 378 print('... ERROR: ' + str(e)) … … 415 418 https://software.ecmwf.int/wiki/display/GRIB/index.py; 2018-03-16 416 419 420 It was released under the following license: 421 https://confluence.ecmwf.int/display/ECC/License 422 417 423 Example 418 424 ------- … … 531 537 return [] 532 538 if not isinstance(pars, str): 533 pars =str(pars)539 pars = str(pars) 534 540 535 541 cpar = pars.upper().split('/') … … 575 581 return [] 576 582 if not isinstance(pars, str): 577 pars =str(pars)583 pars = str(pars) 578 584 579 585 cpar = pars.upper().split('/') … … 768 774 769 775 # information needed from grib message 770 keys = [ 771 'Ni', 776 keys = ['Ni', 772 777 'Nj', 773 778 'latitudeOfFirstGridPointInDegrees', … … 783 788 for key in keys: 784 789 # 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])) 787 792 788 793 # Free the memory for the message referred as gribid. -
Source/Python/_config.py
r44174de r0f89116 54 54 55 55 FILE_MARS_REQUESTS = 'mars_requests.csv' 56 FORTRAN_EXECUTABLE = ' CONVERT2'56 FORTRAN_EXECUTABLE = 'calc_etadot' 57 57 TEMPFILE_USER_ENVVARS = 'ECMWF_ENV.template' 58 58 FILE_USER_ENVVARS = 'ECMWF_ENV' … … 97 97 PATH_PYTHONTEST_SRC = os.path.join(PATH_SOURCES, 'Pythontest') 98 98 PATH_INPUT_DIR = os.path.join(PATH_RUN_DIR, INPUT_DIRNAME_DEFAULT) 99 PATH_TEST = os.path.join(PATH_FLEXEXTRACT_DIR, 'Test ')99 PATH_TEST = os.path.join(PATH_FLEXEXTRACT_DIR, 'Testing') 100 100 if os.getenv('CONTROL'): 101 101 # this is only needed if (gateway) version with job script is used! -
Source/Python/install.py
r3a41083 r0f89116 68 68 import os 69 69 import sys 70 import glob71 70 import subprocess 72 import inspect73 71 import tarfile 74 72 from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter … … 179 177 180 178 ''' 181 import tarfile182 179 183 180 tarball_name = _config.FLEXEXTRACT_DIRNAME + '.tar' 184 181 tar_file = os.path.join(_config.PATH_FLEXEXTRACT_DIR, tarball_name) 185 182 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) 191 186 192 187 mk_env_vars(c.ecuid, c.ecgid, c.gateway, c.destination) … … 205 200 print('Job compilation script has been submitted to ecgate for ' + 206 201 'installation in ' + c.installdir + 207 202 '/' + _config.FLEXEXTRACT_DIRNAME) 208 203 print('You should get an email with subject "flexcompile" within ' + 209 204 'the next few minutes!') … … 224 219 225 220 ''' 226 import tarfile227 221 228 222 tar_file = os.path.join(_config.PATH_FLEXEXTRACT_DIR, 229 223 _config.FLEXEXTRACT_DIRNAME + '.tar') 230 224 231 if c.installdir == _config.PATH_FLEXEXTRACT_DIR 225 if c.installdir == _config.PATH_FLEXEXTRACT_DIR: 232 226 print('WARNING: installdir has not been specified') 233 227 print('flex_extract will be installed in here by compiling the ' + … … 241 235 mk_tarball(tar_file, c.install_target) 242 236 make_dir(os.path.join(c.installdir, 243 237 _config.FLEXEXTRACT_DIRNAME)) 244 238 os.chdir(os.path.join(c.installdir, 245 239 _config.FLEXEXTRACT_DIRNAME)) 246 240 un_tarball(tar_file) 247 241 os.chdir(os.path.join(c.installdir, 248 242 _config.FLEXEXTRACT_DIRNAME, 249 243 _config.PATH_REL_FORTRAN_SRC)) 250 244 … … 286 280 print('target: ', c.install_target) 287 281 print('please specify correct installation target ' + 288 str( INSTALL_TARGETS))282 str(_config.INSTALL_TARGETS)) 289 283 print('use -h or --help for help') 290 284 sys.exit(1) … … 334 328 335 329 ''' 336 from glob import glob337 330 338 331 print('Create tarball ...') … … 345 338 # get lists of the files to be added to the tar file 346 339 if target == 'local': 347 ECMWF_ENV_FILE= []340 ecmwf_env_file = [] 348 341 runfile = [os.path.relpath(x, ecd) 349 342 for x in UioFiles(_config.PATH_REL_RUN_DIR, 350 343 'run_local.sh').files] 351 344 else: 352 ECMWF_ENV_FILE= [_config.PATH_REL_ECMWF_ENV]345 ecmwf_env_file = [_config.PATH_REL_ECMWF_ENV] 353 346 runfile = [os.path.relpath(x, ecd) 354 355 347 for x in UioFiles(_config.PATH_REL_RUN_DIR, 348 'run.sh').files] 356 349 357 350 pyfiles = [os.path.relpath(x, ecd) 358 351 for x in UioFiles(_config.PATH_REL_PYTHON_SRC, '*py').files] 359 352 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] 361 354 controlfiles = [os.path.relpath(x, ecd) 362 355 for x in UioFiles(_config.PATH_REL_CONTROLFILES, 363 356 'CONTROL*').files] 364 357 testfiles = [os.path.relpath(x, ecd) 365 for x in UioFiles(_config.PATH_REL_TEST 358 for x in UioFiles(_config.PATH_REL_TEST, '*').files] 366 359 tempfiles = [os.path.relpath(x, ecd) 367 for x in UioFiles(_config.PATH_REL_TEMPLATES 360 for x in UioFiles(_config.PATH_REL_TEMPLATES, '*.temp').files] 368 361 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] 370 363 gribtable = [os.path.relpath(x, ecd) 371 for x in UioFiles(_config.PATH_REL_TEMPLATES 364 for x in UioFiles(_config.PATH_REL_TEMPLATES, '*grib*').files] 372 365 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] 374 367 hfiles = [os.path.relpath(x, ecd) 375 368 for x in UioFiles(_config.PATH_REL_FORTRAN_SRC, '*.h').files] … … 380 373 # concatenate single lists to one for a better looping 381 374 filelist = pyfiles + pytestfiles + controlfiles + tempfiles + nlfiles + \ 382 ffiles + gribtable + hfiles + makefiles + ECMWF_ENV_FILE+ \375 ffiles + gribtable + hfiles + makefiles + ecmwf_env_file + \ 383 376 runfile + jobdir + testfiles +\ 384 377 ['CODE_OF_CONDUCT.md', 'LICENSE.md', 'README.md'] 385 378 386 379 # create installation tar-file 387 exclude_files = [".ksh" ]380 exclude_files = [".ksh", ".tar"] 388 381 try: 389 382 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, 392 385 filter=lambda tarinfo: None 393 394 395 386 if os.path.splitext(tarinfo.name)[1] 387 in exclude_files 388 else tarinfo) 396 389 except tarfile.TarError as e: 390 print('... ERROR: ' + str(e)) 391 397 392 sys.exit('\n... error occured while trying to create the tar-file ' + 398 393 str(tarball_path)) 399 394 400 395 return … … 422 417 except tarfile.TarError as e: 423 418 sys.exit('\n... error occured while trying to read tar-file ' + 424 419 str(tarball_path)) 425 420 except OSError as e: 426 421 print('... ERROR CODE: ' + str(e.errno)) … … 465 460 cls=NewTextTemplate) 466 461 467 stream = ecmwfvars_template.generate(user_name =ecuid,468 user_group =ecgid,469 gateway_name =gateway,470 destination_name =destination471 462 stream = ecmwfvars_template.generate(user_name=ecuid, 463 user_group=ecgid, 464 gateway_name=gateway, 465 destination_name=destination 466 ) 472 467 except UndefinedError as e: 473 468 print('... ERROR ' + str(e)) … … 494 489 return 495 490 496 def mk_compilejob(makefile, target,ecuid, ecgid, fp_root):491 def mk_compilejob(makefile, ecuid, ecgid, fp_root): 497 492 '''Modifies the original job template file so that it is specified 498 493 for the user and the environment were it will be applied. Result … … 505 500 CONVERT2 program. 506 501 507 target : str508 The target where the installation should be done, e.g. the queue.509 510 502 ecuid : str 511 503 The user id on ECMWF server. … … 535 527 536 528 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_EXECUTABLE529 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 543 535 ) 544 536 except UndefinedError as e: … … 569 561 return 570 562 571 def mk_job_template(ecuid, ecgid, gateway, destination,fp_root):563 def mk_job_template(ecuid, ecgid, fp_root): 572 564 '''Modifies the original job template file so that it is specified 573 565 for the user and the environment were it will be applied. Result … … 581 573 ecgid : str 582 574 The group id on ECMWF server. 583 584 gateway : str585 The gateway server the user is using.586 587 destination : str588 The remote destination which is used to transfer files589 from ECMWF server to local gateway server.590 575 591 576 fp_root : str … … 615 600 616 601 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, 621 606 ) 622 607 except UndefinedError as e: … … 711 696 print(e) 712 697 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!') 716 701 717 702 return -
Source/Python/submit.py
r44174de r0f89116 64 64 import os 65 65 import sys 66 import subprocess67 import inspect68 import collections69 66 from datetime import datetime, timedelta 70 67 71 68 # software specific classes and modules from flex_extract 72 69 import _config 73 from Mods.tools import (setup_controldata, normal_exit, get_cmdline_args,74 submit_job_to_ecserver, read_ecenv)70 from Mods.tools import (setup_controldata, normal_exit, 71 submit_job_to_ecserver) 75 72 from Mods.get_mars_data import get_mars_data 76 73 from Mods.prepare_flexpart import prepare_flexpart 77 from Classes.ControlFile import ControlFile74 #from Classes.ControlFile import ControlFile 78 75 79 76 -
Source/Pythontest/TestInput.py
rba99230 r76c37a9 1 #!/usr/bin/env python 1 #!/usr/bin/env python3 2 2 # -*- coding: utf-8 -*- 3 3 … … 6 6 import pytest 7 7 8 sys.path.append('../ python')9 from classes.ControlFile import ControlFile10 from mods.tools import get_cmdline_arguments8 sys.path.append('../Python') 9 from Classes.ControlFile import ControlFile 10 from Mods.tools import get_cmdline_args 11 11 12 12 … … 21 21 # 2. check of parameter 22 22 23 def __init__(self): 23 @classmethod 24 def setup_class(self): 24 25 # Default values for ArgumentParser 25 26 self.args = {'start_date':None, … … 36 37 'job_template':'job.temp', 37 38 'queue':None, 38 'controlfile':'CONTROL.te mp',39 'controlfile':'CONTROL.test', 39 40 'debug':0, 40 41 } … … 43 44 sys.argv = ['dummy.py', '--start_date=20180101'] 44 45 45 self.args = tools.get_commandline_arguments()46 self.args = get_cmdline_args() 46 47 47 self.c = ControlFile(' TestData/CONTROL.temp')48 self.c = ControlFile('../../Testing/Regression/Unit/Testfiles/CONTROL.test') 48 49 49 50 self.c.assign_args_to_control(self.args) … … 57 58 '--step=0/to/11/BY/3', '--area=20./20./0./90.'] 58 59 59 arguments = tools.get_cmdline_arguments()60 arguments = get_cmdline_args() 60 61 61 62 args_exp = {'start_date':'20180101', … … 72 73 'job_template':'job.temp', 73 74 'queue':None, 74 'controlfile':'CONTROL.te mp',75 'controlfile':'CONTROL.test', 75 76 'debug':1, 76 77 } … … 89 90 'area': None, 90 91 'basetime': None, 91 'controlfile': 'CONTROL.te mp',92 'controlfile': 'CONTROL.test', 92 93 'cwc': 0, 93 94 'date_chunk': 3, … … 158 159 159 160 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 2 2 # -*- coding: utf-8 -*- 3 3 … … 11 11 import shutil 12 12 from genshi.template import TemplateLoader 13 from genshi.template.eval import UndefinedError 14 from exceptions import OSError 13 from genshi.template.eval import UndefinedError 14 15 try: 16 import exceptions 17 except ImportError: 18 import builtins 15 19 import pytest 16 20 from mock import patch 17 21 18 sys.path.append('../ python')22 sys.path.append('../Python') 19 23 import _config 20 import _config_test24 from . import _config_test 21 25 from install import (mk_tarball, un_tarball, mk_env_vars, mk_compilejob, 22 26 mk_job_template) 23 27 24 from mods.tools import make_dir, silent_remove28 from Mods.tools import make_dir, silent_remove 25 29 26 30 # - main … … 44 48 45 49 # un tar the test tarballs from shell script 46 subprocess.check_output([os.path.join(self.testinstalldir,47 50 # subprocess.check_output([os.path.join(self.testinstalldir, 51 # 'un_install_tar.sh')]) 48 52 49 53 … … 56 60 tarballname = _config.FLEXEXTRACT_DIRNAME + '_localtest.tar' 57 61 58 with pytest.raises(SystemExit):59 mk_tarball(ecd + tarballname, 'local')60 62 with pytest.raises(SystemExit): 61 63 mk_tarball(ecd + tarballname, 'local') … … 78 80 79 81 # remove test tar file from flex_extract directory 80 os.remove(ecd + tarballname)82 #os.remove(ecd + tarballname) 81 83 82 84 # test if comparison filelist is equal to the … … 310 312 test_dir = os.path.join(self.testinstalldir, 311 313 _config.FLEXEXTRACT_DIRNAME + '_local') 312 shutil.rmtree(test_dir)314 # shutil.rmtree(test_dir) 313 315 test_dir = os.path.join(self.testinstalldir, 314 316 _config.FLEXEXTRACT_DIRNAME + '_ecgate') 315 shutil.rmtree(test_dir)317 # shutil.rmtree(test_dir) 316 318 317 319 test_dir = os.path.join(self.testinstalldir, 318 320 'test_local') 319 shutil.rmtree(test_dir)321 # shutil.rmtree(test_dir) 320 322 test_dir = os.path.join(self.testinstalldir, 321 323 'test_ecgate') 322 shutil.rmtree(test_dir)324 # shutil.rmtree(test_dir) 323 325 324 326 tar_file = os.path.join(self.testinstalldir, 325 327 _config.FLEXEXTRACT_DIRNAME + '_local.tar') 326 os.remove(tar_file)328 # os.remove(tar_file) 327 329 tar_file = os.path.join(self.testinstalldir, 328 330 _config.FLEXEXTRACT_DIRNAME + '_ecgate.tar') 329 os.remove(tar_file)331 # os.remove(tar_file) 330 332 pass -
Source/Pythontest/TestTools.py
rba99230 r76c37a9 7 7 import sys 8 8 import errno 9 from exceptions import OSError9 #from exceptions import OSError 10 10 import subprocess 11 11 import pipes 12 13 try: 14 import exceptions 15 except ImportError: 16 import builtins 17 12 18 import pytest 13 19 from mock import patch, call … … 16 22 17 23 import _config 18 import _config_test19 from classes.ControlFile import ControlFile20 from mods.tools import (none_or_str, none_or_int, get_cmdline_arguments,24 from . import _config_test 25 from Classes.ControlFile import ControlFile 26 from Mods.tools import (none_or_str, none_or_int, get_cmdline_args, 21 27 read_ecenv, clean_up, my_error, send_mail, 22 28 normal_exit, product, silent_remove, … … 25 31 26 32 class TestTools(object): 27 ''' 28 ''' 33 """Test the tools module.""" 29 34 30 35 def setup_method(self): … … 48 53 sys.argv = ['dummy.py', '--wrong=1'] 49 54 with pytest.raises(SystemExit): 50 results = get_cmdline_arg uments()55 results = get_cmdline_args() 51 56 52 57 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} 70 78 71 79 sys.argv = ['dummy.py'] 72 80 73 results = get_cmdline_arg uments()81 results = get_cmdline_args() 74 82 75 83 assert cmd_dict_control == vars(results) 76 84 77 85 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} 95 105 96 106 sys.argv = ['dummy.py', … … 104 114 '--inputdir=../work', 105 115 '--outputdir=None', 106 '--flexpart_root_scripts=../',107 116 '--ppid=1234', 108 117 '--job_template=job.sh', … … 111 120 '--debug=1', 112 121 '--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() 116 128 117 129 assert cmd_dict_control == vars(results) … … 121 133 expected_sample = {'078': 'TCLW', '130': 'T', '034': 'SST'} 122 134 # 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)]) 127 139 def test_fail_open_init128(self, mock_openfile): 128 140 with pytest.raises(SystemExit): … … 145 157 146 158 @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) 148 160 def test_success_my_error(self, mock_mail, mock_trace, capfd): 149 161 with pytest.raises(SystemExit): 150 my_error( ['any_user'],'Failed!')162 my_error('Failed!') 151 163 out, err = capfd.readouterr() 152 164 assert out == "Failed!\n\nempty_trace\n" … … 160 172 send_mail(['${USER}', 'any_user'], 'ERROR', message='error mail') 161 173 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' 163 175 164 176 @patch('subprocess.Popen') … … 169 181 send_mail(['any-user'], 'ERROR', message='error mail') 170 182 out, err = capfd.readouterr() 171 assert out == b'Email sent to any_user\n'183 assert out == 'Email sent to any_user\n' 172 184 173 185 @patch('subprocess.Popen', side_effect=[ValueError, OSError]) … … 189 201 assert envs_ref == envs 190 202 191 @patch(' __builtin__.open', side_effect=[OSError(errno.EPERM)])203 @patch('builtins.open', side_effect=[OSError(errno.EPERM)]) 192 204 def test_fail_read_ecenv(self, mock_open): 193 205 with pytest.raises(SystemExit): … … 195 207 196 208 @patch('glob.glob', return_value=[]) 197 @patch(' mods.tools.silent_remove')209 @patch('Mods.tools.silent_remove') 198 210 def test_empty_clean_up(self, mock_rm, mock_clean): 199 211 clean_up(self.c) … … 203 215 @patch('os.remove', return_value=0) 204 216 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 211 218 self.c.prefix = 'EI' 212 219 self.c.ecapi = False … … 215 222 mock_rm.reset_mock() 216 223 217 # ectrans=0; ecstorage=0; ecapi=True; prefix in filename218 self.c.prefix = 'EI'219 self.c.ecapi = True220 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 filename225 self.c.prefix = 'EI'226 self.c.ecapi = True227 self.c.ectrans = 1228 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 filename233 self.c.prefix = 'EI'234 self.c.ecapi = False235 self.c.ectrans = 1236 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 filename241 self.c.prefix = 'EI'242 self.c.ecapi = False243 self.c.ectrans = 1244 self.c.ecstorage = 1245 clean_up(self.c)246 mock_rm.assert_has_calls([call('any_file'), call('EIfile')])247 mock_rm.reset_mock()248 224 249 225 def test_default_normal_exit(self, capfd): -
Source/Pythontest/TestUIOFiles.py
rba99230 r76c37a9 5 5 import sys 6 6 import pytest 7 from mock import patch 7 8 8 sys.path.append('../python') 9 from classes.UioFiles import UioFiles 9 from . import _config_test 10 sys.path.append('../Python') 11 12 from Classes.UioFiles import UioFiles 10 13 11 14 12 15 class 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') 16 24 17 25 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'] 21 35 22 @Input:23 self: instance of TestClass24 Class to test the UIOFiles methods.25 26 @Return:27 <nothing>28 '''29 # set comparison information30 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 filenames40 files = UioFiles(self.testpath, '*.grb')41 36 # 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] 43 38 # comparison of expected filenames against the collected ones 44 39 assert sorted(self.expected) == sorted(filelist) 45 40 46 return47 41 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 2 2 # -*- coding: utf-8 -*- 3 3 ''' … … 27 27 import sys 28 28 29 sys.path.append('../ python')29 sys.path.append('../Python') 30 30 import _config 31 31 … … 38 38 # DIRECTORY NAMES 39 39 # ------------------------------------------------------------------------------ 40 TEST_DIR = ' test/Unit'40 TEST_DIR = 'Testing/Regression/Unit' 41 41 TESTFILES_DIR = 'Testfiles' 42 42 TESTINSTALL_DIR = 'InstallTar' -
Source/Pythontest/conftest.py
rba99230 rd9abaac 2 2 import pytest 3 3 4 sys.path.append('../ python')4 sys.path.append('../Python') 5 5 import _config 6 6 … … 8 8 #def prep_test_env(): 9 9 # testdir = _config.PATH_TEST_DIR 10 print ''10 print('')
Note: See TracChangeset
for help on using the changeset viewer.