Changes between Version 7 and Version 8 of FpInputMetMkavail


Ignore:
Timestamp:
Dec 13, 2018, 3:09:06 PM (5 years ago)
Author:
pesei
Comment:

version 7 now also inline

Legend:

Unmodified
Added
Removed
Modified
  • FpInputMetMkavail

    v7 v8  
    1010{{{#!python
    1111#!/usr/bin/env python
    12 #!/usr/bin/env python
    13 
    14 """
    15 SYNOPSIS
    16 
    17   mk_AVAILABLE.py: [-s,--startdate] [-e,--enddate] [-m,--model /ECWMF/ERAI/EI/E5/EA/GFS] [-p, --path] [-a, --avpath] [-i, --interval] [-h] [-v,--verbose] [--version]
    18 
    19 DESCRIPTION
    20 
    21   mk_AVAIL is a script to create AVAILABLE files for FLEXPART windfields.
    22 
    23   Example usage:
    24   %mk_AVAIL.py -s 200601 -e 200701 -m ECMWF -p . -h
    25 
    26   would create a file: AVAIALABLE that contained paths
    27   of all files available in the current directory between 200601 and 200701.
    28   The default start date is 197001 and the default end date is TODAY.
    29  
    30   adapted and simplified version / Petra Seibert
    31   v.004: add ERA-Interim with EI as model, proper sorting of dates if year 2000 included, option to define a path for AVAILABLE / Petra Seibert 2015-10-21
    32   v.005: check whether any files are found before opening AVAILABLE, if not issue warning and stop. / Petra Seibert 2015-12-07
    33   v.006 PS 2018-04-24:   add ERA5 as model option
    34  
    35 QUESTIONS to
    36 
    37   JFB: <jfb@nilu.no>
    38   version>=003: petra.seibert at boku.ac.at
    39 
    40 LICENSE
    41 
    42   This script follows creative commons usage.
    43   Valid-License-Identifier: CC-BY-4.0
    44 
    45 VERSION
    46 
    47   $Id: 0.006 $
    48 
    49 """
    50 
    51 import sys
    52 import os
    53 import traceback
    54 import optparse
    55 import time
    56 import datetime
    57 import socket
    58 import glob
    59 import string
    60 
    61 
    62 def main ():
    63 
    64   global options, args, models
    65   version = '$Id: 0.006 $' 
    66  
    67   WIND_dir = '/xnilu_wrk/flex_wrk/WIND_FIELDS'
    68  
    69   # dict of dicts with model information
    70   # timeindex: index in the filne name string where the time information starts
    71   print  MODEL.keys()
    72 
    73   AVAIL_head = """DATE   TIME     FILENAME       SPECIFICATIONS\
    74   \nYYYYMMDD HHMISS\
    75   \n________ ______    __________________    __________________\n"""
    76   start_date = options.startdate
    77   sy = int(start_date[0:4])
    78   sm = int(start_date[4:6])
    79   end_date = options.enddate
    80   ey = int(end_date[0:4])
    81   em = int(end_date[4:6])
    82  
    83   #Get the directory information
    84   M = MODEL[options.model]
    85   prfx = M['prefix']
    86   t = options.path
    87   avpath = options.avpath
    88  
    89  
    90   #Loop through the files in the directories
    91  
    92   warned = False
    93   d = t #directory
    94  
    95   tind = M['timeindex'] #timestamp index
    96   searchstr = os.path.join(t,prfx)
    97   print 'searchstring:',searchstr
    98   files = glob.glob(searchstr + '*')
    99   if options.verbose: print len(files), ' wind-field files found'
    100   dict_dates={}
    101   for f in files:
    102     if (f[0:2] == './'): f = f[2:] # PS - remove this part if present
    103     fn = os.path.basename(f)
    104     if fn[-1] != '*':
    105       timestamp = fn[tind:]
    106       year = int(timestamp[0:2])
    107       if year < 58:
    108         year += 2000
    109       else:
    110         year += 1900
    111       dtstring = str(year)+' '+timestamp[2:9]
    112       dict_dates[dtstring] = f
    113   dates = sorted(dict_dates.items())
    114   if len(dates) == 0:
    115     print 'no files found with this search string'
    116     print 'aborting. '
    117     sys.exit(0)
    118   else:
    119     print 'found ',len(dates),'files'
    120     #Prepare output files
    121     fout = file(os.path.join(avpath,'AVAILABLE'),'w')
    122     fout.write(AVAIL_head)
    123 
    124   for i,date in enumerate(dates): # go through dates in ascending order
    125     f = date[1] # now we have the filename+path
    126     fn = os.path.basename(f)
    127     if fn[-1]!='*':
    128       timestamp = fn[tind:]
    129       year = int(timestamp[0:2])
    130       if year < 58:
    131         year += 2000
    132       else:
    133         year += 1900
    134       month = int(timestamp[2:4])
    135       day   = int(timestamp[4:6])
    136       hour  = int(timestamp[6:8])
    137       fileT = year*100 + int(month)
    138 # PS: now check for irregular intervals     
    139       date = datetime.datetime(year,month,day,hour)
    140       if i == 2:
    141         if options.timeint == '':
    142           timeint = date - date1
    143         else:
    144           timeint = datetime.timedelta(0,3600*int(options.timeint)) 
    145         if timeint != date - date1:
    146           print 'WARNING - irregular interval',date - date1
    147           print date1,f1,'\n',date, f,'\n'
    148       elif i > 2:
    149         if timeint != date - date1:
    150           print 'WARNING - irregular interval',date - date1
    151           print date1,f1,'\n',date, f,'\n'
    152         if options.timeint == '': timeint = date - date1
    153       date1 = date 
    154       f1 = f
    155      
    156       if i%5000 == 0: print 'progress:', i, 'of', len(dates), f
    157      
    158       if fileT >= sy*100 + sm and fileT <= ey*100 + em :
    159 
    160         relpath = os.path.relpath( os.path.dirname(f), avpath )
    161         f = os.path.join(relpath,fn)
    162 
    163         if (f[0:2] == './'): f = f[2:] #  remove this part if present
    164 
    165         if len(f) > 18: #PS
    166           if not warned:
    167             print 'WARNING: Flexpart can only read 18 chars in WF-name'
    168             print f, ' has ', len(f), ' characters!\n'
    169             warned = True
    170 
    171         #This is the fortran format: (i8,1x,i6,2(6x,a18))
    172         string = "%s%s%s %s0000    %s    ON DISC\n" %\
    173          (year,str(month).zfill(2),str(day).zfill(2),str(hour).zfill(2),f.ljust(18))
    174         fout.write(string)
    175 
    176   print 'Done: ',i+1 # as i starts with 0
    177   print 'Written:', os.path.join(avpath,'AVAILABLE')
    178   fout.close()
    179 
    180 if __name__ == '__main__':
    181   MODEL = {}
    182   MODEL['ECMWF'] = {'prefix':'EN', 'timeindex':2}
    183   MODEL['ERAI']  = {'prefix':'EI', 'timeindex':2}
    184   MODEL['EI']  = {'prefix':'EI', 'timeindex':2}
    185   MODEL['E5']  = {'prefix':'E5', 'timeindex':2}
    186   MODEL['EA']  = {'prefix':'EA', 'timeindex':2}
    187   MODEL['GFS']   = {'prefix':'GF', 'timeindex':2}
    188  
    189   models = '/'.join(MODEL.keys())
    190  
    191   try:
    192     start_time = time.time()
    193     today = datetime.datetime.now()
    194 
    195     parser = optparse.OptionParser(
    196         formatter = optparse.TitledHelpFormatter(),
    197         usage = globals()['__doc__'])
    198 
    199     parser.add_option ('-v', '--verbose', action = 'store_true',
    200         default = False, help = 'verbose output')
    201 
    202     parser.add_option ('-s', '--startdate',
    203         dest = 'startdate',
    204         default = '197001',
    205         help = 'startdate YYYYMM integer')
    206 
    207     parser.add_option ('-e', '--enddate',
    208         # setting default as TODAY
    209         dest = 'enddate',
    210         default = str(today.year) + str(today.month).zfill(2),
    211         #default = '200712',
    212         help = 'enddate YYYYMM integer')
    213 
    214     parser.add_option ('-m', '--model',
    215         dest = 'model',
    216         default = 'ECMWF', help = models)
    217 
    218     parser.add_option ('-p', '--path',
    219         dest = 'path',
    220         default = '.', help = 'path to be searched for windfields. Escape or quote * and ? ')
    221 
    222     parser.add_option ('-a', '--avpath',
    223         dest = 'avpath',
    224         default = '.', help = 'path for AVAILABLE file ')
    225 
    226     parser.add_option ('-i', '--interval',
    227         dest = 'timeint',
    228         default = '', help = 'expected time interval in h. If omitted, show every change')
    229 
    230     (options, args) = parser.parse_args()
    231 
    232     #QUERY['modelType'] = options.model
    233     #QUERY['start_date'] = options.startdate
    234     #QUERY['end_date'] = options.enddate
    235  
    236     #if len(args) < 1:
    237     #  parser.error ('missing argument')
    238 
    239     if options.verbose: print time.asctime()
    240     exit_code = main()
    241     if exit_code is None:
    242       exit_code = 0
    243     if options.verbose: print time.asctime()
    244     if options.verbose: print 'TOTAL TIME IN MINUTES:',
    245     if options.verbose: print (time.time() - start_time) / 60.0
    246     sys.exit(exit_code)
    247   except KeyboardInterrupt, e: # Ctrl-C
    248     raise e
    249   except SystemExit, e: # sys.exit()
    250     raise e
    251   except Exception, e:
    252     print 'ERROR, UNEXPECTED EXCEPTION'
    253     print str(e)
    254     traceback.print_exc()
    255     os._exit(1)
    256    
    257  
    258 
    259 # vim:set sr et ts=4 sw=4 ft=python fenc=utf-8: // See Vim, :help 'modeline'
     122       
     133       """
     144       SYNOPSIS
     155       
     166         mk_AVAILABLE.py: [-s,--startdate] [-e,--enddate] [-m,--model /ECWMF/ERAI/EI/E5/EA/GFS] [-p, --path] [-a, --avpath] [-i, --interval] [-h] [-v,--verbose] [--version]
     177       
     188       DESCRIPTION
     199       
     2010        mk_AVAIL is a script to create AVAILABLE files for FLEXPART windfields.
     2111     
     2212        Example usage:
     2313        %mk_AVAIL.py -s 200601 -e 200701 -m ECMWF -p . -h
     2414     
     2515        would create a file: AVAIALABLE that contained paths
     2616        of all files available in the current directory between 200601 and 200701.
     2717        The default start date is 197001 and the default end date is TODAY.
     2818       
     2919        adapted and simplified version / Petra Seibert
     3020        v.004: add ERA-Interim with EI as model, proper sorting of dates if year 2000 included, option to define a path for AVAILABLE / Petra Seibert 2015-10-21
     3121        v.005: check whether any files are found before opening AVAILABLE, if not issue warning and stop. / Petra Seibert 2015-12-07
     3222        v.006 PS 2018-04-24:   add ERA5 as model option
     3323        v.007 PS 2018-06-25:   correct bug introduced in v006: 2 spaces missing in output format
     3424       
     3525      QUESTIONS to
     3626     
     3727        JFB: <jfb@nilu.no>
     3828        version>=003: petra.seibert at boku.ac.at
     3929     
     4030      LICENSE
     4131     
     4232        This script follows creative commons usage.
     4333        Valid-License-Identifier: CC-BY-4.0
     4434     
     4535      VERSION
     4636     
     4737        $Id: 0.006 $
     4838     
     4939      """
     5040     
     5141      import sys
     5242      import os
     5343      import traceback
     5444      import optparse
     5545      import time
     5646      import datetime
     5747      import socket
     5848      import glob
     5949      import string
     6050     
     6151     
     6252      def main ():
     6353     
     6454        global options, args, models
     6555        version = '$Id: 0.006 $'
     6656       
     6757        WIND_dir = '/xnilu_wrk/flex_wrk/WIND_FIELDS'
     6858       
     6959        # dict of dicts with model information
     7060        # timeindex: index in the filne name string where the time information starts
     7161        print  MODEL.keys()
     7262     
     7363        AVAIL_head = \
     7464        """DATE     TIME        FILENAME             SPECIFICATIONS\
     7565         \nYYYYMMDD HHMISS\
     7666        \n________ ______      __________________    __________________\n"""
     7767        start_date = options.startdate
     7868        sy = int(start_date[0:4])
     7969        sm = int(start_date[4:6])
     8070        end_date = options.enddate
     8171        ey = int(end_date[0:4])
     8272        em = int(end_date[4:6])
     8373       
     8474        #Get the directory information
     8575        M = MODEL[options.model]
     8676        prfx = M['prefix']
     8777        t = options.path
     8878        avpath = options.avpath
     8979       
     9080       
     9181        #Loop through the files in the directories
     9282       
     9383        warned = False
     9484        d = t #directory
     9585       
     9686        tind = M['timeindex'] #timestamp index
     9787        searchstr = os.path.join(t,prfx)
     9888        print 'searchstring:',searchstr
     9989        files = glob.glob(searchstr + '*')
     10090        if options.verbose: print len(files), ' wind-field files found'
     10191        dict_dates={}
     10292        for f in files:
     10393          if (f[0:2] == './'): f = f[2:] # PS - remove this part if present
     10494          fn = os.path.basename(f)
     10595          if fn[-1] != '*':
     10696            timestamp = fn[tind:]
     10797            year = int(timestamp[0:2])
     10898            if year < 58:
     10999              year += 2000
     110100           else:
     111101             year += 1900
     112102           dtstring = str(year)+' '+timestamp[2:9]
     113103           dict_dates[dtstring] = f
     114104       dates = sorted(dict_dates.items())
     115105       if len(dates) == 0:
     116106         print 'no files found with this search string'
     117107         print 'aborting. '
     118108         sys.exit(0)
     119109       else:
     120110         print 'found ',len(dates),'files'
     121111         #Prepare output files
     122112         fout = file(os.path.join(avpath,'AVAILABLE'),'w')
     123113         fout.write(AVAIL_head)
     124114     
     125115       for i,date in enumerate(dates): # go through dates in ascending order
     126116         f = date[1] # now we have the filename+path
     127117         fn = os.path.basename(f)
     128118         if fn[-1]!='*':
     129119           timestamp = fn[tind:]
     130120           year = int(timestamp[0:2])
     131121           if year < 58:
     132122             year += 2000
     133123           else:
     134124             year += 1900
     135125           month = int(timestamp[2:4])
     136126           day   = int(timestamp[4:6])
     137127           hour  = int(timestamp[6:8])
     138128           fileT = year*100 + int(month)
     139129     # PS: now check for irregular intervals     
     140130           date = datetime.datetime(year,month,day,hour)
     141131           if i == 2:
     142132             if options.timeint == '':
     143133               timeint = date - date1
     144134             else:
     145135               timeint = datetime.timedelta(0,3600*int(options.timeint))
     146136             if timeint != date - date1:
     147137               print 'WARNING - irregular interval',date - date1
     148138               print date1,f1,'\n',date, f,'\n'
     149139           elif i > 2:
     150140             if timeint != date - date1:
     151141               print 'WARNING - irregular interval',date - date1
     152142               print date1,f1,'\n',date, f,'\n'
     153143             if options.timeint == '': timeint = date - date1
     154144           date1 = date
     155145           f1 = f
     156146         
     157147           if i%5000 == 0: print 'progress:', i, 'of', len(dates), f
     158148         
     159149           if fileT >= sy*100 + sm and fileT <= ey*100 + em :
     160150     
     161151             relpath = os.path.relpath( os.path.dirname(f), avpath )
     162152             f = os.path.join(relpath,fn)
     163153     
     164154             if (f[0:2] == './'): f = f[2:] #  remove this part if present
     165155     
     166156             if len(f) > 18: #PS
     167157               if not warned:
     168158                 print 'WARNING: Flexpart can only read 18 chars in WF-name'
     169159                 print f, ' has ', len(f), ' characters!\n'
     170160                 warned = True
     171161     
     172162             #This is the fortran format: (i8,1x,i6,2(6x,a18))
     173163             string = "%s%s%s %s0000      %s    ON DISC\n" %\
     174164              (year,str(month).zfill(2),str(day).zfill(2),str(hour).zfill(2),f.ljust(18))
     175165             fout.write(string)
     176166     
     177167       print 'Done: ',i+1 # as i starts with 0
     178168       print 'Written:', os.path.join(avpath,'AVAILABLE')
     179169       fout.close()
     180170     
     181171     if __name__ == '__main__':
     182172       MODEL = {}
     183173       MODEL['ECMWF'] = {'prefix':'EN', 'timeindex':2}
     184174       MODEL['ERAI']  = {'prefix':'EI', 'timeindex':2}
     185175       MODEL['EI']  = {'prefix':'EI', 'timeindex':2}
     186176       MODEL['E5']  = {'prefix':'E5', 'timeindex':2}
     187177       MODEL['EA']  = {'prefix':'EA', 'timeindex':2}
     188178       MODEL['GFS']   = {'prefix':'GF', 'timeindex':2}
     189179     
     190180       models = '/'.join(MODEL.keys())
     191181     
     192182       try:
     193183         start_time = time.time()
     194184         today = datetime.datetime.now()
     195185     
     196186         parser = optparse.OptionParser(
     197187             formatter = optparse.TitledHelpFormatter(),
     198188             usage = globals()['__doc__'])
     199189     
     200190         parser.add_option ('-v', '--verbose', action = 'store_true',
     201191             default = False, help = 'verbose output')
     202192     
     203193         parser.add_option ('-s', '--startdate',
     204194             dest = 'startdate',
     205195             default = '197001',
     206196             help = 'startdate YYYYMM integer')
     207197     
     208198         parser.add_option ('-e', '--enddate',
     209199             # setting default as TODAY
     210200             dest = 'enddate',
     211201             default = str(today.year) + str(today.month).zfill(2),
     212202             #default = '200712',
     213203             help = 'enddate YYYYMM integer')
     214204     
     215205         parser.add_option ('-m', '--model',
     216206             dest = 'model',
     217207             default = 'ECMWF', help = models)
     218208     
     219209         parser.add_option ('-p', '--path',
     220210             dest = 'path',
     221211             default = '.', help = 'path to be searched for windfields. Escape or quote * and ? ')
     222212     
     223213         parser.add_option ('-a', '--avpath',
     224214             dest = 'avpath',
     225215             default = '.', help = 'path for AVAILABLE file ')
     226216     
     227217         parser.add_option ('-i', '--interval',
     228218             dest = 'timeint',
     229219             default = '', help = 'expected time interval in h. If omitted, show every change')
     230220     
     231221         (options, args) = parser.parse_args()
     232222     
     233223         #QUERY['modelType'] = options.model
     234224         #QUERY['start_date'] = options.startdate
     235225         #QUERY['end_date'] = options.enddate
     236226     
     237227         #if len(args) < 1:
     238228         #  parser.error ('missing argument')
     239229     
     240230         if options.verbose: print time.asctime()
     241231         exit_code = main()
     242232         if exit_code is None:
     243233           exit_code = 0
     244234         if options.verbose: print time.asctime()
     245235         if options.verbose: print 'TOTAL TIME IN MINUTES:',
     246236         if options.verbose: print (time.time() - start_time) / 60.0
     247237         sys.exit(exit_code)
     248238       except KeyboardInterrupt, e: # Ctrl-C
     249239         raise e
     250240       except SystemExit, e: # sys.exit()
     251241         raise e
     252242       except Exception, e:
     253243         print 'ERROR, UNEXPECTED EXCEPTION'
     254244         print str(e)
     255245         traceback.print_exc()
     256246         os._exit(1)
     257247       
     258248     
     259249     
     260250     # vim:set sr et
    260261}}}