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

changed whole tree structure of flex_extract to have better overview

File:
1 moved

Legend:

Unmodified
Added
Removed
  • source/pythontest/TestInstallTar/flex_extract_v7.1_ecgate/source/python/classes/EcFlexpart.py

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