|
| 1 | +import numpy as np |
| 2 | + |
| 3 | +import pytest |
| 4 | + |
| 5 | +from numcodecs.bitinfo import BitInfo, exponent_bias, mutual_information |
| 6 | + |
| 7 | +def test_bitinfo_initialization(): |
| 8 | + bitinfo = BitInfo(0.5) |
| 9 | + assert bitinfo.info_level == 0.5 |
| 10 | + assert bitinfo.axes is None |
| 11 | + |
| 12 | + bitinfo = BitInfo(0.5, axes=1) |
| 13 | + assert bitinfo.axes == [1] |
| 14 | + |
| 15 | + bitinfo = BitInfo(0.5, axes=[1, 2]) |
| 16 | + assert bitinfo.axes == [1, 2] |
| 17 | + |
| 18 | + with pytest.raises(ValueError): |
| 19 | + BitInfo(-0.1) |
| 20 | + |
| 21 | + with pytest.raises(ValueError): |
| 22 | + BitInfo(1.1) |
| 23 | + |
| 24 | + with pytest.raises(ValueError): |
| 25 | + BitInfo(0.5, axes=1.5) |
| 26 | + |
| 27 | + with pytest.raises(ValueError): |
| 28 | + BitInfo(0.5, axes=[1, 1.5]) |
| 29 | + |
| 30 | + |
| 31 | +def test_bitinfo_encode(): |
| 32 | + bitinfo = BitInfo(info_level=0.5) |
| 33 | + a = np.array([1.0, 2.0, 3.0], dtype="float32") |
| 34 | + encoded = bitinfo.encode(a) |
| 35 | + decoded = bitinfo.decode(encoded) |
| 36 | + assert decoded.dtype == a.dtype |
| 37 | + |
| 38 | + |
| 39 | +def test_bitinfo_encode_errors(): |
| 40 | + bitinfo = BitInfo(0.5) |
| 41 | + a = np.array([1, 2, 3], dtype="int32") |
| 42 | + with pytest.raises(TypeError): |
| 43 | + bitinfo.encode(a) |
| 44 | + |
| 45 | + a = np.array([1.0, 2.0, 3.0], dtype="float128") |
| 46 | + with pytest.raises(TypeError): |
| 47 | + bitinfo.encode(a) |
| 48 | + |
| 49 | + |
| 50 | +def test_exponent_bias(): |
| 51 | + assert exponent_bias("f2") == 15 |
| 52 | + assert exponent_bias("f4") == 127 |
| 53 | + assert exponent_bias("f8") == 1023 |
| 54 | + |
| 55 | + with pytest.raises(ValueError): |
| 56 | + exponent_bias("int32") |
| 57 | + |
| 58 | + |
| 59 | +def test_mutual_information(): |
| 60 | + """ Test mutual information calculation |
| 61 | +
|
| 62 | + Tests for changes to the mutual_information |
| 63 | + but not the correcteness of the original. |
| 64 | + """ |
| 65 | + a = np.arange(10.0, dtype='float32') |
| 66 | + b = a + 1000 |
| 67 | + c = a[::-1].copy() |
| 68 | + dt = np.dtype('uint32') |
| 69 | + a,b,c = map(lambda x: x.view(dt), [a,b,c]) |
| 70 | + |
| 71 | + assert mutual_information(a, a).sum() == 7.020411549771797 |
| 72 | + assert mutual_information(a, b).sum() == 0.0 |
| 73 | + assert mutual_information(a, c).sum() == 0.6545015579460758 |
0 commit comments