i.oif.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: i.oif
  5. # AUTHOR(S): Markus Neteler 21.July 1998
  6. # Updated for GRASS 5.7 by Michael Barton 2004/04/05
  7. # Converted to Python by Glynn Clements
  8. # Customised by Nikos Alexandris 04. August 2013
  9. # Customised by Luca Delucchi Vienna Code Sprint 2014
  10. # PURPOSE: calculates the Optimum Index factor of all band combinations
  11. # for LANDSAT TM 1,2,3,4,5,7
  12. # COPYRIGHT: (C) 1999,2008 by the GRASS Development Team
  13. #
  14. # This program is free software under the GNU General Public
  15. # License (>=v2). Read the file COPYING that comes with GRASS
  16. # for details.
  17. #
  18. # Ref.: Jensen: Introductory digital image processing 1996, p.98
  19. #############################################################################
  20. #% Module
  21. #% description: Calculates Optimum-Index-Factor table for spectral bands
  22. #% keywords: imagery
  23. #% keywords: multispectral
  24. #% keywords: statistics
  25. #% End
  26. #% option G_OPT_R_INPUTS
  27. #% end
  28. #% option G_OPT_F_OUTPUT
  29. #% description: Name for output file (if omitted or "-" output to stdout)
  30. #% required: no
  31. #% end
  32. #% Flag
  33. #% key: g
  34. #% description: Print in shell script style
  35. #% End
  36. #% Flag
  37. #% key: s
  38. #% description: Process bands serially (default: run in parallel)
  39. #% End
  40. import sys
  41. import os
  42. from grass.script import core as grass
  43. def oifcalc(sdev, corr, k1, k2, k3):
  44. grass.debug(_("Calculating OIF for combination: %s, %s, %s" % (k1, k2,
  45. k3)), 1)
  46. # calculate SUM of Stddeviations:
  47. ssdev = [sdev[k1], sdev[k2], sdev[k3]]
  48. numer = sum(ssdev)
  49. # calculate SUM of absolute(Correlation values):
  50. scorr = [corr[k1, k2], corr[k1, k3], corr[k2, k3]]
  51. denom = sum(map(abs, scorr))
  52. # Calculate OIF index:
  53. # Divide (SUM of Stddeviations) and (SUM of Correlation)
  54. return numer / denom
  55. def perms(bands):
  56. n = len(bands)
  57. for i in range(0, n - 2):
  58. for j in range(i + 1, n - 1):
  59. for k in range(j + 1, n):
  60. yield (bands[i], bands[j], bands[k])
  61. def main():
  62. shell = flags['g']
  63. serial = flags['s']
  64. bands = options['input'].split(',')
  65. output = options['output']
  66. # calculate the Stddev for TM bands
  67. grass.message(_("Calculating Standard deviations for all bands..."))
  68. stddev = {}
  69. if serial:
  70. for band in bands:
  71. grass.verbose("band %d" % band)
  72. s = grass.read_command('r.univar', flags='g', map=band)
  73. kv = grass.parse_key_val(s)
  74. stddev[band] = float(kv['stddev'])
  75. else:
  76. # run all bands in parallel
  77. if "WORKERS" in os.environ:
  78. workers = int(os.environ["WORKERS"])
  79. else:
  80. workers = len(bands)
  81. proc = {}
  82. pout = {}
  83. # spawn jobs in the background
  84. n = 0
  85. for band in bands:
  86. proc[band] = grass.pipe_command('r.univar', flags='g', map=band)
  87. if n % workers is 0:
  88. # wait for the ones launched so far to finish
  89. for bandp in bands[:n]:
  90. if not proc[bandp].stdout.closed:
  91. pout[bandp] = proc[bandp].communicate()[0]
  92. proc[bandp].wait()
  93. n = n + 1
  94. # wait for jobs to finish, collect the output
  95. for band in bands:
  96. if not proc[band].stdout.closed:
  97. pout[band] = proc[band].communicate()[0]
  98. proc[band].wait()
  99. # parse the results
  100. for band in bands:
  101. kv = grass.parse_key_val(pout[band])
  102. stddev[band] = float(kv['stddev'])
  103. grass.message(_("Calculating Correlation Matrix..."))
  104. correlation = {}
  105. s = grass.read_command('r.covar', flags='r', map=[band for band in bands],
  106. quiet=True)
  107. for i, row in zip(bands, s.splitlines()):
  108. for j, cell in zip(bands, row.split(' ')):
  109. correlation[i, j] = float(cell)
  110. # Calculate all combinations
  111. grass.message(_("Calculating OIF for all band combinations..."))
  112. oif = []
  113. for p in perms(bands):
  114. oif.append((oifcalc(stddev, correlation, *p), p))
  115. oif.sort(reverse=True)
  116. grass.verbose(_("The Optimum Index Factor analysis result " \
  117. "(Best combination comes first):"))
  118. if shell:
  119. fmt = "%s%s%s:%.4f\n"
  120. else:
  121. fmt = "%s%s%s: %.4f\n"
  122. if not output or output == '-':
  123. for v, p in oif:
  124. sys.stdout.write(fmt % (p + (v,)))
  125. else:
  126. outf = file(output, 'w')
  127. for v, p in oif:
  128. outf.write(fmt % (p + (v,)))
  129. outf.close()
  130. if __name__ == "__main__":
  131. options, flags = grass.parser()
  132. main()