r.reclass.area.py 7.4 KB

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