graph.pyx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. import logging
  2. from functools import wraps
  3. from rdflib import Graph
  4. from rdflib.term import Node
  5. from lakesuperior import env
  6. from libc.string cimport memcmp
  7. from lakesuperior.cy_include cimport calg
  8. from lakesuperior.store.ldp_rs.lmdb_triplestore cimport (
  9. TRP_KLEN, TripleKey, LmdbTriplestore)
  10. from lakesuperior.store.ldp_rs.keyset cimport Keyset
  11. from lakesuperior.store.ldp_rs.triple cimport Triple
  12. from lakesuperior.util.hash cimport hash64
  13. ctypedef struct SetItem:
  14. unsigned char *data
  15. size_t size
  16. logger = logging.getLogger(__name__)
  17. def use_data(fn):
  18. """
  19. Decorator to indicate that a set operation between two SimpleGraph
  20. instances should use the ``data`` property of the second term. The second
  21. term can also be a simple set.
  22. """
  23. @wraps(fn)
  24. def _wrapper(self, other):
  25. if isinstance(other, SimpleGraph):
  26. other = other.data
  27. return _wrapper
  28. cdef unsigned int set_item_hash_fn(calg.SetValue data):
  29. """
  30. Hash function for the CAlg set implementation.
  31. https://fragglet.github.io/c-algorithms/doc/set_8h.html#6c7986a2a80d7a3cb7b9d74e1c6fef97
  32. :param SetItem *data: Pointer to a SetItem structure.
  33. """
  34. return hash64((<SetItem>data).data, (<SetItem>data).size)
  35. cdef bint set_item_cmp_fn(calg.SetValue v1, calg.SetValue v2):
  36. """
  37. Compare function for two CAlg set items.
  38. https://fragglet.github.io/c-algorithms/doc/set_8h.html#40fa2c86d5b003c1b0b0e8dd1e4df9f4
  39. """
  40. if (<SetItem *>v1)[0].size != (<SetItem *>v2)[0].size:
  41. return False
  42. return memcmp(
  43. (<SetItem *>v1)[0].data, (<SetItem *>v2)[0].data,
  44. (<SetItem *>v1)[0].size)
  45. cdef class SimpleGraph:
  46. """
  47. Fast and simple implementation of a graph.
  48. Most functions should mimic RDFLib's graph with less overhead. It uses
  49. the same funny but functional slicing notation.
  50. A SimpleGraph can be obtained from a
  51. :py:class:`lakesuperior.store.keyset.Keyset` which is convenient bacause
  52. a Keyset can be obtained very efficiently from querying a store, then also
  53. very efficiently filtered and eventually converted into a set of readable
  54. terms.
  55. An instance of this class can also be converted to and from a
  56. ``rdflib.Graph`` instance.
  57. """
  58. cdef:
  59. calg.Set *_data
  60. def __cinit__(
  61. self, calg.Set *cdata=NULL, Keyset keyset=None, store=None,
  62. set data=set()):
  63. """
  64. Initialize the graph with pre-existing data or by looking up a store.
  65. One of ``cdata``, ``keyset``, or ``data`` can be provided. If more than
  66. one of these is provided, precedence is given in the mentioned order.
  67. If none of them is specified, an empty graph is initialized.
  68. :param rdflib.URIRef uri: The graph URI.
  69. This will serve as the subject for some queries.
  70. :param calg.Set cdata: Initial data as a C ``Set`` struct.
  71. :param Keyset keyset: Keyset to create the graph from. Keys will be
  72. converted to set elements.
  73. :param lakesuperior.store.ldp_rs.LmdbTripleStore store: store to
  74. look up the keyset. Only used if ``keyset`` is specified. If not
  75. set, the environment store is used.
  76. :param set data: Initial data as a set of 3-tuples of RDFLib terms.
  77. :param tuple lookup: tuple of a 3-tuple of lookup terms, and a context.
  78. E.g. ``((URIRef('urn:ns:a'), None, None), URIRef('urn:ns:ctx'))``.
  79. Any and all elements may be ``None``.
  80. :param lmdbStore store: the store to look data up.
  81. """
  82. self.store = store or env.app_defaults.rdf_store
  83. cdef:
  84. Triple strp
  85. TripleKey spok
  86. if cdata is not NULL:
  87. # Build data from provided C set.
  88. self._data = cdata
  89. else:
  90. # Initialize empty data set.
  91. self._data = calg.set_new(set_item_hash_fn, set_item_cmp_fn)
  92. if keyset is not None:
  93. # Populate with provided key set.
  94. while keyset.next(spok):
  95. calg.set_insert(self._data, self.store.from_trp_key(spok))
  96. else:
  97. # Populate with provided Python set.
  98. for trp in data:
  99. strp = serialize_triple(trp)
  100. calg.set_insert(self._data, strp)
  101. @property
  102. def data(self):
  103. """
  104. Triple data as a Python set.
  105. :rtype: set
  106. """
  107. return self._data_as_set()
  108. cdef void _data_from_lookup(
  109. self, LmdbTriplestore store, tuple trp_ptn, ctx=None) except *:
  110. """
  111. Look up triples in the triplestore and load them into ``data``.
  112. :param tuple lookup: 3-tuple of RDFlib terms or ``None``.
  113. :param LmdbTriplestore store: Reference to a LMDB triplestore. This
  114. is normally set to ``lakesuperior.env.app_globals.rdf_store``.
  115. """
  116. cdef:
  117. size_t i
  118. unsigned char spok[TRP_KLEN]
  119. self._data = calg.set_new(set_item_hash_fn, set_item_cmp_fn)
  120. with store.txn_ctx():
  121. keyset = store.triple_keys(trp_ptn, ctx)
  122. for i in range(keyset.ct):
  123. spok = keyset.data + i * TRP_KLEN
  124. self.data.add(store.from_trp_key(spok[: TRP_KLEN]))
  125. strp = serialize_triple(trp)
  126. calg.set_insert(self._data, strp)
  127. cdef _data_as_set(self):
  128. """
  129. Convert triple data to a Python set.
  130. :rtype: set
  131. """
  132. pass
  133. # Basic set operations.
  134. def add(self, dataset):
  135. """ Set union. """
  136. self.data.add(dataset)
  137. def remove(self, item):
  138. """
  139. Remove one item from the graph.
  140. :param tuple item: A 3-tuple of RDFlib terms. Only exact terms, i.e.
  141. wildcards are not accepted.
  142. """
  143. self.data.remove(item)
  144. def __len__(self):
  145. """ Number of triples in the graph. """
  146. return len(self.data)
  147. @use_data
  148. def __eq__(self, other):
  149. """ Equality operator between ``SimpleGraph`` instances. """
  150. return self.data == other
  151. def __repr__(self):
  152. """
  153. String representation of the graph.
  154. It provides the number of triples in the graph and memory address of
  155. the instance.
  156. """
  157. return (f'<{self.__class__.__name__} @{hex(id(self))} '
  158. f'length={len(self.data)}>')
  159. def __str__(self):
  160. """ String dump of the graph triples. """
  161. return str(self.data)
  162. @use_data
  163. def __sub__(self, other):
  164. """ Set subtraction. """
  165. return self.data - other
  166. @use_data
  167. def __isub__(self, other):
  168. """ In-place set subtraction. """
  169. self.data -= other
  170. return self
  171. @use_data
  172. def __and__(self, other):
  173. """ Set intersection. """
  174. return self.data & other
  175. @use_data
  176. def __iand__(self, other):
  177. """ In-place set intersection. """
  178. self.data &= other
  179. return self
  180. @use_data
  181. def __or__(self, other):
  182. """ Set union. """
  183. return self.data | other
  184. @use_data
  185. def __ior__(self, other):
  186. """ In-place set union. """
  187. self.data |= other
  188. return self
  189. @use_data
  190. def __xor__(self, other):
  191. """ Set exclusive intersection (XOR). """
  192. return self.data ^ other
  193. @use_data
  194. def __ixor__(self, other):
  195. """ In-place set exclusive intersection (XOR). """
  196. self.data ^= other
  197. return self
  198. def __contains__(self, item):
  199. """
  200. Whether the graph contains a triple.
  201. :rtype: boolean
  202. """
  203. return item in self.data
  204. def __iter__(self):
  205. """ Graph iterator. It iterates over the set triples. """
  206. return self.data.__iter__()
  207. # Slicing.
  208. def __getitem__(self, item):
  209. """
  210. Slicing function.
  211. It behaves similarly to `RDFLib graph slicing
  212. <https://rdflib.readthedocs.io/en/stable/utilities.html#slicing-graphs>`__
  213. """
  214. if isinstance(item, slice):
  215. s, p, o = item.start, item.stop, item.step
  216. return self._slice(s, p, o)
  217. else:
  218. raise TypeError(f'Wrong slice format: {item}.')
  219. cpdef void set(self, tuple trp) except *:
  220. """
  221. Set a single value for subject and predicate.
  222. Remove all triples matching ``s`` and ``p`` before adding ``s p o``.
  223. """
  224. self.remove_triples((trp[0], trp[1], None))
  225. if None in trp:
  226. raise ValueError(f'Invalid triple: {trp}')
  227. self.data.add(trp)
  228. cpdef void remove_triples(self, pattern) except *:
  229. """
  230. Remove triples by pattern.
  231. The pattern used is similar to :py:meth:`LmdbTripleStore.delete`.
  232. """
  233. s, p, o = pattern
  234. for match in self.lookup(s, p, o):
  235. logger.debug(f'Removing from graph: {match}.')
  236. self.data.remove(match)
  237. cpdef object as_rdflib(self):
  238. """
  239. Return the data set as an RDFLib Graph.
  240. :rtype: rdflib.Graph
  241. """
  242. gr = Graph()
  243. for trp in self.data:
  244. gr.add(trp)
  245. return gr
  246. cdef _slice(self, s, p, o):
  247. """
  248. Return terms filtered by other terms.
  249. This behaves like the rdflib.Graph slicing policy.
  250. """
  251. if s is None and p is None and o is None:
  252. return self.data
  253. elif s is None and p is None:
  254. return {(r[0], r[1]) for r in self.data if r[2] == o}
  255. elif s is None and o is None:
  256. return {(r[0], r[2]) for r in self.data if r[1] == p}
  257. elif p is None and o is None:
  258. return {(r[1], r[2]) for r in self.data if r[0] == s}
  259. elif s is None:
  260. return {r[0] for r in self.data if r[1] == p and r[2] == o}
  261. elif p is None:
  262. return {r[1] for r in self.data if r[0] == s and r[2] == o}
  263. elif o is None:
  264. return {r[2] for r in self.data if r[0] == s and r[1] == p}
  265. else:
  266. # all given
  267. return (s,p,o) in self.data
  268. cpdef lookup(self, s, p, o):
  269. """
  270. Look up triples by a pattern.
  271. """
  272. logger.debug(f'Looking up in graph: {s}, {p}, {o}.')
  273. if s is None and p is None and o is None:
  274. return self.data
  275. elif s is None and p is None:
  276. return {r for r in self.data if r[2] == o}
  277. elif s is None and o is None:
  278. return {r for r in self.data if r[1] == p}
  279. elif p is None and o is None:
  280. return {r for r in self.data if r[0] == s}
  281. elif s is None:
  282. return {r for r in self.data if r[1] == p and r[2] == o}
  283. elif p is None:
  284. return {r for r in self.data if r[0] == s and r[2] == o}
  285. elif o is None:
  286. return {r for r in self.data if r[0] == s and r[1] == p}
  287. else:
  288. # all given
  289. return (s,p,o) if (s, p, o) in self.data else set()
  290. cpdef set terms(self, str type):
  291. """
  292. Get all terms of a type: subject, predicate or object.
  293. :param str type: One of ``s``, ``p`` or ``o``.
  294. """
  295. i = 'spo'.index(type)
  296. return {r[i] for r in self.data}
  297. cdef class Imr(SimpleGraph):
  298. """
  299. In-memory resource data container.
  300. This is an extension of :py:class:`~SimpleGraph` that adds a subject URI to
  301. the data set and some convenience methods.
  302. An instance of this class can be converted to a ``rdflib.Resource``
  303. instance.
  304. Some set operations that produce a new object (``-``, ``|``, ``&``, ``^``)
  305. will create a new ``Imr`` instance with the same subject URI.
  306. """
  307. cdef:
  308. readonly object uri
  309. def __init__(self, uri, *args, **kwargs):
  310. """
  311. Initialize the graph with pre-existing data or by looking up a store.
  312. Either ``data``, or ``lookup`` *and* ``store``, can be provide.
  313. ``lookup`` and ``store`` have precedence. If none of them is specified,
  314. an empty graph is initialized.
  315. :param rdflib.URIRef uri: The graph URI.
  316. This will serve as the subject for some queries.
  317. :param set data: Initial data as a set of 3-tuples of RDFLib terms.
  318. :param tuple lookup: tuple of a 3-tuple of lookup terms, and a context.
  319. E.g. ``((URIRef('urn:ns:a'), None, None), URIRef('urn:ns:ctx'))``.
  320. Any and all elements may be ``None``.
  321. :param lmdbStore store: the store to look data up.
  322. """
  323. super().__init__(*args, **kwargs)
  324. self.uri = uri
  325. @property
  326. def identifier(self):
  327. """
  328. IMR URI. For compatibility with RDFLib Resource.
  329. :rtype: string
  330. """
  331. return self.uri
  332. @property
  333. def graph(self):
  334. """
  335. Return a SimpleGraph with the same data.
  336. :rtype: SimpleGraph
  337. """
  338. return SimpleGraph(self.data)
  339. def __repr__(self):
  340. """
  341. String representation of an Imr.
  342. This includes the subject URI, number of triples contained and the
  343. memory address of the instance.
  344. """
  345. return (f'<{self.__class__.__name__} @{hex(id(self))} uri={self.uri}, '
  346. f'length={len(self.data)}>')
  347. @use_data
  348. def __sub__(self, other):
  349. """
  350. Set difference. This creates a new Imr with the same subject URI.
  351. """
  352. return self.__class__(uri=self.uri, data=self.data - other)
  353. @use_data
  354. def __and__(self, other):
  355. """
  356. Set intersection. This creates a new Imr with the same subject URI.
  357. """
  358. return self.__class__(uri=self.uri, data=self.data & other)
  359. @use_data
  360. def __or__(self, other):
  361. """
  362. Set union. This creates a new Imr with the same subject URI.
  363. """
  364. return self.__class__(uri=self.uri, data=self.data | other)
  365. @use_data
  366. def __xor__(self, other):
  367. """
  368. Set exclusive OR (XOR). This creates a new Imr with the same subject
  369. URI.
  370. """
  371. return self.__class__(uri=self.uri, data=self.data ^ other)
  372. def __getitem__(self, item):
  373. """
  374. Supports slicing notation.
  375. """
  376. if isinstance(item, slice):
  377. s, p, o = item.start, item.stop, item.step
  378. return self._slice(s, p, o)
  379. elif isinstance(item, Node):
  380. # If a Node is given, return all values for that predicate.
  381. return {
  382. r[2] for r in self.data
  383. if r[0] == self.uri and r[1] == item}
  384. else:
  385. raise TypeError(f'Wrong slice format: {item}.')
  386. def value(self, p, strict=False):
  387. """
  388. Get an individual value.
  389. :param rdflib.termNode p: Predicate to search for.
  390. :param bool strict: If set to ``True`` the method raises an error if
  391. more than one value is found. If ``False`` (the default) only
  392. the first found result is returned.
  393. :rtype: rdflib.term.Node
  394. """
  395. values = self[p]
  396. if strict and len(values) > 1:
  397. raise RuntimeError('More than one value found for {}, {}.'.format(
  398. self.uri, p))
  399. for ret in values:
  400. return ret
  401. return None
  402. cpdef as_rdflib(self):
  403. """
  404. Return the IMR as a RDFLib Resource.
  405. :rtype: rdflib.Resource
  406. """
  407. gr = Graph()
  408. for trp in self.data:
  409. gr.add(trp)
  410. return gr.resource(identifier=self.uri)