i.oif.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. if len(bands) < 4:
  66. grass.fatal(_("At least four input maps required"))
  67. output = options['output']
  68. # calculate the Stddev for TM bands
  69. grass.message(_("Calculating standard deviations for all bands..."))
  70. stddev = {}
  71. if serial:
  72. for band in bands:
  73. grass.verbose("band %d" % band)
  74. s = grass.read_command('r.univar', flags='g', map=band)
  75. kv = grass.parse_key_val(s)
  76. stddev[band] = float(kv['stddev'])
  77. else:
  78. # run all bands in parallel
  79. if "WORKERS" in os.environ:
  80. workers = int(os.environ["WORKERS"])
  81. else:
  82. workers = len(bands)
  83. proc = {}
  84. pout = {}
  85. # spawn jobs in the background
  86. n = 0
  87. for band in bands:
  88. proc[band] = grass.pipe_command('r.univar', flags='g', map=band)
  89. if n % workers is 0:
  90. # wait for the ones launched so far to finish
  91. for bandp in bands[:n]:
  92. if not proc[bandp].stdout.closed:
  93. pout[bandp] = proc[bandp].communicate()[0]
  94. proc[bandp].wait()
  95. n = n + 1
  96. # wait for jobs to finish, collect the output
  97. for band in bands:
  98. if not proc[band].stdout.closed:
  99. pout[band] = proc[band].communicate()[0]
  100. proc[band].wait()
  101. # parse the results
  102. for band in bands:
  103. kv = grass.parse_key_val(pout[band])
  104. stddev[band] = float(kv['stddev'])
  105. grass.message(_("Calculating Correlation Matrix..."))
  106. correlation = {}
  107. s = grass.read_command('r.covar', flags='r', map=[band for band in bands],
  108. quiet=True)
  109. for i, row in zip(bands, s.splitlines()):
  110. for j, cell in zip(bands, row.split(' ')):
  111. correlation[i, j] = float(cell)
  112. # Calculate all combinations
  113. grass.message(_("Calculating OIF for all band combinations..."))
  114. oif = []
  115. for p in perms(bands):
  116. oif.append((oifcalc(stddev, correlation, *p), p))
  117. oif.sort(reverse=True)
  118. grass.verbose(_("The Optimum Index Factor analysis result " \
  119. "(best combination shown first):"))
  120. if shell:
  121. fmt = "%s,%s,%s:%.4f\n"
  122. else:
  123. fmt = "%s, %s, %s: %.4f\n"
  124. if not output or output == '-':
  125. for v, p in oif:
  126. sys.stdout.write(fmt % (p + (v,)))
  127. else:
  128. outf = file(output, 'w')
  129. for v, p in oif:
  130. outf.write(fmt % (p + (v,)))
  131. outf.close()
  132. if __name__ == "__main__":
  133. options, flags = grass.parser()
  134. main()