graph.pyx 14 KB

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