keyset.pyx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import logging
  2. from libc.string cimport memcmp, memcpy
  3. from cpython.mem cimport PyMem_Malloc, PyMem_Realloc, PyMem_Free
  4. cimport lakesuperior.model.callbacks as cb
  5. from lakesuperior.model.base cimport NULL_TRP, TRP_KLEN, TripleKey
  6. logger = logging.getLogger(__name__)
  7. cdef class Keyset:
  8. """
  9. Pre-allocated set of ``TripleKey``s.
  10. The set is not checked for duplicates all the time: e.g., when creating
  11. from a single set of triples coming from the store, the duplicate check
  12. is turned off for efficiency. When merging with other sets, duplicate
  13. checking should be turned on.
  14. Since this class is based on a contiguous block of memory, it is best to
  15. do very little manipulation. Several operations involve copying the whole
  16. data block, so e.g. bulk removal and intersection are much more efficient
  17. than individual record operations.
  18. """
  19. def __cinit__(self, size_t capacity=0, expand_ratio=.5):
  20. """
  21. Initialize and allocate memory for the data set.
  22. :param size_t capacity: Number of elements to be accounted for.
  23. """
  24. self.capacity = capacity
  25. self.expand_ratio = expand_ratio
  26. self.data = <TripleKey*>PyMem_Malloc(self.capacity * TRP_KLEN)
  27. if capacity and not self.data:
  28. raise MemoryError('Error allocating Keyset data.')
  29. self._cur = 0
  30. self._free_i = 0
  31. def __dealloc__(self):
  32. """
  33. Free the memory.
  34. This is called when the Python instance is garbage collected, which
  35. makes it handy to safely pass a Keyset instance across functions.
  36. """
  37. PyMem_Free(self.data)
  38. # Access methods.
  39. cdef void seek(self, size_t idx=0):
  40. """
  41. Place the cursor at a certain index, 0 by default.
  42. """
  43. self._cur = idx
  44. cdef size_t size(self):
  45. """
  46. Size of the object as the number of occupied data slots.
  47. Note that this is different from :py:data:`capacity`_, which indicates
  48. the number of allocated items in memory.
  49. """
  50. return self._free_i
  51. cdef size_t tell(self):
  52. """
  53. Tell the position of the cursor in the keyset.
  54. """
  55. return self._cur
  56. cdef bint get_next(self, TripleKey* val):
  57. """
  58. Populate the current value and advance the cursor by 1.
  59. :param void *val: Addres of value returned. It is NULL if
  60. the end of the buffer was reached.
  61. :rtype: bint
  62. :return: True if a value was found, False if the end of the buffer
  63. has been reached.
  64. """
  65. if self._cur >= self._free_i:
  66. return False
  67. val[0] = self.data[self._cur]
  68. self._cur += 1
  69. return True
  70. cdef void add(self, const TripleKey* val, bint check_dup=False) except *:
  71. """
  72. Add a triple key to the array.
  73. """
  74. # Check for deleted triples and optionally duplicates.
  75. if val[0] == NULL_TRP or (check_dup and self.contains(val)):
  76. return
  77. if self._free_i >= self.capacity:
  78. if self.expand_ratio > 0:
  79. # In some edge casees, a very small ratio may round down to a
  80. # zero increase, so the baseline increase is 1 element.
  81. self.resize(1 + <size_t>(self.capacity * (1 + self.expand_ratio)))
  82. else:
  83. raise MemoryError('No space left in key set.')
  84. self.data[self._free_i] = val[0]
  85. self._free_i += 1
  86. cdef void remove(self, const TripleKey* val) except *:
  87. """
  88. Remove a triple key.
  89. This method replaces a triple with NULL_TRP if found. It
  90. does not reclaim space. Therefore, if many removal operations are
  91. forseen, using :py:meth:`subtract`_ is advised.
  92. """
  93. cdef:
  94. TripleKey stored_val
  95. self.seek()
  96. while self.get_next(&stored_val):
  97. logger.info(f'Looking up for removal: {stored_val}')
  98. if memcmp(val, stored_val, TRP_KLEN) == 0:
  99. memcpy(&stored_val, NULL_TRP, TRP_KLEN)
  100. return
  101. cdef bint contains(self, const TripleKey* val):
  102. """
  103. Whether a value exists in the set.
  104. """
  105. cdef TripleKey stored_val
  106. self.seek()
  107. while self.get_next(&stored_val):
  108. if memcmp(val, stored_val, TRP_KLEN) == 0:
  109. return True
  110. return False
  111. cdef Keyset copy(self):
  112. """
  113. Copy a Keyset.
  114. """
  115. cdef Keyset new_ks = Keyset(self.capacity, expand_ratio=self.expand_ratio)
  116. memcpy(new_ks.data, self.data, self.capacity * TRP_KLEN)
  117. new_ks.seek()
  118. return new_ks
  119. cdef Keyset sparse_copy(self):
  120. """
  121. Copy a Keyset and plug holes.
  122. ``NULL_TRP`` values left from removing triple keys are skipped in the
  123. copy and the set is shrunk to its used size.
  124. """
  125. cdef:
  126. TripleKey val
  127. Keyset new_ks = Keyset(self.capacity, self.expand_ratio)
  128. self.seek()
  129. while self.get_next(&val):
  130. if val != NULL_TRP:
  131. new_ks.add(&val)
  132. new_ks.resize()
  133. return new_ks
  134. cdef void resize(self, size_t size=0) except *:
  135. """
  136. Change the array capacity.
  137. :param size_t size: The new capacity size. If not specified or 0, the
  138. array is shrunk to the last used item. The resulting size
  139. therefore will always be greater than 0. The only exception
  140. to this is if the specified size is 0 and no items have been added
  141. to the array, in which case the array will be effectively shrunk
  142. to 0.
  143. """
  144. if not size:
  145. size = self._free_i
  146. tmp = <TripleKey*>PyMem_Realloc(self.data, size * TRP_KLEN)
  147. if not tmp:
  148. raise MemoryError('Could not reallocate Keyset data.')
  149. self.data = tmp
  150. self.capacity = size
  151. self.seek()
  152. cdef Keyset lookup(self, const Key sk, const Key pk, const Key ok):
  153. """
  154. Look up triple keys.
  155. This works in a similar way that the ``Graph`` and ``LmdbStore``
  156. methods work.
  157. Any and all the terms may be NULL. A NULL term is treated as unbound.
  158. :param const Key* sk: s key pointer.
  159. :param const Key* pk: p key pointer.
  160. :param const Key* ok: o key pointer.
  161. """
  162. cdef:
  163. TripleKey spok
  164. Keyset ret = Keyset(self.capacity)
  165. Key k1, k2
  166. key_cmp_fn_t cmp_fn
  167. if sk and pk and ok: # s p o
  168. pass # TODO
  169. elif sk:
  170. k1 = sk
  171. if pk: # s p ?
  172. k2 = pk
  173. cmp_fn = cb.lookup_skpk_cmp_fn
  174. elif ok: # s ? o
  175. k2 = ok
  176. cmp_fn = cb.lookup_skok_cmp_fn
  177. else: # s ? ?
  178. cmp_fn = cb.lookup_sk_cmp_fn
  179. elif pk:
  180. k1 = pk
  181. if ok: # ? p o
  182. k2 = ok
  183. cmp_fn = cb.lookup_pkok_cmp_fn
  184. else: # ? p ?
  185. cmp_fn = cb.lookup_pk_cmp_fn
  186. elif ok: # ? ? o
  187. k1 = ok
  188. cmp_fn = cb.lookup_ok_cmp_fn
  189. else: # ? ? ?
  190. return self.copy()
  191. self.seek()
  192. while self.get_next(&spok):
  193. if cmp_fn(&spok, k1, k2):
  194. ret.add(&spok)
  195. ret.resize()
  196. return ret
  197. ## Boolean operations.
  198. cdef Keyset merge(Keyset ks1, Keyset ks2):
  199. """
  200. Create a Keyset by merging an``ks2`` Keyset with the current one.
  201. :rtype: Keyset
  202. """
  203. cdef:
  204. TripleKey val
  205. Keyset ks3 = ks1.copy()
  206. ks2.seek()
  207. while ks2.get_next(&val):
  208. ks3.add(&val, True)
  209. ks3.resize()
  210. return ks3
  211. cdef Keyset subtract(Keyset ks1, Keyset ks2):
  212. """
  213. Create a Keyset by subtracting an``ks2`` Keyset from the current one.
  214. :rtype: Keyset
  215. """
  216. cdef:
  217. TripleKey val
  218. Keyset ks3 = Keyset(ks1.capacity)
  219. ks1.seek()
  220. while ks1.get_next(&val):
  221. if val != NULL_TRP and not ks2.contains(&val):
  222. ks3.add(&val)
  223. ks3.resize()
  224. return ks3
  225. cdef Keyset intersect(Keyset ks1, Keyset ks2):
  226. """
  227. Create a Keyset by intersection with an``ks2`` Keyset.
  228. :rtype: Keyset
  229. """
  230. cdef:
  231. TripleKey val
  232. Keyset ks3 = Keyset(ks1.capacity)
  233. ks1.seek()
  234. while ks1.get_next(&val):
  235. if val != NULL_TRP and ks2.contains(&val):
  236. ks3.add(&val)
  237. ks3.resize()
  238. return ks3
  239. cdef Keyset xor(Keyset ks1, Keyset ks2):
  240. """
  241. Create a Keyset by disjunction (XOR) with an``ks2`` Keyset.
  242. :rtype: Keyset
  243. """
  244. cdef:
  245. TripleKey val
  246. Keyset ks3 = Keyset(ks1.capacity + ks2.capacity)
  247. ks1.seek()
  248. while ks1.get_next(&val):
  249. if val != NULL_TRP and not ks2.contains(&val):
  250. ks3.add(&val)
  251. ks2.seek()
  252. while ks2.get_next(&val):
  253. if val != NULL_TRP and not ks1.contains(&val):
  254. ks3.add(&val)
  255. ks3.resize()
  256. return ks3