db.univar.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. #% keywords: database
  20. #% keywords: statistics
  21. #% keywords: 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. from grass.script import core 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. if not shellstyle:
  92. grass.message(_("Calculation for column <%s> of table <%s>...") % (column, table))
  93. grass.message(_("Reading column values..."))
  94. sql = "SELECT %s FROM %s" % (column, table)
  95. if where:
  96. sql += " WHERE " + where
  97. if not database:
  98. database = None
  99. if not driver:
  100. driver = None
  101. tmpf = file(tmp, 'w')
  102. grass.run_command('db.select', flags = 'c', table = table,
  103. database = database, driver = driver, sql = sql,
  104. stdout = tmpf)
  105. tmpf.close()
  106. # check if result is empty
  107. tmpf = file(tmp)
  108. if tmpf.read(1) == '':
  109. grass.fatal(_("Table <%s> contains no data.") % table)
  110. tmpf.close()
  111. # calculate statistics
  112. if not shellstyle:
  113. grass.message(_("Calculating statistics..."))
  114. N = 0
  115. sum = 0.0
  116. sum2 = 0.0
  117. sum3 = 0.0
  118. minv = 1e300
  119. maxv = -1e300
  120. tmpf = file(tmp)
  121. for line in tmpf:
  122. if len(line.rstrip('\r\n')) == 0:
  123. continue
  124. x = float(line.rstrip('\r\n'))
  125. N += 1
  126. sum += x
  127. sum2 += x * x
  128. sum3 += abs(x)
  129. maxv = max(maxv, x)
  130. minv = min(minv, x)
  131. tmpf.close()
  132. if N <= 0:
  133. grass.fatal(_("No non-null values found"))
  134. if not shellstyle:
  135. print ""
  136. print "Number of values: %d" % N
  137. print "Minimum: %.15g" % minv
  138. print "Maximum: %.15g" % maxv
  139. print "Range: %.15g" % (maxv - minv)
  140. print "-----"
  141. print "Mean: %.15g" % (sum/N)
  142. print "Arithmetic mean of absolute values: %.15g" % (sum3/N)
  143. print "Variance: %.15g" % ((sum2 - sum*sum/N)/N)
  144. print "Standard deviation: %.15g" % (math.sqrt((sum2 - sum*sum/N)/N))
  145. print "Coefficient of variation: %.15g" % ((math.sqrt((sum2 - sum*sum/N)/N))/(math.sqrt(sum*sum)/N))
  146. print "Sum: %.15g" % sum
  147. print "-----"
  148. else:
  149. print "n=%d" % N
  150. print "min=%.15g" % minv
  151. print "max=%.15g" % maxv
  152. print "range=%.15g" % (maxv - minv)
  153. print "mean=%.15g" % (sum/N)
  154. print "mean_abs=%.15g" % (sum3/N)
  155. print "variance=%.15g" % ((sum2 - sum*sum/N)/N)
  156. print "stddev=%.15g" % (math.sqrt((sum2 - sum*sum/N)/N))
  157. print "coeff_var=%.15g" % ((math.sqrt((sum2 - sum*sum/N)/N))/(math.sqrt(sum*sum)/N))
  158. print "sum=%.15g" % sum
  159. if not extend:
  160. return
  161. # preparations:
  162. sortfile(tmp, tmp + ".sort")
  163. number = N
  164. odd = N % 2
  165. eostr = ['even','odd'][odd]
  166. q25pos = round(N * 0.25)
  167. if q25pos == 0:
  168. q25pos = 1
  169. q50apos = round(N * 0.50)
  170. if q50apos == 0:
  171. q50apos = 1
  172. q50bpos = q50apos + (1 - odd)
  173. q75pos = round(N * 0.75)
  174. if q75pos == 0:
  175. q75pos = 1
  176. ppos = {}
  177. pval = {}
  178. for i in range(len(perc)):
  179. ppos[i] = round(N * perc[i] / 100)
  180. if ppos[i] == 0:
  181. ppos[i] = 1
  182. pval[i] = 0
  183. inf = file(tmp + ".sort")
  184. l = 1
  185. for line in inf:
  186. if l == q25pos:
  187. q25 = float(line.rstrip('\r\n'))
  188. if l == q50apos:
  189. q50a = float(line.rstrip('\r\n'))
  190. if l == q50bpos:
  191. q50b = float(line.rstrip('\r\n'))
  192. if l == q75pos:
  193. q75 = float(line.rstrip('\r\n'))
  194. for i in range(len(ppos)):
  195. if l == ppos[i]:
  196. pval[i] = float(line.rstrip('\r\n'))
  197. l += 1
  198. q50 = (q50a + q50b) / 2
  199. if not shellstyle:
  200. print "1st Quartile: %.15g" % q25
  201. print "Median (%s N): %.15g" % (eostr, q50)
  202. print "3rd Quartile: %.15g" % q75
  203. for i in range(len(perc)):
  204. if perc[i] == int(perc[i]): # integer
  205. if int(perc[i]) % 10 == 1 and int(perc[i]) != 11:
  206. print "%dst Percentile: %.15g" % (int(perc[i]), pval[i])
  207. elif int(perc[i]) % 10 == 2 and int(perc[i]) != 12:
  208. print "%dnd Percentile: %.15g" % (int(perc[i]), pval[i])
  209. elif int(perc[i]) % 10 == 3 and int(perc[i]) != 13:
  210. print "%drd Percentile: %.15g" % (int(perc[i]), pval[i])
  211. else:
  212. print "%dth Percentile: %.15g" % (int(perc[i]), pval[i])
  213. else:
  214. print "%.15g Percentile: %.15g" % (perc[i], pval[i])
  215. else:
  216. print "first_quartile=%.15g" % q25
  217. print "median=%.15g" % q50
  218. print "third_quartile=%.15g" % q75
  219. for i in range(len(perc)):
  220. percstr = "%.15g" % perc[i]
  221. percstr = percstr.replace('.','_')
  222. print "percentile_%s=%.15g" % (percstr, pval[i])
  223. if __name__ == "__main__":
  224. options, flags = grass.parser()
  225. atexit.register(cleanup)
  226. main()