r.reclass.area.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: r.reclass.area
  5. # AUTHOR(S): NRCS
  6. # Converted to Python by Glynn Clements
  7. # PURPOSE: Reclasses a raster map greater or less than user specified area size (in hectares)
  8. # COPYRIGHT: (C) 1999,2008 by the GRASS Development Team
  9. #
  10. # This program is free software under the GNU General Public
  11. # License (>=v2). Read the file COPYING that comes with GRASS
  12. # for details.
  13. #
  14. #############################################################################
  15. # 10/2013: added option to use a pre-clumped input map (Eric Goddard)
  16. # 8/2012: added fp maps support, cleanup, removed tabs AK
  17. # 3/2007: added label support MN
  18. # 3/2004: added parser support MN
  19. # 11/2001 added mapset support markus
  20. # 2/2001 fixes markus
  21. # 2000: updated to GRASS 5
  22. # 1998 from NRCS, slightly modified for GRASS 4.2.1
  23. #%module
  24. #% description: Reclasses a raster map greater or less than user specified area size (in hectares).
  25. #% keywords: raster
  26. #% keywords: statistics
  27. #% keywords: aggregation
  28. #%end
  29. #%option G_OPT_R_INPUT
  30. #%end
  31. #%option G_OPT_R_OUTPUT
  32. #%end
  33. #%option
  34. #% key: lesser
  35. #% type: double
  36. #% description: Lesser value option that sets the <= area size limit [hectares]
  37. #% guisection: Area
  38. #%end
  39. #%option
  40. #% key: greater
  41. #% type: double
  42. #% description: Greater value option that sets the >= area size limit [hectares]
  43. #% guisection: Area
  44. #%end
  45. #%flag
  46. #% key: c
  47. #% description: Input map is clumped
  48. #%end
  49. #%flag
  50. #% key: d
  51. #% description: Clumps including diagonal neighbors
  52. #%end
  53. import sys
  54. import os
  55. import atexit
  56. import grass.script as grass
  57. TMPRAST = []
  58. def main():
  59. infile = options['input']
  60. lesser = options['lesser']
  61. greater = options['greater']
  62. outfile = options['output']
  63. clumped = flags['c']
  64. diagonal = flags['d']
  65. s = grass.read_command("g.region", flags='p')
  66. kv = grass.parse_key_val(s, sep=':')
  67. s = kv['projection'].strip().split()
  68. if s == '0':
  69. grass.fatal(_("xy-locations are not supported"))
  70. grass.fatal(_("Need projected data with grids in meters"))
  71. if not lesser and not greater:
  72. grass.fatal(_("You have to specify either lesser= or greater="))
  73. if lesser and greater:
  74. grass.fatal(_("lesser= and greater= are mutually exclusive"))
  75. if lesser:
  76. limit = float(lesser)
  77. if greater:
  78. limit = float(greater)
  79. if not grass.find_file(infile)['name']:
  80. grass.fatal(_("Raster map <%s> not found") % infile)
  81. if clumped and diagonal:
  82. grass.fatal(_("flags c and d are mutually exclusive"))
  83. if clumped:
  84. clumpfile = infile
  85. else:
  86. clumpfile = "%s.clump.%s" % (infile.split('@')[0], outfile)
  87. TMPRAST.append(clumpfile)
  88. if not grass.overwrite():
  89. if grass.find_file(clumpfile)['name']:
  90. grass.fatal(_("Temporary raster map <%s> exists") % clumpfile)
  91. if diagonal:
  92. grass.message(_("Generating a clumped raster file including diagonal neighbors..."))
  93. grass.run_command('r.clump', flags='d', input=infile, output=clumpfile)
  94. else:
  95. grass.message(_("Generating a clumped raster file ..."))
  96. grass.run_command('r.clump', input=infile, output=clumpfile)
  97. if lesser:
  98. grass.message(_("Generating a reclass map with area size less than " \
  99. "or equal to %f hectares...") % limit)
  100. else:
  101. grass.message(_("Generating a reclass map with area size greater " \
  102. "than or equal to %f hectares...") % limit)
  103. recfile = outfile + '.recl'
  104. TMPRAST.append(recfile)
  105. sflags = 'aln'
  106. if grass.raster_info(infile)['datatype'] in ('FCELL', 'DCELL'):
  107. sflags += 'i'
  108. p1 = grass.pipe_command('r.stats', flags=sflags, input=(clumpfile, infile),
  109. sep=';')
  110. p2 = grass.feed_command('r.reclass', input=clumpfile, output=recfile,
  111. rules='-')
  112. rules = ''
  113. for line in p1.stdout:
  114. f = line.rstrip(os.linesep).split(';')
  115. if len(f) < 5:
  116. continue
  117. hectares = float(f[4]) * 0.0001
  118. if lesser:
  119. test = hectares <= limit
  120. else:
  121. test = hectares >= limit
  122. if test:
  123. rules += "%s = %s %s\n" % (f[0], f[2], f[3])
  124. if rules:
  125. p2.stdin.write(rules)
  126. p1.wait()
  127. p2.stdin.close()
  128. p2.wait()
  129. if p2.returncode != 0:
  130. if lesser:
  131. grass.fatal(_("No areas of size less than or equal to %f " \
  132. "hectares found.") % limit)
  133. else:
  134. grass.fatal(_("No areas of size greater than or equal to %f " \
  135. "hectares found.") % limit)
  136. grass.message(_("Generating output raster map <%s>...") % outfile)
  137. grass.mapcalc("$outfile = $recfile", outfile=outfile, recfile=recfile)
  138. def cleanup():
  139. """!Delete temporary maps"""
  140. TMPRAST.reverse() # reclassed map first
  141. for rast in TMPRAST:
  142. grass.run_command("g.remove", rast=rast, quiet=True)
  143. if __name__ == "__main__":
  144. options, flags = grass.parser()
  145. atexit.register(cleanup)
  146. sys.exit(main())