encoding.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. import array
  2. import math
  3. import struct
  4. import cStringIO
  5. import logging
  6. from ttypes import Type
  7. logger = logging.getLogger("parquet")
  8. def read_plain_boolean(fo):
  9. """Reads a boolean using the plain encoding"""
  10. raise NotImplemented
  11. def read_plain_int32(fo):
  12. """Reads a 32-bit int using the plain encoding"""
  13. tup = struct.unpack("<i", fo.read(4))
  14. return tup[0]
  15. def read_plain_int64(fo):
  16. """Reads a 64-bit int using the plain encoding"""
  17. tup = struct.unpack("<q", fo.read(8))
  18. return tup[0]
  19. def read_plain_int96(fo):
  20. """Reads a 96-bit int using the plain encoding"""
  21. tup = struct.unpack("<qi", fo.read(12))
  22. return tup[0] << 32 | tup[1]
  23. def read_plain_float(fo):
  24. """Reads a 32-bit float using the plain encoding"""
  25. tup = struct.unpack("<f", fo.read(4))
  26. return tup[0]
  27. def read_plain_double(fo):
  28. """Reads a 64-bit float (double) using the plain encoding"""
  29. tup = struct.unpack("<d", fo.read(8))
  30. return tup[0]
  31. def read_plain_byte_array(fo):
  32. """Reads a byte array using the plain encoding"""
  33. length = read_plain_int32(fo)
  34. return fo.read(length)
  35. def read_plain_byte_array_fixed(fo, fixed_length):
  36. """Reads a byte array of the given fixed_length"""
  37. return fo.read(fixed_length)
  38. DECODE_PLAIN = {
  39. Type.BOOLEAN: read_plain_boolean,
  40. Type.INT32: read_plain_int32,
  41. Type.INT64: read_plain_int64,
  42. Type.INT96: read_plain_int96,
  43. Type.FLOAT: read_plain_float,
  44. Type.DOUBLE: read_plain_double,
  45. Type.BYTE_ARRAY: read_plain_byte_array,
  46. Type.FIXED_LEN_BYTE_ARRAY: read_plain_byte_array_fixed
  47. }
  48. def read_plain(fo, type_, type_length):
  49. conv = DECODE_PLAIN[type_]
  50. if type_ == Type.FIXED_LEN_BYTE_ARRAY:
  51. return conv(fo, type_length)
  52. return conv(fo)
  53. def read_unsigned_var_int(fo):
  54. result = 0
  55. shift = 0
  56. while True:
  57. byte = struct.unpack("<B", fo.read(1))[0]
  58. result |= ((byte & 0x7F) << shift)
  59. if (byte & 0x80) == 0:
  60. break
  61. shift += 7
  62. return result
  63. def byte_width(bit_width):
  64. "Returns the byte width for the given bit_width"
  65. return (bit_width + 7) / 8
  66. def read_rle(fo, header, bit_width):
  67. """Read a run-length encoded run from the given fo with the given header
  68. and bit_width.
  69. The count is determined from the header and the width is used to grab the
  70. value that's repeated. Yields the value repeated count times.
  71. """
  72. count = header >> 1
  73. zero_data = "\x00\x00\x00\x00"
  74. data = ""
  75. width = byte_width(bit_width)
  76. if width >= 1:
  77. data += fo.read(1)
  78. if width >= 2:
  79. data += fo.read(1)
  80. if width >= 3:
  81. data += fo.read(1)
  82. if width == 4:
  83. data += fo.read(1)
  84. data = data + zero_data[len(data):]
  85. value = struct.unpack("<i", data)[0]
  86. logger.debug("Read RLE group with value %s of byte-width %s and count %s",
  87. value, width, count)
  88. for i in range(count):
  89. yield value
  90. def width_from_max_int(value):
  91. """Converts the value specified to a bit_width."""
  92. return int(math.ceil(math.log(value + 1, 2)))
  93. def _mask_for_bits(i):
  94. """Helper function for read_bitpacked to generage a mask to grab i bits."""
  95. return (1 << i) - 1
  96. def read_bitpacked(fo, header, width):
  97. """Reads a bitpacked run of the rle/bitpack hybrid.
  98. Supports width >8 (crossing bytes).
  99. """
  100. num_groups = header >> 1
  101. count = num_groups * 8
  102. byte_count = (width * count)/8
  103. logger.debug("Reading a bit-packed run with: %s groups, count %s, bytes %s",
  104. num_groups, count, byte_count)
  105. raw_bytes = array.array('B', fo.read(byte_count)).tolist()
  106. current_byte = 0
  107. b = raw_bytes[current_byte]
  108. mask = _mask_for_bits(width)
  109. bits_wnd_l = 8
  110. bits_wnd_r = 0
  111. res = []
  112. total = len(raw_bytes)*8;
  113. while (total >= width):
  114. # TODO zero-padding could produce extra zero-values
  115. logger.debug(" read bitpacked: width=%s window=(%s %s) b=%s,"
  116. " current_byte=%s",
  117. width, bits_wnd_l, bits_wnd_r, bin(b), current_byte)
  118. if bits_wnd_r >= 8:
  119. bits_wnd_r -= 8
  120. bits_wnd_l -= 8
  121. b >>= 8
  122. elif bits_wnd_l - bits_wnd_r >= width:
  123. res.append((b >> bits_wnd_r) & mask)
  124. total -= width
  125. bits_wnd_r += width
  126. logger.debug(" read bitpackage: added: %s", res[-1])
  127. elif current_byte + 1 < len(raw_bytes):
  128. current_byte += 1
  129. b |= (raw_bytes[current_byte] << bits_wnd_l)
  130. bits_wnd_l += 8
  131. return res
  132. def read_bitpacked_deprecated(fo, byte_count, count, width):
  133. raw_bytes = array.array('B', fo.read(byte_count)).tolist()
  134. mask = _mask_for_bits(width)
  135. index = 0
  136. res = []
  137. word = 0
  138. bits_in_word = 0
  139. while len(res) < count and index <= len(raw_bytes):
  140. logger.debug("index = %d", index)
  141. logger.debug("bits in word = %d", bits_in_word)
  142. logger.debug("word = %s", bin(word))
  143. if bits_in_word >= width:
  144. # how many bits over the value is stored
  145. offset = (bits_in_word - width)
  146. logger.debug("offset = %d", offset)
  147. # figure out the value
  148. value = (word & (mask << offset)) >> offset
  149. logger.debug("value = %d (%s)", value, bin(value))
  150. res.append(value)
  151. bits_in_word -= width
  152. else:
  153. word = (word << 8) | raw_bytes[index]
  154. index += 1
  155. bits_in_word += 8
  156. return res
  157. def read_rle_bit_packed_hybrid(fo, width, length=None):
  158. """Implemenation of a decoder for the rel/bit-packed hybrid encoding.
  159. If length is not specified, then a 32-bit int is read first to grab the
  160. length of the encoded data.
  161. """
  162. io_obj = fo
  163. if length is None:
  164. length = read_plain_int32(fo)
  165. raw_bytes = fo.read(length)
  166. if raw_bytes == '':
  167. return None
  168. io_obj = cStringIO.StringIO(raw_bytes)
  169. res = []
  170. while io_obj.tell() < length:
  171. header = read_unsigned_var_int(io_obj)
  172. if header & 1 == 0:
  173. res += read_rle(io_obj, header, width)
  174. else:
  175. res += read_bitpacked(io_obj, header, width)
  176. return res