graph.pyx 18 KB

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