v.rast.stats.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: v.rast.stats
  5. # AUTHOR(S): Markus Neteler
  6. # converted to Python by Glynn Clements
  7. # speed up by Markus Metz
  8. # add column choose by Luca Delucchi
  9. # PURPOSE: Calculates univariate statistics from a GRASS raster map
  10. # only for areas covered by vector objects on a per-category base
  11. # COPYRIGHT: (C) 2005-2010 by the GRASS Development Team
  12. #
  13. # This program is free software under the GNU General Public
  14. # License (>=v2). Read the file COPYING that comes with GRASS
  15. # for details.
  16. #
  17. #############################################################################
  18. #%module
  19. #% description: Calculates univariate statistics from a raster map based on vector polygon map and uploads statistics to new attribute columns.
  20. #% keywords: vector
  21. #% keywords: statistics
  22. #% keywords: raster
  23. #% keywords: univariate statistics
  24. #% keywords: zonal statistics
  25. #%end
  26. #%flag
  27. #% key: c
  28. #% description: Continue if upload column(s) already exist
  29. #%end
  30. #%flag
  31. #% key: e
  32. #% description: Calculate extended statistics
  33. #%end
  34. #%option G_OPT_V_MAP
  35. #%end
  36. #%option G_OPT_V_FIELD
  37. #%end
  38. #%option G_OPT_R_INPUT
  39. #% key: raster
  40. #% description: Name of input raster map to calculate statistics from
  41. #%end
  42. #%option
  43. #% key: column_prefix
  44. #% type: string
  45. #% description: Column prefix for new attribute columns
  46. #% required : yes
  47. #%end
  48. #%option
  49. #% key: method
  50. #% type: string
  51. #% description: The methods to use
  52. #% required: no
  53. #% multiple: yes
  54. #% options: number,minimum,maximum,range,average,stddev,variance,coeff_var,sum
  55. #% answer: number,minimum,maximum,range,average,stddev,variance,coeff_var,sum
  56. #%end
  57. #%option
  58. #% key: percentile
  59. #% type: integer
  60. #% description: Percentile to calculate (requires extended statistics flag)
  61. #% options: 0-100
  62. #% answer: 90
  63. #% required : no
  64. #%end
  65. import sys
  66. import os
  67. import atexit
  68. import grass.script as grass
  69. def cleanup():
  70. if rastertmp:
  71. grass.run_command('g.remove', rast=rastertmp, quiet=True)
  72. grass.run_command('g.remove', rast='MASK', quiet=True, stderr=nuldev)
  73. if mask_found:
  74. grass.message(_("Restoring previous MASK..."))
  75. grass.run_command('g.rename', rast=(tmpname + "_origmask", 'MASK'),
  76. quiet=True)
  77. # for f in [tmp, tmpname, sqltmp]:
  78. # grass.try_remove(f)
  79. def main():
  80. global tmp, sqltmp, tmpname, nuldev, vector, mask_found, rastertmp
  81. mask_found = False
  82. rastertmp = False
  83. #### setup temporary files
  84. tmp = grass.tempfile()
  85. sqltmp = tmp + ".sql"
  86. # we need a random name
  87. tmpname = grass.basename(tmp)
  88. nuldev = file(os.devnull, 'w')
  89. raster = options['raster']
  90. colprefix = options['column_prefix']
  91. vector = options['map']
  92. layer = options['layer']
  93. percentile = options['percentile']
  94. basecols = options['method'].split(',')
  95. ### setup enviro vars ###
  96. env = grass.gisenv()
  97. mapset = env['MAPSET']
  98. vs = vector.split('@')
  99. if len(vs) > 1:
  100. vect_mapset = vs[1]
  101. else:
  102. vect_mapset = mapset
  103. # does map exist in CURRENT mapset?
  104. if vect_mapset != mapset or not grass.find_file(vector, 'vector', mapset)['file']:
  105. grass.fatal(_("Vector map <%s> not found in current mapset") % vector)
  106. vector = vs[0]
  107. rastertmp = "%s_%s" % (vector, tmpname)
  108. # check the input raster map
  109. if not grass.find_file(raster, 'cell')['file']:
  110. grass.fatal(_("Raster map <%s> not found") % raster)
  111. # check presence of raster MASK, put it aside
  112. mask_found = bool(grass.find_file('MASK', 'cell')['file'])
  113. if mask_found:
  114. grass.message(_("Raster MASK found, temporarily disabled"))
  115. grass.run_command('g.rename', rast=('MASK', tmpname + "_origmask"),
  116. quiet=True)
  117. # save current settings:
  118. grass.use_temp_region()
  119. # Temporarily aligning region resolution to $RASTER resolution
  120. # keep boundary settings
  121. grass.run_command('g.region', align=raster)
  122. # prepare raster MASK
  123. if grass.run_command('v.to.rast', input=vector, output=rastertmp,
  124. use='cat', quiet=True) != 0:
  125. grass.fatal(_("An error occurred while converting vector to raster"))
  126. # dump cats to file to avoid "too many argument" problem:
  127. p = grass.pipe_command('r.category', map=rastertmp, sep=';', quiet=True)
  128. cats = []
  129. for line in p.stdout:
  130. cats.append(line.rstrip('\r\n').split(';')[0])
  131. p.wait()
  132. number = len(cats)
  133. if number < 1:
  134. grass.fatal(_("No categories found in raster map"))
  135. # check if DBF driver used, in this case cut to 10 chars col names:
  136. try:
  137. fi = grass.vector_db(map=vector)[int(layer)]
  138. except KeyError:
  139. grass.fatal(_('There is no table connected to this map. Run v.db.connect or v.db.addtable first.'))
  140. # we need this for non-DBF driver:
  141. dbfdriver = fi['driver'] == 'dbf'
  142. # Find out which table is linked to the vector map on the given layer
  143. if not fi['table']:
  144. grass.fatal(_('There is no table connected to this map. Run v.db.connect or v.db.addtable first.'))
  145. # replaced by user choiche
  146. #basecols = ['n', 'min', 'max', 'range', 'mean', 'stddev', 'variance', 'cf_var', 'sum']
  147. # we need at least three chars to distinguish [mea]n from [med]ian
  148. # so colprefix can't be longer than 6 chars with DBF driver
  149. if dbfdriver:
  150. colprefix = colprefix[:6]
  151. variables_dbf = {}
  152. # do extended stats?
  153. # by default perccol variable is used only for "variables" variable
  154. perccol = "percentile"
  155. if flags['e']:
  156. # namespace is limited in DBF but the % value is important
  157. if dbfdriver:
  158. perccol = "per" + percentile
  159. else:
  160. perccol = "percentile_" + percentile
  161. extracols = ['first_quartile', 'median', 'third_quartile'] + [perccol]
  162. else:
  163. extracols = []
  164. # dictionary with name of methods and position in "r.univar -gt" output
  165. variables = {'number': 2, 'minimum': 4, 'maximum': 5, 'range': 6,
  166. 'average': 7, 'stddev': 9, 'variance': 10, 'coeff_var': 11,
  167. 'sum': 12, 'first_quartile': 14, 'median': 15,
  168. 'third_quartile': 16, perccol: 17}
  169. addcols = []
  170. colnames = []
  171. for i in basecols + extracols:
  172. # this check the complete name of out input that should be truncated
  173. for k in variables.keys():
  174. if i in k:
  175. i = k
  176. break
  177. # check if column already present
  178. currcolumn = ("%s_%s" % (colprefix, i))
  179. if dbfdriver:
  180. currcolumn = currcolumn[:10]
  181. variables_dbf[currcolumn.replace("%s_" % colprefix, '')] = i
  182. colnames.append(currcolumn)
  183. if currcolumn in grass.vector_columns(vector, layer).keys():
  184. if not flags['c']:
  185. grass.fatal((_("Cannot create column <%s> (already present). ") % currcolumn) +
  186. _("Use -c flag to update values in this column."))
  187. else:
  188. if i == "n":
  189. coltype = "INTEGER"
  190. else:
  191. coltype = "DOUBLE PRECISION"
  192. addcols.append(currcolumn + ' ' + coltype)
  193. if addcols:
  194. grass.verbose(_("Adding columns '%s'") % addcols)
  195. if grass.run_command('v.db.addcolumn', map=vector, columns=addcols,
  196. layer=layer) != 0:
  197. grass.fatal(_("Adding columns failed. Exiting."))
  198. # calculate statistics:
  199. grass.message(_("Processing data (%d categories)...") % number)
  200. # get rid of any earlier attempts
  201. grass.try_remove(sqltmp)
  202. # do extended stats?
  203. if flags['e']:
  204. extstat = 'e'
  205. else:
  206. extstat = ""
  207. f = file(sqltmp, 'w')
  208. # do the stats
  209. p = grass.pipe_command('r.univar', flags='t' + 'g' + extstat, map=raster,
  210. zones=rastertmp, percentile=percentile, sep=';')
  211. first_line = 1
  212. if not dbfdriver:
  213. f.write("BEGIN TRANSACTION\n")
  214. for line in p.stdout:
  215. if first_line:
  216. first_line = 0
  217. continue
  218. vars = line.rstrip('\r\n').split(';')
  219. f.write("UPDATE %s SET" % fi['table'])
  220. first_var = 1
  221. for colname in colnames:
  222. variable = colname.replace("%s_" % colprefix, '')
  223. if dbfdriver:
  224. variable = variables_dbf[variable]
  225. i = variables[variable]
  226. value = vars[i]
  227. # convert nan, +nan, -nan to NULL
  228. if value.lower().endswith('nan'):
  229. value = 'NULL'
  230. if not first_var:
  231. f.write(" , ")
  232. else:
  233. first_var = 0
  234. f.write(" %s=%s" % (colname, value))
  235. f.write(" WHERE %s=%s;\n" % (fi['key'], vars[0]))
  236. if not dbfdriver:
  237. f.write("COMMIT\n")
  238. p.wait()
  239. f.close()
  240. grass.message(_("Updating the database ..."))
  241. exitcode = grass.run_command('db.execute', input=sqltmp,
  242. database=fi['database'], driver=fi['driver'])
  243. grass.run_command('g.remove', rast='MASK', quiet=True, stderr=nuldev)
  244. if exitcode == 0:
  245. grass.message((_("Statistics calculated from raster map <%s>") % raster) +
  246. (_(" and uploaded to attribute table of vector map <%s>.") % vector))
  247. else:
  248. grass.warning(_("Failed to upload statistics to attribute table of vector map <%s>.") % vector)
  249. sys.exit(exitcode)
  250. if __name__ == "__main__":
  251. options, flags = grass.parser()
  252. atexit.register(cleanup)
  253. main()