encoding.py 7.8 KB

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