Pack elements into nbits representation, by starting with the least significant bit (LSB) and moving upward to the most significant bit (MSB). Returns packed elements as np.uint8.
(elements: np.ndarray, nbits: int)
| 754 | |
| 755 | |
| 756 | def pack_elements_into_bits(elements: np.ndarray, nbits: int) -> np.ndarray: |
| 757 | """ |
| 758 | Pack elements into nbits representation, by starting with the least significant bit (LSB) and |
| 759 | moving upward to the most significant bit (MSB). |
| 760 | |
| 761 | Returns packed elements as np.uint8. |
| 762 | """ |
| 763 | if not np.issubdtype(elements.dtype, np.integer): |
| 764 | raise ValueError(f"Only support packing integers elements, but got {elements.dtype}") |
| 765 | |
| 766 | # Adjust allowed value range based on if the input is signed or unsigned. |
| 767 | if np.issubdtype(elements.dtype, np.signedinteger): |
| 768 | max_val = 2 ** (nbits - 1) - 1 |
| 769 | min_val = -max_val - 1 |
| 770 | else: |
| 771 | max_val = 2**nbits - 1 |
| 772 | min_val = 0 |
| 773 | if np.max(elements) > max_val: |
| 774 | raise ValueError( |
| 775 | f"To pack elements into {nbits}-bit, the max value is {max_val}, but got {np.max(elements)}" |
| 776 | ) |
| 777 | if np.min(elements) < min_val: |
| 778 | raise ValueError( |
| 779 | f"To pack elements into {nbits}-bit, the min value is {min_val}, but got {np.min(elements)}" |
| 780 | ) |
| 781 | |
| 782 | # As np.unpackbits only supports uint8, convert to uint8 first. |
| 783 | # Notice that it will not lose information, because the bits are unchanged when converting int8 |
| 784 | # to uint8. For example, the signed int -6 has bit representation '11111010', and when we unpackbits |
| 785 | # we get [0, 1, 0, 1, 1, 1, 1, 1], where only first 4 elements are needed for 4-bit representation. |
| 786 | elements = elements.astype(np.uint8) |
| 787 | bitarray = np.unpackbits(elements.reshape(-1, 1), bitorder="little", axis=-1)[:, :nbits] |
| 788 | return np.packbits(bitarray.flatten(), bitorder="little") |
| 789 | |
| 790 | |
| 791 | def restore_elements_from_packed_bits( |
no test coverage detected