i.oif.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. #% keyword: imagery
  23. #% keyword: multispectral
  24. #% keyword: 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.utils import parse_key_val
  43. from grass.script import core as grass
  44. def oifcalc(sdev, corr, k1, k2, k3):
  45. grass.debug(_("Calculating OIF for combination: %s, %s, %s" % (k1, k2,
  46. k3)), 1)
  47. # calculate SUM of Stddeviations:
  48. ssdev = [sdev[k1], sdev[k2], sdev[k3]]
  49. numer = sum(ssdev)
  50. # calculate SUM of absolute(Correlation values):
  51. scorr = [corr[k1, k2], corr[k1, k3], corr[k2, k3]]
  52. denom = sum(map(abs, scorr))
  53. # Calculate OIF index:
  54. # Divide (SUM of Stddeviations) and (SUM of Correlation)
  55. return numer / denom
  56. def perms(bands):
  57. n = len(bands)
  58. for i in range(0, n - 2):
  59. for j in range(i + 1, n - 1):
  60. for k in range(j + 1, n):
  61. yield (bands[i], bands[j], bands[k])
  62. def main():
  63. shell = flags['g']
  64. serial = flags['s']
  65. bands = options['input'].split(',')
  66. if len(bands) < 4:
  67. grass.fatal(_("At least four input maps required"))
  68. output = options['output']
  69. # calculate the Stddev for TM bands
  70. grass.message(_("Calculating standard deviations for all bands..."))
  71. stddev = {}
  72. if serial:
  73. for band in bands:
  74. grass.verbose("band %d" % band)
  75. s = grass.read_command('r.univar', flags='g', map=band)
  76. kv = parse_key_val(s)
  77. stddev[band] = float(kv['stddev'])
  78. else:
  79. # run all bands in parallel
  80. if "WORKERS" in os.environ:
  81. workers = int(os.environ["WORKERS"])
  82. else:
  83. workers = len(bands)
  84. proc = {}
  85. pout = {}
  86. # spawn jobs in the background
  87. n = 0
  88. for band in bands:
  89. proc[band] = grass.pipe_command('r.univar', flags='g', map=band)
  90. if n % workers is 0:
  91. # wait for the ones launched so far to finish
  92. for bandp in bands[:n]:
  93. if not proc[bandp].stdout.closed:
  94. pout[bandp] = proc[bandp].communicate()[0]
  95. proc[bandp].wait()
  96. n = n + 1
  97. # wait for jobs to finish, collect the output
  98. for band in bands:
  99. if not proc[band].stdout.closed:
  100. pout[band] = proc[band].communicate()[0]
  101. proc[band].wait()
  102. # parse the results
  103. for band in bands:
  104. kv = parse_key_val(pout[band])
  105. stddev[band] = float(kv['stddev'])
  106. grass.message(_("Calculating Correlation Matrix..."))
  107. correlation = {}
  108. s = grass.read_command('r.covar', flags='r', map=[band for band in bands],
  109. quiet=True)
  110. # We need to skip the first line, since r.covar prints the number of values
  111. lines = s.splitlines()
  112. for i, row in zip(bands, lines[1:]):
  113. for j, cell in zip(bands, row.split(' ')):
  114. correlation[i, j] = float(cell)
  115. # Calculate all combinations
  116. grass.message(_("Calculating OIF for all band combinations..."))
  117. oif = []
  118. for p in perms(bands):
  119. oif.append((oifcalc(stddev, correlation, *p), p))
  120. oif.sort(reverse=True)
  121. grass.verbose(_("The Optimum Index Factor analysis result "
  122. "(best combination shown first):"))
  123. if shell:
  124. fmt = "%s,%s,%s:%.4f\n"
  125. else:
  126. fmt = "%s, %s, %s: %.4f\n"
  127. if not output or output == '-':
  128. for v, p in oif:
  129. sys.stdout.write(fmt % (p + (v,)))
  130. else:
  131. outf = open(output, 'w')
  132. for v, p in oif:
  133. outf.write(fmt % (p + (v,)))
  134. outf.close()
  135. if __name__ == "__main__":
  136. options, flags = grass.parser()
  137. main()