idsets.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. """
  2. An implementation of an object that acts like a collection of on/off bits.
  3. """
  4. import operator
  5. from array import array
  6. from bisect import bisect_left, bisect_right, insort
  7. from whoosh.compat import integer_types, izip, izip_longest, next, xrange
  8. from whoosh.util.numeric import bytes_for_bits
  9. # Number of '1' bits in each byte (0-255)
  10. _1SPERBYTE = array('B', [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2,
  11. 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4,
  12. 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3,
  13. 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  14. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5,
  15. 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4,
  16. 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5,
  17. 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5,
  18. 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4,
  19. 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7,
  20. 6, 7, 7, 8])
  21. class DocIdSet(object):
  22. """Base class for a set of positive integers, implementing a subset of the
  23. built-in ``set`` type's interface with extra docid-related methods.
  24. This is a superclass for alternative set implementations to the built-in
  25. ``set`` which are more memory-efficient and specialized toward storing
  26. sorted lists of positive integers, though they will inevitably be slower
  27. than ``set`` for most operations since they're pure Python.
  28. """
  29. def __eq__(self, other):
  30. for a, b in izip(self, other):
  31. if a != b:
  32. return False
  33. return True
  34. def __neq__(self, other):
  35. return not self.__eq__(other)
  36. def __len__(self):
  37. raise NotImplementedError
  38. def __iter__(self):
  39. raise NotImplementedError
  40. def __contains__(self, i):
  41. raise NotImplementedError
  42. def __or__(self, other):
  43. return self.union(other)
  44. def __and__(self, other):
  45. return self.intersection(other)
  46. def __sub__(self, other):
  47. return self.difference(other)
  48. def copy(self):
  49. raise NotImplementedError
  50. def add(self, n):
  51. raise NotImplementedError
  52. def discard(self, n):
  53. raise NotImplementedError
  54. def update(self, other):
  55. add = self.add
  56. for i in other:
  57. add(i)
  58. def intersection_update(self, other):
  59. for n in self:
  60. if n not in other:
  61. self.discard(n)
  62. def difference_update(self, other):
  63. for n in other:
  64. self.discard(n)
  65. def invert_update(self, size):
  66. """Updates the set in-place to contain numbers in the range
  67. ``[0 - size)`` except numbers that are in this set.
  68. """
  69. for i in xrange(size):
  70. if i in self:
  71. self.discard(i)
  72. else:
  73. self.add(i)
  74. def intersection(self, other):
  75. c = self.copy()
  76. c.intersection_update(other)
  77. return c
  78. def union(self, other):
  79. c = self.copy()
  80. c.update(other)
  81. return c
  82. def difference(self, other):
  83. c = self.copy()
  84. c.difference_update(other)
  85. return c
  86. def invert(self, size):
  87. c = self.copy()
  88. c.invert_update(size)
  89. return c
  90. def isdisjoint(self, other):
  91. a = self
  92. b = other
  93. if len(other) < len(self):
  94. a, b = other, self
  95. for num in a:
  96. if num in b:
  97. return False
  98. return True
  99. def before(self, i):
  100. """Returns the previous integer in the set before ``i``, or None.
  101. """
  102. raise NotImplementedError
  103. def after(self, i):
  104. """Returns the next integer in the set after ``i``, or None.
  105. """
  106. raise NotImplementedError
  107. def first(self):
  108. """Returns the first (lowest) integer in the set.
  109. """
  110. raise NotImplementedError
  111. def last(self):
  112. """Returns the last (highest) integer in the set.
  113. """
  114. raise NotImplementedError
  115. class BaseBitSet(DocIdSet):
  116. # Methods to override
  117. def byte_count(self):
  118. raise NotImplementedError
  119. def _get_byte(self, i):
  120. raise NotImplementedError
  121. def _iter_bytes(self):
  122. raise NotImplementedError
  123. # Base implementations
  124. def __len__(self):
  125. return sum(_1SPERBYTE[b] for b in self._iter_bytes())
  126. def __iter__(self):
  127. base = 0
  128. for byte in self._iter_bytes():
  129. for i in xrange(8):
  130. if byte & (1 << i):
  131. yield base + i
  132. base += 8
  133. def __nonzero__(self):
  134. return any(n for n in self._iter_bytes())
  135. __bool__ = __nonzero__
  136. def __contains__(self, i):
  137. bucket = i // 8
  138. if bucket >= self.byte_count():
  139. return False
  140. return bool(self._get_byte(bucket) & (1 << (i & 7)))
  141. def first(self):
  142. return self.after(-1)
  143. def last(self):
  144. return self.before(self.byte_count() * 8 + 1)
  145. def before(self, i):
  146. _get_byte = self._get_byte
  147. size = self.byte_count() * 8
  148. if i <= 0:
  149. return None
  150. elif i >= size:
  151. i = size - 1
  152. else:
  153. i -= 1
  154. bucket = i // 8
  155. while i >= 0:
  156. byte = _get_byte(bucket)
  157. if not byte:
  158. bucket -= 1
  159. i = bucket * 8 + 7
  160. continue
  161. if byte & (1 << (i & 7)):
  162. return i
  163. if i % 8 == 0:
  164. bucket -= 1
  165. i -= 1
  166. return None
  167. def after(self, i):
  168. _get_byte = self._get_byte
  169. size = self.byte_count() * 8
  170. if i >= size:
  171. return None
  172. elif i < 0:
  173. i = 0
  174. else:
  175. i += 1
  176. bucket = i // 8
  177. while i < size:
  178. byte = _get_byte(bucket)
  179. if not byte:
  180. bucket += 1
  181. i = bucket * 8
  182. continue
  183. if byte & (1 << (i & 7)):
  184. return i
  185. i += 1
  186. if i % 8 == 0:
  187. bucket += 1
  188. return None
  189. class OnDiskBitSet(BaseBitSet):
  190. """A DocIdSet backed by an array of bits on disk.
  191. >>> st = RamStorage()
  192. >>> f = st.create_file("test.bin")
  193. >>> bs = BitSet([1, 10, 15, 7, 2])
  194. >>> bytecount = bs.to_disk(f)
  195. >>> f.close()
  196. >>> # ...
  197. >>> f = st.open_file("test.bin")
  198. >>> odbs = OnDiskBitSet(f, bytecount)
  199. >>> list(odbs)
  200. [1, 2, 7, 10, 15]
  201. """
  202. def __init__(self, dbfile, basepos, bytecount):
  203. """
  204. :param dbfile: a :class:`~whoosh.filedb.structfile.StructFile` object
  205. to read from.
  206. :param basepos: the base position of the bytes in the given file.
  207. :param bytecount: the number of bytes to use for the bit array.
  208. """
  209. self._dbfile = dbfile
  210. self._basepos = basepos
  211. self._bytecount = bytecount
  212. def __repr__(self):
  213. return "%s(%s, %d, %d)" % (self.__class__.__name__, self.dbfile,
  214. self._basepos, self.bytecount)
  215. def byte_count(self):
  216. return self._bytecount
  217. def _get_byte(self, n):
  218. return self._dbfile.get_byte(self._basepos + n)
  219. def _iter_bytes(self):
  220. dbfile = self._dbfile
  221. dbfile.seek(self._basepos)
  222. for _ in xrange(self._bytecount):
  223. yield dbfile.read_byte()
  224. class BitSet(BaseBitSet):
  225. """A DocIdSet backed by an array of bits. This can also be useful as a bit
  226. array (e.g. for a Bloom filter). It is much more memory efficient than a
  227. large built-in set of integers, but wastes memory for sparse sets.
  228. """
  229. def __init__(self, source=None, size=0):
  230. """
  231. :param maxsize: the maximum size of the bit array.
  232. :param source: an iterable of positive integers to add to this set.
  233. :param bits: an array of unsigned bytes ("B") to use as the underlying
  234. bit array. This is used by some of the object's methods.
  235. """
  236. # If the source is a list, tuple, or set, we can guess the size
  237. if not size and isinstance(source, (list, tuple, set, frozenset)):
  238. size = max(source)
  239. bytecount = bytes_for_bits(size)
  240. self.bits = array("B", (0 for _ in xrange(bytecount)))
  241. if source:
  242. add = self.add
  243. for num in source:
  244. add(num)
  245. def __repr__(self):
  246. return "%s(%r)" % (self.__class__.__name__, list(self))
  247. def byte_count(self):
  248. return len(self.bits)
  249. def _get_byte(self, n):
  250. return self.bits[n]
  251. def _iter_bytes(self):
  252. return iter(self.bits)
  253. def _trim(self):
  254. bits = self.bits
  255. last = len(self.bits) - 1
  256. while last >= 0 and not bits[last]:
  257. last -= 1
  258. del self.bits[last + 1:]
  259. def _resize(self, tosize):
  260. curlength = len(self.bits)
  261. newlength = bytes_for_bits(tosize)
  262. if newlength > curlength:
  263. self.bits.extend((0,) * (newlength - curlength))
  264. elif newlength < curlength:
  265. del self.bits[newlength + 1:]
  266. def _zero_extra_bits(self, size):
  267. bits = self.bits
  268. spill = size - ((len(bits) - 1) * 8)
  269. if spill:
  270. mask = 2 ** spill - 1
  271. bits[-1] = bits[-1] & mask
  272. def _logic(self, obj, op, other):
  273. objbits = obj.bits
  274. for i, (byte1, byte2) in enumerate(izip_longest(objbits, other.bits,
  275. fillvalue=0)):
  276. value = op(byte1, byte2) & 0xFF
  277. if i >= len(objbits):
  278. objbits.append(value)
  279. else:
  280. objbits[i] = value
  281. obj._trim()
  282. return obj
  283. def to_disk(self, dbfile):
  284. dbfile.write_array(self.bits)
  285. return len(self.bits)
  286. @classmethod
  287. def from_bytes(cls, bs):
  288. b = cls()
  289. b.bits = array("B", bs)
  290. return b
  291. @classmethod
  292. def from_disk(cls, dbfile, bytecount):
  293. return cls.from_bytes(dbfile.read_array("B", bytecount))
  294. def copy(self):
  295. b = self.__class__()
  296. b.bits = array("B", iter(self.bits))
  297. return b
  298. def clear(self):
  299. for i in xrange(len(self.bits)):
  300. self.bits[i] = 0
  301. def add(self, i):
  302. bucket = i >> 3
  303. if bucket >= len(self.bits):
  304. self._resize(i + 1)
  305. self.bits[bucket] |= 1 << (i & 7)
  306. def discard(self, i):
  307. bucket = i >> 3
  308. self.bits[bucket] &= ~(1 << (i & 7))
  309. def _resize_to_other(self, other):
  310. if isinstance(other, (list, tuple, set, frozenset)):
  311. maxbit = max(other)
  312. if maxbit // 8 > len(self.bits):
  313. self._resize(maxbit)
  314. def update(self, iterable):
  315. self._resize_to_other(iterable)
  316. DocIdSet.update(self, iterable)
  317. def intersection_update(self, other):
  318. if isinstance(other, BitSet):
  319. return self._logic(self, operator.__and__, other)
  320. discard = self.discard
  321. for n in self:
  322. if n not in other:
  323. discard(n)
  324. def difference_update(self, other):
  325. if isinstance(other, BitSet):
  326. return self._logic(self, lambda x, y: x & ~y, other)
  327. discard = self.discard
  328. for n in other:
  329. discard(n)
  330. def invert_update(self, size):
  331. bits = self.bits
  332. for i in xrange(len(bits)):
  333. bits[i] = ~bits[i] & 0xFF
  334. self._zero_extra_bits(size)
  335. def union(self, other):
  336. if isinstance(other, BitSet):
  337. return self._logic(self.copy(), operator.__or__, other)
  338. b = self.copy()
  339. b.update(other)
  340. return b
  341. def intersection(self, other):
  342. if isinstance(other, BitSet):
  343. return self._logic(self.copy(), operator.__and__, other)
  344. return BitSet(source=(n for n in self if n in other))
  345. def difference(self, other):
  346. if isinstance(other, BitSet):
  347. return self._logic(self.copy(), lambda x, y: x & ~y, other)
  348. return BitSet(source=(n for n in self if n not in other))
  349. class SortedIntSet(DocIdSet):
  350. """A DocIdSet backed by a sorted array of integers.
  351. """
  352. def __init__(self, source=None, typecode="I"):
  353. if source:
  354. self.data = array(typecode, sorted(source))
  355. else:
  356. self.data = array(typecode)
  357. self.typecode = typecode
  358. def copy(self):
  359. sis = SortedIntSet()
  360. sis.data = array(self.typecode, self.data)
  361. return sis
  362. def size(self):
  363. return len(self.data) * self.data.itemsize
  364. def __repr__(self):
  365. return "%s(%r)" % (self.__class__.__name__, self.data)
  366. def __len__(self):
  367. return len(self.data)
  368. def __iter__(self):
  369. return iter(self.data)
  370. def __nonzero__(self):
  371. return bool(self.data)
  372. __bool__ = __nonzero__
  373. def __contains__(self, i):
  374. data = self.data
  375. if not data or i < data[0] or i > data[-1]:
  376. return False
  377. pos = bisect_left(data, i)
  378. if pos == len(data):
  379. return False
  380. return data[pos] == i
  381. def add(self, i):
  382. data = self.data
  383. if not data or i > data[-1]:
  384. data.append(i)
  385. else:
  386. mn = data[0]
  387. mx = data[-1]
  388. if i == mn or i == mx:
  389. return
  390. elif i > mx:
  391. data.append(i)
  392. elif i < mn:
  393. data.insert(0, i)
  394. else:
  395. pos = bisect_left(data, i)
  396. if data[pos] != i:
  397. data.insert(pos, i)
  398. def discard(self, i):
  399. data = self.data
  400. pos = bisect_left(data, i)
  401. if data[pos] == i:
  402. data.pop(pos)
  403. def clear(self):
  404. self.data = array(self.typecode)
  405. def intersection_update(self, other):
  406. self.data = array(self.typecode, (num for num in self if num in other))
  407. def difference_update(self, other):
  408. self.data = array(self.typecode,
  409. (num for num in self if num not in other))
  410. def intersection(self, other):
  411. return SortedIntSet((num for num in self if num in other))
  412. def difference(self, other):
  413. return SortedIntSet((num for num in self if num not in other))
  414. def first(self):
  415. return self.data[0]
  416. def last(self):
  417. return self.data[-1]
  418. def before(self, i):
  419. data = self.data
  420. pos = bisect_left(data, i)
  421. if pos < 1:
  422. return None
  423. else:
  424. return data[pos - 1]
  425. def after(self, i):
  426. data = self.data
  427. if not data or i >= data[-1]:
  428. return None
  429. elif i < data[0]:
  430. return data[0]
  431. pos = bisect_right(data, i)
  432. return data[pos]
  433. class ReverseIdSet(DocIdSet):
  434. """
  435. Wraps a DocIdSet object and reverses its semantics, so docs in the wrapped
  436. set are not in this set, and vice-versa.
  437. """
  438. def __init__(self, idset, limit):
  439. """
  440. :param idset: the DocIdSet object to wrap.
  441. :param limit: the highest possible ID plus one.
  442. """
  443. self.idset = idset
  444. self.limit = limit
  445. def __len__(self):
  446. return self.limit - len(self.idset)
  447. def __contains__(self, i):
  448. return i not in self.idset
  449. def __iter__(self):
  450. ids = iter(self.idset)
  451. try:
  452. nx = next(ids)
  453. except StopIteration:
  454. nx = -1
  455. for i in xrange(self.limit):
  456. if i == nx:
  457. try:
  458. nx = next(ids)
  459. except StopIteration:
  460. nx = -1
  461. else:
  462. yield i
  463. def add(self, n):
  464. self.idset.discard(n)
  465. def discard(self, n):
  466. self.idset.add(n)
  467. def first(self):
  468. for i in self:
  469. return i
  470. def last(self):
  471. idset = self.idset
  472. maxid = self.limit - 1
  473. if idset.last() < maxid - 1:
  474. return maxid
  475. for i in xrange(maxid, -1, -1):
  476. if i not in idset:
  477. return i
  478. ROARING_CUTOFF = 1 << 12
  479. class RoaringIdSet(DocIdSet):
  480. """
  481. Separates IDs into ranges of 2^16 bits, and stores each range in the most
  482. efficient type of doc set, either a BitSet (if the range has >= 2^12 IDs)
  483. or a sorted ID set of 16-bit shorts.
  484. """
  485. cutoff = 2**12
  486. def __init__(self, source=None):
  487. self.idsets = []
  488. if source:
  489. self.update(source)
  490. def __len__(self):
  491. if not self.idsets:
  492. return 0
  493. return sum(len(idset) for idset in self.idsets)
  494. def __contains__(self, n):
  495. bucket = n >> 16
  496. if bucket >= len(self.idsets):
  497. return False
  498. return (n - (bucket << 16)) in self.idsets[bucket]
  499. def __iter__(self):
  500. for i, idset in self.idsets:
  501. floor = i << 16
  502. for n in idset:
  503. yield floor + n
  504. def _find(self, n):
  505. bucket = n >> 16
  506. floor = n << 16
  507. if bucket >= len(self.idsets):
  508. self.idsets.extend([SortedIntSet() for _
  509. in xrange(len(self.idsets), bucket + 1)])
  510. idset = self.idsets[bucket]
  511. return bucket, floor, idset
  512. def add(self, n):
  513. bucket, floor, idset = self._find(n)
  514. oldlen = len(idset)
  515. idset.add(n - floor)
  516. if oldlen <= ROARING_CUTOFF < len(idset):
  517. self.idsets[bucket] = BitSet(idset)
  518. def discard(self, n):
  519. bucket, floor, idset = self._find(n)
  520. oldlen = len(idset)
  521. idset.discard(n - floor)
  522. if oldlen > ROARING_CUTOFF >= len(idset):
  523. self.idsets[bucket] = SortedIntSet(idset)
  524. class MultiIdSet(DocIdSet):
  525. """Wraps multiple SERIAL sub-DocIdSet objects and presents them as an
  526. aggregated, read-only set.
  527. """
  528. def __init__(self, idsets, offsets):
  529. """
  530. :param idsets: a list of DocIdSet objects.
  531. :param offsets: a list of offsets corresponding to the DocIdSet objects
  532. in ``idsets``.
  533. """
  534. assert len(idsets) == len(offsets)
  535. self.idsets = idsets
  536. self.offsets = offsets
  537. def _document_set(self, n):
  538. offsets = self.offsets
  539. return max(bisect_left(offsets, n), len(self.offsets) - 1)
  540. def _set_and_docnum(self, n):
  541. setnum = self._document_set(n)
  542. offset = self.offsets[setnum]
  543. return self.idsets[setnum], n - offset
  544. def __len__(self):
  545. return sum(len(idset) for idset in self.idsets)
  546. def __iter__(self):
  547. for idset, offset in izip(self.idsets, self.offsets):
  548. for docnum in idset:
  549. yield docnum + offset
  550. def __contains__(self, item):
  551. idset, n = self._set_and_docnum(item)
  552. return n in idset