- Timestamp:
- Sep 20, 2018, 11:56:37 AM (6 years ago)
- Branches:
- master, ctbto, dev
- Children:
- 5d42acd
- Parents:
- 3232589
- Location:
- python
- Files:
-
- 68 added
- 1 deleted
- 12 edited
- 1 moved
Legend:
- Unmodified
- Added
- Removed
-
python/ControlFile.py
r54a8a01 r2fb99de 53 53 # ------------------------------------------------------------------------------ 54 54 import os 55 import re 55 56 import sys 56 57 import inspect 58 59 import _config 57 60 58 61 # ------------------------------------------------------------------------------ … … 110 113 self.stream = None 111 114 self.number = 'OFF' 112 self.expver = None115 self.expver = '1' 113 116 self.grid = None 114 117 self.area = '' … … 142 145 self.inputdir = '../work' 143 146 self.outputdir = self.inputdir 144 self.ecmwfdatadir = None145 self.exedir = None147 self.ecmwfdatadir = _config.PATH_FLEXEXTRACT_DIR 148 self.exedir = _config.PATH_FORTRAN_SRC 146 149 self.flexpart_root_scripts = None 147 self.makefile = None150 self.makefile = 'Makefile.gfortran' 148 151 self.destination = None 149 152 self.gateway = None … … 152 155 self.install_target = None 153 156 self.debug = 0 157 self.request = 0 158 159 self.logicals = ['gauss', 'omega', 'omegadiff', 'eta', 'etadiff', 160 'dpdeta', 'cwc', 'wrf', 'grib2flexpart', 'ecstorage', 161 'ectrans', 'debug', 'request'] 154 162 155 163 self.__read_controlfile__() … … 172 180 173 181 # read whole CONTROL file 174 with open(self.controlfile) as f: 182 with open(os.path.join(_config.PATH_CONTROLFILES, 183 self.controlfile)) as f: 175 184 fdata = f.read().split('\n') 176 185 … … 222 231 pass 223 232 224 # script directory225 self.ecmwfdatadir = os.path.dirname(os.path.abspath(inspect.getfile(226 inspect.currentframe()))) + '/../'227 228 # Fortran source directory229 self.exedir = self.ecmwfdatadir + 'src/'230 231 233 return 232 234 … … 310 312 return 311 313 312 def check_conditions(self ):314 def check_conditions(self, queue): 313 315 ''' 314 316 @Description: … … 321 323 Description see class documentation. 322 324 325 queue: string 326 Name of the queue if submitted to the ECMWF servers. 327 Used to check if ecuid, ecgid, gateway and destination 328 are set correctly and are not empty. 329 323 330 @Return: 324 331 <nothing> … … 330 337 # otherwise program is not allowed to run 331 338 if self.start_date is None: 332 print 'start_date specified neither in command line nor ' +\333 'in CONTROL file ' + self.controlfile334 print 'Try "' + sys.argv[0].split('/')[-1] + \335 ' -h" to print usage information' 339 print('start_date specified neither in command line nor \ 340 in CONTROL file ' + self.controlfile) 341 print('Try "' + sys.argv[0].split('/')[-1] + 342 ' -h" to print usage information') 336 343 sys.exit(1) 337 344 … … 341 348 342 349 # assure consistency of levelist and level 343 if self.levelist is None: 344 if self.level is None: 345 print 'Warning: neither levelist nor level ' + \ 346 'specified in CONTROL file' 347 sys.exit(1) 350 if self.levelist is None and self.level is None: 351 print('Warning: neither levelist nor level \ 352 specified in CONTROL file') 353 sys.exit(1) 354 elif self.levelist is None and self.level: 355 self.levelist = '1/to/' + self.level 356 elif (self.levelist and self.level is None) or \ 357 (self.levelist[-1] != self.level[-1]): 358 self.level = self.levelist.split('/')[-1] 359 else: 360 pass 361 362 # if area was provided (only from commandline) 363 # decompose area into its 4 components 364 if self.area: 365 components = self.area.split('/') 366 # convert float to integer coordinates 367 if '.' in self.area: 368 components = [str(int(float(item) * 1000)) 369 for i, item in enumerate(components)] 370 self.upper, self.left, self.lower, self.right = components 371 372 # prepare step list if "/" signs are found 373 if '/' in self.step: 374 steps = self.step.split('/') 375 if 'to' in self.step.lower() and 'by' in self.step.lower(): 376 ilist = np.arange(int(steps[0]), 377 int(steps[2]) + 1, 378 int(steps[4])) 379 self.step = ['{:0>3}'.format(i) for i in ilist] 380 elif 'to' in self.step.lower() and 'by' not in self.step.lower(): 381 my_error(self.mailfail, self.step + ':\n' + 382 'if "to" is used in steps parameter, \ 383 please use "by" as well') 348 384 else: 349 self.levelist = '1/to/' + self.level 350 else: 351 if 'to' in self.levelist.lower(): 352 self.level = self.levelist.split('/')[2] 353 else: 354 self.level = self.levelist.split('/')[-1] 355 356 # if area was provided at command line 357 # decompse area into its 4 components 358 if self.area: 359 afloat = '.' in self.area 360 l = self.area.split('/') 361 if afloat: 362 for i, item in enumerate(l): 363 item = str(int(float(item) * 1000)) 364 self.upper, self.left, self.lower, self.right = l 365 366 # prepare step for correct usage 367 if '/' in self.step: 368 l = self.step.split('/') 369 if 'to' in self.step.lower(): 370 if 'by' in self.step.lower(): 371 ilist = np.arange(int(l[0]), int(l[2]) + 1, int(l[4])) 372 self.step = ['{:0>3}'.format(i) for i in ilist] 373 else: 374 my_error(self.mailfail, self.step + ':\n' + 375 'if "to" is used, please use "by" as well') 376 else: 377 self.step = l 385 self.step = steps 378 386 379 387 # if maxstep wasn't provided … … 407 415 self.mailops = [self.mailops] 408 416 409 if not self.gateway or not self.destination or \ 417 if queue in ['ecgate', 'cca'] and \ 418 not self.gateway or not self.destination or \ 410 419 not self.ecuid or not self.ecgid: 411 print '\nEnvironment variables GATWAY, DESTINATION, ECUID and ' +\412 'ECGID were not set properly!'413 print 'Please check for excistence of file "ECMWF_ENV" in the ' +\414 'python directory!'420 print('\nEnvironment variables GATEWAY, DESTINATION, ECUID and \ 421 ECGID were not set properly!') 422 print('Please check for existence of file "ECMWF_ENV" in the \ 423 python directory!') 415 424 sys.exit(1) 425 426 if self.request != 0: 427 marsfile = os.path.join(_config.PATH_RUN_DIR, 428 _config.FILE_MARS_REQUESTS) 429 if os.path.isfile(marsfile): 430 os.remove(marsfile) 431 432 # check all logical variables for data type 433 # if its a string change to integer 434 for var in self.logicals: 435 if not isinstance(getattr(self, var), int): 436 setattr(self, var, int(getattr(self, var))) 416 437 417 438 return … … 434 455 if self.install_target and \ 435 456 self.install_target not in ['local', 'ecgate', 'cca']: 436 print 'ERROR: unknown or missing installation target '437 print 'target: ', self.install_target438 print 'please specify correct installation target \439 (local | ecgate | cca)'440 print 'use -h or --help for help'457 print('ERROR: unknown or missing installation target ') 458 print('target: ', self.install_target) 459 print('please specify correct installation target ' + 460 '(local | ecgate | cca)') 461 print('use -h or --help for help') 441 462 sys.exit(1) 442 463 … … 444 465 if not self.ecgid or not self.ecuid or \ 445 466 not self.gateway or not self.destination: 446 print 'Please enter your ECMWF user id and group id as well as \447 the \nname of the local gateway and the ectrans \448 destination '449 print 450 --gateway --destination' 451 print 452 ' -h" to print usage information' 453 print 454 support for further details' 467 print('Please enter your ECMWF user id and group id as well ' + 468 'as the \nname of the local gateway and the ectrans ' + 469 'destination ') 470 print('with command line options --ecuid --ecgid \ 471 --gateway --destination') 472 print('Try "' + sys.argv[0].split('/')[-1] + \ 473 ' -h" to print usage information') 474 print('Please consult ecaccess documentation or ECMWF user \ 475 support for further details') 455 476 sys.exit(1) 456 477 … … 459 480 else: 460 481 self.flexpart_root_scripts = self.flexpart_root_scripts 461 else: 482 else: # local 462 483 if not self.flexpart_root_scripts: 463 self.flexpart_root_scripts = '../' 464 465 if not self.makefile: 466 self.makefile = 'Makefile.gfortran' 484 self.flexpart_root_scripts = _config.PATH_FLEXEXTRACT_DIR 467 485 468 486 return -
python/EcFlexpart.py
rdda0e9d r2fb99de 102 102 103 103 # software specific classes and modules from flex_extract 104 import _config 104 105 from GribTools import GribTools 105 106 from tools import init128, to_param_id, silent_remove, product, my_error … … 204 205 self.accuracy = c.accuracy 205 206 self.level = c.level 206 207 if c.levelist: 208 self.levelist = c.levelist 209 else: 210 self.levelist = '1/to/' + c.level 211 207 self.expver = c.expver 212 208 # for gaussian grid retrieval 213 209 self.glevelist = '1/to/' + c.level … … 217 213 else: 218 214 self.gaussian = '' 219 220 if hasattr(c, 'expver') and c.expver:221 self.expver = c.expver222 else:223 self.expver = '1'224 225 if hasattr(c, 'number') and c.number:226 self.number = c.number227 else:228 self.number = '0'229 215 230 216 if 'N' in c.grid: # Gaussian output grid … … 250 236 # 4) Download also data for WRF 251 237 252 253 238 # Different grids need different retrievals 254 239 # SH = Spherical Harmonics, GG = Gaussian Grid, … … 274 259 self.params['OG__ML'] = ['T/Q', 'ML', self.levelist, self.grid] 275 260 276 if c.gauss == '0' and c.eta == '1': 261 #if c.gauss == '0' and c.eta == '1': 262 if not c.gauss and c.eta: 277 263 # the simplest case 278 264 self.params['OG__ML'][0] += '/U/V/77' 279 elif c.gauss == '0' and c.eta == '0': 265 #elif c.gauss == '0' and c.eta == '0': 266 elif not c.gauss and not c.eta: 280 267 # this is not recommended (inaccurate) 281 268 self.params['OG__ML'][0] += '/U/V' 282 elif c.gauss == '1' and c.eta == '0': 269 #elif c.gauss == '1' and c.eta == '0': 270 elif c.gauss and not c.eta: 283 271 # this is needed for data before 2008, or for reanalysis data 284 272 self.params['GG__SL'] = ['Q', 'ML', '1', \ … … 286 274 self.params['SH__ML'] = ['U/V/D', 'ML', self.glevelist, 'OFF'] 287 275 else: 288 print 289 use only for debugging!'276 print('Warning: This is a very costly parameter combination, \ 277 use only for debugging!') 290 278 self.params['GG__SL'] = ['Q', 'ML', '1', \ 291 279 '{}'.format((int(self.resol) + 1) / 2)] … … 293 281 '{}'.format((int(self.resol) + 1) / 2)] 294 282 295 if hasattr(c, 'omega') and c.omega == '1':283 if c.omega: 296 284 self.params['OG__ML'][0] += '/W' 297 285 298 286 # add cloud water content if necessary 299 if hasattr(c, 'cwc') and c.cwc == '1':287 if c.cwc: 300 288 self.params['OG__ML'][0] += '/CLWC/CIWC' 301 289 302 290 # add vorticity and geopotential height for WRF if necessary 303 if hasattr(c, 'wrf') and c.wrf == '1':291 if c.wrf: 304 292 self.params['OG__ML'][0] += '/Z/VO' 305 293 if '/D' not in self.params['OG__ML'][0]: … … 367 355 f.write('&NAMGEN\n') 368 356 f.write(',\n '.join(['maxl = ' + str(maxl), 'maxb = ' + str(maxb), 369 'mlevel = ' + self.level, 370 'mlevelist = ' + '"' + self.levelist + '"', 371 'mnauf = ' + self.resol, 357 'mlevel = ' + str(self.level), 358 'mlevelist = ' + '"' + str(self.levelist) 359 + '"', 360 'mnauf = ' + str(self.resol), 372 361 'metapar = ' + '77', 373 362 'rlo0 = ' + str(area[1]), … … 375 364 'rla0 = ' + str(area[2]), 376 365 'rla1 = ' + str(area[0]), 377 'momega = ' + c.omega,378 'momegadiff = ' + c.omegadiff,379 'mgauss = ' + c.gauss,380 'msmooth = ' + c.smooth,381 'meta = ' + c.eta,382 'metadiff = ' + c.etadiff,383 'mdpdeta = ' + c.dpdeta]))366 'momega = ' + str(c.omega), 367 'momegadiff = ' + str(c.omegadiff), 368 'mgauss = ' + str(c.gauss), 369 'msmooth = ' + str(c.smooth), 370 'meta = ' + str(c.eta), 371 'metadiff = ' + str(c.etadiff), 372 'mdpdeta = ' + str(c.dpdeta)])) 384 373 385 374 f.write('\n/\n') … … 387 376 return 388 377 389 def retrieve(self, server, dates, inputdir='.'):378 def retrieve(self, server, dates, request, inputdir='.'): 390 379 ''' 391 380 @Description: … … 437 426 pass 438 427 if pk == 'OG_OROLSM__SL': 439 if oro is False:428 if not oro: 440 429 mfstream = 'OPER' 441 430 mftype = 'AN' … … 457 446 458 447 # ------ on demand path -------------------------------------------------- 459 if self.basetime is None:448 if not self.basetime: 460 449 MR = MarsRetrieval(self.server, 461 450 marsclass=self.marsclass, … … 477 466 param=pv[0]) 478 467 479 MR.display_info() 480 MR.data_retrieve() 468 if request == 0: 469 MR.display_info() 470 MR.data_retrieve() 471 elif request == 1: 472 MR.print_info() 473 elif request == 2: 474 MR.print_info() 475 MR.display_info() 476 MR.data_retrieve() 477 else: 478 print('Failure') 481 479 # ------ operational path ------------------------------------------------ 482 480 else: … … 566 564 567 565 MR.display_info() 566 568 567 MR.data_retrieve() 569 568 # -------------- non flux data ------------------------ … … 662 661 MR.data_retrieve() 663 662 664 print "MARS retrieve done... " 663 if request == 0 or request == 2: 664 print('MARS retrieve done ... ') 665 elif request == 1: 666 print('MARS request printed ...') 665 667 666 668 return … … 702 704 ''' 703 705 704 print '\n\nPostprocessing:\n Format: {}\n'.format(c.format)705 706 if c.ecapi is False:706 print('\n\nPostprocessing:\n Format: {}\n'.format(c.format)) 707 708 if not c.ecapi: 707 709 print('ecstorage: {}\n ecfsdir: {}\n'. 708 710 format(c.ecstorage, c.ecfsdir)) 709 if not hasattr(c, 'gateway'):710 c.gateway = os.getenv('GATEWAY')711 if not hasattr(c, 'destination'):712 c.destination = os.getenv('DESTINATION')711 #if not hasattr(c, 'gateway'): 712 # c.gateway = os.getenv('GATEWAY') 713 #if not hasattr(c, 'destination'): 714 # c.destination = os.getenv('DESTINATION') 713 715 print('ectrans: {}\n gateway: {}\n destination: {}\n ' 714 716 .format(c.ectrans, c.gateway, c.destination)) 715 717 716 print 'Output filelist: \n'717 print self.outputfilelist718 print('Output filelist: \n') 719 print(self.outputfilelist) 718 720 719 721 if c.format.lower() == 'grib2': … … 724 726 p = subprocess.check_call(['mv', ofile + '_2', ofile]) 725 727 726 if int(c.ectrans) == 1 and c.ecapi is False:728 if c.ectrans and not c.ecapi: 727 729 for ofile in self.outputfilelist: 728 730 p = subprocess.check_call(['ectrans', '-overwrite', '-gateway', … … 731 733 #print('ectrans:', p) 732 734 733 if int(c.ecstorage) == 1 and c.ecapi is False:735 if c.ecstorage and not c.ecapi: 734 736 for ofile in self.outputfilelist: 735 737 p = subprocess.check_call(['ecp', '-o', ofile, … … 742 744 # prepare environment for the grib2flexpart run 743 745 # to convert grib to flexpart binary 744 if c.grib2flexpart == '1':746 if c.grib2flexpart: 745 747 746 748 # generate AVAILABLE file … … 858 860 859 861 index_keys = ["date", "time", "step"] 860 indexfile = c.inputdir + "/date_time_stepRange.idx"862 indexfile = os.path.join(c.inputdir, _config.FILE_GRIB_INDEX) 861 863 silent_remove(indexfile) 862 864 grib = GribTools(inputfiles.files) … … 868 870 for key in index_keys: 869 871 index_vals.append(grib_index_get(iid, key)) 870 print index_vals[-1]872 print(index_vals[-1]) 871 873 # index_vals looks for example like: 872 874 # index_vals[0]: ('20171106', '20171107', '20171108') ; date … … 878 880 879 881 for prod in product(*index_vals): 882 # e.g. prod = ('20170505', '0', '12') 883 # ( date ,time, step) 884 # per date e.g. time = 0, 1200 885 # per time e.g. step = 3, 6, 9, 12 880 886 # flag for Fortran program CONVERT2 and file merging 881 887 convertFlag = False 882 print 'current prod: ', prod888 print('current prod: ', prod) 883 889 # e.g. prod = ('20170505', '0', '12') 884 890 # ( date ,time, step) … … 902 908 # they are just valid for a single product 903 909 for k, f in fdict.iteritems(): 904 silent_remove(c.inputdir + "/fort." + k) 905 fdict[k] = open(c.inputdir + '/fort.' + k, 'w') 910 fortfile = os.path.join(c.inputdir, 'fort.' + k) 911 silent_remove(fortfile) 912 fdict[k] = open(fortfile, 'w') 906 913 907 914 cdate = str(grib_get(gid, 'date')) … … 931 938 if timestamp < slimit or timestamp > elimit: 932 939 continue 940 else: 941 pass 933 942 934 943 try: 935 if c.wrf == '1': 936 if 'olddate' not in locals(): 937 fwrf = open(c.outputdir + '/WRF' + cdate + 938 '.{:0>2}'.format(time) + '.000.grb2', 'w') 944 if c.wrf: 945 if 'olddate' not in locals() or cdate != olddate: 946 fwrf = open(os.path.join(c.outputdir, 947 'WRF' + cdate + '.{:0>2}'.format(time) + 948 '.000.grb2'), 'w') 939 949 olddate = cdate[:] 940 else:941 if cdate != olddate:942 fwrf = open(c.outputdir + '/WRF' + cdate +943 '.{:0>2}'.format(time) + '.000.grb2',944 'w')945 olddate = cdate[:]946 950 except AttributeError: 947 951 pass 948 952 949 # helper variable to remember which fields are already used.953 # helper variable to remember which fields were already used. 950 954 savedfields = [] 951 955 while 1: … … 958 962 # Specific humidity (Q.grb) is used as a template only 959 963 # so we need the first we "meet" 960 with open( c.inputdir + '/fort.18', 'w') as fout:964 with open(os.path.join(c.inputdir, 'fort.18'), 'w') as fout: 961 965 grib_write(gid, fout) 962 966 elif paramId == 131 or paramId == 132: … … 971 975 grib_write(gid, fdict['13']) 972 976 elif paramId in [129, 138, 155] and levtype == 'hybrid' \ 973 and c.wrf == '1':977 and c.wrf: 974 978 pass 975 979 elif paramId == 246 or paramId == 247: … … 991 995 savedfields.append(paramId) 992 996 else: 993 print 'duplicate ' + str(paramId) + ' not written'997 print('duplicate ' + str(paramId) + ' not written') 994 998 995 999 try: 996 if c.wrf == '1': 997 if levtype == 'hybrid': # model layer 998 if paramId in [129, 130, 131, 132, 133, 138, 155]: 999 grib_write(gid, fwrf) 1000 else: # sfc layer 1001 if paramId in wrfpars: 1002 grib_write(gid, fwrf) 1000 if c.wrf: 1001 # model layer 1002 if levtype == 'hybrid' and \ 1003 paramId in [129, 130, 131, 132, 133, 138, 155]: 1004 grib_write(gid, fwrf) 1005 # sfc layer 1006 elif paramId in wrfpars: 1007 grib_write(gid, fwrf) 1003 1008 except AttributeError: 1004 1009 pass … … 1014 1019 pwd = os.getcwd() 1015 1020 os.chdir(c.inputdir) 1016 if os.stat('fort.21').st_size == 0 and int(c.eta) == 1:1017 print 1018 not available for this type or date/time\n' 1019 print 'Check parameters CLASS, TYPE, STREAM, START_DATE\n'1021 if os.stat('fort.21').st_size == 0 and c.eta: 1022 print('Parameter 77 (etadot) is missing, most likely it is \ 1023 not available for this type or date/time\n') 1024 print('Check parameters CLASS, TYPE, STREAM, START_DATE\n') 1020 1025 my_error(c.mailfail, 'fort.21 is empty while parameter eta \ 1021 1026 is set to 1 in CONTROL file') … … 1023 1028 # create the corresponding output file fort.15 1024 1029 # (generated by CONVERT2) + fort.16 (paramId 167 and 168) 1025 p = subprocess.check_call( 1026 [os.path.expandvars(os.path.expanduser(c.exedir)) + 1027 '/CONVERT2'], shell=True) 1030 p = subprocess.check_call([os.path.join(c.exedir, 'CONVERT2')], 1031 shell=True) 1028 1032 os.chdir(pwd) 1029 1033 1030 1034 # create final output filename, e.g. EN13040500 (ENYYMMDDHH) 1031 fnout = c.inputdir + '/' + c.prefix1035 fnout = os.path.join(c.inputdir, c.prefix) 1032 1036 if c.maxstep > 12: 1033 1037 suffix = cdate[2:8] + '.{:0>2}'.format(time/100) + \ … … 1036 1040 suffix = cdateH[2:10] 1037 1041 fnout += suffix 1038 print "outputfile = " + fnout1042 print("outputfile = " + fnout) 1039 1043 self.outputfilelist.append(fnout) # needed for final processing 1040 1044 … … 1044 1048 c.inputdir + '/OG_OROLSM__SL.*.' + c.ppid + '*')[0]) 1045 1049 fluxfile = 'flux' + cdate[0:2] + suffix 1046 if c.cwc != '1':1050 if not c.cwc: 1047 1051 flist = ['fort.15', fluxfile, 'fort.16', orolsm] 1048 1052 else: … … 1051 1055 with open(fnout, 'wb') as fout: 1052 1056 for f in flist: 1057 shutil.copyfileobj(open(os.path.join(c.inputdir, f), 1058 'rb'), fout) 1059 1060 if c.omega: 1061 with open(os.path.join(c.outputdir, 'OMEGA'), 'wb') as fout: 1053 1062 shutil.copyfileobj( 1054 open(c.inputdir + '/' + f, 'rb'), fout) 1055 1056 if c.omega == '1': 1057 with open(c.outputdir + '/OMEGA', 'wb') as fout: 1058 shutil.copyfileobj( 1059 open(c.inputdir + '/fort.25', 'rb'), fout) 1060 1061 if hasattr(c, 'wrf') and c.wrf == '1': 1063 open(os.path.join(c.inputdir, 'fort.25'), 1064 'rb'), fout) 1065 else: 1066 pass 1067 1068 if c.wrf: 1062 1069 fwrf.close() 1063 1070 … … 1102 1109 pars = to_param_id(self.params['OG_acc_SL'][0], table128) 1103 1110 index_keys = ["date", "time", "step"] 1104 indexfile = c.inputdir + "/date_time_stepRange.idx"1111 indexfile = os.path.join(c.inputdir, _config.FILE_GRIB_INDEX) 1105 1112 silent_remove(indexfile) 1106 1113 grib = GribTools(inputfiles.files) … … 1112 1119 for key in index_keys: 1113 1120 key_vals = grib_index_get(iid, key) 1114 print key_vals1121 print(key_vals) 1115 1122 # have to sort the steps for disaggregation, 1116 1123 # therefore convert to int first … … 1133 1140 stepsdict[str(p)] = [] 1134 1141 1135 print 'maxstep: ', c.maxstep1142 print('maxstep: ', c.maxstep) 1136 1143 1137 1144 for prod in product(*index_vals): … … 1140 1147 # per date e.g. time = 0, 1200 1141 1148 # per time e.g. step = 3, 6, 9, 12 1149 print('current prod: ', prod) 1142 1150 for i in range(len(index_keys)): 1143 1151 grib_index_select(iid, index_keys[i], prod[i]) 1144 1152 1153 # get first id from current product 1145 1154 gid = grib_new_from_index(iid) 1155 1156 # if there is data for this product combination 1157 # prepare some date and time parameter before reading the data 1146 1158 if gid is not None: 1147 1159 cdate = grib_get(gid, 'date') … … 1161 1173 1162 1174 if c.maxstep > 12: 1163 fnout = c.inputdir + '/flux' + \ 1164 sdate.strftime('%Y%m%d') + '.{:0>2}'.format(time/100) + \ 1165 '.{:0>3}'.format(step-2*int(c.dtime)) 1166 gnout = c.inputdir + '/flux' + \ 1167 sdate.strftime('%Y%m%d') + '.{:0>2}'.format(time/100) + \ 1168 '.{:0>3}'.format(step-int(c.dtime)) 1169 hnout = c.inputdir + '/flux' + \ 1170 sdate.strftime('%Y%m%d') + '.{:0>2}'.format(time/100) + \ 1171 '.{:0>3}'.format(step) 1172 g = open(gnout, 'w') 1173 h = open(hnout, 'w') 1175 fnout = os.path.join(c.inputdir, 'flux' + 1176 sdate.strftime('%Y%m%d') + 1177 '.{:0>2}'.format(time/100) + 1178 '.{:0>3}'.format(step-2*int(c.dtime))) 1179 gnout = os.path.join(c.inputdir, 'flux' + 1180 sdate.strftime('%Y%m%d') + 1181 '.{:0>2}'.format(time/100) + 1182 '.{:0>3}'.format(step-int(c.dtime))) 1183 hnout = os.path.join(c.inputdir, 'flux' + 1184 sdate.strftime('%Y%m%d') + 1185 '.{:0>2}'.format(time/100) + 1186 '.{:0>3}'.format(step)) 1174 1187 else: 1175 fnout = c.inputdir + '/flux' + fdate.strftime('%Y%m%d%H') 1176 gnout = c.inputdir + '/flux' + (fdate + 1177 timedelta(hours=int(c.dtime)) 1178 ).strftime('%Y%m%d%H') 1179 hnout = c.inputdir + '/flux' + sdates.strftime('%Y%m%d%H') 1180 g = open(gnout, 'w') 1181 h = open(hnout, 'w') 1182 1183 print "outputfile = " + fnout 1184 f = open(fnout, 'w') 1188 fnout = os.path.join(c.inputdir, 'flux' + 1189 fdate.strftime('%Y%m%d%H')) 1190 gnout = os.path.join(c.inputdir, 'flux' + 1191 (fdate + timedelta(hours=int(c.dtime))). 1192 strftime('%Y%m%d%H')) 1193 hnout = os.path.join(c.inputdir, 'flux' + 1194 sdates.strftime('%Y%m%d%H')) 1195 1196 print("outputfile = " + fnout) 1197 f_handle = open(fnout, 'w') 1198 g_handle = open(gnout, 'w') 1199 h_handle = open(hnout, 'w') 1185 1200 1186 1201 # read message for message and store relevant data fields … … 1243 1258 grib_set(gid, 'date', fdate.year*10000 + 1244 1259 fdate.month*100+fdate.day) 1245 grib_write(gid, f )1260 grib_write(gid, f_handle) 1246 1261 1247 1262 if c.basetime is not None: … … 1270 1285 truedatetime.month * 100 + 1271 1286 truedatetime.day) 1272 grib_write(gid, h )1287 grib_write(gid, h_handle) 1273 1288 1274 1289 #values = (svdp[1]+svdp[2])/2. … … 1285 1300 truedatetime.day) 1286 1301 grib_set_values(gid, values) 1287 grib_write(gid, g )1302 grib_write(gid, g_handle) 1288 1303 1289 1304 grib_release(gid) … … 1291 1306 gid = grib_new_from_index(iid) 1292 1307 1293 f .close()1294 g .close()1295 h .close()1308 f_handle.close() 1309 g_handle.close() 1310 h_handle.close() 1296 1311 1297 1312 grib_index_release(iid) -
python/GribTools.py
r54a8a01 r2fb99de 297 297 Grib index id. 298 298 ''' 299 print "... index will be done"299 print("... index will be done") 300 300 iid = None 301 301 302 302 if os.path.exists(index_file): 303 303 iid = grib_index_read(index_file) 304 print "Use existing index file: %s " % (index_file)304 print("Use existing index file: %s " % (index_file)) 305 305 else: 306 306 for filename in self.filenames: 307 print "Inputfile: %s " % (filename)307 print("Inputfile: %s " % (filename)) 308 308 if iid is None: 309 309 iid = grib_index_new_from_file(filename, index_keys) … … 314 314 grib_index_write(iid, index_file) 315 315 316 print '... index done'316 print('... index done') 317 317 318 318 return iid -
python/MarsRetrieval.py
r54a8a01 r2fb99de 65 65 import os 66 66 67 import _config 67 68 # ------------------------------------------------------------------------------ 68 69 # CLASS … … 310 311 ''' 311 312 @Description: 312 Prints all class attributes and their values. 313 Prints all class attributes and their values to the 314 standard output. 313 315 314 316 @Input: … … 328 330 pass 329 331 else: 330 print item[0] + ': ' + str(item[1]) 332 print(item[0] + ': ' + str(item[1])) 333 334 return 335 336 337 def print_info(self): 338 ''' 339 @Description: 340 Prints all mars requests to an extra file for debugging and 341 information. 342 343 @Input: 344 self: instance of MarsRetrieval 345 For description see class documentation. 346 347 @Return: 348 <nothing> 349 ''' 350 # Get all class attributes and their values as a dictionary 351 attrs = vars(self) 352 353 # open a file to store all requests to 354 with open(os.path.join(_config.PATH_RUN_DIR, 355 _config.FILE_MARS_REQUESTS), 'a') as f: 356 f.write('mars\n') 357 # iterate through all attributes and print them 358 # with their corresponding values 359 for item in attrs.items(): 360 if item[0] in 'server': 361 pass 362 else: 363 f.write(item[0] + ': ' + str(item[1]) + '\n') 364 f.write('\n\n') 331 365 332 366 return … … 371 405 self.server.execute(s, target) 372 406 except: 373 print 374 have you already registered at apps.ecmwf.int?'407 print('MARS Request failed, \ 408 have you already registered at apps.ecmwf.int?') 375 409 raise IOError 376 410 if os.stat(target).st_size == 0: 377 print 'MARS Request returned no data - please check request'411 print('MARS Request returned no data - please check request') 378 412 raise IOError 379 413 # MARS request via extra process in shell … … 384 418 stderr=subprocess.PIPE, bufsize=1) 385 419 pout = p.communicate(input=s)[0] 386 print pout.decode()420 print(pout.decode()) 387 421 388 422 if 'Some errors reported' in pout.decode(): 389 print 'MARS Request failed - please check request'423 print('MARS Request failed - please check request') 390 424 raise IOError 391 425 392 426 if os.stat(target).st_size == 0: 393 print 'MARS Request returned no data - please check request'427 print('MARS Request returned no data - please check request') 394 428 raise IOError 395 429 -
python/_config.py
r222aa11 r2fb99de 28 28 _VERSION_STR = '7.1' 29 29 30 # add path to pythonpath 30 # ------------------------------------------------------------------------------ 31 # FILENAMES 32 # ------------------------------------------------------------------------------ 33 34 FLEXEXTRACT_DIRNAME = 'flex_extract_v' + _VERSION_STR 35 FILE_MARS_REQUESTS = 'mars_requests.dat' 36 FORTRAN_EXECUTABLE = 'CONVERT2' 37 FILE_USER_ENVVARS = 'ECMWF_ENV' 38 TEMPFILE_INSTALL_COMPILEJOB = 'compilejob.temp' 39 FILE_INSTALL_COMPILEJOB = 'compilejob.ksh' 40 TEMPFILE_INSTALL_JOB = 'job.temp.o' 41 TEMPFILE_JOB = 'job.temp' 42 FILE_JOB_OD = 'job.ksh' 43 FILE_JOB_OP = 'jopoper.ksh' 44 FILE_NAMELIST = 'fort.4' 45 FILE_GRIB_INDEX = 'date_time_stepRange.idx' 46 47 # ------------------------------------------------------------------------------ 48 # PATHES 49 # ------------------------------------------------------------------------------ 50 51 # path to the flex_extract directory 52 PATH_FLEXEXTRACT_DIR = os.path.normpath(os.path.dirname(os.path.abspath( 53 inspect.getfile(inspect.currentframe()))) + '/../') 54 55 # path to the local python source files 31 56 PATH_LOCAL_PYTHON = os.path.dirname(os.path.abspath( 32 57 inspect.getfile(inspect.currentframe()))) 58 PATH_RELATIVE_PYTHON = os.path.relpath(PATH_LOCAL_PYTHON, PATH_FLEXEXTRACT_DIR) 59 # add path to pythonpath 33 60 if PATH_LOCAL_PYTHON not in sys.path: 34 61 sys.path.append(PATH_LOCAL_PYTHON) 35 62 36 PATH_FLEXEXTRACT_DIR = os.path.normpath(os.path.dirname(os.path.abspath( 37 inspect.getfile(inspect.currentframe()))) + '/../') 63 # path to the templates 64 PATH_TEMPLATES = os.path.join(PATH_FLEXEXTRACT_DIR, '_templates') 65 PATH_RELATIVE_TEMPLATES = os.path.relpath(PATH_TEMPLATES, PATH_FLEXEXTRACT_DIR) 38 66 39 PATH_TEMPLATES = os.path.join(PATH_FLEXEXTRACT_DIR + os.path.sep + 40 '_templates') 67 # path to the environment parameter file 68 PATH_ECMWF_ENV = os.path.join(PATH_LOCAL_PYTHON, FILE_USER_ENVVARS) 69 PATH_RELATIVE_ECMWF_ENV = os.path.relpath(PATH_ECMWF_ENV, PATH_FLEXEXTRACT_DIR) 41 70 42 71 # path to gribtable 43 PATH_GRIBTABLE = os.path.join(PATH_TEMPLATES + os.path.sep + 44 'ecmwf_grib1_table_128') 72 PATH_GRIBTABLE = os.path.join(PATH_TEMPLATES, 'ecmwf_grib1_table_128') 45 73 46 PATH_RUN_DIR = os.path.join(PATH_FLEXEXTRACT_DIR + os.path.sep + 47 'run') 74 # path to run directory 75 PATH_RUN_DIR = os.path.join(PATH_FLEXEXTRACT_DIR, 'run') 76 PATH_RELATIVE_RUN_DIR = os.path.relpath(PATH_RUN_DIR, PATH_FLEXEXTRACT_DIR) 48 77 49 PATH_CONTROLFILES = os.path.join(PATH_RUN_DIR + os.path.sep + 50 'control') 78 # path to directory where all control files are stored 79 PATH_CONTROLFILES = os.path.join(PATH_RUN_DIR, 'control') 80 PATH_RELATIVE_CONTROLFILES = os.path.relpath(PATH_CONTROLFILES, PATH_FLEXEXTRACT_DIR) 81 82 # path to directory where all job scripts are stored 83 PATH_JOBSCRIPTS = os.path.join(PATH_RUN_DIR, 'jobscripts') 84 PATH_RELATIVE_JOBSCRIPTS = os.path.relpath(PATH_JOBSCRIPTS, PATH_FLEXEXTRACT_DIR) 85 86 # path to the fortran executable and the source code 87 PATH_FORTRAN_SRC = os.path.join(PATH_FLEXEXTRACT_DIR, 'src') 88 PATH_RELATIVE_FORTRAN_SRC = os.path.relpath(PATH_FORTRAN_SRC, PATH_FLEXEXTRACT_DIR) 89 90 # path to the python testing directory 91 PATH_TEST_DIR = os.path.join(PATH_LOCAL_PYTHON, 'pythontest') 92 -
python/get_mars_data.py
r54a8a01 r2fb99de 57 57 58 58 # software specific classes and modules from flex_extract 59 import _config 59 60 from tools import my_error, normal_exit, get_cmdline_arguments, read_ecenv 60 61 from EcFlexpart import EcFlexpart 61 62 from UioFiles import UioFiles 62 63 # add path to pythonpath so that python finds its buddies64 LOCAL_PYTHON_PATH = os.path.dirname(os.path.abspath(65 inspect.getfile(inspect.currentframe())))66 if LOCAL_PYTHON_PATH not in sys.path:67 sys.path.append(LOCAL_PYTHON_PATH)68 69 63 # ------------------------------------------------------------------------------ 70 64 # FUNCTION … … 89 83 c = ControlFile(args.controlfile) 90 84 except IOError: 91 try: 92 c = ControlFile(LOCAL_PYTHON_PATH + args.controlfile) 93 except IOError: 94 print 'Could not read CONTROL file "' + args.controlfile + '"' 95 print 'Either it does not exist or its syntax is wrong.' 96 print 'Try "' + sys.argv[0].split('/')[-1] + \ 97 ' -h" to print usage information' 98 sys.exit(1) 99 100 env_parameter = read_ecenv(c.ecmwfdatadir + 'python/ECMWF_ENV') 85 print('Could not read CONTROL file "' + args.controlfile + '"') 86 print('Either it does not exist or its syntax is wrong.') 87 print('Try "' + sys.argv[0].split('/')[-1] + \ 88 ' -h" to print usage information') 89 sys.exit(1) 90 91 env_parameter = read_ecenv(_config.PATH_ECMWF_ENV) 101 92 c.assign_args_to_control(args, env_parameter) 102 93 c.assign_envs_to_control(env_parameter) 103 c.check_conditions( )94 c.check_conditions(args.queue) 104 95 105 96 get_mars_data(c) … … 137 128 os.makedirs(c.inputdir) 138 129 139 print "Retrieving EC data!" 140 print "start date %s " % (c.start_date) 141 print "end date %s " % (c.end_date) 130 if c.request == 0 or c.request == 2: 131 print("Retrieving EC data!") 132 elif c.request == 1: 133 print("Printing mars requests!") 134 135 print("start date %s " % (c.start_date)) 136 print("end date %s " % (c.end_date)) 142 137 143 138 if ecapi: … … 147 142 148 143 c.ecapi = ecapi 149 print 'ecapi: ', c.ecapi144 print('Using ECMWF WebAPI: ' + str(c.ecapi)) 150 145 151 146 # basetime geht rückwärts … … 192 187 193 188 # -------------- flux data ------------------------------------------------ 194 print 'removing old flux content of ' + c.inputdir 195 tobecleaned = UioFiles(c.inputdir, 196 '*_acc_*.' + str(os.getppid()) + '.*.grb') 197 tobecleaned.delete_files() 189 if c.request == 0 or c.request == 2: 190 print('... removing old flux content of ' + c.inputdir) 191 tobecleaned = UioFiles(c.inputdir, 192 '*_acc_*.' + str(os.getppid()) + '.*.grb') 193 tobecleaned.delete_files() 198 194 199 195 # if forecast for maximum one day (upto 24h) are to be retrieved, … … 213 209 214 210 # -------------- non flux data -------------------------------------------- 215 print 'removing old non flux content of ' + c.inputdir 216 tobecleaned = UioFiles(c.inputdir, 217 '*__*.' + str(os.getppid()) + '.*.grb') 218 tobecleaned.delete_files() 211 if c.request == 0 or c.request == 2: 212 print('... removing old non flux content of ' + c.inputdir) 213 tobecleaned = UioFiles(c.inputdir, 214 '*__*.' + str(os.getppid()) + '.*.grb') 215 tobecleaned.delete_files() 219 216 220 217 do_retrievement(c, server, start, end, datechunk, fluxes=False) … … 280 277 end.strftime("%Y%m%d") 281 278 282 print "retrieve " + dates + " in dir " + c.inputdir279 print("... retrieve " + dates + " in dir " + c.inputdir) 283 280 284 281 try: 285 flexpart.retrieve(server, dates, c. inputdir)282 flexpart.retrieve(server, dates, c.request, c.inputdir) 286 283 except IOError: 287 284 my_error(c.mailfail, 'MARS request failed') -
python/install.py
r222aa11 r2fb99de 12 12 # - added documentation 13 13 # - moved install_args_and_control in here 14 # - splitted code in smaller functions 15 # - delete convert build files in here instead of compile job script 16 # - changed static path names to Variables from config file 14 17 # 15 18 # @License: … … 34 37 # - install_via_gateway 35 38 # - mk_tarball 39 # - un_tarball 36 40 # - mk_env_vars 37 41 # - mk_compilejob … … 47 51 import os 48 52 import sys 53 import glob 49 54 import subprocess 50 55 import inspect … … 52 57 53 58 # software specific classes and modules from flex_extract 59 import _config 54 60 from ControlFile import ControlFile 55 61 from UioFiles import UioFiles 56 62 from tools import make_dir, put_file_to_ecserver, submit_job_to_ecserver 57 58 # add path to pythonpath so that python finds its buddies59 LOCAL_PYTHON_PATH = os.path.dirname(os.path.abspath(60 inspect.getfile(inspect.currentframe())))61 if LOCAL_PYTHON_PATH not in sys.path:62 sys.path.append(LOCAL_PYTHON_PATH)63 64 _VERSION_STR = '7.1'65 63 66 64 # ------------------------------------------------------------------------------ … … 80 78 ''' 81 79 82 os.chdir(LOCAL_PYTHON_PATH) 80 #os.chdir(_config.PATH_LOCAL_PYTHON) 81 83 82 args = get_install_cmdline_arguments() 84 83 … … 86 85 c = ControlFile(args.controlfile) 87 86 except IOError: 88 print 'Could not read CONTROL file "' + args.controlfile + '"'89 print 'Either it does not exist or its syntax is wrong.'90 print 'Try "' + sys.argv[0].split('/')[-1] + \91 ' -h" to print usage information' 87 print('Could not read CONTROL file "' + args.controlfile + '"') 88 print('Either it does not exist or its syntax is wrong.') 89 print('Try "' + sys.argv[0].split('/')[-1] + 90 ' -h" to print usage information') 92 91 exit(1) 93 92 … … 134 133 servers (to find grib2flexpart and COMMAND file)\n\ 135 134 Normally flex_extract resides in the scripts directory \ 136 of the FLEXPART distribution , thus the:")135 of the FLEXPART distribution.") 137 136 138 137 # arguments for job submission to ECMWF, only needed by submit.py … … 171 170 <nothing> 172 171 ''' 173 174 ecd = c.ecmwfdatadir 175 tarball_name = 'flex_extract_v' + _VERSION_STR + '.tar' 176 target_dir = 'flex_extract_v' + _VERSION_STR 177 fortran_executable = 'CONVERT2' 172 import tarfile 173 174 ecd = _config.PATH_FLEXEXTRACT_DIR 175 tarball_name = _config.FLEXEXTRACT_DIRNAME + '.tar' 176 tar_file = os.path.join(ecd, tarball_name) 177 178 target_dirname = _config.FLEXEXTRACT_DIRNAME 179 fortran_executable = _config.FORTRAN_EXECUTABLE 178 180 179 181 if c.install_target.lower() != 'local': # ecgate or cca 180 182 181 mk_compilejob(ecd + 'python/compilejob.temp', c.makefile, 182 c.install_target, c.ecuid, c.ecgid, 183 mk_compilejob(c.makefile, c.install_target, c.ecuid, c.ecgid, 183 184 c.flexpart_root_scripts) 184 185 185 mk_job_template( ecd + 'python/job.temp.o',c.ecuid, c.ecgid, c.gateway,186 mk_job_template(c.ecuid, c.ecgid, c.gateway, 186 187 c.destination, c.flexpart_root_scripts) 187 188 188 mk_env_vars(ecd, c.ecuid, c.ecgid, c.gateway, c.destination) 189 190 #os.chdir('/') 191 192 mk_tarball(ecd, tarball_name) 189 mk_env_vars(c.ecuid, c.ecgid, c.gateway, c.destination) 190 191 mk_tarball(tar_file) 193 192 194 193 put_file_to_ecserver(ecd, tarball_name, c.install_target, 195 194 c.ecuid, c.ecgid) 196 195 197 submit_job_to_ecserver(ecd + '/python/', c.install_target, 198 'compilejob.ksh') 199 200 print 'job compilation script has been submitted to ecgate for ' + \ 201 'installation in ' + c.flexpart_root_scripts + \ 202 '/' + target_dir 203 print 'You should get an email with subject "flexcompile" within ' + \ 204 'the next few minutes!' 196 submit_job_to_ecserver(c.install_target, 197 os.path.join(_config.PATH_RELATIVE_JOBSCRIPTS, 198 _config.FILE_INSTALL_COMPILEJOB)) 199 200 print('job compilation script has been submitted to ecgate for ' + 201 'installation in ' + c.flexpart_root_scripts + 202 '/' + target_dirname) 203 print('You should get an email with subject "flexcompile" within ' + 204 'the next few minutes!') 205 205 206 206 else: #local 207 if not c.flexpart_root_scripts or c.flexpart_root_scripts == '../':208 print 'WARNING: FLEXPART_ROOT_SCRIPTS has not been specified'209 print 'There will be only the compilation of ' + \210 ' in ' + ecd + '/src'211 os.chdir( ecd + '/src')207 if c.flexpart_root_scripts == _config.PATH_FLEXEXTRACT_DIR : 208 print('WARNING: FLEXPART_ROOT_SCRIPTS has not been specified') 209 print('flex_extract will be installed in here by compiling the ' + 210 'Fortran source in ' + _config.PATH_FORTRAN_SRC) 211 os.chdir(_config.PATH_FORTRAN_SRC) 212 212 else: # creates the target working directory for flex_extract 213 213 c.flexpart_root_scripts = os.path.expandvars(os.path.expanduser( 214 c.flexpart_root_scripts))214 c.flexpart_root_scripts)) 215 215 if os.path.abspath(ecd) != os.path.abspath(c.flexpart_root_scripts): 216 os.chdir('/') 217 mk_tarball(ecd, tarball_name) 218 make_dir(c.flexpart_root_scripts + '/' + target_dir) 219 os.chdir(c.flexpart_root_scripts + '/' + target_dir) 220 print 'Untar ...' 221 subprocess.check_call(['tar', '-xvf', 222 ecd + '../' + tarball_name]) 223 os.chdir(c.flexpart_root_scripts + '/' + target_dir + '/src') 216 mk_tarball(tar_file) 217 make_dir(os.path.join(c.flexpart_root_scripts, 218 target_dirname)) 219 os.chdir(os.path.join(c.flexpart_root_scripts, 220 target_dirname)) 221 un_tarball(tar_file) 222 os.chdir(os.path.join(c.flexpart_root_scripts, 223 target_dirname, 224 _config.PATH_RELATIVE_FORTRAN_SRC)) 224 225 225 226 # Create Fortran executable - CONVERT2 226 print 'Install ' + target_dir + ' software on ' + \ 227 c.install_target + ' in directory ' + \ 228 os.path.abspath(os.getcwd() + '/../') + '\n' 229 230 delete_convert_build('') 231 make_convert_build('', c.makefile, fortran_executable) 232 233 return 234 235 def mk_tarball(ecd, tarname): 236 ''' 237 @Description: 238 Creates a tarball from all files which need to be sent to the 227 print('Install ' + target_dirname + ' software at ' + 228 c.install_target + ' in directory ' + 229 os.path.abspath(c.flexpart_root_scripts) + '\n') 230 231 delete_convert_build('.') 232 make_convert_build('.', c.makefile) 233 234 os.chdir(ecd) 235 if os.path.isfile(tar_file): 236 os.remove(tar_file) 237 238 return 239 240 def mk_tarball(tarball_path): 241 ''' 242 @Description: 243 Creates a tarball with all necessary files which need to be sent to the 239 244 installation directory. 240 245 It does not matter if this is local or remote. 241 246 Collects all python files, the Fortran source and makefiles, 242 the ECMWF_ENV file, the CONTROL files as well as 243 the korn shell and template files. 244 245 @Input: 246 ecd: string 247 The path were the file is to be stored. 248 249 tarname: string 250 The name of the file to send to the ECMWF server. 251 252 @Return: 253 <nothing> 254 ''' 255 256 print 'Create tarball ...' 247 the ECMWF_ENV file, the CONTROL files as well as the 248 template files. 249 250 @Input: 251 tarball_path: string 252 The complete path to the tar file which will contain all 253 relevant data for flex_extract. 254 255 @Return: 256 <nothing> 257 ''' 258 import tarfile 259 from glob import glob 260 261 print('Create tarball ...') 262 263 # change to FLEXEXTRACT directory so that the tar can contain 264 # relative pathes to the files and directories 265 ecd = _config.PATH_FLEXEXTRACT_DIR + '/' 266 os.chdir(ecd) 267 268 # get lists of the files to be added to the tar file 269 ECMWF_ENV_FILE = [_config.PATH_RELATIVE_ECMWF_ENV] 270 pyfiles = [os.path.relpath(x, ecd) 271 for x in glob(_config.PATH_LOCAL_PYTHON + 272 os.path.sep + '*py')] 273 controlfiles = [os.path.relpath(x, ecd) 274 for x in glob(_config.PATH_CONTROLFILES + 275 os.path.sep + 'CONTROL*')] 276 tempfiles = [os.path.relpath(x, ecd) 277 for x in glob(_config.PATH_TEMPLATES + 278 os.path.sep + '*')] 279 ffiles = [os.path.relpath(x, ecd) 280 for x in glob(_config.PATH_FORTRAN_SRC + 281 os.path.sep + '*.f*')] 282 hfiles = [os.path.relpath(x, ecd) 283 for x in glob(_config.PATH_FORTRAN_SRC + 284 os.path.sep + '*.h')] 285 makefiles = [os.path.relpath(x, ecd) 286 for x in glob(_config.PATH_FORTRAN_SRC + 287 os.path.sep + 'Makefile*')] 288 289 # concatenate single lists to one for a better looping 290 filelist = pyfiles + controlfiles + tempfiles + ffiles + hfiles + \ 291 makefiles + ECMWF_ENV_FILE 292 293 # create installation tar-file 257 294 try: 258 subprocess.check_call(['tar -cvf '+ 259 ecd + '../' + tarname + ' ' + 260 ecd + 'python/*py ' + 261 ecd + 'python/CONTROL* ' + 262 ecd + 'python/*ksh ' + 263 ecd + 'python/*temp* ' + 264 ecd + 'python/ECMWF_ENV ' + 265 ecd + '_templates ' + 266 ecd + 'src/*.f ' + 267 ecd + 'src/*.f90 ' + 268 ecd + 'src/*.h ' + 269 ecd + 'src/Makefile*'], shell=True) 295 with tarfile.open(tarball_path, "w:gz") as tar_handle: 296 for file in filelist: 297 tar_handle.add(file) 298 270 299 except subprocess.CalledProcessError as e: 271 print 'ERROR:' 272 print e.output 273 sys.exit('could not make installation tar ball!') 274 275 return 276 277 def mk_env_vars(ecd, ecuid, ecgid, gateway, destination): 300 print('... ERROR CODE:\n ... ' + str(e.returncode)) 301 print('... ERROR MESSAGE:\n ... ' + str(e)) 302 303 sys.exit('... could not make installation tar ball!') 304 305 return 306 307 308 def un_tarball(tarball_path): 309 ''' 310 @Description: 311 Extracts the given tarball into current directory. 312 313 @Input: 314 tarball_path: string 315 The complete path to the tar file which will contain all 316 relevant data for flex_extract. 317 318 @Return: 319 <nothing> 320 ''' 321 import tarfile 322 323 print('Untar ...') 324 325 with tarfile.open(tarball_path) as tar_handle: 326 tar_handle.extractall() 327 328 return 329 330 def mk_env_vars(ecuid, ecgid, gateway, destination): 278 331 ''' 279 332 @Description: … … 282 335 283 336 @Input: 284 ecd: string285 The path were the file is to be stored.286 287 337 ecuid: string 288 338 The user id on ECMWF server. … … 302 352 ''' 303 353 304 with open( ecd + 'python/ECMWF_ENV', 'w') as fo:354 with open(_config.PATH_RELATIVE_ECMWF_ENV, 'w') as fo: 305 355 fo.write('ECUID ' + ecuid + '\n') 306 356 fo.write('ECGID ' + ecgid + '\n') … … 310 360 return 311 361 312 def mk_compilejob( template,makefile, target, ecuid, ecgid, fp_root):362 def mk_compilejob(makefile, target, ecuid, ecgid, fp_root): 313 363 ''' 314 364 @Description: … … 318 368 319 369 @Input: 320 template: string321 File which contains the original text for the job template.322 It must contain the complete path to the file.323 324 370 makefile: string 325 371 Name of the makefile which should be used to compile FORTRAN … … 343 389 ''' 344 390 391 template = os.path.join(_config.PATH_RELATIVE_TEMPLATES, 392 _config.TEMPFILE_INSTALL_COMPILEJOB) 345 393 with open(template) as f: 346 394 fdata = f.read().split('\n') 347 395 348 with open(template[:-4] + 'ksh', 'w') as fo: 396 compilejob = os.path.join(_config.PATH_RELATIVE_JOBSCRIPTS, 397 _config.FILE_INSTALL_COMPILEJOB) 398 with open(compilejob, 'w') as fo: 349 399 for data in fdata: 350 400 if 'MAKEFILE=' in data: … … 371 421 return 372 422 373 def mk_job_template( template,ecuid, ecgid, gateway, destination, fp_root):423 def mk_job_template(ecuid, ecgid, gateway, destination, fp_root): 374 424 ''' 375 425 @Description: 376 426 Modifies the original job template file so that it is specified 377 427 for the user and the environment were it will be applied. Result 378 is stored in a new file "job.temp" in the python directory. 379 380 @Input: 381 template: string 382 File which contains the original text for the job template. 383 It must contain the complete path to the file. 384 428 is stored in a new file. 429 430 @Input: 385 431 ecuid: string 386 432 The user id on ECMWF server. … … 403 449 <nothing> 404 450 ''' 405 451 fp_root_path_to_python = os.path.join(fp_root, _config.FLEXEXTRACT_DIRNAME, 452 _config.PATH_RELATIVE_PYTHON) 453 454 template = os.path.join(_config.PATH_RELATIVE_TEMPLATES, 455 _config.TEMPFILE_INSTALL_JOB) 406 456 with open(template) as f: 407 457 fdata = f.read().split('\n') 408 458 409 with open(template[:-2], 'w') as fo: 459 jobfile_temp = os.path.join(_config.PATH_RELATIVE_TEMPLATES, 460 _config.TEMPFILE_JOB) 461 with open(jobfile_temp, 'w') as fo: 410 462 for data in fdata: 411 463 if '--workdir' in data: 412 data = '#SBATCH --workdir=/scratch/ms/' + ecgid + \ 413 '/' + ecuid 464 data = '#SBATCH --workdir=/scratch/ms/' + ecgid + '/' + ecuid 414 465 elif '##PBS -o' in data: 415 466 data = '##PBS -o /scratch/ms/' + ecgid + '/' + \ 416 467 ecuid + 'flex_ecmwf.$Jobname.$Job_ID.out' 417 468 elif 'export PATH=${PATH}:' in data: 418 data += fp_root + '/flex_extract_v7.1/python'469 data += fp_root_path_to_python 419 470 420 471 fo.write(data + '\n') 421 472 return 422 473 423 def delete_convert_build( ecd):474 def delete_convert_build(src_path): 424 475 ''' 425 476 @Description: … … 428 479 429 480 @Input: 430 ecd: string431 The path to the Fortran program.432 433 @Return: 434 <nothing> 435 ''' 436 437 modfiles = UioFiles( ecd, '*.mod')438 objfiles = UioFiles( ecd, '*.o')439 exefile = UioFiles( ecd, 'CONVERT2')481 src_path: string 482 Path to the fortran source directory. 483 484 @Return: 485 <nothing> 486 ''' 487 488 modfiles = UioFiles(src_path, '*.mod') 489 objfiles = UioFiles(src_path, '*.o') 490 exefile = UioFiles(src_path, _config.FORTRAN_EXECUTABLE) 440 491 441 492 modfiles.delete_files() … … 445 496 return 446 497 447 def make_convert_build( ecd, makefile, f_executable):498 def make_convert_build(src_path, makefile): 448 499 ''' 449 500 @Description: … … 451 502 452 503 @Input: 453 ecd: string454 The path were the file is to be stored.504 src_path: string 505 Path to the fortran source directory. 455 506 456 507 makefile: string 457 508 The name of the makefile which should be used. 458 509 459 f_executable: string460 The name of the executable the Fortran program generates after461 compilation.462 463 510 @Return: 464 511 <nothing> … … 466 513 467 514 try: 468 print 'Using makefile: ' + makefile 469 p = subprocess.Popen(['make', '-f', ecd + makefile], 515 print('Using makefile: ' + makefile) 516 p = subprocess.Popen(['make', '-f', 517 os.path.join(src_path, makefile)], 470 518 stdin=subprocess.PIPE, 471 519 stdout=subprocess.PIPE, … … 473 521 bufsize=1) 474 522 pout, perr = p.communicate() 475 print pout523 print(pout) 476 524 if p.returncode != 0: 477 print perr478 print 'Please edit ' + makefile + \479 ' or try another Makefile in the src directory.' 480 print 'Most likely GRIB_API_INCLUDE_DIR, GRIB_API_LIB ' \481 'and EMOSLIB must be adapted.' 482 print 'Available Makefiles:'483 print UioFiles('.', 'Makefile*')525 print(perr) 526 print('Please edit ' + makefile + 527 ' or try another Makefile in the src directory.') 528 print('Most likely GRIB_API_INCLUDE_DIR, GRIB_API_LIB ' 529 'and EMOSLIB must be adapted.') 530 print('Available Makefiles:') 531 print(UioFiles(src_path, 'Makefile*')) 484 532 sys.exit('Compilation failed!') 485 533 except ValueError as e: 486 print 'ERROR: Makefile call failed:'487 print e534 print('ERROR: Makefile call failed:') 535 print(e) 488 536 else: 489 subprocess.check_call(['ls', '-l', ecd + f_executable]) 537 subprocess.check_call(['ls', '-l', 538 os.path.join(src_path, 539 _config.FORTRAN_EXECUTABLE)]) 490 540 491 541 return -
python/prepare_flexpart.py
r54a8a01 r2fb99de 57 57 import sys 58 58 import socket 59 import _config60 59 61 60 # software specific classes and modules from flex_extract 61 import _config 62 62 from UioFiles import UioFiles 63 63 from tools import clean_up, get_cmdline_arguments, read_ecenv … … 70 70 except ImportError: 71 71 ecapi = False 72 73 # add path to pythonpath so that python finds its buddies74 LOCAL_PYTHON_PATH = os.path.dirname(os.path.abspath(75 inspect.getfile(inspect.currentframe())))76 if LOCAL_PYTHON_PATH not in sys.path:77 sys.path.append(LOCAL_PYTHON_PATH)78 79 72 80 73 # ------------------------------------------------------------------------------ … … 100 93 c = ControlFile(args.controlfile) 101 94 except IOError: 102 try: 103 c = ControlFile(LOCAL_PYTHON_PATH + args.controlfile) 104 except IOError: 105 print 'Could not read CONTROL file "' + args.controlfile + '"' 106 print 'Either it does not exist or its syntax is wrong.' 107 print 'Try "' + sys.argv[0].split('/')[-1] + \ 108 ' -h" to print usage information' 109 sys.exit(1) 95 print('Could not read CONTROL file "' + args.controlfile + '"') 96 print('Either it does not exist or its syntax is wrong.') 97 print('Try "' + sys.argv[0].split('/')[-1] + \ 98 ' -h" to print usage information') 99 sys.exit(1) 110 100 111 env_parameter = read_ecenv( c.ecmwfdatadir + 'python/ECMWF_ENV')101 env_parameter = read_ecenv(_config.PATH_ECMWF_ENV) 112 102 c.assign_args_to_control(args, env_parameter) 113 103 c.assign_envs_to_control(env_parameter) 114 c.check_conditions( )104 c.check_conditions(args.queue) 115 105 prepare_flexpart(args.ppid, c) 116 106 … … 170 160 start = start - datetime.timedelta(days=1) 171 161 172 print 'Prepare ' + start.strftime("%Y%m%d") + \173 "/to/" + end.strftime("%Y%m%d") 162 print('Prepare ' + start.strftime("%Y%m%d") + 163 "/to/" + end.strftime("%Y%m%d")) 174 164 175 165 # create output dir if necessary … … 182 172 # deaccumulate the flux data 183 173 flexpart = EcFlexpart(c, fluxes=True) 184 flexpart.write_namelist(c, 'fort.4')174 flexpart.write_namelist(c, _config.FILE_NAMELIST) 185 175 flexpart.deacc_fluxes(inputfiles, c) 186 176 … … 197 187 # otherwise delete temporary files 198 188 if int(c.debug) != 0: 199 print '\nTemporary files left intact'189 print('\nTemporary files left intact') 200 190 else: 201 191 clean_up(c) -
python/profiling.py
r54a8a01 r2fb99de 66 66 result = fn(*args, **kwargs) 67 67 t2 = time.time() 68 print "@timefn:" + fn.func_name + " took " + str(t2 - t1) + " seconds"68 print("@timefn:" + fn.func_name + " took " + str(t2 - t1) + " seconds") 69 69 70 70 return result -
python/pythontest/TestInstall.py
r067a0c3 r2fb99de 6 6 import os 7 7 import inspect 8 sys.path.append('../python') 8 sys.path.append('../') 9 import _config 9 10 import install 11 from tools import make_dir 10 12 11 13 … … 17 19 pass 18 20 21 # - main 22 # - get_install_cmdline_arguments 23 # - install_via_gateway 24 #! - mk_tarball 25 #! - un_tarball 26 # - mk_env_vars 27 # - mk_compilejob 28 # - mk_job_template 29 # - delete_convert_build 30 # - make_convert_build 19 31 20 32 def test_mk_tarball(self): 21 ecd = os.path.dirname(os.path.abspath(inspect.getfile( 22 inspect.currentframe()))) + '/../' 23 #print ecd 24 install.mk_tarball(ecd) 33 import tarfile 25 34 35 ecd = _config.PATH_FLEXEXTRACT_DIR + os.path.sep 36 37 # list comparison files for tarball content 38 tar_test_dir = os.path.join(_config.PATH_TEST_DIR + 39 os.path.sep + 'TestInstallTar') 40 tar_test_fedir = os.path.join(tar_test_dir, 'flex_extract_v7.1') 41 42 comparison_list = [] 43 for path, subdirs, files in os.walk(tar_test_fedir): 44 for name in files: 45 if 'tar' not in name: 46 comparison_list.append(os.path.relpath(os.path.join(path, name), tar_test_fedir)) 47 48 # create test tarball and list its content files 49 tarballname = _config.FLEXEXTRACT_DIRNAME + '_test.tar' 50 install.mk_tarball(ecd + tarballname) 51 with tarfile.open(ecd + tarballname, 'r') as tar_handle: 52 tar_content_list = tar_handle.getnames() 53 54 # remove test tar file from flex_extract directory 55 os.remove(ecd + tarballname) 56 57 # test if comparison filelist is equal to the 58 # filelist of tarball content 59 assert sorted(comparison_list) == sorted(tar_content_list) 60 61 def test_un_tarball(self): 62 import tarfile 63 import shutil 64 65 ecd = _config.PATH_FLEXEXTRACT_DIR + os.path.sep 66 67 # list comparison files for tarball content 68 tar_test_dir = os.path.join(_config.PATH_TEST_DIR + 69 os.path.sep + 'TestInstallTar') 70 tar_test_fedir = os.path.join(tar_test_dir, 'flex_extract_v7.1') 71 comparison_list = [] 72 for path, subdirs, files in os.walk(tar_test_fedir): 73 for name in files: 74 if 'tar' not in name: 75 comparison_list.append(os.path.relpath(os.path.join(path, name), tar_test_fedir)) 76 77 # untar in test directory 78 test_dir = os.path.join(tar_test_dir, 'test_untar') 79 make_dir(test_dir) 80 os.chdir(test_dir) 81 tarballname = _config.FLEXEXTRACT_DIRNAME + '.tar' 82 install.un_tarball(os.path.join(tar_test_dir, tarballname)) 83 tarfiles_list = [] 84 for path, subdirs, files in os.walk(test_dir): 85 for name in files: 86 tarfiles_list.append(os.path.relpath(os.path.join(path, name), test_dir)) 87 88 # test for equality 89 assert sorted(tarfiles_list) == sorted(comparison_list) 90 91 # clean up temp test dir 92 shutil.rmtree(test_dir) 26 93 27 94 -
python/submit.py
r222aa11 r2fb99de 16 16 # - added documentation 17 17 # - minor changes in programming style (for consistence) 18 # - changed path names to variables from config file 19 # - added option for writing mars requests to extra file 20 # additionally,as option without submitting the mars jobs 18 21 # 19 22 # @License: … … 73 76 ''' 74 77 75 called_from_dir = os.getcwd()76 77 78 args = get_cmdline_arguments() 78 79 … … 80 81 c = ControlFile(args.controlfile) 81 82 except IOError: 82 try: 83 c = ControlFile(_config.PATH_LOCAL_PYTHON + args.controlfile) 84 except IOError: 85 print 'Could not read CONTROL file "' + args.controlfile + '"' 86 print 'Either it does not exist or its syntax is wrong.' 87 print 'Try "' + sys.argv[0].split('/')[-1] + \ 88 ' -h" to print usage information' 89 sys.exit(1) 90 91 env_parameter = read_ecenv(c.ecmwfdatadir + 'python/ECMWF_ENV') 83 print('Could not read CONTROL file "' + args.controlfile + '"') 84 print('Either it does not exist or its syntax is wrong.') 85 print('Try "' + sys.argv[0].split('/')[-1] + \ 86 ' -h" to print usage information') 87 sys.exit(1) 88 89 env_parameter = read_ecenv(_config.PATH_ECMWF_ENV) 92 90 c.assign_args_to_control(args) 93 91 c.assign_envs_to_control(env_parameter) 94 c.check_conditions( )92 c.check_conditions(args.queue) 95 93 96 94 # on local side 97 # on ECMWF server this would be the local side 95 # on ECMWF server this would also be the local side 96 called_from_dir = os.getcwd() 98 97 if args.queue is None: 99 98 if c.inputdir[0] != '/': … … 102 101 c.outputdir = os.path.join(called_from_dir, c.outputdir) 103 102 get_mars_data(c) 104 prepare_flexpart(args.ppid, c) 105 normal_exit(c.mailfail, 'Done!') 106 # on ECMWF server 103 if c.request == 0 or c.request == 2: 104 prepare_flexpart(args.ppid, c) 105 normal_exit(c.mailfail, 'FLEX_EXTRACT IS DONE!') 106 else: 107 normal_exit(c.mailfail, 'PRINTING MARS_REQUESTS DONE!') 108 # send files to ECMWF server and install there 107 109 else: 108 110 submit(args.job_template, c, args.queue) … … 117 119 @Input: 118 120 jtemplate: string 119 Job template file for submission to ECMWF. It contains all necessary 121 Job template file from sub-directory "_templates" for 122 submission to ECMWF. It contains all necessary 120 123 module and variable settings for the ECMWF environment as well as 121 124 the job call and mail report instructions. … … 143 146 144 147 # read template file and get index for CONTROL input 145 with open( jtemplate) as f:148 with open(os.path.join(_config.PATH_TEMPLATES, jtemplate)) as f: 146 149 lftext = f.read().split('\n') 147 150 insert_point = lftext.index('EOF') … … 150 153 # --------- create on demand job script ------------------------------------ 151 154 if c.maxstep > 24: 152 print '---- Pure forecast mode! ----'155 print('---- Pure forecast mode! ----') 153 156 else: 154 print '---- On-demand mode! ----' 155 job_file = jtemplate[:-4] + 'ksh' 157 print('---- On-demand mode! ----') 158 job_file = os.path.join(_config.PATH_JOBSCRIPTS, 159 jtemplate[:-4] + 'ksh') 156 160 clist = c.to_list() 157 161 … … 161 165 f.write('\n'.join(lftextondemand)) 162 166 163 result_code =submit_job_to_ecserver(queue, job_file)167 submit_job_to_ecserver(queue, job_file) 164 168 165 169 else: 166 170 # --------- create operational job script ---------------------------------- 167 print '---- Operational mode! ----'168 job_file = jtemplate[:-5] + 'oper.ksh'169 #colist = []171 print('---- Operational mode! ----') 172 job_file = os.path.join(_config.PATH_JOBSCRIPTS, 173 jtemplate[:-5] + 'oper.ksh') 170 174 171 175 if c.maxstep: … … 187 191 f.write('\n'.join(lftextoper)) 188 192 189 result_code =submit_job_to_ecserver(queue, job_file)193 submit_job_to_ecserver(queue, job_file) 190 194 191 195 # -------------------------------------------------------------------------- 192 print 'You should get an email with subject flex.hostname.pid'196 print('You should get an email with subject flex.hostname.pid') 193 197 194 198 return -
python/tools.py
refa05d7 r2fb99de 124 124 parser.add_argument("--debug", dest="debug", default=None, 125 125 help="debug mode - leave temporary files intact") 126 parser.add_argument("--request", dest="request", default=None, 127 help="list all mars request in file mars_requests.dat \ 128 and skip submission to mars") 126 129 127 130 args = parser.parse_args() … … 137 140 @Input: 138 141 filename: string 139 Name offile where the ECMWV environment parameters are stored.142 Path to file where the ECMWV environment parameters are stored. 140 143 141 144 @Return: 142 145 envs: dict 146 Contains the environment parameter ecuid, ecgid, gateway 147 and destination for ECMWF server environments. 143 148 ''' 144 149 envs= {} 145 print filename 150 146 151 with open(filename, 'r') as f: 147 152 for line in f: … … 175 180 ''' 176 181 177 print "clean_up"182 print("clean_up") 178 183 179 184 cleanlist = glob.glob(c.inputdir + "/*") … … 184 189 silent_remove(clist) 185 190 186 print "Done"191 print("Done") 187 192 188 193 return … … 208 213 ''' 209 214 210 print message215 print(message) 211 216 212 217 # comment if user does not want email notification directly from python … … 224 229 pout = p.communicate(input=message + '\n\n' + trace)[0] 225 230 except ValueError as e: 226 print 'ERROR: ', e231 print('ERROR: ', e) 227 232 sys.exit('Email could not be sent!') 228 233 else: 229 print 'Email sent to ' + os.path.expandvars(user) + ' ' + \230 pout.decode() 234 print('Email sent to ' + os.path.expandvars(user) + ' ' + 235 pout.decode()) 231 236 232 237 sys.exit(1) … … 253 258 254 259 ''' 255 print message260 print(message) 256 261 257 262 # comment if user does not want notification directly from python … … 268 273 pout = p.communicate(input=message+'\n\n')[0] 269 274 except ValueError as e: 270 print 'ERROR: ', e271 print 'Email could not be sent!'275 print('ERROR: ', e) 276 print('Email could not be sent!') 272 277 else: 273 print 'Email sent to ' + os.path.expandvars(user) + ' ' + \274 pout.decode() 278 print('Email sent to ' + os.path.expandvars(user) + ' ' + 279 pout.decode()) 275 280 276 281 return … … 392 397 break 393 398 else: 394 print 'Warning: par ' + par + ' not found in table 128'399 print('Warning: par ' + par + ' not found in table 128') 395 400 396 401 return ipar … … 438 443 raise # re-raise exception if a different error occured 439 444 else: 440 print 'WARNING: Directory {0} already exists!'.format(directory)445 print('WARNING: Directory {0} already exists!'.format(directory)) 441 446 442 447 return … … 482 487 stderr=subprocess.STDOUT) 483 488 except subprocess.CalledProcessError as e: 484 print '... ERROR CODE:\n ... ', e.returncode 485 print '... ERROR MESSAGE:\n ... ', e 486 print '... COMMAND MESSAGE:\n ...', e.output 487 488 print '\nDo you have a valid eccert key?' 489 print('... ERROR CODE:\n ... ' + str(e.returncode)) 490 print('... ERROR MESSAGE:\n ... ' + str(e)) 491 492 print('\n... Do you have a valid ecaccess certification key?') 489 493 sys.exit('... ECACCESS-FILE-PUT FAILED!') 490 494 … … 520 524 jobname]) 521 525 except subprocess.CalledProcessError as e: 522 print '... ERROR CODE: ', e.returncode523 print '... ERROR MESSAGE:\n ... ', e524 print '... COMMAND MESSAGE:\n ...', e.output 525 526 print '\nDo you have a valid eccert key?'526 print('... ERROR CODE:\n ... ' + str(e.returncode)) 527 print('... ERROR MESSAGE:\n ... ' + str(e)) 528 529 530 print('\n... Do you have a valid ecaccess certification key?') 527 531 sys.exit('... ECACCESS-JOB-SUBMIT FAILED!') 528 532
Note: See TracChangeset
for help on using the changeset viewer.