db.univar.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: db.univar (formerly called v.univar.sh)
  5. # AUTHOR(S): Michael Barton, Arizona State University
  6. # Converted to Python by Glynn Clements
  7. # Sync'ed to r.univar by Markus Metz
  8. # PURPOSE: Calculates univariate statistics from a GRASS vector map attribute column.
  9. # Based on r.univar.sh by Markus Neteler
  10. # COPYRIGHT: (C) 2005, 2007, 2008 by the GRASS Development Team
  11. #
  12. # This program is free software under the GNU General Public
  13. # License (>=v2). Read the file COPYING that comes with GRASS
  14. # for details.
  15. #
  16. #############################################################################
  17. #%module
  18. #% description: Calculates univariate statistics on selected table column.
  19. #% keyword: database
  20. #% keyword: statistics
  21. #% keyword: attribute table
  22. #%end
  23. #%option G_OPT_DB_TABLE
  24. #% key: table
  25. #% required: yes
  26. #%end
  27. #%option G_OPT_DB_COLUMN
  28. #% description: Name of attribute column on which to calculate statistics (must be numeric)
  29. #% required: yes
  30. #%end
  31. #%option G_OPT_DB_DATABASE
  32. #%end
  33. #%option G_OPT_DB_DRIVER
  34. #% options: dbf,odbc,ogr,sqlite,pg
  35. #%end
  36. #%option G_OPT_DB_WHERE
  37. #%end
  38. #%option
  39. #% key: percentile
  40. #% type: double
  41. #% description: Percentile to calculate (requires extended statistics flag)
  42. #% required : no
  43. #% answer: 90
  44. #% options: 0-100
  45. #% multiple: yes
  46. #%end
  47. #%flag
  48. #% key: e
  49. #% description: Extended statistics (quartiles and 90th percentile)
  50. #%end
  51. #%flag
  52. #% key: g
  53. #% description: Print stats in shell script style
  54. #%end
  55. import sys
  56. import atexit
  57. import math
  58. import grass.script as gscript
  59. def cleanup():
  60. for ext in ['', '.sort']:
  61. gscript.try_remove(tmp + ext)
  62. def sortfile(infile, outfile):
  63. inf = file(infile, 'r')
  64. outf = file(outfile, 'w')
  65. if gscript.find_program('sort', '--help'):
  66. gscript.run_command('sort', flags='n', stdin=inf, stdout=outf)
  67. else:
  68. # FIXME: we need a large-file sorting function
  69. gscript.warning(_("'sort' not found: sorting in memory"))
  70. lines = inf.readlines()
  71. for i in range(len(lines)):
  72. lines[i] = float(lines[i].rstrip('\r\n'))
  73. lines.sort()
  74. for line in lines:
  75. outf.write(str(line) + '\n')
  76. inf.close()
  77. outf.close()
  78. def main():
  79. global tmp
  80. tmp = gscript.tempfile()
  81. extend = flags['e']
  82. shellstyle = flags['g']
  83. table = options['table']
  84. column = options['column']
  85. database = options['database']
  86. driver = options['driver']
  87. where = options['where']
  88. perc = options['percentile']
  89. perc = [float(p) for p in perc.split(',')]
  90. desc_table = gscript.db_describe(table, database=database, driver=driver)
  91. if not desc_table:
  92. gscript.fatal(_("Unable to describe table <%s>") % table)
  93. found = False
  94. for cname, ctype, cwidth in desc_table['cols']:
  95. if cname == column:
  96. found = True
  97. if ctype not in ('INTEGER', 'DOUBLE PRECISION'):
  98. gscript.fatal(_("Column <%s> is not numeric") % cname)
  99. if not found:
  100. gscript.fatal(_("Column <%s> not found in table <%s>") % (column, table))
  101. if not shellstyle:
  102. gscript.verbose(_("Calculation for column <%s> of table <%s>..."
  103. ) % (column, table))
  104. gscript.message(_("Reading column values..."))
  105. sql = "SELECT %s FROM %s" % (column, table)
  106. if where:
  107. sql += " WHERE " + where
  108. if not database:
  109. database = None
  110. if not driver:
  111. driver = None
  112. tmpf = file(tmp, 'w')
  113. gscript.run_command('db.select', flags='c', table=table,
  114. database=database, driver=driver, sql=sql,
  115. stdout=tmpf)
  116. tmpf.close()
  117. # check if result is empty
  118. tmpf = file(tmp)
  119. if tmpf.read(1) == '':
  120. gscript.fatal(_("Table <%s> contains no data.") % table)
  121. tmpf.close()
  122. # calculate statistics
  123. if not shellstyle:
  124. gscript.verbose(_("Calculating statistics..."))
  125. N = 0
  126. sum = 0.0
  127. sum2 = 0.0
  128. sum3 = 0.0
  129. minv = 1e300
  130. maxv = -1e300
  131. tmpf = file(tmp)
  132. for line in tmpf:
  133. if len(line.rstrip('\r\n')) == 0:
  134. continue
  135. x = float(line.rstrip('\r\n'))
  136. N += 1
  137. sum += x
  138. sum2 += x * x
  139. sum3 += abs(x)
  140. maxv = max(maxv, x)
  141. minv = min(minv, x)
  142. tmpf.close()
  143. if N <= 0:
  144. gscript.fatal(_("No non-null values found"))
  145. if not shellstyle:
  146. sys.stdout.write("Number of values: %d\n" % N)
  147. sys.stdout.write("Minimum: %.15g\n" % minv)
  148. sys.stdout.write("Maximum: %.15g\n" % maxv)
  149. sys.stdout.write("Range: %.15g\n" % (maxv - minv))
  150. sys.stdout.write("Mean: %.15g\n" % (sum / N))
  151. sys.stdout.write(
  152. "Arithmetic mean of absolute values: %.15g\n" %
  153. (sum3 / N))
  154. sys.stdout.write("Variance: %.15g\n" % ((sum2 - sum * sum / N) / N))
  155. sys.stdout.write(
  156. "Standard deviation: %.15g\n" %
  157. (math.sqrt((sum2 - sum * sum / N) / N)))
  158. sys.stdout.write(
  159. "Coefficient of variation: %.15g\n" %
  160. ((math.sqrt((sum2 - sum * sum / N) / N)) /
  161. (math.sqrt(sum * sum) / N)))
  162. sys.stdout.write("Sum: %.15g\n" % sum)
  163. else:
  164. sys.stdout.write("n=%d\n" % N)
  165. sys.stdout.write("min=%.15g\n" % minv)
  166. sys.stdout.write("max=%.15g\n" % maxv)
  167. sys.stdout.write("range=%.15g\n" % (maxv - minv))
  168. sys.stdout.write("mean=%.15g\n" % (sum / N))
  169. sys.stdout.write("mean_abs=%.15g\n" % (sum3 / N))
  170. sys.stdout.write("variance=%.15g\n" % ((sum2 - sum * sum / N) / N))
  171. sys.stdout.write(
  172. "stddev=%.15g\n" %
  173. (math.sqrt(
  174. (sum2 - sum * sum / N) / N)))
  175. sys.stdout.write(
  176. "coeff_var=%.15g\n" %
  177. ((math.sqrt((sum2 - sum * sum / N) / N)) /
  178. (math.sqrt(sum * sum) / N)))
  179. sys.stdout.write("sum=%.15g\n" % sum)
  180. if not extend:
  181. return
  182. # preparations:
  183. sortfile(tmp, tmp + ".sort")
  184. odd = N % 2
  185. eostr = ['even', 'odd'][odd]
  186. q25pos = round(N * 0.25)
  187. if q25pos == 0:
  188. q25pos = 1
  189. q50apos = round(N * 0.50)
  190. if q50apos == 0:
  191. q50apos = 1
  192. q50bpos = q50apos + (1 - odd)
  193. q75pos = round(N * 0.75)
  194. if q75pos == 0:
  195. q75pos = 1
  196. ppos = {}
  197. pval = {}
  198. for i in range(len(perc)):
  199. ppos[i] = round(N * perc[i] / 100)
  200. if ppos[i] == 0:
  201. ppos[i] = 1
  202. pval[i] = 0
  203. inf = file(tmp + ".sort")
  204. l = 1
  205. for line in inf:
  206. if l == q25pos:
  207. q25 = float(line.rstrip('\r\n'))
  208. if l == q50apos:
  209. q50a = float(line.rstrip('\r\n'))
  210. if l == q50bpos:
  211. q50b = float(line.rstrip('\r\n'))
  212. if l == q75pos:
  213. q75 = float(line.rstrip('\r\n'))
  214. for i in range(len(ppos)):
  215. if l == ppos[i]:
  216. pval[i] = float(line.rstrip('\r\n'))
  217. l += 1
  218. q50 = (q50a + q50b) / 2
  219. if not shellstyle:
  220. sys.stdout.write("1st Quartile: %.15g\n" % q25)
  221. sys.stdout.write("Median (%s N): %.15g\n" % (eostr, q50))
  222. sys.stdout.write("3rd Quartile: %.15g\n" % q75)
  223. for i in range(len(perc)):
  224. if perc[i] == int(perc[i]): # integer
  225. if int(perc[i]) % 10 == 1 and int(perc[i]) != 11:
  226. sys.stdout.write(
  227. "%dst Percentile: %.15g\n" %
  228. (int(
  229. perc[i]),
  230. pval[i]))
  231. elif int(perc[i]) % 10 == 2 and int(perc[i]) != 12:
  232. sys.stdout.write(
  233. "%dnd Percentile: %.15g\n" %
  234. (int(
  235. perc[i]),
  236. pval[i]))
  237. elif int(perc[i]) % 10 == 3 and int(perc[i]) != 13:
  238. sys.stdout.write(
  239. "%drd Percentile: %.15g\n" %
  240. (int(
  241. perc[i]),
  242. pval[i]))
  243. else:
  244. sys.stdout.write(
  245. "%dth Percentile: %.15g\n" %
  246. (int(
  247. perc[i]),
  248. pval[i]))
  249. else:
  250. sys.stdout.write(
  251. "%.15g Percentile: %.15g\n" %
  252. (perc[i], pval[i]))
  253. else:
  254. sys.stdout.write("first_quartile=%.15g\n" % q25)
  255. sys.stdout.write("median=%.15g\n" % q50)
  256. sys.stdout.write("third_quartile=%.15g\n" % q75)
  257. for i in range(len(perc)):
  258. percstr = "%.15g" % perc[i]
  259. percstr = percstr.replace('.', '_')
  260. sys.stdout.write("percentile_%s=%.15g\n" % (percstr, pval[i]))
  261. if __name__ == "__main__":
  262. options, flags = gscript.parser()
  263. atexit.register(cleanup)
  264. main()