v.rast.stats.py 9.3 KB

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