encoding.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. """encoding.py - methods for reading parquet encoded data blocks."""
  2. from __future__ import absolute_import
  3. from __future__ import division
  4. from __future__ import print_function
  5. from __future__ import unicode_literals
  6. import array
  7. import io
  8. import logging
  9. import math
  10. import os
  11. import struct
  12. import thriftpy
  13. THRIFT_FILE = os.path.join(os.path.dirname(__file__), "parquet.thrift")
  14. parquet_thrift = thriftpy.load(THRIFT_FILE, module_name=str("parquet_thrift")) # pylint: disable=invalid-name
  15. logger = logging.getLogger("parquet") # pylint: disable=invalid-name
  16. def read_plain_boolean(file_obj, count):
  17. """Read `count` booleans using the plain encoding."""
  18. # for bit packed, the count is stored shifted up. But we want to pass in a count,
  19. # so we shift up.
  20. # bit width is 1 for a single-bit boolean.
  21. return read_bitpacked(file_obj, count << 1, 1, logger.isEnabledFor(logging.DEBUG))
  22. def read_plain_int32(file_obj, count):
  23. """Read `count` 32-bit ints using the plain encoding."""
  24. length = 4 * count
  25. data = file_obj.read(length)
  26. if len(data) != length:
  27. raise EOFError("Expected {} bytes but got {0} bytes".format(length, len(data)))
  28. res = struct.unpack(b"<{0}i".format(count), data)
  29. return res
  30. def read_plain_int64(file_obj, count):
  31. """Read `count` 64-bit ints using the plain encoding."""
  32. return struct.unpack(b"<{0}q".format(count), file_obj.read(8 * count))
  33. def read_plain_int96(file_obj, count):
  34. """Read `count` 96-bit ints using the plain encoding."""
  35. items = struct.unpack(b"<qi" * count, file_obj.read(12) * count)
  36. args = [iter(items)] * 2
  37. return [q << 32 | i for (q, i) in zip(*args)]
  38. def read_plain_float(file_obj, count):
  39. """Read `count` 32-bit floats using the plain encoding."""
  40. return struct.unpack(b"<{0}f".format(count), file_obj.read(4 * count))
  41. def read_plain_double(file_obj, count):
  42. """Read `count` 64-bit float (double) using the plain encoding."""
  43. return struct.unpack(b"<{0}d".format(count), file_obj.read(8 * count))
  44. def read_plain_byte_array(file_obj, count):
  45. """Read `count` byte arrays using the plain encoding."""
  46. return [file_obj.read(struct.unpack(b"<i", file_obj.read(4))[0]) for i in range(count)]
  47. def read_plain_byte_array_fixed(file_obj, fixed_length):
  48. """Read a byte array of the given fixed_length."""
  49. return file_obj.read(fixed_length)
  50. DECODE_PLAIN = {
  51. parquet_thrift.Type.BOOLEAN: read_plain_boolean,
  52. parquet_thrift.Type.INT32: read_plain_int32,
  53. parquet_thrift.Type.INT64: read_plain_int64,
  54. parquet_thrift.Type.INT96: read_plain_int96,
  55. parquet_thrift.Type.FLOAT: read_plain_float,
  56. parquet_thrift.Type.DOUBLE: read_plain_double,
  57. parquet_thrift.Type.BYTE_ARRAY: read_plain_byte_array,
  58. parquet_thrift.Type.FIXED_LEN_BYTE_ARRAY: read_plain_byte_array_fixed
  59. }
  60. def read_plain(file_obj, type_, count):
  61. """Read `count` items `type` from the fo using the plain encoding."""
  62. if count == 0:
  63. return []
  64. conv = DECODE_PLAIN[type_]
  65. return conv(file_obj, count)
  66. def read_unsigned_var_int(file_obj):
  67. """Read a value using the unsigned, variable int encoding."""
  68. result = 0
  69. shift = 0
  70. while True:
  71. byte = struct.unpack(b"<B", file_obj.read(1))[0]
  72. result |= ((byte & 0x7F) << shift)
  73. if (byte & 0x80) == 0:
  74. break
  75. shift += 7
  76. return result
  77. def read_rle(file_obj, header, bit_width, debug_logging):
  78. """Read a run-length encoded run from the given fo with the given header
  79. and bit_width.
  80. The count is determined from the header and the width is used to grab the
  81. value that's repeated. Yields the value repeated count times.
  82. """
  83. count = header >> 1
  84. zero_data = b"\x00\x00\x00\x00"
  85. width = (bit_width + 7) // 8
  86. data = file_obj.read(width)
  87. data = data + zero_data[len(data):]
  88. value = struct.unpack(b"<i", data)[0]
  89. if debug_logging:
  90. logger.debug("Read RLE group with value %s of byte-width %s and count %s",
  91. value, width, count)
  92. for _ in range(count):
  93. yield value
  94. def width_from_max_int(value):
  95. """Convert the value specified to a bit_width."""
  96. return int(math.ceil(math.log(value + 1, 2)))
  97. def _mask_for_bits(i):
  98. """Generate a mask to grab `i` bits from an int value."""
  99. return (1 << i) - 1
  100. def read_bitpacked(file_obj, header, width, debug_logging):
  101. """Read a bitpacked run of the rle/bitpack hybrid.
  102. Supports width >8 (crossing bytes).
  103. """
  104. num_groups = header >> 1
  105. count = num_groups * 8
  106. byte_count = (width * count) // 8
  107. if debug_logging:
  108. logger.debug("Reading a bit-packed run with: %s groups, count %s, bytes %s",
  109. num_groups, count, byte_count)
  110. raw_bytes = array.array(str('B'), file_obj.read(byte_count)).tolist()
  111. current_byte = 0
  112. data = raw_bytes[current_byte]
  113. mask = _mask_for_bits(width)
  114. bits_wnd_l = 8
  115. bits_wnd_r = 0
  116. res = []
  117. total = len(raw_bytes) * 8
  118. while total >= width:
  119. # NOTE zero-padding could produce extra zero-values
  120. if debug_logging:
  121. logger.debug(" read bitpacked: width=%s window=(%s %s) b=%s,"
  122. " current_byte=%s",
  123. width, bits_wnd_l, bits_wnd_r, bin(data), current_byte)
  124. if bits_wnd_r >= 8:
  125. bits_wnd_r -= 8
  126. bits_wnd_l -= 8
  127. data >>= 8
  128. elif bits_wnd_l - bits_wnd_r >= width:
  129. res.append((data >> bits_wnd_r) & mask)
  130. total -= width
  131. bits_wnd_r += width
  132. if debug_logging:
  133. logger.debug(" read bitpackage: added: %s", res[-1])
  134. elif current_byte + 1 < len(raw_bytes):
  135. current_byte += 1
  136. data |= (raw_bytes[current_byte] << bits_wnd_l)
  137. bits_wnd_l += 8
  138. return res
  139. def read_bitpacked_deprecated(file_obj, byte_count, count, width, debug_logging):
  140. """Read `count` values from `fo` using the deprecated bitpacking encoding."""
  141. raw_bytes = array.array(str('B'), file_obj.read(byte_count)).tolist()
  142. mask = _mask_for_bits(width)
  143. index = 0
  144. res = []
  145. word = 0
  146. bits_in_word = 0
  147. while len(res) < count and index <= len(raw_bytes):
  148. if debug_logging:
  149. logger.debug("index = %d", index)
  150. logger.debug("bits in word = %d", bits_in_word)
  151. logger.debug("word = %s", bin(word))
  152. if bits_in_word >= width:
  153. # how many bits over the value is stored
  154. offset = (bits_in_word - width)
  155. # figure out the value
  156. value = (word & (mask << offset)) >> offset
  157. if debug_logging:
  158. logger.debug("offset = %d", offset)
  159. logger.debug("value = %d (%s)", value, bin(value))
  160. res.append(value)
  161. bits_in_word -= width
  162. else:
  163. word = (word << 8) | raw_bytes[index]
  164. index += 1
  165. bits_in_word += 8
  166. return res
  167. def read_rle_bit_packed_hybrid(file_obj, width, length=None):
  168. """Read values from `fo` using the rel/bit-packed hybrid encoding.
  169. If length is not specified, then a 32-bit int is read first to grab the
  170. length of the encoded data.
  171. """
  172. debug_logging = logger.isEnabledFor(logging.DEBUG)
  173. io_obj = file_obj
  174. if length is None:
  175. length = read_plain_int32(file_obj, 1)[0]
  176. raw_bytes = file_obj.read(length)
  177. if raw_bytes == b'':
  178. return None
  179. io_obj = io.BytesIO(raw_bytes)
  180. res = []
  181. while io_obj.tell() < length:
  182. header = read_unsigned_var_int(io_obj)
  183. if header & 1 == 0:
  184. res += read_rle(io_obj, header, width, debug_logging)
  185. else:
  186. res += read_bitpacked(io_obj, header, width, debug_logging)
  187. return res