v.rast.stats.py 12 KB

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