Changeset 0f89116 in flex_extract.git for Source/Python/Classes/EcFlexpart.py


Ignore:
Timestamp:
Dec 19, 2019, 8:07:12 PM (4 years ago)
Author:
Anne Philipp <anne.philipp@…>
Branches:
master, ctbto, dev
Children:
a73c0f6
Parents:
0d99607
Message:

diverse changes due to PEP8 style guide and eliminating grib2flexpart; removed unused parameter

File:
1 edited

Legend:

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

    rc77630a r0f89116  
    5353#pylint: disable=consider-using-enumerate
    5454# this is not useful in this case
     55#pylint: disable=unsubscriptable-object
     56# this error is a bug
     57#pylint: disable=ungrouped-imports
     58# not necessary that we group the imports
    5559# ------------------------------------------------------------------------------
    5660# MODULES
     
    6266import glob
    6367import shutil
    64 import subprocess
    6568from datetime import datetime, timedelta
    6669
    6770# software specific classes and modules from flex_extract
     71#pylint: disable=wrong-import-position
    6872sys.path.append('../')
    6973import _config
    7074from Classes.GribUtil import GribUtil
    7175from Mods.tools import (init128, to_param_id, silent_remove, product,
    72                         my_error, make_dir, get_informations, get_dimensions,
     76                        my_error, get_informations, get_dimensions,
    7377                        execute_subprocess, to_param_id_with_tablenumber,
    7478                        generate_retrieval_period_boundary)
     
    7680from Classes.UioFiles import UioFiles
    7781import Mods.disaggregation as disaggregation
    78 
     82#pylint: enable=wrong-import-position
    7983# ------------------------------------------------------------------------------
    8084# CLASS
     
    401405        else:  # GAUSS and ETA
    402406            print('Warning: Collecting etadot and parameters for gaussian grid '
    403                            'is a very costly parameter combination, '
    404                            'use this combination only for debugging!')
     407                  'is a very costly parameter combination, '
     408                  'use this combination only for debugging!')
    405409            self.params['GG__SL'] = ['Q', 'ML', '1',
    406410                                     '{}'.format((int(self.resol) + 1) // 2)]
     
    415419
    416420        # ADDITIONAL FIELDS FOR FLEXPART-WRF MODEL (IF QUESTIONED)
    417         # -----------------------------------------------------------------------
     421        # ----------------------------------------------------------------------
    418422        if wrf:
    419423            # @WRF
     
    710714                    retr_param_dict['date'] = self.dates.split('/')[0]
    711715                    retr_param_dict['target'] = self._mk_targetname('',
    712                                             pk, retr_param_dict['date'])
     716                                                                    pk,
     717                                                                    retr_param_dict['date'])
    713718                elif pk == 'OG_OROLSM__SL' and oro:
    714719                    continue
     
    752757                        if 'acc' in pk:
    753758                            startdate = retr_param_dict['date'].split('/')[0]
    754                             enddate = datetime.strftime(elimit - t24h,'%Y%m%d')
     759                            enddate = datetime.strftime(elimit - t24h, '%Y%m%d')
    755760                            retr_param_dict['date'] = '/'.join([startdate,
    756761                                                                'to',
     
    781786                        timesave = ''.join(retr_param_dict['time'])
    782787
    783                         if ('/' in retr_param_dict['time'] and
    784                             pk != 'OG_OROLSM__SL' and
    785                             'acc' not in pk ) :
     788                        if all(['/' in retr_param_dict['time'],
     789                                pk != 'OG_OROLSM__SL',
     790                                'acc' not in pk]):
    786791                            times = retr_param_dict['time'].split('/')
    787792                            steps = retr_param_dict['step'].split('/')
     
    794799                                    retr_param_dict['time'] = times[0]
    795800
    796                         if (pk != 'OG_OROLSM__SL' and
    797                             int(retr_param_dict['step'].split('/')[0]) == 0 and
    798                             int(timesave.split('/')[0]) == 0):
     801                        if all([pk != 'OG_OROLSM__SL',
     802                                int(retr_param_dict['step'].split('/')[0]) == 0,
     803                                int(timesave.split('/')[0]) == 0]):
    799804
    800805                            retr_param_dict['date'] = \
     
    810815                    else:
    811816                        raise ValueError('ERROR: Basetime has an invalid value '
    812                                                  '-> {}'.format(str(basetime)))
     817                                         '-> {}'.format(str(self.basetime)))
    813818
    814819        if request == 0 or request == 2:
     
    860865
    861866            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)
     867                maxl=str(maxl),
     868                maxb=str(maxb),
     869                mlevel=str(self.level),
     870                mlevelist=str(self.levelist),
     871                mnauf=str(self.resol),
     872                metapar='77',
     873                rlo0=str(area[1]),
     874                rlo1=str(area[3]),
     875                rla0=str(area[2]),
     876                rla1=str(area[0]),
     877                momega=str(c.omega),
     878                momegadiff=str(c.omegadiff),
     879                mgauss=str(c.gauss),
     880                msmooth=str(c.smooth),
     881                meta=str(c.eta),
     882                metadiff=str(c.etadiff),
     883                mdpdeta=str(c.dpdeta)
    879884            )
    880885        except UndefinedError as e:
     
    928933        '''
    929934        import numpy as np
    930         from eccodes import (codes_index_select, codes_new_from_index, codes_get,
     935        from eccodes import (codes_index_select, codes_get,
    931936                             codes_get_values, codes_set_values, codes_set,
    932937                             codes_write, codes_release, codes_new_from_index,
     
    10531058            step = codes_get(gid, 'step') # integer
    10541059            ctime = '{:0>2}'.format(time)
    1055             cstep = '{:0>3}'.format(step)
    10561060
    10571061            t_date = datetime.strptime(cdate + ctime, '%Y%m%d%H')
     
    11321136                    deac_vals[parId].append(
    11331137                        (orig_vals[parId][-1] - orig_vals[parId][-2]) /
    1134                          int(c.dtime))
     1138                        int(c.dtime))
    11351139
    11361140                # store precipitation if new disaggregation method is selected
     
    13321336            for inum in range(maxnum):
    13331337                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]
     1338                    lsp_new_np[inum, ix, :] = disaggregation.IA3(lsp_np[inum, ix, :])[:-1]
     1339                    cp_new_np[inum, ix, :] = disaggregation.IA3(cp_np[inum, ix, :])[:-1]
    13361340        else:
    13371341            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]
     1342                lsp_new_np[0, ix, :] = disaggregation.IA3(lsp_np[ix, :])[:-1]
     1343                cp_new_np[0, ix, :] = disaggregation.IA3(cp_np[ix, :])[:-1]
    13401344
    13411345        # write to grib files (full/orig times to flux file and inbetween
     
    14021406            # write original time step to flux file as usual
    14031407            fluxfile = GribUtil(os.path.join(c.inputdir, fluxfilename))
    1404             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1408            fluxfile.set_keys(tmpfile, filemode='ab',
    14051409                              wherekeynames=['paramId'], wherekeyvalues=[142],
    1406                               keynames=['perturbationNumber','date','time','stepRange','values'],
     1410                              keynames=['perturbationNumber', 'date', 'time',
     1411                                        'stepRange', 'values'],
    14071412                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
    1408                                          date.hour*100, 0, lsp_new_np[inumb,:,it]],
     1413                                         date.hour*100, 0, lsp_new_np[inumb, :, it]],
    14091414                             )
    1410             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1415            fluxfile.set_keys(tmpfile, filemode='ab',
    14111416                              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]]
     1417                              keynames=['perturbationNumber', 'date', 'time',
     1418                                        'stepRange', 'values'],
     1419                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1420                                         date.hour*100, 0, cp_new_np[inumb, :, it]]
    14151421                             )
    14161422
    14171423            # rr for first subgrid point is identified by step = 1
    1418             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1424            fluxfile.set_keys(tmpfile, filemode='ab',
    14191425                              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,
     1426                              keynames=['perturbationNumber', 'date', 'time',
     1427                                        'stepRange', 'values'],
     1428                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1429                                         date.hour*100, '1', lsp_new_np[inumb, :, it+1]]
     1430                             )
     1431            fluxfile.set_keys(tmpfile, filemode='ab',
    14251432                              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                               )
     1433                              keynames=['perturbationNumber', 'date', 'time',
     1434                                        'stepRange', 'values'],
     1435                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1436                                         date.hour*100, '1', cp_new_np[inumb, :, it+1]]
     1437                             )
    14301438
    14311439            # rr for second subgrid point is identified by step = 2
    1432             fluxfile.set_keys(tmpfile, filemode='ab', strict=True,
     1440            fluxfile.set_keys(tmpfile, filemode='ab',
    14331441                              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,
     1442                              keynames=['perturbationNumber', 'date', 'time',
     1443                                        'stepRange', 'values'],
     1444                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1445                                         date.hour*100, '2', lsp_new_np[inumb, :, it+2]]
     1446                             )
     1447            fluxfile.set_keys(tmpfile, filemode='ab',
    14391448                              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                               )
     1449                              keynames=['perturbationNumber', 'date', 'time',
     1450                                        'stepRange', 'values'],
     1451                              keyvalues=[inumb, int(date.strftime('%Y%m%d')),
     1452                                         date.hour*100, '2', cp_new_np[inumb, :, it+2]]
     1453                             )
    14441454
    14451455            it = it + 3 # jump to next original time step in rr fields
     
    14631473        '''
    14641474
    1465         gribfile = GribUtil(os.path.join(inputdir,'rr_grib_dummy.grb'))
     1475        gribfile = GribUtil(os.path.join(inputdir, 'rr_grib_dummy.grb'))
    14661476
    14671477        gribfile.copy_dummy_msg(ifile, keynames=['paramId'],
    1468                       keyvalues=[142], filemode='wb')
     1478                                keyvalues=[142], filemode='wb')
    14691479
    14701480        gribfile.copy_dummy_msg(ifile, keynames=['paramId'],
    1471                       keyvalues=[143], filemode='ab')
     1481                                keyvalues=[143], filemode='ab')
    14721482
    14731483        return
     
    15011511
    15021512        '''
    1503         from eccodes import (codes_index_select, codes_new_from_index, codes_get,
     1513        from eccodes import (codes_index_select, codes_get,
    15041514                             codes_get_values, codes_set_values, codes_set,
    15051515                             codes_write, codes_release, codes_new_from_index,
     
    15831593            cdate_hour = datetime.strftime(timestamp, '%Y%m%d%H')
    15841594
     1595            # if basetime is used, adapt start/end date period
     1596            if c.basetime is not None:
     1597                time_delta = timedelta(hours=12-int(c.dtime))
     1598                start_period = datetime.strptime(c.end_date + str(c.basetime),
     1599                                               '%Y%m%d%H') - time_delta
     1600                end_period = datetime.strptime(c.end_date + str(c.basetime),
     1601                                             '%Y%m%d%H')
     1602
    15851603            # skip all temporary times
    1586             # which are outside the retrieval period
     1604            # which are outside the retrieval period               
    15871605            if timestamp < start_period or \
    15881606               timestamp > end_period:
    15891607                continue
    1590 
    1591             # if the timestamp is out of basetime start/end date period,
    1592             # skip this specific product
    1593             if c.basetime is not None:
    1594                 time_delta = timedelta(hours=12-int(c.dtime))
    1595                 start_time = datetime.strptime(c.end_date + str(c.basetime),
    1596                                                 '%Y%m%d%H') - time_delta
    1597                 end_time = datetime.strptime(c.end_date + str(c.basetime),
    1598                                              '%Y%m%d%H')
    1599                 if timestamp < start_time or timestamp > end_time:
    1600                     continue
     1608               
    16011609
    16021610            # @WRF
     
    16201628                paramId = codes_get(gid, 'paramId')
    16211629                gridtype = codes_get(gid, 'gridType')
    1622                 levtype = codes_get(gid, 'typeOfLevel')
    16231630                if paramId == 77: # ETADOT
    16241631                    codes_write(gid, fdict['21'])
     
    17041711            # Fortran program creates file fort.15 (with u,v,etadot,t,sp,q)
    17051712            execute_subprocess([os.path.join(c.exedir,
    1706                                 _config.FORTRAN_EXECUTABLE)],
     1713                                             _config.FORTRAN_EXECUTABLE)],
    17071714                               error_msg='FORTRAN PROGRAM FAILED!')#shell=True)
    17081715
     
    17331740            # to the outputfile (final GRIB input files for FLEXPART)
    17341741            orolsm = os.path.basename(glob.glob(c.inputdir +
    1735                                         '/OG_OROLSM__SL.*.' + c.ppid + '*')[0])
     1742                                                '/OG_OROLSM__SL.*.' +
     1743                                                c.ppid +
     1744                                                '*')[0])
    17361745            fluxfile = 'flux' + cdate[0:2] + suffix
    17371746            if not c.cwc:
     
    17831792        '''
    17841793        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)
     1794                             codes_set_array, codes_release,
     1795                             codes_set, codes_write)
    17871796
    17881797        # max number
     
    17901799
    17911800        # 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:
     1801        cf_filelist = UioFiles(path, prefix + '*.N000')
     1802        cf_filelist.files = sorted(cf_filelist.files)
     1803
     1804        for cffile in cf_filelist.files:
    17961805            with open(cffile, 'rb') as f:
    1797                 cfvalues=[]
     1806                cfvalues = []
    17981807                while True:
    17991808                    fid = codes_grib_new_from_file(f)
     
    19001909
    19011910        return
    1902 
Note: See TracChangeset for help on using the changeset viewer.
hosted by ZAMG