graph.pyx 19 KB

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