aboutsummaryrefslogtreecommitdiff
path: root/bench/statistics.py
blob: 25a26d4aa713bfe8551667d4dc86a57aff2b66ea (plain)
  1. ##  Module statistics.py
  2. ##
  3. ## Copyright (c) 2013 Steven D'Aprano <steve+python@pearwood.info>.
  4. ##
  5. ## Licensed under the Apache License, Version 2.0 (the "License");
  6. ## you may not use this file except in compliance with the License.
  7. ## You may obtain a copy of the License at
  8. ##
  9. ## http://www.apache.org/licenses/LICENSE-2.0
  10. ##
  11. ## Unless required by applicable law or agreed to in writing, software
  12. ## distributed under the License is distributed on an "AS IS" BASIS,
  13. ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. ## See the License for the specific language governing permissions and
  15. ## limitations under the License.
  16. """
  17. Basic statistics module.
  18. This module provides functions for calculating statistics of data, including
  19. averages, variance, and standard deviation.
  20. Calculating averages
  21. --------------------
  22. ================== =============================================
  23. Function Description
  24. ================== =============================================
  25. mean Arithmetic mean (average) of data.
  26. median Median (middle value) of data.
  27. median_low Low median of data.
  28. median_high High median of data.
  29. median_grouped Median, or 50th percentile, of grouped data.
  30. mode Mode (most common value) of data.
  31. ================== =============================================
  32. Calculate the arithmetic mean ("the average") of data:
  33. >>> mean([-1.0, 2.5, 3.25, 5.75])
  34. 2.625
  35. Calculate the standard median of discrete data:
  36. >>> median([2, 3, 4, 5])
  37. 3.5
  38. Calculate the median, or 50th percentile, of data grouped into class intervals
  39. centred on the data values provided. E.g. if your data points are rounded to
  40. the nearest whole number:
  41. >>> median_grouped([2, 2, 3, 3, 3, 4]) #doctest: +ELLIPSIS
  42. 2.8333333333...
  43. This should be interpreted in this way: you have two data points in the class
  44. interval 1.5-2.5, three data points in the class interval 2.5-3.5, and one in
  45. the class interval 3.5-4.5. The median of these data points is 2.8333...
  46. Calculating variability or spread
  47. ---------------------------------
  48. ================== =============================================
  49. Function Description
  50. ================== =============================================
  51. pvariance Population variance of data.
  52. variance Sample variance of data.
  53. pstdev Population standard deviation of data.
  54. stdev Sample standard deviation of data.
  55. ================== =============================================
  56. Calculate the standard deviation of sample data:
  57. >>> stdev([2.5, 3.25, 5.5, 11.25, 11.75]) #doctest: +ELLIPSIS
  58. 4.38961843444...
  59. If you have previously calculated the mean, you can pass it as the optional
  60. second argument to the four "spread" functions to avoid recalculating it:
  61. >>> data = [1, 2, 2, 4, 4, 4, 5, 6]
  62. >>> mu = mean(data)
  63. >>> pvariance(data, mu)
  64. 2.5
  65. Exceptions
  66. ----------
  67. A single exception is defined: StatisticsError is a subclass of ValueError.
  68. """
  69. __all__ = [ 'StatisticsError',
  70. 'pstdev', 'pvariance', 'stdev', 'variance',
  71. 'median', 'median_low', 'median_high', 'median_grouped',
  72. 'mean', 'mode',
  73. ]
  74. import collections
  75. import math
  76. from fractions import Fraction
  77. from decimal import Decimal
  78. # === Exceptions ===
  79. class StatisticsError(ValueError):
  80. pass
  81. # === Private utilities ===
  82. def _sum(data, start=0):
  83. """_sum(data [, start]) -> value
  84. Return a high-precision sum of the given numeric data. If optional
  85. argument ``start`` is given, it is added to the total. If ``data`` is
  86. empty, ``start`` (defaulting to 0) is returned.
  87. Examples
  88. --------
  89. >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75)
  90. 11.0
  91. Some sources of round-off error will be avoided:
  92. >>> _sum([1e50, 1, -1e50] * 1000) # Built-in sum returns zero.
  93. 1000.0
  94. Fractions and Decimals are also supported:
  95. >>> from fractions import Fraction as F
  96. >>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)])
  97. Fraction(63, 20)
  98. >>> from decimal import Decimal as D
  99. >>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")]
  100. >>> _sum(data)
  101. Decimal('0.6963')
  102. Mixed types are currently treated as an error, except that int is
  103. allowed.
  104. """
  105. # We fail as soon as we reach a value that is not an int or the type of
  106. # the first value which is not an int. E.g. _sum([int, int, float, int])
  107. # is okay, but sum([int, int, float, Fraction]) is not.
  108. allowed_types = set([int, type(start)])
  109. n, d = _exact_ratio(start)
  110. partials = {d: n} # map {denominator: sum of numerators}
  111. # Micro-optimizations.
  112. exact_ratio = _exact_ratio
  113. partials_get = partials.get
  114. # Add numerators for each denominator.
  115. for x in data:
  116. _check_type(type(x), allowed_types)
  117. n, d = exact_ratio(x)
  118. partials[d] = partials_get(d, 0) + n
  119. # Find the expected result type. If allowed_types has only one item, it
  120. # will be int; if it has two, use the one which isn't int.
  121. assert len(allowed_types) in (1, 2)
  122. if len(allowed_types) == 1:
  123. assert allowed_types.pop() is int
  124. T = int
  125. else:
  126. T = (allowed_types - set([int])).pop()
  127. if None in partials:
  128. assert issubclass(T, (float, Decimal))
  129. assert not math.isfinite(partials[None])
  130. return T(partials[None])
  131. total = Fraction()
  132. for d, n in sorted(partials.items()):
  133. total += Fraction(n, d)
  134. if issubclass(T, int):
  135. assert total.denominator == 1
  136. return T(total.numerator)
  137. if issubclass(T, Decimal):
  138. return T(total.numerator)/total.denominator
  139. return T(total)
  140. def _check_type(T, allowed):
  141. if T not in allowed:
  142. if len(allowed) == 1:
  143. allowed.add(T)
  144. else:
  145. types = ', '.join([t.__name__ for t in allowed] + [T.__name__])
  146. raise TypeError("unsupported mixed types: %s" % types)
  147. def _exact_ratio(x):
  148. """Convert Real number x exactly to (numerator, denominator) pair.
  149. >>> _exact_ratio(0.25)
  150. (1, 4)
  151. x is expected to be an int, Fraction, Decimal or float.
  152. """
  153. try:
  154. try:
  155. # int, Fraction
  156. return (x.numerator, x.denominator)
  157. except AttributeError:
  158. # float
  159. try:
  160. return x.as_integer_ratio()
  161. except AttributeError:
  162. # Decimal
  163. try:
  164. return _decimal_to_ratio(x)
  165. except AttributeError:
  166. msg = "can't convert type '{}' to numerator/denominator"
  167. raise TypeError(msg.format(type(x).__name__)) from None
  168. except (OverflowError, ValueError):
  169. # INF or NAN
  170. if __debug__:
  171. # Decimal signalling NANs cannot be converted to float :-(
  172. if isinstance(x, Decimal):
  173. assert not x.is_finite()
  174. else:
  175. assert not math.isfinite(x)
  176. return (x, None)
  177. # FIXME This is faster than Fraction.from_decimal, but still too slow.
  178. def _decimal_to_ratio(d):
  179. """Convert Decimal d to exact integer ratio (numerator, denominator).
  180. >>> from decimal import Decimal
  181. >>> _decimal_to_ratio(Decimal("2.6"))
  182. (26, 10)
  183. """
  184. sign, digits, exp = d.as_tuple()
  185. if exp in ('F', 'n', 'N'): # INF, NAN, sNAN
  186. assert not d.is_finite()
  187. raise ValueError
  188. num = 0
  189. for digit in digits:
  190. num = num*10 + digit
  191. if exp < 0:
  192. den = 10**-exp
  193. else:
  194. num *= 10**exp
  195. den = 1
  196. if sign:
  197. num = -num
  198. return (num, den)
  199. def _counts(data):
  200. # Generate a table of sorted (value, frequency) pairs.
  201. table = collections.Counter(iter(data)).most_common()
  202. if not table:
  203. return table
  204. # Extract the values with the highest frequency.
  205. maxfreq = table[0][1]
  206. for i in range(1, len(table)):
  207. if table[i][1] != maxfreq:
  208. table = table[:i]
  209. break
  210. return table
  211. # === Measures of central tendency (averages) ===
  212. def mean(data):
  213. """Return the sample arithmetic mean of data.
  214. >>> mean([1, 2, 3, 4, 4])
  215. 2.8
  216. >>> from fractions import Fraction as F
  217. >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
  218. Fraction(13, 21)
  219. >>> from decimal import Decimal as D
  220. >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
  221. Decimal('0.5625')
  222. If ``data`` is empty, StatisticsError will be raised.
  223. """
  224. if iter(data) is data:
  225. data = list(data)
  226. n = len(data)
  227. if n < 1:
  228. raise StatisticsError('mean requires at least one data point')
  229. return _sum(data)/n
  230. # FIXME: investigate ways to calculate medians without sorting? Quickselect?
  231. def median(data):
  232. """Return the median (middle value) of numeric data.
  233. When the number of data points is odd, return the middle data point.
  234. When the number of data points is even, the median is interpolated by
  235. taking the average of the two middle values:
  236. >>> median([1, 3, 5])
  237. 3
  238. >>> median([1, 3, 5, 7])
  239. 4.0
  240. """
  241. data = sorted(data)
  242. n = len(data)
  243. if n == 0:
  244. raise StatisticsError("no median for empty data")
  245. if n%2 == 1:
  246. return data[n//2]
  247. else:
  248. i = n//2
  249. return (data[i - 1] + data[i])/2
  250. def median_low(data):
  251. """Return the low median of numeric data.
  252. When the number of data points is odd, the middle value is returned.
  253. When it is even, the smaller of the two middle values is returned.
  254. >>> median_low([1, 3, 5])
  255. 3
  256. >>> median_low([1, 3, 5, 7])
  257. 3
  258. """
  259. data = sorted(data)
  260. n = len(data)
  261. if n == 0:
  262. raise StatisticsError("no median for empty data")
  263. if n%2 == 1:
  264. return data[n//2]
  265. else:
  266. return data[n//2 - 1]
  267. def median_high(data):
  268. """Return the high median of data.
  269. When the number of data points is odd, the middle value is returned.
  270. When it is even, the larger of the two middle values is returned.
  271. >>> median_high([1, 3, 5])
  272. 3
  273. >>> median_high([1, 3, 5, 7])
  274. 5
  275. """
  276. data = sorted(data)
  277. n = len(data)
  278. if n == 0:
  279. raise StatisticsError("no median for empty data")
  280. return data[n//2]
  281. def median_grouped(data, interval=1):
  282. """"Return the 50th percentile (median) of grouped continuous data.
  283. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
  284. 3.7
  285. >>> median_grouped([52, 52, 53, 54])
  286. 52.5
  287. This calculates the median as the 50th percentile, and should be
  288. used when your data is continuous and grouped. In the above example,
  289. the values 1, 2, 3, etc. actually represent the midpoint of classes
  290. 0.5-1.5, 1.5-2.5, 2.5-3.5, etc. The middle value falls somewhere in
  291. class 3.5-4.5, and interpolation is used to estimate it.
  292. Optional argument ``interval`` represents the class interval, and
  293. defaults to 1. Changing the class interval naturally will change the
  294. interpolated 50th percentile value:
  295. >>> median_grouped([1, 3, 3, 5, 7], interval=1)
  296. 3.25
  297. >>> median_grouped([1, 3, 3, 5, 7], interval=2)
  298. 3.5
  299. This function does not check whether the data points are at least
  300. ``interval`` apart.
  301. """
  302. data = sorted(data)
  303. n = len(data)
  304. if n == 0:
  305. raise StatisticsError("no median for empty data")
  306. elif n == 1:
  307. return data[0]
  308. # Find the value at the midpoint. Remember this corresponds to the
  309. # centre of the class interval.
  310. x = data[n//2]
  311. for obj in (x, interval):
  312. if isinstance(obj, (str, bytes)):
  313. raise TypeError('expected number but got %r' % obj)
  314. try:
  315. L = x - interval/2 # The lower limit of the median interval.
  316. except TypeError:
  317. # Mixed type. For now we just coerce to float.
  318. L = float(x) - float(interval)/2
  319. cf = data.index(x) # Number of values below the median interval.
  320. # FIXME The following line could be more efficient for big lists.
  321. f = data.count(x) # Number of data points in the median interval.
  322. return L + interval*(n/2 - cf)/f
  323. def mode(data):
  324. """Return the most common data point from discrete or nominal data.
  325. ``mode`` assumes discrete data, and returns a single value. This is the
  326. standard treatment of the mode as commonly taught in schools:
  327. >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
  328. 3
  329. This also works with nominal (non-numeric) data:
  330. >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
  331. 'red'
  332. If there is not exactly one most common value, ``mode`` will raise
  333. StatisticsError.
  334. """
  335. # Generate a table of sorted (value, frequency) pairs.
  336. table = _counts(data)
  337. if len(table) == 1:
  338. return table[0][0]
  339. elif table:
  340. raise StatisticsError(
  341. 'no unique mode; found %d equally common values' % len(table)
  342. )
  343. else:
  344. raise StatisticsError('no mode for empty data')
  345. # === Measures of spread ===
  346. # See http://mathworld.wolfram.com/Variance.html
  347. # http://mathworld.wolfram.com/SampleVariance.html
  348. # http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  349. #
  350. # Under no circumstances use the so-called "computational formula for
  351. # variance", as that is only suitable for hand calculations with a small
  352. # amount of low-precision data. It has terrible numeric properties.
  353. #
  354. # See a comparison of three computational methods here:
  355. # http://www.johndcook.com/blog/2008/09/26/comparing-three-methods-of-computing-standard-deviation/
  356. def _ss(data, c=None):
  357. """Return sum of square deviations of sequence data.
  358. If ``c`` is None, the mean is calculated in one pass, and the deviations
  359. from the mean are calculated in a second pass. Otherwise, deviations are
  360. calculated from ``c`` as given. Use the second case with care, as it can
  361. lead to garbage results.
  362. """
  363. if c is None:
  364. c = mean(data)
  365. ss = _sum((x-c)**2 for x in data)
  366. # The following sum should mathematically equal zero, but due to rounding
  367. # error may not.
  368. ss -= _sum((x-c) for x in data)**2/len(data)
  369. assert not ss < 0, 'negative sum of square deviations: %f' % ss
  370. return ss
  371. def variance(data, xbar=None):
  372. """Return the sample variance of data.
  373. data should be an iterable of Real-valued numbers, with at least two
  374. values. The optional argument xbar, if given, should be the mean of
  375. the data. If it is missing or None, the mean is automatically calculated.
  376. Use this function when your data is a sample from a population. To
  377. calculate the variance from the entire population, see ``pvariance``.
  378. Examples:
  379. >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
  380. >>> variance(data)
  381. 1.3720238095238095
  382. If you have already calculated the mean of your data, you can pass it as
  383. the optional second argument ``xbar`` to avoid recalculating it:
  384. >>> m = mean(data)
  385. >>> variance(data, m)
  386. 1.3720238095238095
  387. This function does not check that ``xbar`` is actually the mean of
  388. ``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
  389. impossible results.
  390. Decimals and Fractions are supported:
  391. >>> from decimal import Decimal as D
  392. >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
  393. Decimal('31.01875')
  394. >>> from fractions import Fraction as F
  395. >>> variance([F(1, 6), F(1, 2), F(5, 3)])
  396. Fraction(67, 108)
  397. """
  398. if iter(data) is data:
  399. data = list(data)
  400. n = len(data)
  401. if n < 2:
  402. raise StatisticsError('variance requires at least two data points')
  403. ss = _ss(data, xbar)
  404. return ss/(n-1)
  405. def pvariance(data, mu=None):
  406. """Return the population variance of ``data``.
  407. data should be an iterable of Real-valued numbers, with at least one
  408. value. The optional argument mu, if given, should be the mean of
  409. the data. If it is missing or None, the mean is automatically calculated.
  410. Use this function to calculate the variance from the entire population.
  411. To estimate the variance from a sample, the ``variance`` function is
  412. usually a better choice.
  413. Examples:
  414. >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
  415. >>> pvariance(data)
  416. 1.25
  417. If you have already calculated the mean of the data, you can pass it as
  418. the optional second argument to avoid recalculating it:
  419. >>> mu = mean(data)
  420. >>> pvariance(data, mu)
  421. 1.25
  422. This function does not check that ``mu`` is actually the mean of ``data``.
  423. Giving arbitrary values for ``mu`` may lead to invalid or impossible
  424. results.
  425. Decimals and Fractions are supported:
  426. >>> from decimal import Decimal as D
  427. >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
  428. Decimal('24.815')
  429. >>> from fractions import Fraction as F
  430. >>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
  431. Fraction(13, 72)
  432. """
  433. if iter(data) is data:
  434. data = list(data)
  435. n = len(data)
  436. if n < 1:
  437. raise StatisticsError('pvariance requires at least one data point')
  438. ss = _ss(data, mu)
  439. return ss/n
  440. def stdev(data, xbar=None):
  441. """Return the square root of the sample variance.
  442. See ``variance`` for arguments and other details.
  443. >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
  444. 1.0810874155219827
  445. """
  446. var = variance(data, xbar)
  447. try:
  448. return var.sqrt()
  449. except AttributeError:
  450. return math.sqrt(var)
  451. def pstdev(data, mu=None):
  452. """Return the square root of the population variance.
  453. See ``pvariance`` for arguments and other details.
  454. >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
  455. 0.986893273527251
  456. """
  457. var = pvariance(data, mu)
  458. try:
  459. return var.sqrt()
  460. except AttributeError:
  461. return math.sqrt(var)