test_histograms.py 33 KB

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