v.rast.stats.py 9.5 KB

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