get_LiNox.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #! /usr/bin/env python
  2. #
  3. # Just type:
  4. #
  5. # ./get_LiNox.py -h
  6. #
  7. # 27 Aug 2013 - P. Le Sager - V0
  8. #
  9. import os
  10. import sys
  11. import glob
  12. import re
  13. import time
  14. import argparse
  15. def total_linox(file):
  16. '''Return total LiNOx in "Tg N" from one log file'''
  17. # open file
  18. f=open(file,'r')
  19. r1='dynamics step from.*(\d{4}/\d{2}/\d{2} *\d+:\d+)'
  20. r2='global.*lightning emission *: *(\d+\.\d+) *Tg\[N\]/a'
  21. r3='--> second half : \d{4}/\d{2}/\d{2} *\d+:\d+ - (\d{4}/\d{2}/\d{2} *\d+:\d+)'
  22. total=0.
  23. line='abc'
  24. while line !='':
  25. line=f.readline()
  26. match=re.search(r1,line)
  27. if match:
  28. date1=match.group(1)
  29. while line !='':
  30. line=f.readline()
  31. emiss=re.search(r2,line)
  32. if emiss:
  33. while line !='':
  34. line=f.readline()
  35. half=re.search(r3,line)
  36. if half:
  37. date1_p=time.mktime(time.strptime(date1,"%Y/%m/%d %H:%M"))
  38. date2_p=time.mktime(time.strptime(half.group(1),"%Y/%m/%d %H:%M"))
  39. delta_sec = date2_p-date1_p
  40. total+=float(emiss.group(1))*delta_sec/(365.*24*60*60)
  41. break
  42. break
  43. return total
  44. ############################################################################################
  45. # MAIN : process all the files in specific directory #
  46. ############################################################################################
  47. if __name__ == "__main__":
  48. # --- Options: DIR and MASK
  49. parser = argparse.ArgumentParser(description='Compute Lightning NOx emissions total.')
  50. parser.add_argument('-d', '--dir', default=os.getcwd(),
  51. help='directory with log files to process. Default=current working dir.')
  52. parser.add_argument('-m', '--mask', default='*.out',
  53. help='mask to find the log files. Default="*.out"')
  54. args = parser.parse_args()
  55. directory = args.dir
  56. mask = args.mask
  57. # --- Get list of files
  58. print ""
  59. print "Looking for files in %s directory" % directory
  60. print ""
  61. try:
  62. os.chdir(directory)
  63. except:
  64. print "Cannot switch to %s directory" % directory
  65. sys.exit(1)
  66. files=glob.glob(os.path.join(directory,mask))
  67. if not files:
  68. print "No '%s' files in %s" % (mask, directory)
  69. sys.exit(0)
  70. # --- Proceed
  71. summ=0.
  72. for f in files:
  73. month=total_linox(f)
  74. print os.path.basename(f), month, 'Tg [N]'
  75. summ+=month
  76. print ""
  77. print 'Total: %s Tg[N]' % summ