|
| 1 | +import pytest |
| 2 | + |
| 3 | +import dpnp |
| 4 | + |
| 5 | +import numpy |
| 6 | + |
| 7 | + |
| 8 | +class TestHistogram: |
| 9 | + |
| 10 | + def setup(self): |
| 11 | + pass |
| 12 | + |
| 13 | + def teardown(self): |
| 14 | + pass |
| 15 | + |
| 16 | + def test_simple(self): |
| 17 | + n = 100 |
| 18 | + v = dpnp.random.rand(n) |
| 19 | + (a, b) = dpnp.histogram(v) |
| 20 | + # check if the sum of the bins equals the number of samples |
| 21 | + numpy.testing.assert_equal(dpnp.sum(a, axis=0)[0], n) |
| 22 | + # check that the bin counts are evenly spaced when the data is from |
| 23 | + # a linear function |
| 24 | + (a, b) = dpnp.histogram(numpy.linspace(0, 10, 100)) |
| 25 | + numpy.testing.assert_array_equal(a, 10) |
| 26 | + |
| 27 | + def test_one_bin(self): |
| 28 | + # Ticket 632 |
| 29 | + hist, edges = dpnp.histogram([1, 2, 3, 4], [1, 2]) |
| 30 | + numpy.testing.assert_array_equal(hist, [2, ]) |
| 31 | + numpy.testing.assert_array_equal(edges, [1, 2]) |
| 32 | + numpy.testing.assert_raises(ValueError, dpnp.histogram, [1, 2], bins=0) |
| 33 | + h, e = dpnp.histogram([1, 2], bins=1) |
| 34 | + numpy.testing.assert_equal(h, dpnp.array([2])) |
| 35 | + numpy.testing.assert_allclose(e, dpnp.array([1., 2.])) |
| 36 | + |
| 37 | + def test_density(self): |
| 38 | + # Check that the integral of the density equals 1. |
| 39 | + n = 100 |
| 40 | + v = dpnp.random.rand(n) |
| 41 | + a, b = dpnp.histogram(v, density=True) |
| 42 | + area = dpnp.sum(a * dpnp.diff(b)[0])[0] |
| 43 | + numpy.testing.assert_almost_equal(area, 1) |
| 44 | + |
| 45 | + # Check with non-constant bin widths |
| 46 | + v = dpnp.arange(10) |
| 47 | + bins = [0, 1, 3, 6, 10] |
| 48 | + a, b = dpnp.histogram(v, bins, density=True) |
| 49 | + numpy.testing.assert_array_equal(a, .1) |
| 50 | + numpy.testing.assert_equal(dpnp.sum(a * dpnp.diff(b))[0], 1) |
| 51 | + |
| 52 | + # Test that passing False works too |
| 53 | + a, b = dpnp.histogram(v, bins, density=False) |
| 54 | + numpy.testing.assert_array_equal(a, [1, 2, 3, 4]) |
| 55 | + |
| 56 | + # Variable bin widths are especially useful to deal with |
| 57 | + # infinities. |
| 58 | + v = dpnp.arange(10) |
| 59 | + bins = [0, 1, 3, 6, numpy.inf] |
| 60 | + a, b = dpnp.histogram(v, bins, density=True) |
| 61 | + numpy.testing.assert_array_equal(a, [.1, .1, .1, 0.]) |
| 62 | + |
| 63 | + # Taken from a bug report from N. Becker on the numpy-discussion |
| 64 | + # mailing list Aug. 6, 2010. |
| 65 | + counts, dmy = dpnp.histogram( |
| 66 | + [1, 2, 3, 4], [0.5, 1.5, numpy.inf], density=True) |
| 67 | + numpy.testing.assert_equal(counts, [.25, 0]) |
| 68 | + |
| 69 | + def test_arr_weights_mismatch(self): |
| 70 | + a = dpnp.arange(10) + .5 |
| 71 | + w = dpnp.arange(11) + .5 |
| 72 | + with numpy.testing.assert_raises_regex(ValueError, "same shape as"): |
| 73 | + h, b = dpnp.histogram(a, range=[1, 9], weights=w, density=True) |
0 commit comments