v.rast.stats.py 10.0 KB

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