|
| 1 | +import numpy as np |
| 2 | + |
| 3 | +import pytest |
| 4 | + |
| 5 | +from numcodecs.bitround import BitRound, max_bits |
| 6 | + |
| 7 | +# adapted from https://github.com/milankl/BitInformation.jl/blob/main/test/round_nearest.jl |
| 8 | + |
| 9 | + |
| 10 | +# TODO: add other dtypes |
| 11 | +@pytest.fixture(params=["float32", "float64"]) |
| 12 | +def dtype(request): |
| 13 | + return request.param |
| 14 | + |
| 15 | + |
| 16 | +def round(data, keepbits): |
| 17 | + codec = BitRound(keepbits=keepbits) |
| 18 | + data = data.copy() # otherwise overwrites the input |
| 19 | + encoded = codec.encode(data) |
| 20 | + return codec.decode(encoded) |
| 21 | + |
| 22 | + |
| 23 | +def test_round_zero_to_zero(dtype): |
| 24 | + a = np.zeros((3, 2), dtype=dtype) |
| 25 | + # Don't understand Milan's original test: |
| 26 | + # How is it possible to have negative keepbits? |
| 27 | + # for k in range(-5, 50): |
| 28 | + for k in range(0, max_bits[dtype]): |
| 29 | + ar = round(a, k) |
| 30 | + np.testing.assert_equal(a, ar) |
| 31 | + |
| 32 | + |
| 33 | +def test_round_one_to_one(dtype): |
| 34 | + a = np.ones((3, 2), dtype=dtype) |
| 35 | + for k in range(0, max_bits[dtype]): |
| 36 | + ar = round(a, k) |
| 37 | + np.testing.assert_equal(a, ar) |
| 38 | + |
| 39 | + |
| 40 | +def test_round_minus_one_to_minus_one(dtype): |
| 41 | + a = -np.ones((3, 2), dtype=dtype) |
| 42 | + for k in range(0, max_bits[dtype]): |
| 43 | + ar = round(a, k) |
| 44 | + np.testing.assert_equal(a, ar) |
| 45 | + |
| 46 | + |
| 47 | +def test_no_rounding(dtype): |
| 48 | + a = np.random.random_sample((300, 200)).astype(dtype) |
| 49 | + keepbits = max_bits[dtype] |
| 50 | + ar = round(a, keepbits) |
| 51 | + np.testing.assert_equal(a, ar) |
| 52 | + |
| 53 | + |
| 54 | +APPROX_KEEPBITS = {"float32": 11, "float64": 18} |
| 55 | + |
| 56 | + |
| 57 | +def test_approx_equal(dtype): |
| 58 | + a = np.random.random_sample((300, 200)).astype(dtype) |
| 59 | + ar = round(a, APPROX_KEEPBITS[dtype]) |
| 60 | + # Mimic julia behavior - https://docs.julialang.org/en/v1/base/math/#Base.isapprox |
| 61 | + rtol = np.sqrt(np.finfo(np.float32).eps) |
| 62 | + # This gets us much closer but still failing for ~6% of the array |
| 63 | + # It does pass if we add 1 to keepbits (11 instead of 10) |
| 64 | + # Is there an off-by-one issue here? |
| 65 | + np.testing.assert_allclose(a, ar, rtol=rtol) |
| 66 | + |
| 67 | + |
| 68 | +def test_idempotence(dtype): |
| 69 | + a = np.random.random_sample((300, 200)).astype(dtype) |
| 70 | + for k in range(20): |
| 71 | + ar = round(a, k) |
| 72 | + ar2 = round(a, k) |
| 73 | + np.testing.assert_equal(ar, ar2) |
| 74 | + |
| 75 | + |
| 76 | +def test_errors(): |
| 77 | + with pytest.raises(ValueError): |
| 78 | + BitRound(keepbits=99).encode(np.array([0], dtype="float32")) |
| 79 | + with pytest.raises(TypeError): |
| 80 | + BitRound(keepbits=10).encode(np.array([0])) |
0 commit comments