db.univar.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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 os
  57. import atexit
  58. import math
  59. import grass.script as grass
  60. def cleanup():
  61. for ext in ['', '.sort']:
  62. grass.try_remove(tmp + ext)
  63. def sortfile(infile, outfile):
  64. inf = file(infile, 'r')
  65. outf = file(outfile, 'w')
  66. if grass.find_program('sort', '--help'):
  67. grass.run_command('sort', flags = 'n', stdin = inf, stdout = outf)
  68. else:
  69. # FIXME: we need a large-file sorting function
  70. grass.warning(_("'sort' not found: sorting in memory"))
  71. lines = inf.readlines()
  72. for i in range(len(lines)):
  73. lines[i] = float(lines[i].rstrip('\r\n'))
  74. lines.sort()
  75. for line in lines:
  76. outf.write(str(line) + '\n')
  77. inf.close()
  78. outf.close()
  79. def main():
  80. global tmp
  81. tmp = grass.tempfile()
  82. extend = flags['e']
  83. shellstyle = flags['g']
  84. table = options['table']
  85. column = options['column']
  86. database = options['database']
  87. driver = options['driver']
  88. where = options['where']
  89. perc = options['percentile']
  90. perc = [float(p) for p in perc.split(',')]
  91. desc_table = grass.db_describe(table, database=database, driver=driver)
  92. if not desc_table:
  93. grass.fatal(_("Unable to describe table <%s>") % table)
  94. found = False
  95. for cname, ctype, cwidth in desc_table['cols']:
  96. if cname == column:
  97. found = True
  98. if ctype not in ('INTEGER', 'DOUBLE PRECISION'):
  99. grass.fatal(_("Column <%s> is not numeric") % cname)
  100. if not found:
  101. grass.fatal(_("Column <%s> not found in table <%s>") % (column, table))
  102. if not shellstyle:
  103. grass.verbose(_("Calculation for column <%s> of table <%s>...") % (column, table))
  104. grass.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. grass.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. grass.fatal(_("Table <%s> contains no data.") % table)
  121. tmpf.close()
  122. # calculate statistics
  123. if not shellstyle:
  124. grass.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. grass.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("Arithmetic mean of absolute values: %.15g\n"% (sum3/N))
  152. sys.stdout.write("Variance: %.15g\n"% ((sum2 - sum*sum/N)/N))
  153. sys.stdout.write("Standard deviation: %.15g\n"% (math.sqrt((sum2 - sum*sum/N)/N)))
  154. sys.stdout.write("Coefficient of variation: %.15g\n"% ((math.sqrt((sum2 - sum*sum/N)/N))/(math.sqrt(sum*sum)/N)))
  155. sys.stdout.write("Sum: %.15g\n"% sum)
  156. else:
  157. sys.stdout.write("n=%d\n"% N)
  158. sys.stdout.write("min=%.15g\n"% minv)
  159. sys.stdout.write("max=%.15g\n"% maxv)
  160. sys.stdout.write("range=%.15g\n"% (maxv - minv))
  161. sys.stdout.write("mean=%.15g\n"% (sum/N))
  162. sys.stdout.write("mean_abs=%.15g\n"% (sum3/N))
  163. sys.stdout.write("variance=%.15g\n"% ((sum2 - sum*sum/N)/N))
  164. sys.stdout.write("stddev=%.15g\n"% (math.sqrt((sum2 - sum*sum/N)/N)))
  165. sys.stdout.write("coeff_var=%.15g\n"% ((math.sqrt((sum2 - sum*sum/N)/N))/(math.sqrt(sum*sum)/N)))
  166. sys.stdout.write("sum=%.15g\n"% sum)
  167. if not extend:
  168. return
  169. # preparations:
  170. sortfile(tmp, tmp + ".sort")
  171. number = N
  172. odd = N % 2
  173. eostr = ['even','odd'][odd]
  174. q25pos = round(N * 0.25)
  175. if q25pos == 0:
  176. q25pos = 1
  177. q50apos = round(N * 0.50)
  178. if q50apos == 0:
  179. q50apos = 1
  180. q50bpos = q50apos + (1 - odd)
  181. q75pos = round(N * 0.75)
  182. if q75pos == 0:
  183. q75pos = 1
  184. ppos = {}
  185. pval = {}
  186. for i in range(len(perc)):
  187. ppos[i] = round(N * perc[i] / 100)
  188. if ppos[i] == 0:
  189. ppos[i] = 1
  190. pval[i] = 0
  191. inf = file(tmp + ".sort")
  192. l = 1
  193. for line in inf:
  194. if l == q25pos:
  195. q25 = float(line.rstrip('\r\n'))
  196. if l == q50apos:
  197. q50a = float(line.rstrip('\r\n'))
  198. if l == q50bpos:
  199. q50b = float(line.rstrip('\r\n'))
  200. if l == q75pos:
  201. q75 = float(line.rstrip('\r\n'))
  202. for i in range(len(ppos)):
  203. if l == ppos[i]:
  204. pval[i] = float(line.rstrip('\r\n'))
  205. l += 1
  206. q50 = (q50a + q50b) / 2
  207. if not shellstyle:
  208. sys.stdout.write("1st Quartile: %.15g\n" % q25)
  209. sys.stdout.write("Median (%s N): %.15g\n" % (eostr, q50))
  210. sys.stdout.write("3rd Quartile: %.15g\n" % q75)
  211. for i in range(len(perc)):
  212. if perc[i] == int(perc[i]): # integer
  213. if int(perc[i]) % 10 == 1 and int(perc[i]) != 11:
  214. sys.stdout.write("%dst Percentile: %.15g\n"% (int(perc[i]), pval[i]))
  215. elif int(perc[i]) % 10 == 2 and int(perc[i]) != 12:
  216. sys.stdout.write("%dnd Percentile: %.15g\n"% (int(perc[i]), pval[i]))
  217. elif int(perc[i]) % 10 == 3 and int(perc[i]) != 13:
  218. sys.stdout.write("%drd Percentile: %.15g\n"% (int(perc[i]), pval[i]))
  219. else:
  220. sys.stdout.write("%dth Percentile: %.15g\n"% (int(perc[i]), pval[i]))
  221. else:
  222. sys.stdout.write("%.15g Percentile: %.15g\n"% (perc[i], pval[i]))
  223. else:
  224. sys.stdout.write("first_quartile=%.15g\n"% q25)
  225. sys.stdout.write("median=%.15g\n"% q50)
  226. sys.stdout.write("third_quartile=%.15g\n"% q75)
  227. for i in range(len(perc)):
  228. percstr = "%.15g" % perc[i]
  229. percstr = percstr.replace('.','_')
  230. sys.stdout.write("percentile_%s=%.15g\n"% (percstr, pval[i]))
  231. if __name__ == "__main__":
  232. options, flags = grass.parser()
  233. atexit.register(cleanup)
  234. main()