r.reclass.area.py 7.5 KB

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