db.univar.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. #!/usr/bin/env python3
  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 = open(infile, 'r')
  64. outf = open(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 = open(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 = open(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 = open(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. if not ((sum2 - sum * sum / N) / N) < 0:
  155. sys.stdout.write("Variance: %.15g\n" % ((sum2 - sum * sum / N) / N))
  156. sys.stdout.write(
  157. "Standard deviation: %.15g\n" %
  158. (math.sqrt((sum2 - sum * sum / N) / N)))
  159. sys.stdout.write(
  160. "Coefficient of variation: %.15g\n" %
  161. ((math.sqrt((sum2 - sum * sum / N) / N)) /
  162. (math.sqrt(sum * sum) / N)))
  163. else:
  164. sys.stdout.write("Variance: 0\n")
  165. sys.stdout.write("Standard deviation: 0\n")
  166. sys.stdout.write("Coefficient of variation: 0\n")
  167. sys.stdout.write("Sum: %.15g\n" % sum)
  168. else:
  169. sys.stdout.write("n=%d\n" % N)
  170. sys.stdout.write("min=%.15g\n" % minv)
  171. sys.stdout.write("max=%.15g\n" % maxv)
  172. sys.stdout.write("range=%.15g\n" % (maxv - minv))
  173. sys.stdout.write("mean=%.15g\n" % (sum / N))
  174. sys.stdout.write("mean_abs=%.15g\n" % (sum3 / N))
  175. if not ((sum2 - sum * sum / N) / N) < 0:
  176. sys.stdout.write("variance=%.15g\n" % ((sum2 - sum * sum / N) / N))
  177. sys.stdout.write(
  178. "stddev=%.15g\n" %
  179. (math.sqrt(
  180. (sum2 - sum * sum / N) / N)))
  181. sys.stdout.write(
  182. "coeff_var=%.15g\n" %
  183. ((math.sqrt((sum2 - sum * sum / N) / N)) /
  184. (math.sqrt(sum * sum) / N)))
  185. else:
  186. sys.stdout.write("variance=0\n")
  187. sys.stdout.write("stddev=0\n")
  188. sys.stdout.write("coeff_var=0\n")
  189. sys.stdout.write("sum=%.15g\n" % sum)
  190. if not extend:
  191. return
  192. # preparations:
  193. sortfile(tmp, tmp + ".sort")
  194. odd = N % 2
  195. eostr = ['even', 'odd'][odd]
  196. q25pos = round(N * 0.25)
  197. if q25pos == 0:
  198. q25pos = 1
  199. q50apos = round(N * 0.50)
  200. if q50apos == 0:
  201. q50apos = 1
  202. q50bpos = q50apos + (1 - odd)
  203. q75pos = round(N * 0.75)
  204. if q75pos == 0:
  205. q75pos = 1
  206. ppos = {}
  207. pval = {}
  208. for i in range(len(perc)):
  209. ppos[i] = round(N * perc[i] / 100)
  210. if ppos[i] == 0:
  211. ppos[i] = 1
  212. pval[i] = 0
  213. inf = open(tmp + ".sort")
  214. l = 1
  215. for line in inf:
  216. if l == q25pos:
  217. q25 = float(line.rstrip('\r\n'))
  218. if l == q50apos:
  219. q50a = float(line.rstrip('\r\n'))
  220. if l == q50bpos:
  221. q50b = float(line.rstrip('\r\n'))
  222. if l == q75pos:
  223. q75 = float(line.rstrip('\r\n'))
  224. for i in range(len(ppos)):
  225. if l == ppos[i]:
  226. pval[i] = float(line.rstrip('\r\n'))
  227. l += 1
  228. q50 = (q50a + q50b) / 2
  229. if not shellstyle:
  230. sys.stdout.write("1st Quartile: %.15g\n" % q25)
  231. sys.stdout.write("Median (%s N): %.15g\n" % (eostr, q50))
  232. sys.stdout.write("3rd Quartile: %.15g\n" % q75)
  233. for i in range(len(perc)):
  234. if perc[i] == int(perc[i]): # integer
  235. if int(perc[i]) % 10 == 1 and int(perc[i]) != 11:
  236. sys.stdout.write(
  237. "%dst Percentile: %.15g\n" %
  238. (int(
  239. perc[i]),
  240. pval[i]))
  241. elif int(perc[i]) % 10 == 2 and int(perc[i]) != 12:
  242. sys.stdout.write(
  243. "%dnd Percentile: %.15g\n" %
  244. (int(
  245. perc[i]),
  246. pval[i]))
  247. elif int(perc[i]) % 10 == 3 and int(perc[i]) != 13:
  248. sys.stdout.write(
  249. "%drd Percentile: %.15g\n" %
  250. (int(
  251. perc[i]),
  252. pval[i]))
  253. else:
  254. sys.stdout.write(
  255. "%dth Percentile: %.15g\n" %
  256. (int(
  257. perc[i]),
  258. pval[i]))
  259. else:
  260. sys.stdout.write(
  261. "%.15g Percentile: %.15g\n" %
  262. (perc[i], pval[i]))
  263. else:
  264. sys.stdout.write("first_quartile=%.15g\n" % q25)
  265. sys.stdout.write("median=%.15g\n" % q50)
  266. sys.stdout.write("third_quartile=%.15g\n" % q75)
  267. for i in range(len(perc)):
  268. percstr = "%.15g" % perc[i]
  269. percstr = percstr.replace('.', '_')
  270. sys.stdout.write("percentile_%s=%.15g\n" % (percstr, pval[i]))
  271. if __name__ == "__main__":
  272. options, flags = gscript.parser()
  273. atexit.register(cleanup)
  274. main()