graph.pyx 19 KB

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