graph.pyx 14 KB

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