keyset.pyx 9.1 KB

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