r.reclass.area.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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(
  99. _("Generating a clumped raster file including " "diagonal neighbors...")
  100. )
  101. grass.run_command("r.clump", flags="d", input=infile, 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(
  107. _(
  108. "Generating a reclass map with area size less than "
  109. "or equal to %f hectares..."
  110. )
  111. % limit
  112. )
  113. else:
  114. grass.message(
  115. _(
  116. "Generating a reclass map with area size greater "
  117. "than or equal to %f hectares..."
  118. )
  119. % limit
  120. )
  121. recfile = outfile + ".recl"
  122. TMPRAST.append(recfile)
  123. sflags = "aln"
  124. if grass.raster_info(infile)["datatype"] in ("FCELL", "DCELL"):
  125. sflags += "i"
  126. p1 = grass.pipe_command("r.stats", flags=sflags, input=(clumpfile, infile), sep=";")
  127. p2 = grass.feed_command("r.reclass", input=clumpfile, output=recfile, rules="-")
  128. rules = ""
  129. for line in p1.stdout:
  130. f = decode(line).rstrip(os.linesep).split(";")
  131. if len(f) < 5:
  132. continue
  133. hectares = float(f[4]) * 0.0001
  134. if lesser:
  135. test = hectares <= limit
  136. else:
  137. test = hectares >= limit
  138. if test:
  139. rules += "%s = %s %s\n" % (f[0], f[2], f[3])
  140. if rules:
  141. p2.stdin.write(encode(rules))
  142. p1.wait()
  143. p2.stdin.close()
  144. p2.wait()
  145. if p2.returncode != 0:
  146. if lesser:
  147. grass.fatal(
  148. _("No areas of size less than or equal to %f " "hectares found.")
  149. % limit
  150. )
  151. else:
  152. grass.fatal(
  153. _("No areas of size greater than or equal to %f " "hectares found.")
  154. % limit
  155. )
  156. grass.mapcalc("$outfile = $recfile", outfile=outfile, recfile=recfile)
  157. def rmarea(infile, outfile, thresh, coef):
  158. # transform user input from hectares to map units (kept this for future)
  159. # thresh = thresh * 10000.0 / (float(coef)**2)
  160. # grass.debug("Threshold: %d, coeff linear: %s, coef squared: %d" % (thresh, coef, (float(coef)**2)), 0)
  161. # transform user input from hectares to meters because currently v.clean
  162. # rmarea accept only meters as threshold
  163. thresh = thresh * 10000.0
  164. vectfile = "%s_vect_%s" % (infile.split("@")[0], outfile)
  165. TMPRAST.append(vectfile)
  166. grass.run_command("r.to.vect", input=infile, output=vectfile, type="area")
  167. cleanfile = "%s_clean_%s" % (infile.split("@")[0], outfile)
  168. TMPRAST.append(cleanfile)
  169. grass.run_command(
  170. "v.clean", input=vectfile, output=cleanfile, tool="rmarea", threshold=thresh
  171. )
  172. grass.run_command(
  173. "v.to.rast", input=cleanfile, output=outfile, use="attr", attrcolumn="value"
  174. )
  175. def main():
  176. infile = options["input"]
  177. value = options["value"]
  178. mode = options["mode"]
  179. outfile = options["output"]
  180. global method
  181. method = options["method"]
  182. clumped = flags["c"]
  183. diagonal = flags["d"]
  184. # check for unsupported locations
  185. in_proj = grass.parse_command("g.proj", flags="g")
  186. if in_proj["unit"].lower() == "degree":
  187. grass.fatal(_("Latitude-longitude locations are not supported"))
  188. if in_proj["name"].lower() == "xy_location_unprojected":
  189. grass.fatal(_("xy-locations are not supported"))
  190. # check lesser and greater parameters
  191. limit = float(value)
  192. if mode == "greater" and method == "rmarea":
  193. grass.fatal(_("You have to specify mode='lesser' with method='rmarea'"))
  194. if not grass.find_file(infile)["name"]:
  195. grass.fatal(_("Raster map <%s> not found") % infile)
  196. if method == "reclass":
  197. reclass(infile, outfile, limit, clumped, diagonal, mode == "lesser")
  198. elif method == "rmarea":
  199. rmarea(infile, outfile, limit, in_proj["meters"])
  200. grass.message(_("Generating output raster map <%s>...") % outfile)
  201. def cleanup():
  202. """!Delete temporary maps"""
  203. TMPRAST.reverse() # reclassed map first
  204. for mapp in TMPRAST:
  205. if method == "rmarea":
  206. grass.run_command(
  207. "g.remove", flags="f", type="vector", name=mapp, quiet=True
  208. )
  209. else:
  210. grass.run_command(
  211. "g.remove", flags="f", type="raster", name=mapp, quiet=True
  212. )
  213. if __name__ == "__main__":
  214. options, flags = grass.parser()
  215. atexit.register(cleanup)
  216. sys.exit(main())