r.reclass.area.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. #!/usr/bin/env python3
  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. from grass.script.utils import decode, encode
  70. TMPRAST = []
  71. def reclass(inf, outf, lim, clump, diag, les):
  72. infile = inf
  73. outfile = outf
  74. lesser = les
  75. limit = lim
  76. clumped = clump
  77. diagonal = diag
  78. s = grass.read_command("g.region", flags='p')
  79. s = decode(s)
  80. kv = grass.parse_key_val(s, sep=':')
  81. s = kv['projection'].strip().split()
  82. if s == '0':
  83. grass.fatal(_("xy-locations are not supported"))
  84. grass.fatal(_("Need projected data with grids in meters"))
  85. if not grass.find_file(infile)['name']:
  86. grass.fatal(_("Raster map <%s> not found") % infile)
  87. if clumped and diagonal:
  88. grass.fatal(_("flags c and d are mutually exclusive"))
  89. if clumped:
  90. clumpfile = infile
  91. else:
  92. clumpfile = "%s.clump.%s" % (infile.split('@')[0], outfile)
  93. TMPRAST.append(clumpfile)
  94. if not grass.overwrite():
  95. if grass.find_file(clumpfile)['name']:
  96. grass.fatal(_("Temporary raster map <%s> exists") % clumpfile)
  97. if diagonal:
  98. grass.message(_("Generating a clumped raster file including "
  99. "diagonal neighbors..."))
  100. grass.run_command('r.clump', flags='d', input=infile,
  101. output=clumpfile)
  102. else:
  103. grass.message(_("Generating a clumped raster file ..."))
  104. grass.run_command('r.clump', input=infile, output=clumpfile)
  105. if lesser:
  106. grass.message(_("Generating a reclass map with area size less than "
  107. "or equal to %f hectares...") % limit)
  108. else:
  109. grass.message(_("Generating a reclass map with area size greater "
  110. "than or equal to %f hectares...") % limit)
  111. recfile = outfile + '.recl'
  112. TMPRAST.append(recfile)
  113. sflags = 'aln'
  114. if grass.raster_info(infile)['datatype'] in ('FCELL', 'DCELL'):
  115. sflags += 'i'
  116. p1 = grass.pipe_command('r.stats', flags=sflags, input=(clumpfile, infile),
  117. sep=';')
  118. p2 = grass.feed_command('r.reclass', input=clumpfile, output=recfile,
  119. rules='-')
  120. rules = ''
  121. for line in p1.stdout:
  122. f = decode(line).rstrip(os.linesep).split(';')
  123. if len(f) < 5:
  124. continue
  125. hectares = float(f[4]) * 0.0001
  126. if lesser:
  127. test = hectares <= limit
  128. else:
  129. test = hectares >= limit
  130. if test:
  131. rules += "%s = %s %s\n" % (f[0], f[2], f[3])
  132. if rules:
  133. p2.stdin.write(encode(rules))
  134. p1.wait()
  135. p2.stdin.close()
  136. p2.wait()
  137. if p2.returncode != 0:
  138. if lesser:
  139. grass.fatal(_("No areas of size less than or equal to %f "
  140. "hectares found.") % limit)
  141. else:
  142. grass.fatal(_("No areas of size greater than or equal to %f "
  143. "hectares found.") % limit)
  144. grass.mapcalc("$outfile = $recfile", outfile=outfile, recfile=recfile)
  145. def rmarea(infile, outfile, thresh, coef):
  146. # transform user input from hectares to map units (kept this for future)
  147. # thresh = thresh * 10000.0 / (float(coef)**2)
  148. # grass.debug("Threshold: %d, coeff linear: %s, coef squared: %d" % (thresh, coef, (float(coef)**2)), 0)
  149. # transform user input from hectares to meters because currently v.clean
  150. # rmarea accept only meters as threshold
  151. thresh = thresh * 10000.0
  152. vectfile = "%s_vect_%s" % (infile.split('@')[0], outfile)
  153. TMPRAST.append(vectfile)
  154. grass.run_command('r.to.vect', input=infile, output=vectfile, type='area')
  155. cleanfile = "%s_clean_%s" % (infile.split('@')[0], outfile)
  156. TMPRAST.append(cleanfile)
  157. grass.run_command('v.clean', input=vectfile, output=cleanfile,
  158. tool='rmarea', threshold=thresh)
  159. grass.run_command('v.to.rast', input=cleanfile, output=outfile,
  160. use='attr', attrcolumn='value')
  161. def main():
  162. infile = options['input']
  163. value = options['value']
  164. mode = options['mode']
  165. outfile = options['output']
  166. global method
  167. method = options['method']
  168. clumped = flags['c']
  169. diagonal = flags['d']
  170. # check for unsupported locations
  171. in_proj = grass.parse_command('g.proj', flags='g')
  172. if in_proj['unit'].lower() == 'degree':
  173. grass.fatal(_("Latitude-longitude locations are not supported"))
  174. if in_proj['name'].lower() == 'xy_location_unprojected':
  175. grass.fatal(_("xy-locations are not supported"))
  176. # check lesser and greater parameters
  177. limit = float(value)
  178. if mode == 'greater' and method == 'rmarea':
  179. grass.fatal(_("You have to specify mode='lesser' with method='rmarea'"))
  180. if not grass.find_file(infile)['name']:
  181. grass.fatal(_("Raster map <%s> not found") % infile)
  182. if method == 'reclass':
  183. reclass(infile, outfile, limit, clumped, diagonal, mode == 'lesser')
  184. elif method == 'rmarea':
  185. rmarea(infile, outfile, limit, in_proj['meters'])
  186. grass.message(_("Generating output raster map <%s>...") % outfile)
  187. def cleanup():
  188. """!Delete temporary maps"""
  189. TMPRAST.reverse() # reclassed map first
  190. for mapp in TMPRAST:
  191. if method == 'rmarea':
  192. grass.run_command("g.remove", flags='f', type='vector', name=mapp,
  193. quiet=True)
  194. else:
  195. grass.run_command("g.remove", flags='f', type='raster', name=mapp,
  196. quiet=True)
  197. if __name__ == "__main__":
  198. options, flags = grass.parser()
  199. atexit.register(cleanup)
  200. sys.exit(main())