| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
MSNumpress decoder class |
| 5 |
|
| 6 |
|
| 7 |
Authors: |
| 8 |
|
| 9 |
Manuel Kösters |
| 10 |
Christian Fufezan |
| 11 |
""" |
| 12 |
import sys |
| 13 |
import struct |
| 14 |
import math |
| 15 |
|
| 16 |
import numpy as np |
| 17 |
|
| 18 |
|
| 19 |
class MSNumpress: |
| 20 |
""" |
| 21 |
The library provides implementations of 4 different algorithms, |
| 22 |
1 designed to compress first order smooth data like retention time or M/Z |
| 23 |
arrays, 1 designed to transform first order smooth data for more efficient |
| 24 |
zlib compression, and 2 for compressing non-smooth data with lower |
| 25 |
requirements on precision like ion count arrays. |
| 26 |
|
| 27 |
|
| 28 |
..Note:: |
| 29 |
This is a Python implementation of the Golomb-Rice encoding, |
| 30 |
also known as MS-Numpress. As such it is considerably slower than |
| 31 |
the C implementation, which we wrapped into cython. Please make |
| 32 |
yourself a favor and use the the wrapper/c implementation and only |
| 33 |
as a last result this Python implementation. |
| 34 |
|
| 35 |
""" |
| 36 |
|
| 37 |
def __init__(self, data=None): |
| 38 |
""" |
| 39 |
Initialize stateful Numpress De- and Encoding. |
| 40 |
|
| 41 |
Args: |
| 42 |
array (list): data array with compressed or decompressed data |
| 43 |
""" |
| 44 |
self.is_little_endian = True if sys.byteorder == "little" else False |
| 45 |
self.Filler = { |
| 46 |
8: "00000000", |
| 47 |
7: "0000000", |
| 48 |
6: "000000", |
| 49 |
5: "00000", |
| 50 |
4: "0000", |
| 51 |
3: "000", |
| 52 |
2: "00", |
| 53 |
1: "0", |
| 54 |
0: "", |
| 55 |
9: "f", |
| 56 |
10: "ff", |
| 57 |
11: "fff", |
| 58 |
12: "ffff", |
| 59 |
13: "fffff", |
| 60 |
14: "ffffff", |
| 61 |
15: "fffffff", |
| 62 |
} |
| 63 |
|
| 64 |
self._encoded_data = None |
| 65 |
self._decoded_data = None |
| 66 |
|
| 67 |
if type(data) == bytearray: |
| 68 |
|
| 69 |
self.data_state = "encoded" |
| 70 |
self._encoded_data = data |
| 71 |
elif type(data) == list: |
| 72 |
|
| 73 |
self.data_state = "decoded" |
| 74 |
self._decoded_data = data |
| 75 |
else: |
| 76 |
pass |
| 77 |
|
| 78 |
@property |
| 79 |
def decoded_data(self): |
| 80 |
if self._decoded_data is None: |
| 81 |
raise Exception("decoded data is not set") |
| 82 |
return self._decoded_data |
| 83 |
|
| 84 |
@decoded_data.setter |
| 85 |
def decoded_data(self, data): |
| 86 |
if type(data) is not list and type(data) is not np.ndarray: |
| 87 |
raise Exception("data must be list") |
| 88 |
self._decoded_data = data |
| 89 |
|
| 90 |
@property |
| 91 |
def encoded_data(self): |
| 92 |
if self._encoded_data is None: |
| 93 |
raise Exception("encoded data is not set") |
| 94 |
return self._encoded_data |
| 95 |
|
| 96 |
@encoded_data.setter |
| 97 |
def encoded_data(self, data): |
| 98 |
"""Set the data.""" |
| 99 |
if type(data) is not bytearray: |
| 100 |
raise Exception("data must be bytearray") |
| 101 |
self._encoded_data = data |
| 102 |
|
| 103 |
def _linear_fixed_point(self): |
| 104 |
""" |
| 105 |
Calculate the optimal predictor coefficient for linear prediction model |
| 106 |
for the Numpress Linear algorithm. |
| 107 |
|
| 108 |
Returns: |
| 109 |
fixed_point(int): scaling factor for linear prediction |
| 110 |
""" |
| 111 |
data = self.decoded_data |
| 112 |
data_size = len(data) |
| 113 |
if data_size == 0: |
| 114 |
return 0 |
| 115 |
if data_size == 1: |
| 116 |
return math.floor(0xFFFFFFFF) / data[0] |
| 117 |
max_double = max(data[:2]) |
| 118 |
for i in range(2, data_size): |
| 119 |
extrapol = data[i - 1] + (data[i - 1] - data[i - 2]) |
| 120 |
diff = data[i] - extrapol |
| 121 |
max_double = max([max_double, math.ceil(abs(diff) + 1)]) |
| 122 |
return math.floor(0x7FFFFFFF / max_double) |
| 123 |
|
| 124 |
def _slof_fixed_point(self): |
| 125 |
""" |
| 126 |
Calculate the optimal predictor coefficient for linear prediction model |
| 127 |
for the Numpress Slof algorithm. |
| 128 |
|
| 129 |
Returns: |
| 130 |
fixed_point(int): scaling factor for linear prediction |
| 131 |
""" |
| 132 |
data = self.decoded_data |
| 133 |
if len(data) == 0: |
| 134 |
return 0 |
| 135 |
max_double = 1 |
| 136 |
for i in range(len(data)): |
| 137 |
x = math.log(data[i] + 1) |
| 138 |
max_double = max([max_double, x]) |
| 139 |
fp = math.floor(0xFFFF / max_double) |
| 140 |
return fp |
| 141 |
|
| 142 |
def _encodeInt(self, integer): |
| 143 |
""" |
| 144 |
# RENAME FUNCTION :) |
| 145 |
Encode a given 4 byte integer by truncating leading 1s and 0s |
| 146 |
and saving them in a halfbyte along with the original data |
| 147 |
|
| 148 |
Args: |
| 149 |
integer (int): Value to be compressed |
| 150 |
|
| 151 |
Returns: |
| 152 |
bytes (bytearray): encoded bytes |
| 153 |
""" |
| 154 |
mask = 0xF0000000 |
| 155 |
|
| 156 |
try: |
| 157 |
integer_as_bytes = struct.pack(">i", integer) |
| 158 |
except: |
| 159 |
integer_as_bytes = None |
| 160 |
init = integer & 0xF0000000 |
| 161 |
results = bytearray() |
| 162 |
|
| 163 |
if integer_as_bytes == b"\x00\x00\x00\x00": |
| 164 |
results.append(0x8) |
| 165 |
x = 8 |
| 166 |
|
| 167 |
elif init == 0: |
| 168 |
x = 0 |
| 169 |
for b in integer_as_bytes: |
| 170 |
first_half_byte = (0xFF & b) >> 4 |
| 171 |
second_half_byte = 0xF & b |
| 172 |
if first_half_byte == 0: |
| 173 |
x += 1 |
| 174 |
if second_half_byte == 0: |
| 175 |
x += 1 |
| 176 |
continue |
| 177 |
else: |
| 178 |
results.append(x) |
| 179 |
break |
| 180 |
else: |
| 181 |
results.append(x) |
| 182 |
break |
| 183 |
|
| 184 |
else: |
| 185 |
for x in range(8): |
| 186 |
m = mask >> 4 * x |
| 187 |
if integer & m == m: |
| 188 |
continue |
| 189 |
else: |
| 190 |
results.append(x + 8) |
| 191 |
break |
| 192 |
if len(results) == 0: |
| 193 |
results.append(x + 8) |
| 194 |
|
| 195 |
if x < 8: |
| 196 |
for m in range(8 - x): |
| 197 |
r_to_l_mask = 0xF |
| 198 |
np_byte = (integer >> 4 * m) & r_to_l_mask |
| 199 |
results.append(np_byte) |
| 200 |
|
| 201 |
return results |
| 202 |
|
| 203 |
def _decodeInt(self, encodedInt): |
| 204 |
""" |
| 205 |
Decode an integer from bytes encoded by :py:func:`_encodeInt` |
| 206 |
|
| 207 |
Args: |
| 208 |
encodedInt (bytearray): encoded bytes |
| 209 |
|
| 210 |
Returns: |
| 211 |
result (int): decoded form of the encoded integer |
| 212 |
""" |
| 213 |
hex_string = "" |
| 214 |
fill = "0" |
| 215 |
for pos, byte in enumerate(encodedInt): |
| 216 |
if pos == 0: |
| 217 |
leading = byte & 0xF |
| 218 |
if leading > 8: |
| 219 |
leading -= 8 |
| 220 |
fill = "f" |
| 221 |
else: |
| 222 |
hex_string = str(hex(byte))[2:] + hex_string |
| 223 |
hex_string = fill * leading + hex_string |
| 224 |
x = int(hex_string, 16) |
| 225 |
if x > 0x7FFFFFFF: |
| 226 |
x -= 0x100000000 |
| 227 |
|
| 228 |
return x |
| 229 |
|
| 230 |
def encode_linear(self): |
| 231 |
""" |
| 232 |
Use Linear prediction and Golomb coding to compress an array |
| 233 |
of mz values. |
| 234 |
|
| 235 |
Returns: |
| 236 |
result (bytearray): Golomb encoded bytearray |
| 237 |
|
| 238 |
EXPAMPLE |
| 239 |
|
| 240 |
IN: |
| 241 |
[ 12.23123, 14.21431, 23.22222 ] |
| 242 |
OUT: |
| 243 |
(b'\x50\x0c\x0f\x08\x51\x02\x03\x01\x23\x00') <class 'bytearray'> |
| 244 |
""" |
| 245 |
|
| 246 |
ints = [0 for x in range(3)] |
| 247 |
data = self.decoded_data |
| 248 |
fp = self._linear_fixed_point() |
| 249 |
|
| 250 |
encoded_fixed_point = self._encode_fixed_point(fp) |
| 251 |
result = bytearray(encoded_fixed_point) |
| 252 |
if len(data) == 0: |
| 253 |
return 8 |
| 254 |
|
| 255 |
ints[1] = int(round(data[0] * fp)) |
| 256 |
|
| 257 |
for i in range(4): |
| 258 |
result.append((ints[1] >> (i * 8)) & 0xFF) |
| 259 |
|
| 260 |
if len(data) == 1: |
| 261 |
return 12 |
| 262 |
|
| 263 |
ints[2] = int(round(data[1] * fp)) |
| 264 |
|
| 265 |
for i in range(4): |
| 266 |
result.append((ints[2] >> (i * 8)) & 0xFF) |
| 267 |
|
| 268 |
enc_diff = bytearray() |
| 269 |
for i in range(2, len(data)): |
| 270 |
ints[0] = ints[1] |
| 271 |
ints[1] = ints[2] |
| 272 |
ints[2] = int(round(data[i] * fp)) |
| 273 |
extrapol = ints[1] + (ints[1] - ints[0]) |
| 274 |
|
| 275 |
diff = ints[2] - extrapol |
| 276 |
enc_diff += self._encodeInt(diff) |
| 277 |
for i in range(1, len(enc_diff), 2): |
| 278 |
final_byte = enc_diff[i] & 0xF | enc_diff[i - 1] << 4 |
| 279 |
result.append(final_byte) |
| 280 |
if len(enc_diff) % 2 != 0: |
| 281 |
enc_diff = bytearray([enc_diff[-1]]) |
| 282 |
else: |
| 283 |
enc_diff = bytearray() |
| 284 |
|
| 285 |
self.encoded_data = result |
| 286 |
return result |
| 287 |
|
| 288 |
def decode_linear(self): |
| 289 |
""" |
| 290 |
Decode a Golomb encoded bytearray to its corresponding numpy array. |
| 291 |
|
| 292 |
Returns: |
| 293 |
result (np.ndarray): NumLin decoded numpy array of the |
| 294 |
original data |
| 295 |
|
| 296 |
""" |
| 297 |
ints = [0 for x in range(3)] |
| 298 |
data = self.encoded_data |
| 299 |
|
| 300 |
if len(data) < 8: |
| 301 |
raise Exception("Corrupt input data.\nnot enough bytes to read fixed point") |
| 302 |
|
| 303 |
enc_fp = data |
| 304 |
fp = self._decode_fixed_point(enc_fp) |
| 305 |
|
| 306 |
if len(data) < 12: |
| 307 |
raise Exception("Corrupt input data.\nnot enough bytes to read first value") |
| 308 |
|
| 309 |
for i in range(4): |
| 310 |
ints[1] = ints[1] | ((0xFF & (data[8 + i])) << (i * 8)) |
| 311 |
i1 = ints[1] / fp |
| 312 |
|
| 313 |
if len(data) < 16: |
| 314 |
raise Exception("Corrupt input data\nnot enough bytes to read second value") |
| 315 |
|
| 316 |
for i in range(4): |
| 317 |
ints[2] = ints[2] | ((0xFF & (data[12 + i])) << (i * 8)) |
| 318 |
i2 = ints[2] / fp |
| 319 |
|
| 320 |
diff_vals = self._decode_ints_from_bytearray(16, fp) |
| 321 |
result = [0 for x in range(len(diff_vals) + 2)] |
| 322 |
result[0] = i1 |
| 323 |
result[1] = i2 |
| 324 |
i = 2 |
| 325 |
for diff in diff_vals: |
| 326 |
ints[0] = ints[1] |
| 327 |
ints[1] = ints[2] |
| 328 |
ints[2] = diff |
| 329 |
extrapol = ints[1] + (ints[1] - ints[0]) |
| 330 |
val = extrapol + ints[2] |
| 331 |
result[i] = val / fp |
| 332 |
ints[2] = val |
| 333 |
i += 1 |
| 334 |
|
| 335 |
return result |
| 336 |
|
| 337 |
def _decode_ints_from_bytearray(self, pos, normalization=1): |
| 338 |
""" |
| 339 |
Decode truncated integer encoded values and end position |
| 340 |
in bytearray. |
| 341 |
|
| 342 |
Args: |
| 343 |
pos (int) : start position in array |
| 344 |
|
| 345 |
Returns: |
| 346 |
results (list): ... |
| 347 |
""" |
| 348 |
|
| 349 |
results = [0 for x in range(len(self.encoded_data) * 2)] |
| 350 |
leading_count = None |
| 351 |
i = 0 |
| 352 |
while pos < len(self.encoded_data): |
| 353 |
current_byte = "{0:02x}".format(self.encoded_data[pos]) |
| 354 |
for byte_pos in [0, 1]: |
| 355 |
hb = current_byte[byte_pos] |
| 356 |
if leading_count is None: |
| 357 |
if hb == "8": |
| 358 |
results[i] = 0 |
| 359 |
i += 1 |
| 360 |
else: |
| 361 |
leading_count = int(hb, 16) |
| 362 |
hex_str = "" |
| 363 |
cb = leading_count - (8 * math.floor(leading_count / 8)) |
| 364 |
else: |
| 365 |
hex_str = "{0}{1}".format(hb, hex_str) |
| 366 |
cb += 1 |
| 367 |
try: |
| 368 |
1 / (cb - 8) |
| 369 |
except: |
| 370 |
final_int = int(self.Filler[leading_count] + hex_str, 16) |
| 371 |
if final_int > 0x7FFFFFFF: |
| 372 |
final_int -= 0x100000000 |
| 373 |
results[i] = final_int |
| 374 |
i += 1 |
| 375 |
leading_count = None |
| 376 |
pos += 1 |
| 377 |
return results[:i] |
| 378 |
|
| 379 |
def encode_pic(self): |
| 380 |
""" |
| 381 |
Encode Ion count data by rounding to the next integer and |
| 382 |
store in a truncated form. |
| 383 |
|
| 384 |
Returns: |
| 385 |
result (bytearray): array with rounded |
| 386 |
ion count data in bytes |
| 387 |
""" |
| 388 |
|
| 389 |
res = bytearray() |
| 390 |
final = bytearray() |
| 391 |
|
| 392 |
for val in self.decoded_data: |
| 393 |
val = int(round(val)) |
| 394 |
enc_int = self._encodeInt(val) |
| 395 |
res.extend(enc_int) |
| 396 |
|
| 397 |
|
| 398 |
if len(res) % 2 != 0: |
| 399 |
res.append(0) |
| 400 |
|
| 401 |
|
| 402 |
for i in range(1, len(res), 2): |
| 403 |
val = (res[i - 1] << 4) | res[i] & 0xF |
| 404 |
final.append(val) |
| 405 |
|
| 406 |
self.encoded_data = final |
| 407 |
return final |
| 408 |
|
| 409 |
def decode_pic(self): |
| 410 |
""" |
| 411 |
Decode ion count data compressed with :py:func:`encodePic` |
| 412 |
|
| 413 |
Returns: |
| 414 |
result (array): decoded Ion count data as numpy array |
| 415 |
""" |
| 416 |
results = [] |
| 417 |
data = self.encoded_data |
| 418 |
read_first = True |
| 419 |
hb_to_read = 0 |
| 420 |
current_value = bytearray() |
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
for val in data: |
| 426 |
if hb_to_read == 0: |
| 427 |
if read_first is True: |
| 428 |
current_value = bytearray() |
| 429 |
count = (0xFF & val) >> 4 |
| 430 |
current_value.append(count) |
| 431 |
hb_to_read = 8 - count |
| 432 |
read_first = False |
| 433 |
else: |
| 434 |
current_value = bytearray() |
| 435 |
count = 0xF & val |
| 436 |
current_value.append(count) |
| 437 |
hb_to_read = 8 - count |
| 438 |
read_first = True |
| 439 |
if hb_to_read != 0: |
| 440 |
if hb_to_read == 1: |
| 441 |
if read_first is True: |
| 442 |
hb = (0xFF & val) >> 4 |
| 443 |
current_value.append(hb) |
| 444 |
hb_to_read -= 1 |
| 445 |
dec_int = self._decodeInt(current_value) |
| 446 |
current_value = bytearray() |
| 447 |
results.append(dec_int) |
| 448 |
count = 0xF & val |
| 449 |
current_value.append(count) |
| 450 |
hb_to_read = 8 - count |
| 451 |
continue |
| 452 |
else: |
| 453 |
hb = 0xF & val |
| 454 |
current_value.append(hb) |
| 455 |
hb_to_read -= 1 |
| 456 |
dec_int = self._decodeInt(current_value) |
| 457 |
current_value = bytearray() |
| 458 |
results.append(dec_int) |
| 459 |
read_first = True |
| 460 |
continue |
| 461 |
if read_first is True: |
| 462 |
hb1 = (0xFF & val) >> 4 |
| 463 |
hb2 = 0xF & val |
| 464 |
current_value.append(hb1) |
| 465 |
current_value.append(hb2) |
| 466 |
hb_to_read -= 2 |
| 467 |
if hb_to_read == 0: |
| 468 |
dec_int = self._decodeInt(current_value) |
| 469 |
results.append(dec_int) |
| 470 |
current_value = bytearray() |
| 471 |
continue |
| 472 |
else: |
| 473 |
hb = 0xF & val |
| 474 |
current_value.append(hb) |
| 475 |
read_first = True |
| 476 |
hb_to_read -= 1 |
| 477 |
|
| 478 |
self.decoded_data = results |
| 479 |
|
| 480 |
return results |
| 481 |
|
| 482 |
def encode_slof(self): |
| 483 |
""" |
| 484 |
encode ion count data by multiplying the logarithm of each value with |
| 485 |
a scaling factor, rounding to nearest integer, and saving the 2 LSB. |
| 486 |
|
| 487 |
Returns: |
| 488 |
result (bytearray): short logged float compressed bytearray |
| 489 |
""" |
| 490 |
data = self.decoded_data |
| 491 |
self.fixed_point = self._slof_fixed_point() |
| 492 |
res = self._encode_fixed_point(self.fixed_point) |
| 493 |
for i in range(len(data)): |
| 494 |
x = math.floor((math.log(data[i] + 1)) * self.fixed_point + 0.5) |
| 495 |
res.append(0xFF & x) |
| 496 |
res.append(x >> 8) |
| 497 |
self.encoded_data = res |
| 498 |
return res |
| 499 |
|
| 500 |
def decode_slof(self): |
| 501 |
""" |
| 502 |
Decode short logged float compressed data. |
| 503 |
|
| 504 |
Returns: |
| 505 |
result (bytearray): array with decoded ion count data |
| 506 |
""" |
| 507 |
data = self.encoded_data |
| 508 |
if len(data) < 8: |
| 509 |
return -1 |
| 510 |
res = list() |
| 511 |
fixed_point = self._decode_fixed_point(data) |
| 512 |
|
| 513 |
for i in range(8, len(data), 2): |
| 514 |
x = 0xFF & data[i] | ((0xFF & data[i + 1]) << 8) |
| 515 |
res.append(math.exp((0xFFFF & x) / fixed_point) - 1) |
| 516 |
|
| 517 |
self.decoded_data = res |
| 518 |
return res |
| 519 |
|
| 520 |
def encode_safe(self): |
| 521 |
""" |
| 522 |
Transform values by linear prediction without scaling or truncated |
| 523 |
representation. |
| 524 |
|
| 525 |
Returns: |
| 526 |
result (bytearray): transformed data in bytes |
| 527 |
""" |
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
pass |
| 537 |
|
| 538 |
def decode_safe(self): |
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
|
| 547 |
|
| 548 |
|
| 549 |
pass |
| 550 |
|
| 551 |
def _encode_fixed_point(self, value): |
| 552 |
""" |
| 553 |
Save a given float as bytes. |
| 554 |
|
| 555 |
Args: |
| 556 |
value(float): fixed point |
| 557 |
Returns: |
| 558 |
res (bytearray): encoded fixed point |
| 559 |
""" |
| 560 |
res = bytearray(8) |
| 561 |
fp = value |
| 562 |
fp = struct.pack("<d", fp) |
| 563 |
fp = struct.unpack("<q", fp)[0] |
| 564 |
if self.is_little_endian: |
| 565 |
for i in range(8): |
| 566 |
res[7 - i] = (fp >> (8 * i)) & 0xFF |
| 567 |
else: |
| 568 |
for i in range(7, -1, -1): |
| 569 |
res[7 - i] = (fp >> (8 * i)) & 0xFF |
| 570 |
return res |
| 571 |
|
| 572 |
def _decode_fixed_point(self, value): |
| 573 |
""" |
| 574 |
Decode a given bytearray to float. |
| 575 |
|
| 576 |
Args: |
| 577 |
value(bytearray): encoded fixed point |
| 578 |
Returns: |
| 579 |
res (float): encoded fixed point |
| 580 |
""" |
| 581 |
fp = 0 |
| 582 |
if self.is_little_endian: |
| 583 |
for i in range(8): |
| 584 |
fp = fp | ((0x00FF & value[7 - i]) << (8 * i)) |
| 585 |
else: |
| 586 |
for i in range(7, -1, -1): |
| 587 |
fp = fp | ((0x00FF & value[7 - i]) << (8 * i)) |
| 588 |
fp = struct.pack("<q", fp) |
| 589 |
fp = struct.unpack("<d", fp)[0] |
| 590 |
return fp |
| 591 |
|
| 592 |
|
| 593 |
if __name__ == "__main__": |
| 594 |
print(__doc__) |