v.db.univar.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: v.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 for a GRASS vector map.
  19. #% keywords: vector
  20. #% keywords: statistics
  21. #%end
  22. #%flag
  23. #% key: e
  24. #% description: Extended statistics (quartiles and 90th percentile)
  25. #%end
  26. #%flag
  27. #% key: g
  28. #% description: Print stats in shell script style
  29. #%end
  30. #%option G_OPT_DB_TABLE
  31. #% key: table
  32. #% required: yes
  33. #%end
  34. #%option G_OPT_DB_COLUMN
  35. #% description: Name of attribute column on which to calculate statistics (must be numeric)
  36. #% required: yes
  37. #%end
  38. #%option G_OPT_DB_DATABASE
  39. #%end
  40. #%option G_OPT_DB_DRIVER
  41. #% options: dbf,odbc,ogr,sqlite,pg
  42. #%end
  43. #%option G_OPT_DB_WHERE
  44. #%end
  45. #%option
  46. #% key: percentile
  47. #% type: double
  48. #% description: Percentile to calculate (requires extended statistics flag)
  49. #% required : no
  50. #% answer: 90
  51. #% options: 0-100
  52. #% multiple: yes
  53. #%end
  54. import sys
  55. import os
  56. import atexit
  57. import math
  58. from grass.script import core as grass
  59. def cleanup():
  60. for ext in ['', '.sort']:
  61. grass.try_remove(tmp + ext)
  62. def sortfile(infile, outfile):
  63. inf = file(infile, 'r')
  64. outf = file(outfile, 'w')
  65. if grass.find_program('sort', ['-n']):
  66. grass.run_command('sort', flags = 'n', stdin = inf, stdout = outf)
  67. else:
  68. # FIXME: we need a large-file sorting function
  69. grass.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 = grass.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. if not shellstyle:
  91. grass.message(_("Calculation for column <%s> of table <%s>...") % (column, table))
  92. grass.message(_("Reading column values..."))
  93. sql = "SELECT %s FROM %s" % (column, table)
  94. if where:
  95. sql += " WHERE " + where
  96. if not database:
  97. database = None
  98. if not driver:
  99. driver = None
  100. tmpf = file(tmp, 'w')
  101. grass.run_command('db.select', flags = 'c', table = table,
  102. database = database, driver = driver, sql = sql,
  103. stdout = tmpf)
  104. tmpf.close()
  105. # check if result is empty
  106. tmpf = file(tmp)
  107. if tmpf.read(1) == '':
  108. grass.fatal(_("Table <%s> contains no data.") % table)
  109. tmpf.close()
  110. # calculate statistics
  111. if not shellstyle:
  112. grass.message(_("Calculating statistics..."))
  113. N = 0
  114. sum = 0.0
  115. sum2 = 0.0
  116. sum3 = 0.0
  117. minv = 1e300
  118. maxv = -1e300
  119. tmpf = file(tmp)
  120. for line in tmpf:
  121. if len(line.rstrip('\r\n')) == 0:
  122. continue
  123. x = float(line.rstrip('\r\n'))
  124. N += 1
  125. sum += x
  126. sum2 += x * x
  127. sum3 += abs(x)
  128. maxv = max(maxv, x)
  129. minv = min(minv, x)
  130. tmpf.close()
  131. if N <= 0:
  132. grass.fatal(_("No non-null values found"))
  133. if not shellstyle:
  134. print ""
  135. print "Number of values: %d" % N
  136. print "Minimum: %g" % minv
  137. print "Maximum: %g" % maxv
  138. print "Range: %g" % (maxv - minv)
  139. print "-----"
  140. print "Mean: %g" % (sum/N)
  141. print "Arithmetic mean of absolute values: %g" % (sum3/N)
  142. print "Variance: %g" % ((sum2 - sum*sum/N)/N)
  143. print "Standard deviation: %g" % (math.sqrt((sum2 - sum*sum/N)/N))
  144. print "Coefficient of variation: %g" % ((math.sqrt((sum2 - sum*sum/N)/N))/(math.sqrt(sum*sum)/N))
  145. print "Sum: %g" % sum
  146. print "-----"
  147. else:
  148. print "n=%d" % N
  149. print "min=%.15g" % minv
  150. print "max=%.15g" % maxv
  151. print "range=%.15g" % (maxv - minv)
  152. print "mean=%.15g" % (sum/N)
  153. print "mean_abs=%.15g" % (sum3/N)
  154. print "variance=%.15g" % ((sum2 - sum*sum/N)/N)
  155. print "stddev=%.15g" % (math.sqrt((sum2 - sum*sum/N)/N))
  156. print "coeff_var=%.15g" % ((math.sqrt((sum2 - sum*sum/N)/N))/(math.sqrt(sum*sum)/N))
  157. print "sum=%.15g" % sum
  158. if not extend:
  159. return
  160. # preparations:
  161. sortfile(tmp, tmp + ".sort")
  162. number = N
  163. odd = N % 2
  164. eostr = ['even','odd'][odd]
  165. q25pos = round(N * 0.25)
  166. if q25pos == 0:
  167. q25pos = 1
  168. q50apos = round(N * 0.50)
  169. if q50apos == 0:
  170. q50apos = 1
  171. q50bpos = q50apos + (1 - odd)
  172. q75pos = round(N * 0.75)
  173. if q75pos == 0:
  174. q75pos = 1
  175. ppos = {}
  176. pval = {}
  177. for i in range(len(perc)):
  178. ppos[i] = round(N * perc[i] / 100)
  179. if ppos[i] == 0:
  180. ppos[i] = 1
  181. pval[i] = 0
  182. inf = file(tmp + ".sort")
  183. l = 1
  184. for line in inf:
  185. if l == q25pos:
  186. q25 = float(line.rstrip('\r\n'))
  187. if l == q50apos:
  188. q50a = float(line.rstrip('\r\n'))
  189. if l == q50bpos:
  190. q50b = float(line.rstrip('\r\n'))
  191. if l == q75pos:
  192. q75 = float(line.rstrip('\r\n'))
  193. for i in range(len(ppos)):
  194. if l == ppos[i]:
  195. pval[i] = float(line.rstrip('\r\n'))
  196. l += 1
  197. q50 = (q50a + q50b) / 2
  198. if not shellstyle:
  199. print "1st Quartile: %g" % q25
  200. print "Median (%s N): %g" % (eostr, q50)
  201. print "3rd Quartile: %g" % q75
  202. for i in range(len(perc)):
  203. if perc[i] == int(perc[i]): # integer
  204. if int(perc[i]) % 10 == 1 and int(perc[i]) != 11:
  205. print "%dst Percentile: %g" % (int(perc[i]), pval[i])
  206. elif int(perc[i]) % 10 == 2 and int(perc[i]) != 12:
  207. print "%dnd Percentile: %g" % (int(perc[i]), pval[i])
  208. elif int(perc[i]) % 10 == 3 and int(perc[i]) != 13:
  209. print "%drd Percentile: %g" % (int(perc[i]), pval[i])
  210. else:
  211. print "%dth Percentile: %g" % (int(perc[i]), pval[i])
  212. else:
  213. print "%.15g Percentile: %g" % (perc[i], pval[i])
  214. else:
  215. print "first_quartile=%g" % q25
  216. print "median=%g" % q50
  217. print "third_quartile=%g" % q75
  218. for i in range(len(perc)):
  219. percstr = "%.15g" % perc[i]
  220. percstr = percstr.replace('.','_')
  221. print "percentile_%s=%g" % (percstr, pval[i])
  222. if __name__ == "__main__":
  223. options, flags = grass.parser()
  224. atexit.register(cleanup)
  225. main()