r.reclass.area.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 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. #% keywords: raster
  27. #% keywords: statistics
  28. #% keywords: aggregation
  29. #%end
  30. #%option G_OPT_R_INPUT
  31. #%end
  32. #%option G_OPT_R_OUTPUT
  33. #%end
  34. #%option
  35. #% key: lesser
  36. #% type: double
  37. #% description: Lesser value option that sets the <= area size limit [hectares]
  38. #% guisection: Area
  39. #%end
  40. #%option
  41. #% key: greater
  42. #% type: double
  43. #% description: Greater value option that sets the >= area size limit [hectares]
  44. #% guisection: Area
  45. #%end
  46. #%option
  47. #% key: method
  48. #% type: string
  49. #% description: Method used for reclassification
  50. #% options: reclass,rmarea
  51. #% answer: reclass
  52. #% guisection: Area
  53. #%end
  54. #%flag
  55. #% key: c
  56. #% description: Input map is clumped
  57. #%end
  58. #%flag
  59. #% key: d
  60. #% description: Clumps including diagonal neighbors
  61. #%end
  62. import sys
  63. import os
  64. import atexit
  65. import grass.script as grass
  66. TMPRAST = []
  67. def reclass(inf, outf, lim, clump, diag, les):
  68. infile = inf
  69. outfile = outf
  70. lesser = les
  71. limit = lim
  72. clumped = clump
  73. diagonal = diag
  74. s = grass.read_command("g.region", flags='p')
  75. kv = grass.parse_key_val(s, sep=':')
  76. s = kv['projection'].strip().split()
  77. if s == '0':
  78. grass.fatal(_("xy-locations are not supported"))
  79. grass.fatal(_("Need projected data with grids in meters"))
  80. if not grass.find_file(infile)['name']:
  81. grass.fatal(_("Raster map <%s> not found") % infile)
  82. if clumped and diagonal:
  83. grass.fatal(_("flags c and d are mutually exclusive"))
  84. if clumped:
  85. clumpfile = infile
  86. else:
  87. clumpfile = "%s.clump.%s" % (infile.split('@')[0], outfile)
  88. TMPRAST.append(clumpfile)
  89. if not grass.overwrite():
  90. if grass.find_file(clumpfile)['name']:
  91. grass.fatal(_("Temporary raster map <%s> exists") % clumpfile)
  92. if diagonal:
  93. grass.message(_("Generating a clumped raster file including "
  94. "diagonal neighbors..."))
  95. grass.run_command('r.clump', flags='d', input=infile,
  96. output=clumpfile)
  97. else:
  98. grass.message(_("Generating a clumped raster file ..."))
  99. grass.run_command('r.clump', input=infile, output=clumpfile)
  100. if lesser:
  101. grass.message(_("Generating a reclass map with area size less than "
  102. "or equal to %f hectares...") % limit)
  103. else:
  104. grass.message(_("Generating a reclass map with area size greater "
  105. "than or equal to %f hectares...") % limit)
  106. recfile = outfile + '.recl'
  107. TMPRAST.append(recfile)
  108. sflags = 'aln'
  109. if grass.raster_info(infile)['datatype'] in ('FCELL', 'DCELL'):
  110. sflags += 'i'
  111. p1 = grass.pipe_command('r.stats', flags=sflags, input=(clumpfile, infile),
  112. sep=';')
  113. p2 = grass.feed_command('r.reclass', input=clumpfile, output=recfile,
  114. rules='-')
  115. rules = ''
  116. for line in p1.stdout:
  117. f = line.rstrip(os.linesep).split(';')
  118. if len(f) < 5:
  119. continue
  120. hectares = float(f[4]) * 0.0001
  121. if lesser:
  122. test = hectares <= limit
  123. else:
  124. test = hectares >= limit
  125. if test:
  126. rules += "%s = %s %s\n" % (f[0], f[2], f[3])
  127. if rules:
  128. p2.stdin.write(rules)
  129. p1.wait()
  130. p2.stdin.close()
  131. p2.wait()
  132. if p2.returncode != 0:
  133. if lesser:
  134. grass.fatal(_("No areas of size less than or equal to %f "
  135. "hectares found.") % limit)
  136. else:
  137. grass.fatal(_("No areas of size greater than or equal to %f "
  138. "hectares found.") % limit)
  139. grass.mapcalc("$outfile = $recfile", outfile=outfile, recfile=recfile)
  140. def rmarea(infile, outfile, thresh, coef):
  141. # transform user input from hectares to map units (kept this for future)
  142. # thresh = thresh * 10000.0 / (float(coef)**2)
  143. # grass.debug("Threshold: %d, coeff linear: %s, coef squared: %d" % (thresh, coef, (float(coef)**2)), 0)
  144. # transform user input from hectares to meters because currently v.clean
  145. # rmarea accept only meters as threshold
  146. thresh = thresh * 10000.0
  147. vectfile = "%s_vect_%s" % (infile.split('@')[0], outfile)
  148. TMPRAST.append(vectfile)
  149. grass.run_command('r.to.vect', input=infile, output=vectfile, type='area')
  150. cleanfile = "%s_clean_%s" % (infile.split('@')[0], outfile)
  151. TMPRAST.append(cleanfile)
  152. grass.run_command('v.clean', input=vectfile, output=cleanfile,
  153. tool='rmarea', threshold=thresh)
  154. grass.run_command('v.to.rast', input=cleanfile, output=outfile,
  155. use='attr', attrcolumn='value')
  156. def main():
  157. infile = options['input']
  158. lesser = options['lesser']
  159. greater = options['greater']
  160. outfile = options['output']
  161. global METHOD
  162. METHOD = options['method']
  163. clumped = flags['c']
  164. diagonal = flags['d']
  165. islesser = False
  166. in_proj = grass.parse_command('g.proj', flags='g')
  167. # check non supported location
  168. if in_proj['unit'].lower() == 'degree':
  169. grass.fatal(_("Latitude-Longitude locations are not supported"))
  170. if in_proj['name'].lower() == 'xy_location_unprojected':
  171. grass.fatal(_("xy-locations are not supported"))
  172. grass.fatal(_("Need projected data with grids in metric units"))
  173. # check lesser and greater parameters
  174. if not lesser and not greater:
  175. grass.fatal(_("You have to specify one of lesser= or greater="))
  176. if lesser and greater:
  177. grass.fatal(_("lesser= and greater= are mutually exclusive"))
  178. if lesser:
  179. limit = float(lesser)
  180. islesser = True
  181. if greater and METHOD == 'rmarea':
  182. grass.fatal(_("You have to specify lesser= with method='rmarea'"))
  183. elif greater:
  184. limit = float(greater)
  185. if not grass.find_file(infile)['name']:
  186. grass.fatal(_("Raster map <%s> not found") % infile)
  187. if METHOD == 'reclass':
  188. reclass(infile, outfile, limit, clumped, diagonal, islesser)
  189. elif METHOD == 'rmarea':
  190. rmarea(infile, outfile, limit, in_proj['meters'])
  191. grass.message(_("Generating output raster map <%s>...") % outfile)
  192. def cleanup():
  193. """!Delete temporary maps"""
  194. TMPRAST.reverse() # reclassed map first
  195. for mapp in TMPRAST:
  196. if METHOD == 'rmarea':
  197. grass.run_command("g.remove", flags='f', type='vect', name=mapp,
  198. quiet=True)
  199. else:
  200. grass.run_command("g.remove", flags='f', type='rast', name=mapp,
  201. quiet=True)
  202. if __name__ == "__main__":
  203. options, flags = grass.parser()
  204. atexit.register(cleanup)
  205. sys.exit(main())