test_histograms.py 32 KB

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