keyset.pyx 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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(
  116. self.capacity, expand_ratio=self.expand_ratio
  117. )
  118. memcpy(new_ks.data, self.data, self.capacity * TRP_KLEN)
  119. new_ks.seek()
  120. new_ks._free_i = self._free_i
  121. return new_ks
  122. cdef Keyset sparse_copy(self):
  123. """
  124. Copy a Keyset and plug holes.
  125. ``NULL_TRP`` values left from removing triple keys are skipped in the
  126. copy and the set is shrunk to its used size.
  127. """
  128. cdef:
  129. TripleKey val
  130. Keyset new_ks = Keyset(self.capacity, self.expand_ratio)
  131. self.seek()
  132. while self.get_next(&val):
  133. if val != NULL_TRP:
  134. new_ks.add(&val)
  135. new_ks.resize()
  136. return new_ks
  137. cdef void resize(self, size_t size=0) except *:
  138. """
  139. Change the array capacity.
  140. :param size_t size: The new capacity size. If not specified or 0, the
  141. array is shrunk to the last used item. The resulting size
  142. therefore will always be greater than 0. The only exception
  143. to this is if the specified size is 0 and no items have been added
  144. to the array, in which case the array will be effectively shrunk
  145. to 0.
  146. """
  147. if not size:
  148. size = self._free_i
  149. tmp = <TripleKey*>PyMem_Realloc(self.data, size * TRP_KLEN)
  150. if not tmp:
  151. raise MemoryError('Could not reallocate Keyset data.')
  152. self.data = tmp
  153. self.capacity = size
  154. self.seek()
  155. cdef Keyset lookup(self, const Key sk, const Key pk, const Key ok):
  156. """
  157. Look up triple keys.
  158. This works in a similar way that the ``Graph`` and ``LmdbStore``
  159. methods work.
  160. Any and all the terms may be NULL. A NULL term is treated as unbound.
  161. :param const Key* sk: s key pointer.
  162. :param const Key* pk: p key pointer.
  163. :param const Key* ok: o key pointer.
  164. """
  165. cdef:
  166. TripleKey spok
  167. Keyset ret = Keyset(self.capacity)
  168. Key k1, k2
  169. key_cmp_fn_t cmp_fn
  170. if sk and pk and ok: # s p o
  171. pass # TODO
  172. elif sk:
  173. k1 = sk
  174. if pk: # s p ?
  175. k2 = pk
  176. cmp_fn = cb.lookup_skpk_cmp_fn
  177. elif ok: # s ? o
  178. k2 = ok
  179. cmp_fn = cb.lookup_skok_cmp_fn
  180. else: # s ? ?
  181. cmp_fn = cb.lookup_sk_cmp_fn
  182. elif pk:
  183. k1 = pk
  184. if ok: # ? p o
  185. k2 = ok
  186. cmp_fn = cb.lookup_pkok_cmp_fn
  187. else: # ? p ?
  188. cmp_fn = cb.lookup_pk_cmp_fn
  189. elif ok: # ? ? o
  190. k1 = ok
  191. cmp_fn = cb.lookup_ok_cmp_fn
  192. else: # ? ? ?
  193. return self.copy()
  194. self.seek()
  195. while self.get_next(&spok):
  196. if cmp_fn(&spok, k1, k2):
  197. ret.add(&spok)
  198. ret.resize()
  199. return ret
  200. ## Boolean operations.
  201. cdef Keyset merge(Keyset ks1, Keyset ks2):
  202. """
  203. Create a Keyset by merging an``ks2`` Keyset with the current one.
  204. :rtype: Keyset
  205. """
  206. cdef:
  207. TripleKey val
  208. Keyset ks3 = ks1.copy()
  209. ks2.seek()
  210. while ks2.get_next(&val):
  211. ks3.add(&val, True)
  212. ks3.resize()
  213. return ks3
  214. cdef Keyset subtract(Keyset ks1, Keyset ks2):
  215. """
  216. Create a Keyset by subtracting an``ks2`` Keyset from the current one.
  217. :rtype: Keyset
  218. """
  219. cdef:
  220. TripleKey val
  221. Keyset ks3 = Keyset(ks1.capacity)
  222. ks1.seek()
  223. while ks1.get_next(&val):
  224. if val != NULL_TRP and not ks2.contains(&val):
  225. ks3.add(&val)
  226. ks3.resize()
  227. return ks3
  228. cdef Keyset intersect(Keyset ks1, Keyset ks2):
  229. """
  230. Create a Keyset by intersection with an``ks2`` Keyset.
  231. :rtype: Keyset
  232. """
  233. cdef:
  234. TripleKey val
  235. Keyset ks3 = Keyset(ks1.capacity)
  236. ks1.seek()
  237. while ks1.get_next(&val):
  238. if val != NULL_TRP and ks2.contains(&val):
  239. ks3.add(&val)
  240. ks3.resize()
  241. return ks3
  242. cdef Keyset xor(Keyset ks1, Keyset ks2):
  243. """
  244. Create a Keyset by disjunction (XOR) with an``ks2`` Keyset.
  245. :rtype: Keyset
  246. """
  247. cdef:
  248. TripleKey val
  249. Keyset ks3 = Keyset(ks1.capacity + ks2.capacity)
  250. ks1.seek()
  251. while ks1.get_next(&val):
  252. if val != NULL_TRP and not ks2.contains(&val):
  253. ks3.add(&val)
  254. ks2.seek()
  255. while ks2.get_next(&val):
  256. if val != NULL_TRP and not ks1.contains(&val):
  257. ks3.add(&val)
  258. ks3.resize()
  259. return ks3