r.reclass.area.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: r.reclass.area
  5. # AUTHOR(S): NRCS
  6. # Converted to Python by Glynn Clements
  7. # Added rmarea method by Luca Delucchi
  8. # PURPOSE: Reclasses a raster map greater or less than user specified area size (in hectares)
  9. # COPYRIGHT: (C) 1999,2008,2014 by the GRASS Development Team
  10. #
  11. # This program is free software under the GNU General Public
  12. # License (>=v2). Read the file COPYING that comes with GRASS
  13. # for details.
  14. #
  15. #############################################################################
  16. # 10/2013: added option to use a pre-clumped input map (Eric Goddard)
  17. # 8/2012: added fp maps support, cleanup, removed tabs AK
  18. # 3/2007: added label support MN
  19. # 3/2004: added parser support MN
  20. # 11/2001 added mapset support markus
  21. # 2/2001 fixes markus
  22. # 2000: updated to GRASS 5
  23. # 1998 from NRCS, slightly modified for GRASS 4.2.1
  24. #%module
  25. #% description: Reclasses a raster map greater or less than user specified area size (in hectares).
  26. #% keyword: raster
  27. #% keyword: statistics
  28. #% keyword: aggregation
  29. #%end
  30. #%option G_OPT_R_INPUT
  31. #%end
  32. #%option G_OPT_R_OUTPUT
  33. #%end
  34. #%option
  35. #% key: value
  36. #% type: double
  37. #% description: Value option that sets the area size limit (in hectares)
  38. #% required: yes
  39. #% guisection: Area
  40. #%end
  41. #%option
  42. #% key: mode
  43. #% type: string
  44. #% description: Lesser or greater than specified value
  45. #% options: lesser,greater
  46. #% required: yes
  47. #% guisection: Area
  48. #%end
  49. #%option
  50. #% key: method
  51. #% type: string
  52. #% description: Method used for reclassification
  53. #% options: reclass,rmarea
  54. #% answer: reclass
  55. #% guisection: Area
  56. #%end
  57. #%flag
  58. #% key: c
  59. #% description: Input map is clumped
  60. #%end
  61. #%flag
  62. #% key: d
  63. #% description: Clumps including diagonal neighbors
  64. #%end
  65. import sys
  66. import os
  67. import atexit
  68. import grass.script as grass
  69. TMPRAST = []
  70. def reclass(inf, outf, lim, clump, diag, les):
  71. infile = inf
  72. outfile = outf
  73. lesser = les
  74. limit = lim
  75. clumped = clump
  76. diagonal = diag
  77. s = grass.read_command("g.region", flags='p')
  78. kv = grass.parse_key_val(s, sep=':')
  79. s = kv['projection'].strip().split()
  80. if s == '0':
  81. grass.fatal(_("xy-locations are not supported"))
  82. grass.fatal(_("Need projected data with grids in meters"))
  83. if not grass.find_file(infile)['name']:
  84. grass.fatal(_("Raster map <%s> not found") % infile)
  85. if clumped and diagonal:
  86. grass.fatal(_("flags c and d are mutually exclusive"))
  87. if clumped:
  88. clumpfile = infile
  89. else:
  90. clumpfile = "%s.clump.%s" % (infile.split('@')[0], outfile)
  91. TMPRAST.append(clumpfile)
  92. if not grass.overwrite():
  93. if grass.find_file(clumpfile)['name']:
  94. grass.fatal(_("Temporary raster map <%s> exists") % clumpfile)
  95. if diagonal:
  96. grass.message(_("Generating a clumped raster file including "
  97. "diagonal neighbors..."))
  98. grass.run_command('r.clump', flags='d', input=infile,
  99. output=clumpfile)
  100. else:
  101. grass.message(_("Generating a clumped raster file ..."))
  102. grass.run_command('r.clump', input=infile, output=clumpfile)
  103. if lesser:
  104. grass.message(_("Generating a reclass map with area size less than "
  105. "or equal to %f hectares...") % limit)
  106. else:
  107. grass.message(_("Generating a reclass map with area size greater "
  108. "than or equal to %f hectares...") % limit)
  109. recfile = outfile + '.recl'
  110. TMPRAST.append(recfile)
  111. sflags = 'aln'
  112. if grass.raster_info(infile)['datatype'] in ('FCELL', 'DCELL'):
  113. sflags += 'i'
  114. p1 = grass.pipe_command('r.stats', flags=sflags, input=(clumpfile, infile),
  115. sep=';')
  116. p2 = grass.feed_command('r.reclass', input=clumpfile, output=recfile,
  117. rules='-')
  118. rules = ''
  119. for line in p1.stdout:
  120. f = line.rstrip(os.linesep).split(';')
  121. if len(f) < 5:
  122. continue
  123. hectares = float(f[4]) * 0.0001
  124. if lesser:
  125. test = hectares <= limit
  126. else:
  127. test = hectares >= limit
  128. if test:
  129. rules += "%s = %s %s\n" % (f[0], f[2], f[3])
  130. if rules:
  131. p2.stdin.write(rules)
  132. p1.wait()
  133. p2.stdin.close()
  134. p2.wait()
  135. if p2.returncode != 0:
  136. if lesser:
  137. grass.fatal(_("No areas of size less than or equal to %f "
  138. "hectares found.") % limit)
  139. else:
  140. grass.fatal(_("No areas of size greater than or equal to %f "
  141. "hectares found.") % limit)
  142. grass.mapcalc("$outfile = $recfile", outfile=outfile, recfile=recfile)
  143. def rmarea(infile, outfile, thresh, coef):
  144. # transform user input from hectares to map units (kept this for future)
  145. # thresh = thresh * 10000.0 / (float(coef)**2)
  146. # grass.debug("Threshold: %d, coeff linear: %s, coef squared: %d" % (thresh, coef, (float(coef)**2)), 0)
  147. # transform user input from hectares to meters because currently v.clean
  148. # rmarea accept only meters as threshold
  149. thresh = thresh * 10000.0
  150. vectfile = "%s_vect_%s" % (infile.split('@')[0], outfile)
  151. TMPRAST.append(vectfile)
  152. grass.run_command('r.to.vect', input=infile, output=vectfile, type='area')
  153. cleanfile = "%s_clean_%s" % (infile.split('@')[0], outfile)
  154. TMPRAST.append(cleanfile)
  155. grass.run_command('v.clean', input=vectfile, output=cleanfile,
  156. tool='rmarea', threshold=thresh)
  157. grass.run_command('v.to.rast', input=cleanfile, output=outfile,
  158. use='attr', attrcolumn='value')
  159. def main():
  160. infile = options['input']
  161. value = options['value']
  162. mode = options['mode']
  163. outfile = options['output']
  164. global method
  165. method = options['method']
  166. clumped = flags['c']
  167. diagonal = flags['d']
  168. # check for unsupported locations
  169. in_proj = grass.parse_command('g.proj', flags='g')
  170. if in_proj['unit'].lower() == 'degree':
  171. grass.fatal(_("Latitude-longitude locations are not supported"))
  172. if in_proj['name'].lower() == 'xy_location_unprojected':
  173. grass.fatal(_("xy-locations are not supported"))
  174. # check lesser and greater parameters
  175. limit = float(value)
  176. if mode == 'greater' and method == 'rmarea':
  177. grass.fatal(_("You have to specify mode='lesser' with method='rmarea'"))
  178. if not grass.find_file(infile)['name']:
  179. grass.fatal(_("Raster map <%s> not found") % infile)
  180. if method == 'reclass':
  181. reclass(infile, outfile, limit, clumped, diagonal, mode == 'lesser')
  182. elif method == 'rmarea':
  183. rmarea(infile, outfile, limit, in_proj['meters'])
  184. grass.message(_("Generating output raster map <%s>...") % outfile)
  185. def cleanup():
  186. """!Delete temporary maps"""
  187. TMPRAST.reverse() # reclassed map first
  188. for mapp in TMPRAST:
  189. if method == 'rmarea':
  190. grass.run_command("g.remove", flags='f', type='vector', name=mapp,
  191. quiet=True)
  192. else:
  193. grass.run_command("g.remove", flags='f', type='raster', name=mapp,
  194. quiet=True)
  195. if __name__ == "__main__":
  196. options, flags = grass.parser()
  197. atexit.register(cleanup)
  198. sys.exit(main())