graph.pyx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. import logging
  2. import rdflib
  3. from lakesuperior import env
  4. from libc.string cimport memcpy
  5. from libc.stdlib cimport free
  6. cimport lakesuperior.cy_include.collections as cc
  7. cimport lakesuperior.model.callbacks as cb
  8. cimport lakesuperior.model.structures.keyset as kset
  9. from lakesuperior.model.base cimport Key, TripleKey
  10. from lakesuperior.model.rdf cimport term
  11. from lakesuperior.model.rdf.triple cimport BufferTriple
  12. from lakesuperior.model.structures.hash cimport term_hash_seed32
  13. from lakesuperior.model.structures.keyset cimport Keyset
  14. logger = logging.getLogger(__name__)
  15. cdef class Graph:
  16. """
  17. Fast and simple implementation of a graph.
  18. Most functions should mimic RDFLib's graph with less overhead. It uses
  19. the same funny but functional slicing notation.
  20. A Graph contains a :py:class:`lakesuperior.model.structures.keyset.Keyset`
  21. at its core and is bound to a
  22. :py:class:`~lakesuperior.store.ldp_rs.lmdb_triplestore.LmdbTriplestore`.
  23. This makes lookups and boolean operations very efficient because all these
  24. operations are performed on an array of integers.
  25. In order to retrieve RDF values from a ``Graph``, the underlying store
  26. must be looked up. This can be done in a different transaction than the
  27. one used to create or otherwise manipulate the graph.
  28. Every time a term is looked up or added to even a temporary graph, that
  29. term is added to the store and creates a key. This is because in the
  30. majority of cases that term is likely to be stored permanently anyway, and
  31. it's more efficient to hash it and allocate it immediately. A cleanup
  32. function to remove all orphaned terms (not in any triple or context index)
  33. can be later devised to compact the database.
  34. An instance of this class can also be converted to a ``rdflib.Graph``
  35. instance.
  36. """
  37. def __cinit__(
  38. self, store=None, size_t capacity=0, uri=None, set data=set()
  39. ):
  40. """
  41. Initialize the graph, optionally from Python/RDFlib data.
  42. When initializing a non-empty Graph, a store transaction must be
  43. opened::
  44. >>> from rdflib import URIRef
  45. >>> from lakesuperior import env_setup, env
  46. >>> store = env.app_globals.rdf_store
  47. >>> # Or alternatively:
  48. >>> # from lakesuperior.store.ldp_rs.lmdb_store import LmdbStore
  49. >>> # store = LmdbStore('/tmp/test')
  50. >>> trp = {(URIRef('urn:s:0'), URIRef('urn:p:0'), URIRef('urn:o:0'))}
  51. >>> with store.txn_ctx():
  52. >>> gr = Graph(store, data=trp)
  53. Similarly, any operation such as adding, changing or looking up triples
  54. needs a store transaction.
  55. Note that, even though any operation may involve adding new terms to
  56. the store, a read-only transaction is sufficient. Lakesuperior will
  57. open a write transaction automatically only if necessary and only for
  58. the time needed to enter the new terms.
  59. :type store: lakesuperior.store.ldp_rs.lmdb_triplestore.LmdbTriplestore
  60. :param store: Triplestore where keys are mapped to terms. By default
  61. this is the default application store
  62. (``env.app_globals.rdf_store``).
  63. :param size_t capacity: Initial number of allocated triples.
  64. :param str uri: If specified, the graph becomes a named graph and can
  65. utilize the :py:meth:`value()` method and special slicing notation.
  66. :param set data: If specified, ``capacity`` is ignored and an initial key
  67. set is created from a set of 3-tuples of :py:class:``rdflib.Term``
  68. instances.
  69. """
  70. self.uri = rdflib.URIRef(uri) if uri else None
  71. self.store = store if store is not None else env.app_globals.rdf_store
  72. logger.debug(f'Assigned store at {self.store.env_path}')
  73. # Initialize empty data set.
  74. if data:
  75. # Populate with provided Python set.
  76. self.keys = Keyset(len(data))
  77. self.add(data)
  78. else:
  79. self.keys = Keyset(capacity)
  80. ## PROPERTIES ##
  81. property data:
  82. def __get__(self):
  83. """
  84. Triple data as a Python/RDFlib set.
  85. :rtype: set
  86. """
  87. cdef TripleKey spok
  88. ret = set()
  89. self.keys.seek()
  90. while self.keys.get_next(&spok):
  91. ret.add((
  92. self.store.from_key(spok[0]),
  93. self.store.from_key(spok[1]),
  94. self.store.from_key(spok[2])
  95. ))
  96. return ret
  97. property capacity:
  98. def __get__(self):
  99. """
  100. Total capacity of the underlying Keyset, in number of triples.
  101. """
  102. return self.keys.capacity
  103. property txn_ctx:
  104. def __get__(self):
  105. """ Expose underlying store's ``txn_ctx``. """
  106. return self.store.txn_ctx
  107. ## MAGIC METHODS ##
  108. def __len__(self):
  109. """ Number of triples in the graph. """
  110. return self.keys.size()
  111. def __eq__(self, other):
  112. """ Equality operator between ``Graph`` instances. """
  113. # TODO Use __richcmp__()
  114. return len(self & other) == 0
  115. def __repr__(self):
  116. """
  117. String representation of the graph.
  118. This includes the subject URI, number of triples contained and the
  119. memory address of the instance.
  120. """
  121. id_repr = f' uri={self.uri},' if self.uri else ''
  122. return (
  123. f'<{self.__class__.__name__} @0x{id(self):02x}{id_repr} '
  124. f'length={len(self)}>'
  125. )
  126. def __str__(self):
  127. """ String dump of the graph triples. """
  128. return str(self.data)
  129. def __add__(self, other):
  130. """ Alias for set-theoretical union. """
  131. return self.__or__(other)
  132. def __iadd__(self, other):
  133. """ Alias for in-place set-theoretical union. """
  134. return self.__ior__(other)
  135. def __sub__(self, other):
  136. """ Set-theoretical subtraction. """
  137. cdef Graph gr3 = self.empty_copy()
  138. gr3.keys = kset.subtract(self.keys, other.keys)
  139. return gr3
  140. def __isub__(self, other):
  141. """ In-place set-theoretical subtraction. """
  142. self.keys = kset.subtract(self.keys, other.keys)
  143. return self
  144. def __and__(self, other):
  145. """ Set-theoretical intersection. """
  146. cdef Graph gr3 = self.empty_copy()
  147. gr3.keys = kset.intersect(self.keys, other.keys)
  148. return gr3
  149. def __iand__(self, other):
  150. """ In-place set-theoretical intersection. """
  151. self.keys = kset.intersect(self.keys, other.keys)
  152. return self
  153. def __or__(self, other):
  154. """ Set-theoretical union. """
  155. cdef Graph gr3 = self.empty_copy()
  156. gr3.keys = kset.merge(self.keys, other.keys)
  157. return gr3
  158. def __ior__(self, other):
  159. """ In-place set-theoretical union. """
  160. self.keys = kset.merge(self.keys, other.keys)
  161. return self
  162. def __xor__(self, other):
  163. """ Set-theoretical exclusive disjunction (XOR). """
  164. cdef Graph gr3 = self.empty_copy()
  165. gr3.keys = kset.xor(self.keys, other.keys)
  166. return gr3
  167. def __ixor__(self, other):
  168. """ In-place set-theoretical exclusive disjunction (XOR). """
  169. self.keys = kset.xor(self.keys, other.keys)
  170. return self
  171. def __contains__(self, trp):
  172. """
  173. Whether the graph contains a triple.
  174. :rtype: boolean
  175. """
  176. cdef TripleKey spok
  177. spok = [
  178. self.store.to_key(trp[0]),
  179. self.store.to_key(trp[1]),
  180. self.store.to_key(trp[2]),
  181. ]
  182. return self.keys.contains(&spok)
  183. def __iter__(self):
  184. """ Graph iterator. It iterates over the set triples. """
  185. yield from self.data
  186. # Slicing.
  187. def __getitem__(self, item):
  188. """
  189. Slicing function.
  190. It behaves similarly to `RDFLib graph slicing
  191. <https://rdflib.readthedocs.io/en/stable/utilities.html#slicing-graphs>`__
  192. """
  193. if isinstance(item, slice):
  194. s, p, o = item.start, item.stop, item.step
  195. return self._slice(s, p, o)
  196. elif self.uri and isinstance(item, rdflib.Node):
  197. # If a Node is given, return all values for that predicate.
  198. return self._slice(self.uri, item, None)
  199. else:
  200. raise TypeError(f'Wrong slice format: {item}.')
  201. def __hash__(self):
  202. """ TODO Bogus """
  203. return self.uri
  204. ## BASIC PYTHON-ACCESSIBLE SET OPERATIONS ##
  205. def value(self, p, strict=False):
  206. """
  207. Get an individual value.
  208. :param rdflib.termNode p: Predicate to search for.
  209. :param bool strict: If set to ``True`` the method raises an error if
  210. more than one value is found. If ``False`` (the default) only
  211. the first found result is returned.
  212. :rtype: rdflib.term.Node
  213. """
  214. if not self.uri:
  215. raise ValueError('Cannot use `value` on a non-named graph.')
  216. # TODO use slice.
  217. values = {trp[2] for trp in self.lookup((self.uri, p, None))}
  218. if strict and len(values) > 1:
  219. raise RuntimeError('More than one value found for {}, {}.'.format(
  220. self.uri, p))
  221. for ret in values:
  222. return ret
  223. return None
  224. def terms_by_type(self, type):
  225. """
  226. Get all terms of a type: subject, predicate or object.
  227. :param str type: One of ``s``, ``p`` or ``o``.
  228. """
  229. i = 'spo'.index(type)
  230. return {r[i] for r in self.data}
  231. def add(self, triples):
  232. """
  233. Add triples to the graph.
  234. This method checks for duplicates.
  235. :param iterable triples: iterable of 3-tuple triples.
  236. """
  237. cdef:
  238. TripleKey spok
  239. for s, p, o in triples:
  240. logger.info(f'Adding {s} {p} {o} to store: {self.store}')
  241. spok = [
  242. self.store.to_key(s),
  243. self.store.to_key(p),
  244. self.store.to_key(o),
  245. ]
  246. self.keys.add(&spok, True)
  247. def remove(self, pattern):
  248. """
  249. Remove triples by pattern.
  250. The pattern used is similar to :py:meth:`LmdbTripleStore.delete`.
  251. """
  252. # create an empty copy of the current object.
  253. new_gr = self.empty_copy()
  254. # Reverse lookup: only triples not matching the pattern are added to
  255. # the new set.
  256. self._match_ptn_callback(
  257. pattern, new_gr, add_trp_callback, False
  258. )
  259. # Replace the keyset.
  260. self.keys = new_gr.keys
  261. ## CYTHON-ACCESSIBLE BASIC METHODS ##
  262. cpdef Graph copy(self, str uri=None):
  263. """
  264. Create copy of the graph with a different (or no) URI.
  265. :param str uri: URI of the new graph. This should be different from
  266. the original.
  267. """
  268. cdef Graph new_gr = Graph(self.store, self.capacity, uri=uri)
  269. new_gr.keys = self.keys.copy()
  270. return new_gr
  271. cpdef Graph empty_copy(self, str uri=None):
  272. """
  273. Create an empty copy with same capacity and store binding.
  274. :param str uri: URI of the new graph. This should be different from
  275. the original.
  276. """
  277. return Graph(self.store, self.capacity, uri=uri)
  278. cpdef void set(self, tuple trp) except *:
  279. """
  280. Set a single value for subject and predicate.
  281. Remove all triples matching ``s`` and ``p`` before adding ``s p o``.
  282. """
  283. if None in trp:
  284. raise ValueError(f'Invalid triple: {trp}')
  285. self.remove((trp[0], trp[1], None))
  286. self.add((trp,))
  287. def as_rdflib(self):
  288. """
  289. Return the data set as an RDFLib Graph.
  290. :rtype: rdflib.Graph
  291. """
  292. gr = Graph(identifier=self.uri)
  293. for trp in self.data:
  294. gr.add(trp)
  295. return gr
  296. def _slice(self, s, p, o):
  297. """
  298. Return terms filtered by other terms.
  299. This behaves like the rdflib.Graph slicing policy.
  300. """
  301. logger.info(f'Slicing: {s} {p} {o}')
  302. # If no terms are unbound, check for containment.
  303. if s is not None and p is not None and o is not None: # s p o
  304. return (s, p, o) in self
  305. # If some terms are unbound, do a lookup.
  306. res = self.lookup((s, p, o))
  307. logger.info(f'Slicing results: {res}')
  308. if s is not None:
  309. if p is not None: # s p ?
  310. return {r[2] for r in res}
  311. if o is not None: # s ? o
  312. return {r[1] for r in res}
  313. # s ? ?
  314. return {(r[1], r[2]) for r in res}
  315. if p is not None:
  316. if o is not None: # ? p o
  317. return {r[0] for r in res}
  318. # ? p ?
  319. return {(r[0], r[2]) for r in res}
  320. if o is not None: # ? ? o
  321. return {(r[0], r[1]) for r in res}
  322. # ? ? ?
  323. return res
  324. def lookup(self, pattern):
  325. """
  326. Look up triples by a pattern.
  327. This function converts RDFLib terms into the serialized format stored
  328. in the graph's internal structure and compares them bytewise.
  329. Any and all of the lookup terms msy be ``None``.
  330. :rtype: Graph
  331. "return: New Graph instance with matching triples.
  332. """
  333. cdef:
  334. Graph res_gr = self.empty_copy()
  335. self._match_ptn_callback(pattern, res_gr, add_trp_callback)
  336. res_gr.keys.resize()
  337. return res_gr
  338. cdef void _match_ptn_callback(
  339. self, pattern, Graph gr, lookup_callback_fn_t callback_fn,
  340. bint callback_cond=True, void* ctx=NULL
  341. ) except *:
  342. """
  343. Execute an arbitrary function on a list of triples matching a pattern.
  344. The arbitrary function is applied to each triple found in the current
  345. graph, and to a discrete graph that can be the current graph itself
  346. or a different one.
  347. :param tuple pattern: A 3-tuple of rdflib terms or None.
  348. :param Graph gr: The graph instance to apply the callback function to.
  349. :param lookup_callback_fn_t callback_fn: A callback function to be
  350. applied to the target graph using the matching triples.
  351. :param bint callback_cond: Whether to apply the callback function if
  352. a match is found (``True``) or if it is not found (``False``).
  353. :param void* ctx: Pointer to an arbitrary object that can be used by
  354. the callback function.
  355. """
  356. cdef:
  357. kset.key_cmp_fn_t cmp_fn
  358. Key k1, k2, k3
  359. TripleKey spok
  360. s, p, o = pattern
  361. logger.info(f'Match Callback pattern: {pattern}')
  362. self.keys.seek()
  363. # Decide comparison logic outside the loop.
  364. if all(pattern):
  365. if callback_cond:
  366. # Shortcut for 3-term match—only if callback_cond is True.
  367. spok = [
  368. self.store.to_key(s),
  369. self.store.to_key(p),
  370. self.store.to_key(o),
  371. ]
  372. if self.keys.contains(&spok):
  373. callback_fn(gr, &spok, ctx)
  374. else:
  375. # For negative condition (i.e. "apply this function to all keys
  376. # except the matching one"), the whole set must be scanned.
  377. #logger.info('All terms bound and negative condition.')
  378. k1 = self.store.to_key(s)
  379. k2 = self.store.to_key(p)
  380. k3 = self.store.to_key(o)
  381. #logger.info(f'Keys to match: {k1} {k2} {k3}')
  382. while self.keys.get_next(&spok):
  383. #logger.info(f'Verifying spok: {spok}')
  384. if k1 != spok[0] or k2 != spok[1] or k3 != spok[2]:
  385. logger.info(f'Calling function for spok: {spok}')
  386. callback_fn(gr, &spok, ctx)
  387. return
  388. if s is not None:
  389. k1 = self.store.to_key(s)
  390. if p is not None:
  391. k2 = self.store.to_key(p)
  392. cmp_fn = cb.lookup_skpk_cmp_fn
  393. logger.info('SKPK')
  394. elif o is not None:
  395. k2 = self.store.to_key(o)
  396. cmp_fn = cb.lookup_skok_cmp_fn
  397. logger.info('SKOK')
  398. else:
  399. cmp_fn = cb.lookup_sk_cmp_fn
  400. elif p is not None:
  401. k1 = self.store.to_key(p)
  402. if o is not None:
  403. k2 = self.store.to_key(o)
  404. cmp_fn = cb.lookup_pkok_cmp_fn
  405. else:
  406. cmp_fn = cb.lookup_pk_cmp_fn
  407. elif o is not None:
  408. k1 = self.store.to_key(o)
  409. cmp_fn = cb.lookup_ok_cmp_fn
  410. else:
  411. cmp_fn = cb.lookup_none_cmp_fn
  412. logger.info(f'k1: {k1} k2: {k2}')
  413. # Iterate over serialized triples.
  414. while self.keys.get_next(&spok):
  415. logger.info(f'Verifying spok: {spok}')
  416. if cmp_fn(&spok, k1, k2) == callback_cond:
  417. callback_fn(gr, &spok, ctx)
  418. ## LOOKUP CALLBACK FUNCTIONS
  419. cdef inline void add_trp_callback(
  420. Graph gr, const TripleKey* spok_p, void* ctx
  421. ):
  422. """
  423. Add a triple to a graph as a result of a lookup callback.
  424. """
  425. gr.keys.add(spok_p)