1def compress_ints_lossless(x, *, method: str = "zstd") -> bytes:
2 """Compress integer data using various compression methods.
4 Args:
5 x: NumPy array of integers to compress
6 method: Compression method to use. One of:
7 - "zstd": Zstandard compression (default)
8 - "zlib": zlib compression
9 - "lzma": LZMA compression
10 - "simple_ans": Simple Asymmetric Numeral Systems
12 Returns:
13 Compressed bytes
14 """
15 if method == "zstd":
16 import zstandard as zstd
18 cctx = zstd.ZstdCompressor(level=22)
19 return cctx.compress(x.tobytes())
20 elif method == "zlib":
21 import zlib
23 return zlib.compress(x.tobytes(), level=9)
24 elif method == "lzma":
25 import lzma
27 return lzma.compress(x.tobytes(), preset=9)
28 elif method == "simple_ans":
29 from simple_ans import ans_encode
31 encoding = ans_encode(x)
32 return (
33 encoding.bitstream
34 + encoding.symbol_counts.tobytes()
35 + encoding.symbol_values.tobytes()
36 )
37 else:
38 raise ValueError(f"Unknown method: {method}")