v.rast.stats.py 9.3 KB

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