test_histograms.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. from __future__ import division, absolute_import, print_function
  2. import numpy as np
  3. from numpy.lib.histograms import histogram, histogramdd, histogram_bin_edges
  4. from numpy.testing import (
  5. assert_, assert_equal, assert_array_equal, assert_almost_equal,
  6. assert_array_almost_equal, assert_raises, assert_allclose,
  7. assert_array_max_ulp, assert_raises_regex, suppress_warnings,
  8. )
  9. import pytest
  10. class TestHistogram(object):
  11. def setup(self):
  12. pass
  13. def teardown(self):
  14. pass
  15. def test_simple(self):
  16. n = 100
  17. v = np.random.rand(n)
  18. (a, b) = histogram(v)
  19. # check if the sum of the bins equals the number of samples
  20. assert_equal(np.sum(a, axis=0), n)
  21. # check that the bin counts are evenly spaced when the data is from
  22. # a linear function
  23. (a, b) = histogram(np.linspace(0, 10, 100))
  24. assert_array_equal(a, 10)
  25. def test_one_bin(self):
  26. # Ticket 632
  27. hist, edges = histogram([1, 2, 3, 4], [1, 2])
  28. assert_array_equal(hist, [2, ])
  29. assert_array_equal(edges, [1, 2])
  30. assert_raises(ValueError, histogram, [1, 2], bins=0)
  31. h, e = histogram([1, 2], bins=1)
  32. assert_equal(h, np.array([2]))
  33. assert_allclose(e, np.array([1., 2.]))
  34. def test_normed(self):
  35. sup = suppress_warnings()
  36. with sup:
  37. rec = sup.record(np.VisibleDeprecationWarning, '.*normed.*')
  38. # Check that the integral of the density equals 1.
  39. n = 100
  40. v = np.random.rand(n)
  41. a, b = histogram(v, normed=True)
  42. area = np.sum(a * np.diff(b))
  43. assert_almost_equal(area, 1)
  44. assert_equal(len(rec), 1)
  45. sup = suppress_warnings()
  46. with sup:
  47. rec = sup.record(np.VisibleDeprecationWarning, '.*normed.*')
  48. # Check with non-constant bin widths (buggy but backwards
  49. # compatible)
  50. v = np.arange(10)
  51. bins = [0, 1, 5, 9, 10]
  52. a, b = histogram(v, bins, normed=True)
  53. area = np.sum(a * np.diff(b))
  54. assert_almost_equal(area, 1)
  55. assert_equal(len(rec), 1)
  56. def test_density(self):
  57. # Check that the integral of the density equals 1.
  58. n = 100
  59. v = np.random.rand(n)
  60. a, b = histogram(v, density=True)
  61. area = np.sum(a * np.diff(b))
  62. assert_almost_equal(area, 1)
  63. # Check with non-constant bin widths
  64. v = np.arange(10)
  65. bins = [0, 1, 3, 6, 10]
  66. a, b = histogram(v, bins, density=True)
  67. assert_array_equal(a, .1)
  68. assert_equal(np.sum(a * np.diff(b)), 1)
  69. # Test that passing False works too
  70. a, b = histogram(v, bins, density=False)
  71. assert_array_equal(a, [1, 2, 3, 4])
  72. # Variale bin widths are especially useful to deal with
  73. # infinities.
  74. v = np.arange(10)
  75. bins = [0, 1, 3, 6, np.inf]
  76. a, b = histogram(v, bins, density=True)
  77. assert_array_equal(a, [.1, .1, .1, 0.])
  78. # Taken from a bug report from N. Becker on the numpy-discussion
  79. # mailing list Aug. 6, 2010.
  80. counts, dmy = np.histogram(
  81. [1, 2, 3, 4], [0.5, 1.5, np.inf], density=True)
  82. assert_equal(counts, [.25, 0])
  83. def test_outliers(self):
  84. # Check that outliers are not tallied
  85. a = np.arange(10) + .5
  86. # Lower outliers
  87. h, b = histogram(a, range=[0, 9])
  88. assert_equal(h.sum(), 9)
  89. # Upper outliers
  90. h, b = histogram(a, range=[1, 10])
  91. assert_equal(h.sum(), 9)
  92. # Normalization
  93. h, b = histogram(a, range=[1, 9], density=True)
  94. assert_almost_equal((h * np.diff(b)).sum(), 1, decimal=15)
  95. # Weights
  96. w = np.arange(10) + .5
  97. h, b = histogram(a, range=[1, 9], weights=w, density=True)
  98. assert_equal((h * np.diff(b)).sum(), 1)
  99. h, b = histogram(a, bins=8, range=[1, 9], weights=w)
  100. assert_equal(h, w[1:-1])
  101. def test_arr_weights_mismatch(self):
  102. a = np.arange(10) + .5
  103. w = np.arange(11) + .5
  104. with assert_raises_regex(ValueError, "same shape as"):
  105. h, b = histogram(a, range=[1, 9], weights=w, density=True)
  106. def test_type(self):
  107. # Check the type of the returned histogram
  108. a = np.arange(10) + .5
  109. h, b = histogram(a)
  110. assert_(np.issubdtype(h.dtype, np.integer))
  111. h, b = histogram(a, density=True)
  112. assert_(np.issubdtype(h.dtype, np.floating))
  113. h, b = histogram(a, weights=np.ones(10, int))
  114. assert_(np.issubdtype(h.dtype, np.integer))
  115. h, b = histogram(a, weights=np.ones(10, float))
  116. assert_(np.issubdtype(h.dtype, np.floating))
  117. def test_f32_rounding(self):
  118. # gh-4799, check that the rounding of the edges works with float32
  119. x = np.array([276.318359, -69.593948, 21.329449], dtype=np.float32)
  120. y = np.array([5005.689453, 4481.327637, 6010.369629], dtype=np.float32)
  121. counts_hist, xedges, yedges = np.histogram2d(x, y, bins=100)
  122. assert_equal(counts_hist.sum(), 3.)
  123. def test_bool_conversion(self):
  124. # gh-12107
  125. # Reference integer histogram
  126. a = np.array([1, 1, 0], dtype=np.uint8)
  127. int_hist, int_edges = np.histogram(a)
  128. # Should raise an warning on booleans
  129. # Ensure that the histograms are equivalent, need to suppress
  130. # the warnings to get the actual outputs
  131. with suppress_warnings() as sup:
  132. rec = sup.record(RuntimeWarning, 'Converting input from .*')
  133. hist, edges = np.histogram([True, True, False])
  134. # A warning should be issued
  135. assert_equal(len(rec), 1)
  136. assert_array_equal(hist, int_hist)
  137. assert_array_equal(edges, int_edges)
  138. def test_weights(self):
  139. v = np.random.rand(100)
  140. w = np.ones(100) * 5
  141. a, b = histogram(v)
  142. na, nb = histogram(v, density=True)
  143. wa, wb = histogram(v, weights=w)
  144. nwa, nwb = histogram(v, weights=w, density=True)
  145. assert_array_almost_equal(a * 5, wa)
  146. assert_array_almost_equal(na, nwa)
  147. # Check weights are properly applied.
  148. v = np.linspace(0, 10, 10)
  149. w = np.concatenate((np.zeros(5), np.ones(5)))
  150. wa, wb = histogram(v, bins=np.arange(11), weights=w)
  151. assert_array_almost_equal(wa, w)
  152. # Check with integer weights
  153. wa, wb = histogram([1, 2, 2, 4], bins=4, weights=[4, 3, 2, 1])
  154. assert_array_equal(wa, [4, 5, 0, 1])
  155. wa, wb = histogram(
  156. [1, 2, 2, 4], bins=4, weights=[4, 3, 2, 1], density=True)
  157. assert_array_almost_equal(wa, np.array([4, 5, 0, 1]) / 10. / 3. * 4)
  158. # Check weights with non-uniform bin widths
  159. a, b = histogram(
  160. np.arange(9), [0, 1, 3, 6, 10],
  161. weights=[2, 1, 1, 1, 1, 1, 1, 1, 1], density=True)
  162. assert_almost_equal(a, [.2, .1, .1, .075])
  163. def test_exotic_weights(self):
  164. # Test the use of weights that are not integer or floats, but e.g.
  165. # complex numbers or object types.
  166. # Complex weights
  167. values = np.array([1.3, 2.5, 2.3])
  168. weights = np.array([1, -1, 2]) + 1j * np.array([2, 1, 2])
  169. # Check with custom bins
  170. wa, wb = histogram(values, bins=[0, 2, 3], weights=weights)
  171. assert_array_almost_equal(wa, np.array([1, 1]) + 1j * np.array([2, 3]))
  172. # Check with even bins
  173. wa, wb = histogram(values, bins=2, range=[1, 3], weights=weights)
  174. assert_array_almost_equal(wa, np.array([1, 1]) + 1j * np.array([2, 3]))
  175. # Decimal weights
  176. from decimal import Decimal
  177. values = np.array([1.3, 2.5, 2.3])
  178. weights = np.array([Decimal(1), Decimal(2), Decimal(3)])
  179. # Check with custom bins
  180. wa, wb = histogram(values, bins=[0, 2, 3], weights=weights)
  181. assert_array_almost_equal(wa, [Decimal(1), Decimal(5)])
  182. # Check with even bins
  183. wa, wb = histogram(values, bins=2, range=[1, 3], weights=weights)
  184. assert_array_almost_equal(wa, [Decimal(1), Decimal(5)])
  185. def test_no_side_effects(self):
  186. # This is a regression test that ensures that values passed to
  187. # ``histogram`` are unchanged.
  188. values = np.array([1.3, 2.5, 2.3])
  189. np.histogram(values, range=[-10, 10], bins=100)
  190. assert_array_almost_equal(values, [1.3, 2.5, 2.3])
  191. def test_empty(self):
  192. a, b = histogram([], bins=([0, 1]))
  193. assert_array_equal(a, np.array([0]))
  194. assert_array_equal(b, np.array([0, 1]))
  195. def test_error_binnum_type (self):
  196. # Tests if right Error is raised if bins argument is float
  197. vals = np.linspace(0.0, 1.0, num=100)
  198. histogram(vals, 5)
  199. assert_raises(TypeError, histogram, vals, 2.4)
  200. def test_finite_range(self):
  201. # Normal ranges should be fine
  202. vals = np.linspace(0.0, 1.0, num=100)
  203. histogram(vals, range=[0.25,0.75])
  204. assert_raises(ValueError, histogram, vals, range=[np.nan,0.75])
  205. assert_raises(ValueError, histogram, vals, range=[0.25,np.inf])
  206. def test_invalid_range(self):
  207. # start of range must be < end of range
  208. vals = np.linspace(0.0, 1.0, num=100)
  209. with assert_raises_regex(ValueError, "max must be larger than"):
  210. np.histogram(vals, range=[0.1, 0.01])
  211. def test_bin_edge_cases(self):
  212. # Ensure that floating-point computations correctly place edge cases.
  213. arr = np.array([337, 404, 739, 806, 1007, 1811, 2012])
  214. hist, edges = np.histogram(arr, bins=8296, range=(2, 2280))
  215. mask = hist > 0
  216. left_edges = edges[:-1][mask]
  217. right_edges = edges[1:][mask]
  218. for x, left, right in zip(arr, left_edges, right_edges):
  219. assert_(x >= left)
  220. assert_(x < right)
  221. def test_last_bin_inclusive_range(self):
  222. arr = np.array([0., 0., 0., 1., 2., 3., 3., 4., 5.])
  223. hist, edges = np.histogram(arr, bins=30, range=(-0.5, 5))
  224. assert_equal(hist[-1], 1)
  225. def test_bin_array_dims(self):
  226. # gracefully handle bins object > 1 dimension
  227. vals = np.linspace(0.0, 1.0, num=100)
  228. bins = np.array([[0, 0.5], [0.6, 1.0]])
  229. with assert_raises_regex(ValueError, "must be 1d"):
  230. np.histogram(vals, bins=bins)
  231. def test_unsigned_monotonicity_check(self):
  232. # Ensures ValueError is raised if bins not increasing monotonically
  233. # when bins contain unsigned values (see #9222)
  234. arr = np.array([2])
  235. bins = np.array([1, 3, 1], dtype='uint64')
  236. with assert_raises(ValueError):
  237. hist, edges = np.histogram(arr, bins=bins)
  238. def test_object_array_of_0d(self):
  239. # gh-7864
  240. assert_raises(ValueError,
  241. histogram, [np.array(0.4) for i in range(10)] + [-np.inf])
  242. assert_raises(ValueError,
  243. histogram, [np.array(0.4) for i in range(10)] + [np.inf])
  244. # these should not crash
  245. np.histogram([np.array(0.5) for i in range(10)] + [.500000000000001])
  246. np.histogram([np.array(0.5) for i in range(10)] + [.5])
  247. def test_some_nan_values(self):
  248. # gh-7503
  249. one_nan = np.array([0, 1, np.nan])
  250. all_nan = np.array([np.nan, np.nan])
  251. # the internal comparisons with NaN give warnings
  252. sup = suppress_warnings()
  253. sup.filter(RuntimeWarning)
  254. with sup:
  255. # can't infer range with nan
  256. assert_raises(ValueError, histogram, one_nan, bins='auto')
  257. assert_raises(ValueError, histogram, all_nan, bins='auto')
  258. # explicit range solves the problem
  259. h, b = histogram(one_nan, bins='auto', range=(0, 1))
  260. assert_equal(h.sum(), 2) # nan is not counted
  261. h, b = histogram(all_nan, bins='auto', range=(0, 1))
  262. assert_equal(h.sum(), 0) # nan is not counted
  263. # as does an explicit set of bins
  264. h, b = histogram(one_nan, bins=[0, 1])
  265. assert_equal(h.sum(), 2) # nan is not counted
  266. h, b = histogram(all_nan, bins=[0, 1])
  267. assert_equal(h.sum(), 0) # nan is not counted
  268. def test_datetime(self):
  269. begin = np.datetime64('2000-01-01', 'D')
  270. offsets = np.array([0, 0, 1, 1, 2, 3, 5, 10, 20])
  271. bins = np.array([0, 2, 7, 20])
  272. dates = begin + offsets
  273. date_bins = begin + bins
  274. td = np.dtype('timedelta64[D]')
  275. # Results should be the same for integer offsets or datetime values.
  276. # For now, only explicit bins are supported, since linspace does not
  277. # work on datetimes or timedeltas
  278. d_count, d_edge = histogram(dates, bins=date_bins)
  279. t_count, t_edge = histogram(offsets.astype(td), bins=bins.astype(td))
  280. i_count, i_edge = histogram(offsets, bins=bins)
  281. assert_equal(d_count, i_count)
  282. assert_equal(t_count, i_count)
  283. assert_equal((d_edge - begin).astype(int), i_edge)
  284. assert_equal(t_edge.astype(int), i_edge)
  285. assert_equal(d_edge.dtype, dates.dtype)
  286. assert_equal(t_edge.dtype, td)
  287. def do_signed_overflow_bounds(self, dtype):
  288. exponent = 8 * np.dtype(dtype).itemsize - 1
  289. arr = np.array([-2**exponent + 4, 2**exponent - 4], dtype=dtype)
  290. hist, e = histogram(arr, bins=2)
  291. assert_equal(e, [-2**exponent + 4, 0, 2**exponent - 4])
  292. assert_equal(hist, [1, 1])
  293. def test_signed_overflow_bounds(self):
  294. self.do_signed_overflow_bounds(np.byte)
  295. self.do_signed_overflow_bounds(np.short)
  296. self.do_signed_overflow_bounds(np.intc)
  297. self.do_signed_overflow_bounds(np.int_)
  298. self.do_signed_overflow_bounds(np.longlong)
  299. def do_precision_lower_bound(self, float_small, float_large):
  300. eps = np.finfo(float_large).eps
  301. arr = np.array([1.0], float_small)
  302. range = np.array([1.0 + eps, 2.0], float_large)
  303. # test is looking for behavior when the bounds change between dtypes
  304. if range.astype(float_small)[0] != 1:
  305. return
  306. # previously crashed
  307. count, x_loc = np.histogram(arr, bins=1, range=range)
  308. assert_equal(count, [1])
  309. # gh-10322 means that the type comes from arr - this may change
  310. assert_equal(x_loc.dtype, float_small)
  311. def do_precision_upper_bound(self, float_small, float_large):
  312. eps = np.finfo(float_large).eps
  313. arr = np.array([1.0], float_small)
  314. range = np.array([0.0, 1.0 - eps], float_large)
  315. # test is looking for behavior when the bounds change between dtypes
  316. if range.astype(float_small)[-1] != 1:
  317. return
  318. # previously crashed
  319. count, x_loc = np.histogram(arr, bins=1, range=range)
  320. assert_equal(count, [1])
  321. # gh-10322 means that the type comes from arr - this may change
  322. assert_equal(x_loc.dtype, float_small)
  323. def do_precision(self, float_small, float_large):
  324. self.do_precision_lower_bound(float_small, float_large)
  325. self.do_precision_upper_bound(float_small, float_large)
  326. def test_precision(self):
  327. # not looping results in a useful stack trace upon failure
  328. self.do_precision(np.half, np.single)
  329. self.do_precision(np.half, np.double)
  330. self.do_precision(np.half, np.longdouble)
  331. self.do_precision(np.single, np.double)
  332. self.do_precision(np.single, np.longdouble)
  333. self.do_precision(np.double, np.longdouble)
  334. def test_histogram_bin_edges(self):
  335. hist, e = histogram([1, 2, 3, 4], [1, 2])
  336. edges = histogram_bin_edges([1, 2, 3, 4], [1, 2])
  337. assert_array_equal(edges, e)
  338. arr = np.array([0., 0., 0., 1., 2., 3., 3., 4., 5.])
  339. hist, e = histogram(arr, bins=30, range=(-0.5, 5))
  340. edges = histogram_bin_edges(arr, bins=30, range=(-0.5, 5))
  341. assert_array_equal(edges, e)
  342. hist, e = histogram(arr, bins='auto', range=(0, 1))
  343. edges = histogram_bin_edges(arr, bins='auto', range=(0, 1))
  344. assert_array_equal(edges, e)
  345. class TestHistogramOptimBinNums(object):
  346. """
  347. Provide test coverage when using provided estimators for optimal number of
  348. bins
  349. """
  350. def test_empty(self):
  351. estimator_list = ['fd', 'scott', 'rice', 'sturges',
  352. 'doane', 'sqrt', 'auto', 'stone']
  353. # check it can deal with empty data
  354. for estimator in estimator_list:
  355. a, b = histogram([], bins=estimator)
  356. assert_array_equal(a, np.array([0]))
  357. assert_array_equal(b, np.array([0, 1]))
  358. def test_simple(self):
  359. """
  360. Straightforward testing with a mixture of linspace data (for
  361. consistency). All test values have been precomputed and the values
  362. shouldn't change
  363. """
  364. # Some basic sanity checking, with some fixed data.
  365. # Checking for the correct number of bins
  366. basic_test = {50: {'fd': 4, 'scott': 4, 'rice': 8, 'sturges': 7,
  367. 'doane': 8, 'sqrt': 8, 'auto': 7, 'stone': 2},
  368. 500: {'fd': 8, 'scott': 8, 'rice': 16, 'sturges': 10,
  369. 'doane': 12, 'sqrt': 23, 'auto': 10, 'stone': 9},
  370. 5000: {'fd': 17, 'scott': 17, 'rice': 35, 'sturges': 14,
  371. 'doane': 17, 'sqrt': 71, 'auto': 17, 'stone': 20}}
  372. for testlen, expectedResults in basic_test.items():
  373. # Create some sort of non uniform data to test with
  374. # (2 peak uniform mixture)
  375. x1 = np.linspace(-10, -1, testlen // 5 * 2)
  376. x2 = np.linspace(1, 10, testlen // 5 * 3)
  377. x = np.concatenate((x1, x2))
  378. for estimator, numbins in expectedResults.items():
  379. a, b = np.histogram(x, estimator)
  380. assert_equal(len(a), numbins, err_msg="For the {0} estimator "
  381. "with datasize of {1}".format(estimator, testlen))
  382. def test_small(self):
  383. """
  384. Smaller datasets have the potential to cause issues with the data
  385. adaptive methods, especially the FD method. All bin numbers have been
  386. precalculated.
  387. """
  388. small_dat = {1: {'fd': 1, 'scott': 1, 'rice': 1, 'sturges': 1,
  389. 'doane': 1, 'sqrt': 1, 'stone': 1},
  390. 2: {'fd': 2, 'scott': 1, 'rice': 3, 'sturges': 2,
  391. 'doane': 1, 'sqrt': 2, 'stone': 1},
  392. 3: {'fd': 2, 'scott': 2, 'rice': 3, 'sturges': 3,
  393. 'doane': 3, 'sqrt': 2, 'stone': 1}}
  394. for testlen, expectedResults in small_dat.items():
  395. testdat = np.arange(testlen)
  396. for estimator, expbins in expectedResults.items():
  397. a, b = np.histogram(testdat, estimator)
  398. assert_equal(len(a), expbins, err_msg="For the {0} estimator "
  399. "with datasize of {1}".format(estimator, testlen))
  400. def test_incorrect_methods(self):
  401. """
  402. Check a Value Error is thrown when an unknown string is passed in
  403. """
  404. check_list = ['mad', 'freeman', 'histograms', 'IQR']
  405. for estimator in check_list:
  406. assert_raises(ValueError, histogram, [1, 2, 3], estimator)
  407. def test_novariance(self):
  408. """
  409. Check that methods handle no variance in data
  410. Primarily for Scott and FD as the SD and IQR are both 0 in this case
  411. """
  412. novar_dataset = np.ones(100)
  413. novar_resultdict = {'fd': 1, 'scott': 1, 'rice': 1, 'sturges': 1,
  414. 'doane': 1, 'sqrt': 1, 'auto': 1, 'stone': 1}
  415. for estimator, numbins in novar_resultdict.items():
  416. a, b = np.histogram(novar_dataset, estimator)
  417. assert_equal(len(a), numbins, err_msg="{0} estimator, "
  418. "No Variance test".format(estimator))
  419. def test_limited_variance(self):
  420. """
  421. Check when IQR is 0, but variance exists, we return the sturges value
  422. and not the fd value.
  423. """
  424. lim_var_data = np.ones(1000)
  425. lim_var_data[:3] = 0
  426. lim_var_data[-4:] = 100
  427. edges_auto = histogram_bin_edges(lim_var_data, 'auto')
  428. assert_equal(edges_auto, np.linspace(0, 100, 12))
  429. edges_fd = histogram_bin_edges(lim_var_data, 'fd')
  430. assert_equal(edges_fd, np.array([0, 100]))
  431. edges_sturges = histogram_bin_edges(lim_var_data, 'sturges')
  432. assert_equal(edges_sturges, np.linspace(0, 100, 12))
  433. def test_outlier(self):
  434. """
  435. Check the FD, Scott and Doane with outliers.
  436. The FD estimates a smaller binwidth since it's less affected by
  437. outliers. Since the range is so (artificially) large, this means more
  438. bins, most of which will be empty, but the data of interest usually is
  439. unaffected. The Scott estimator is more affected and returns fewer bins,
  440. despite most of the variance being in one area of the data. The Doane
  441. estimator lies somewhere between the other two.
  442. """
  443. xcenter = np.linspace(-10, 10, 50)
  444. outlier_dataset = np.hstack((np.linspace(-110, -100, 5), xcenter))
  445. outlier_resultdict = {'fd': 21, 'scott': 5, 'doane': 11, 'stone': 6}
  446. for estimator, numbins in outlier_resultdict.items():
  447. a, b = np.histogram(outlier_dataset, estimator)
  448. assert_equal(len(a), numbins)
  449. def test_scott_vs_stone(self):
  450. """Verify that Scott's rule and Stone's rule converges for normally distributed data"""
  451. def nbins_ratio(seed, size):
  452. rng = np.random.RandomState(seed)
  453. x = rng.normal(loc=0, scale=2, size=size)
  454. a, b = len(np.histogram(x, 'stone')[0]), len(np.histogram(x, 'scott')[0])
  455. return a / (a + b)
  456. ll = [[nbins_ratio(seed, size) for size in np.geomspace(start=10, stop=100, num=4).round().astype(int)]
  457. for seed in range(256)]
  458. # the average difference between the two methods decreases as the dataset size increases.
  459. assert_almost_equal(abs(np.mean(ll, axis=0) - 0.5),
  460. [0.1065248,
  461. 0.0968844,
  462. 0.0331818,
  463. 0.0178057],
  464. decimal=3)
  465. def test_simple_range(self):
  466. """
  467. Straightforward testing with a mixture of linspace data (for
  468. consistency). Adding in a 3rd mixture that will then be
  469. completely ignored. All test values have been precomputed and
  470. the shouldn't change.
  471. """
  472. # some basic sanity checking, with some fixed data.
  473. # Checking for the correct number of bins
  474. basic_test = {
  475. 50: {'fd': 8, 'scott': 8, 'rice': 15,
  476. 'sturges': 14, 'auto': 14, 'stone': 8},
  477. 500: {'fd': 15, 'scott': 16, 'rice': 32,
  478. 'sturges': 20, 'auto': 20, 'stone': 80},
  479. 5000: {'fd': 33, 'scott': 33, 'rice': 69,
  480. 'sturges': 27, 'auto': 33, 'stone': 80}
  481. }
  482. for testlen, expectedResults in basic_test.items():
  483. # create some sort of non uniform data to test with
  484. # (3 peak uniform mixture)
  485. x1 = np.linspace(-10, -1, testlen // 5 * 2)
  486. x2 = np.linspace(1, 10, testlen // 5 * 3)
  487. x3 = np.linspace(-100, -50, testlen)
  488. x = np.hstack((x1, x2, x3))
  489. for estimator, numbins in expectedResults.items():
  490. a, b = np.histogram(x, estimator, range = (-20, 20))
  491. msg = "For the {0} estimator".format(estimator)
  492. msg += " with datasize of {0}".format(testlen)
  493. assert_equal(len(a), numbins, err_msg=msg)
  494. @pytest.mark.parametrize("bins", ['auto', 'fd', 'doane', 'scott',
  495. 'stone', 'rice', 'sturges'])
  496. def test_signed_integer_data(self, bins):
  497. # Regression test for gh-14379.
  498. a = np.array([-2, 0, 127], dtype=np.int8)
  499. hist, edges = np.histogram(a, bins=bins)
  500. hist32, edges32 = np.histogram(a.astype(np.int32), bins=bins)
  501. assert_array_equal(hist, hist32)
  502. assert_array_equal(edges, edges32)
  503. def test_simple_weighted(self):
  504. """
  505. Check that weighted data raises a TypeError
  506. """
  507. estimator_list = ['fd', 'scott', 'rice', 'sturges', 'auto']
  508. for estimator in estimator_list:
  509. assert_raises(TypeError, histogram, [1, 2, 3],
  510. estimator, weights=[1, 2, 3])
  511. class TestHistogramdd(object):
  512. def test_simple(self):
  513. x = np.array([[-.5, .5, 1.5], [-.5, 1.5, 2.5], [-.5, 2.5, .5],
  514. [.5, .5, 1.5], [.5, 1.5, 2.5], [.5, 2.5, 2.5]])
  515. H, edges = histogramdd(x, (2, 3, 3),
  516. range=[[-1, 1], [0, 3], [0, 3]])
  517. answer = np.array([[[0, 1, 0], [0, 0, 1], [1, 0, 0]],
  518. [[0, 1, 0], [0, 0, 1], [0, 0, 1]]])
  519. assert_array_equal(H, answer)
  520. # Check normalization
  521. ed = [[-2, 0, 2], [0, 1, 2, 3], [0, 1, 2, 3]]
  522. H, edges = histogramdd(x, bins=ed, density=True)
  523. assert_(np.all(H == answer / 12.))
  524. # Check that H has the correct shape.
  525. H, edges = histogramdd(x, (2, 3, 4),
  526. range=[[-1, 1], [0, 3], [0, 4]],
  527. density=True)
  528. answer = np.array([[[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]],
  529. [[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0]]])
  530. assert_array_almost_equal(H, answer / 6., 4)
  531. # Check that a sequence of arrays is accepted and H has the correct
  532. # shape.
  533. z = [np.squeeze(y) for y in np.split(x, 3, axis=1)]
  534. H, edges = histogramdd(
  535. z, bins=(4, 3, 2), range=[[-2, 2], [0, 3], [0, 2]])
  536. answer = np.array([[[0, 0], [0, 0], [0, 0]],
  537. [[0, 1], [0, 0], [1, 0]],
  538. [[0, 1], [0, 0], [0, 0]],
  539. [[0, 0], [0, 0], [0, 0]]])
  540. assert_array_equal(H, answer)
  541. Z = np.zeros((5, 5, 5))
  542. Z[list(range(5)), list(range(5)), list(range(5))] = 1.
  543. H, edges = histogramdd([np.arange(5), np.arange(5), np.arange(5)], 5)
  544. assert_array_equal(H, Z)
  545. def test_shape_3d(self):
  546. # All possible permutations for bins of different lengths in 3D.
  547. bins = ((5, 4, 6), (6, 4, 5), (5, 6, 4), (4, 6, 5), (6, 5, 4),
  548. (4, 5, 6))
  549. r = np.random.rand(10, 3)
  550. for b in bins:
  551. H, edges = histogramdd(r, b)
  552. assert_(H.shape == b)
  553. def test_shape_4d(self):
  554. # All possible permutations for bins of different lengths in 4D.
  555. bins = ((7, 4, 5, 6), (4, 5, 7, 6), (5, 6, 4, 7), (7, 6, 5, 4),
  556. (5, 7, 6, 4), (4, 6, 7, 5), (6, 5, 7, 4), (7, 5, 4, 6),
  557. (7, 4, 6, 5), (6, 4, 7, 5), (6, 7, 5, 4), (4, 6, 5, 7),
  558. (4, 7, 5, 6), (5, 4, 6, 7), (5, 7, 4, 6), (6, 7, 4, 5),
  559. (6, 5, 4, 7), (4, 7, 6, 5), (4, 5, 6, 7), (7, 6, 4, 5),
  560. (5, 4, 7, 6), (5, 6, 7, 4), (6, 4, 5, 7), (7, 5, 6, 4))
  561. r = np.random.rand(10, 4)
  562. for b in bins:
  563. H, edges = histogramdd(r, b)
  564. assert_(H.shape == b)
  565. def test_weights(self):
  566. v = np.random.rand(100, 2)
  567. hist, edges = histogramdd(v)
  568. n_hist, edges = histogramdd(v, density=True)
  569. w_hist, edges = histogramdd(v, weights=np.ones(100))
  570. assert_array_equal(w_hist, hist)
  571. w_hist, edges = histogramdd(v, weights=np.ones(100) * 2, density=True)
  572. assert_array_equal(w_hist, n_hist)
  573. w_hist, edges = histogramdd(v, weights=np.ones(100, int) * 2)
  574. assert_array_equal(w_hist, 2 * hist)
  575. def test_identical_samples(self):
  576. x = np.zeros((10, 2), int)
  577. hist, edges = histogramdd(x, bins=2)
  578. assert_array_equal(edges[0], np.array([-0.5, 0., 0.5]))
  579. def test_empty(self):
  580. a, b = histogramdd([[], []], bins=([0, 1], [0, 1]))
  581. assert_array_max_ulp(a, np.array([[0.]]))
  582. a, b = np.histogramdd([[], [], []], bins=2)
  583. assert_array_max_ulp(a, np.zeros((2, 2, 2)))
  584. def test_bins_errors(self):
  585. # There are two ways to specify bins. Check for the right errors
  586. # when mixing those.
  587. x = np.arange(8).reshape(2, 4)
  588. assert_raises(ValueError, np.histogramdd, x, bins=[-1, 2, 4, 5])
  589. assert_raises(ValueError, np.histogramdd, x, bins=[1, 0.99, 1, 1])
  590. assert_raises(
  591. ValueError, np.histogramdd, x, bins=[1, 1, 1, [1, 2, 3, -3]])
  592. assert_(np.histogramdd(x, bins=[1, 1, 1, [1, 2, 3, 4]]))
  593. def test_inf_edges(self):
  594. # Test using +/-inf bin edges works. See #1788.
  595. with np.errstate(invalid='ignore'):
  596. x = np.arange(6).reshape(3, 2)
  597. expected = np.array([[1, 0], [0, 1], [0, 1]])
  598. h, e = np.histogramdd(x, bins=[3, [-np.inf, 2, 10]])
  599. assert_allclose(h, expected)
  600. h, e = np.histogramdd(x, bins=[3, np.array([-1, 2, np.inf])])
  601. assert_allclose(h, expected)
  602. h, e = np.histogramdd(x, bins=[3, [-np.inf, 3, np.inf]])
  603. assert_allclose(h, expected)
  604. def test_rightmost_binedge(self):
  605. # Test event very close to rightmost binedge. See Github issue #4266
  606. x = [0.9999999995]
  607. bins = [[0., 0.5, 1.0]]
  608. hist, _ = histogramdd(x, bins=bins)
  609. assert_(hist[0] == 0.0)
  610. assert_(hist[1] == 1.)
  611. x = [1.0]
  612. bins = [[0., 0.5, 1.0]]
  613. hist, _ = histogramdd(x, bins=bins)
  614. assert_(hist[0] == 0.0)
  615. assert_(hist[1] == 1.)
  616. x = [1.0000000001]
  617. bins = [[0., 0.5, 1.0]]
  618. hist, _ = histogramdd(x, bins=bins)
  619. assert_(hist[0] == 0.0)
  620. assert_(hist[1] == 0.0)
  621. x = [1.0001]
  622. bins = [[0., 0.5, 1.0]]
  623. hist, _ = histogramdd(x, bins=bins)
  624. assert_(hist[0] == 0.0)
  625. assert_(hist[1] == 0.0)
  626. def test_finite_range(self):
  627. vals = np.random.random((100, 3))
  628. histogramdd(vals, range=[[0.0, 1.0], [0.25, 0.75], [0.25, 0.5]])
  629. assert_raises(ValueError, histogramdd, vals,
  630. range=[[0.0, 1.0], [0.25, 0.75], [0.25, np.inf]])
  631. assert_raises(ValueError, histogramdd, vals,
  632. range=[[0.0, 1.0], [np.nan, 0.75], [0.25, 0.5]])
  633. def test_equal_edges(self):
  634. """ Test that adjacent entries in an edge array can be equal """
  635. x = np.array([0, 1, 2])
  636. y = np.array([0, 1, 2])
  637. x_edges = np.array([0, 2, 2])
  638. y_edges = 1
  639. hist, edges = histogramdd((x, y), bins=(x_edges, y_edges))
  640. hist_expected = np.array([
  641. [2.],
  642. [1.], # x == 2 falls in the final bin
  643. ])
  644. assert_equal(hist, hist_expected)
  645. def test_edge_dtype(self):
  646. """ Test that if an edge array is input, its type is preserved """
  647. x = np.array([0, 10, 20])
  648. y = x / 10
  649. x_edges = np.array([0, 5, 15, 20])
  650. y_edges = x_edges / 10
  651. hist, edges = histogramdd((x, y), bins=(x_edges, y_edges))
  652. assert_equal(edges[0].dtype, x_edges.dtype)
  653. assert_equal(edges[1].dtype, y_edges.dtype)
  654. def test_large_integers(self):
  655. big = 2**60 # Too large to represent with a full precision float
  656. x = np.array([0], np.int64)
  657. x_edges = np.array([-1, +1], np.int64)
  658. y = big + x
  659. y_edges = big + x_edges
  660. hist, edges = histogramdd((x, y), bins=(x_edges, y_edges))
  661. assert_equal(hist[0, 0], 1)
  662. def test_density_non_uniform_2d(self):
  663. # Defines the following grid:
  664. #
  665. # 0 2 8
  666. # 0+-+-----+
  667. # + | +
  668. # + | +
  669. # 6+-+-----+
  670. # 8+-+-----+
  671. x_edges = np.array([0, 2, 8])
  672. y_edges = np.array([0, 6, 8])
  673. relative_areas = np.array([
  674. [3, 9],
  675. [1, 3]])
  676. # ensure the number of points in each region is proportional to its area
  677. x = np.array([1] + [1]*3 + [7]*3 + [7]*9)
  678. y = np.array([7] + [1]*3 + [7]*3 + [1]*9)
  679. # sanity check that the above worked as intended
  680. hist, edges = histogramdd((y, x), bins=(y_edges, x_edges))
  681. assert_equal(hist, relative_areas)
  682. # resulting histogram should be uniform, since counts and areas are propotional
  683. hist, edges = histogramdd((y, x), bins=(y_edges, x_edges), density=True)
  684. assert_equal(hist, 1 / (8*8))
  685. def test_density_non_uniform_1d(self):
  686. # compare to histogram to show the results are the same
  687. v = np.arange(10)
  688. bins = np.array([0, 1, 3, 6, 10])
  689. hist, edges = histogram(v, bins, density=True)
  690. hist_dd, edges_dd = histogramdd((v,), (bins,), density=True)
  691. assert_equal(hist, hist_dd)
  692. assert_equal(edges, edges_dd[0])
  693. def test_density_via_normed(self):
  694. # normed should simply alias to density argument
  695. v = np.arange(10)
  696. bins = np.array([0, 1, 3, 6, 10])
  697. hist, edges = histogram(v, bins, density=True)
  698. hist_dd, edges_dd = histogramdd((v,), (bins,), normed=True)
  699. assert_equal(hist, hist_dd)
  700. assert_equal(edges, edges_dd[0])
  701. def test_density_normed_redundancy(self):
  702. v = np.arange(10)
  703. bins = np.array([0, 1, 3, 6, 10])
  704. with assert_raises_regex(TypeError, "Cannot specify both"):
  705. hist_dd, edges_dd = histogramdd((v,), (bins,),
  706. density=True,
  707. normed=True)