graph.pyx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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.stdint cimport uint32_t, uint64_t
  7. from libc.string cimport memcmp, memcpy
  8. from libc.stdlib cimport free
  9. from cymem.cymem cimport Pool
  10. from lakesuperior.cy_include cimport cylmdb as lmdb
  11. from lakesuperior.cy_include cimport collections as cc
  12. from lakesuperior.model.graph cimport term
  13. from lakesuperior.store.ldp_rs.lmdb_triplestore cimport (
  14. KLEN, DBL_KLEN, TRP_KLEN, TripleKey)
  15. from lakesuperior.model.structures.hash cimport term_hash_seed32
  16. from lakesuperior.model.structures.keyset cimport Keyset
  17. from lakesuperior.model.base cimport Buffer
  18. from lakesuperior.model.graph.triple cimport BufferTriple
  19. from lakesuperior.model.structures.hash cimport hash64
  20. cdef extern from 'spookyhash_api.h':
  21. uint64_t spookyhash_64(const void *input, size_t input_size, uint64_t seed)
  22. logger = logging.getLogger(__name__)
  23. def use_data(fn):
  24. """
  25. Decorator to indicate that a set operation between two SimpleGraph
  26. instances should use the ``data`` property of the second term. The second
  27. term can also be a simple set.
  28. """
  29. @wraps(fn)
  30. def _wrapper(self, other):
  31. if isinstance(other, SimpleGraph):
  32. other = other.data
  33. return _wrapper
  34. cdef int term_cmp_fn(const void* key1, const void* key2):
  35. """
  36. Compare function for two Buffer objects.
  37. :rtype: int
  38. :return: 0 if the byte streams are the same, another integer otherwise.
  39. """
  40. b1 = <Buffer *>key1
  41. b2 = <Buffer *>key2
  42. if b1.sz != b2.sz:
  43. return 1
  44. #print('Term A:')
  45. #print((<unsigned char *>b1.addr)[:b1.sz])
  46. #print('Term b:')
  47. #print((<unsigned char *>b2.addr)[:b2.sz])
  48. cdef int cmp = memcmp(b1.addr, b2.addr, b1.sz)
  49. logger.info(f'term memcmp: {cmp}')
  50. return cmp
  51. cdef int triple_cmp_fn(const void* key1, const void* key2):
  52. """
  53. Compare function for two triples in a CAlg set.
  54. Here, pointers to terms are compared for s, p, o. The pointers should be
  55. guaranteed to point to unique values (i.e. no two pointers have the same
  56. term value within a graph).
  57. :rtype: int
  58. :return: 0 if the addresses of all terms are the same, 1 otherwise.
  59. """
  60. t1 = <BufferTriple *>key1
  61. t2 = <BufferTriple *>key2
  62. return (
  63. t1.s.addr != t2.s.addr or
  64. t1.p.addr != t2.p.addr or
  65. t1.o.addr != t2.o.addr
  66. )
  67. cdef size_t trp_hash_fn(const void* key, int l, uint32_t seed):
  68. """
  69. Hash function for sets of (serialized) triples.
  70. This function computes the hash of the concatenated pointer values in the
  71. s, p, o members of the triple. The triple structure is treated as a byte
  72. string. This is safe in spite of byte-wise struct evaluation being a
  73. frowned-upon practice (due to padding issues), because it is assumed that
  74. the input value is always the same type of structure.
  75. """
  76. return <size_t>spookyhash_64(key, l, seed)
  77. cdef size_t hash_ptr_passthrough(const void* key, int l, uint32_t seed):
  78. """
  79. No-op function that takes a pointer and does *not* hash it.
  80. The pointer value is used as the "hash".
  81. """
  82. return <size_t>key
  83. cdef inline bint lookup_none_cmp_fn(
  84. const BufferTriple *trp, const Buffer *t1, const Buffer *t2):
  85. """
  86. Dummy callback for queries with all parameters unbound.
  87. This function always returns ``True``
  88. """
  89. return True
  90. cdef inline bint lookup_s_cmp_fn(const BufferTriple *trp, const Buffer *t1, const Buffer *t2):
  91. """
  92. Lookup callback compare function for a given s in a triple.
  93. The function returns ``True`` if ``t1`` matches the first term.
  94. ``t2`` is not used and is declared only for compatibility with the
  95. other interchangeable functions.
  96. """
  97. return term_cmp_fn(t1, trp[0].s)
  98. cdef inline bint lookup_p_cmp_fn(const BufferTriple *trp, const Buffer *t1, const Buffer *t2):
  99. return term_cmp_fn(t1, trp[0].p)
  100. cdef inline bint lookup_o_cmp_fn(const BufferTriple *trp, const Buffer *t1, const Buffer *t2):
  101. return term_cmp_fn(t1, trp[0].o)
  102. cdef inline bint lookup_sp_cmp_fn(const BufferTriple *trp, const Buffer *t1, const Buffer *t2):
  103. return (
  104. term_cmp_fn(t1, trp[0].s)
  105. and term_cmp_fn(t2, trp[0].p))
  106. cdef inline bint lookup_so_cmp_fn(const BufferTriple *trp, const Buffer *t1, const Buffer *t2):
  107. return (
  108. term_cmp_fn(t1, trp[0].s)
  109. and term_cmp_fn(t2, trp[0].o))
  110. cdef inline bint lookup_po_cmp_fn(const BufferTriple *trp, const Buffer *t1, const Buffer *t2):
  111. return (
  112. term_cmp_fn(t1, trp[0].p)
  113. and term_cmp_fn(t2, trp[0].o))
  114. cdef class SimpleGraph:
  115. """
  116. Fast and simple implementation of a graph.
  117. Most functions should mimic RDFLib's graph with less overhead. It uses
  118. the same funny but functional slicing notation. No lookup functions within
  119. the graph are available at this time.
  120. Instances of this class hold a set of
  121. :py:class:`~lakesuperior.store.ldp_rs.term.Term` structures that stores
  122. unique terms within the graph, and a set of
  123. :py:class:`~lakesuperior.store.ldp_rs.triple.Triple` structures referencing
  124. those terms. Therefore, no data duplication occurs and the storage is quite
  125. sparse.
  126. A graph can be instantiated from a store lookup.
  127. A SimpleGraph can also be obtained from a
  128. :py:class:`lakesuperior.store.keyset.Keyset` which is convenient bacause
  129. a Keyset can be obtained very efficiently from querying a store, then also
  130. very efficiently filtered and eventually converted into a set of meaningful
  131. terms.
  132. An instance of this class can also be converted to and from a
  133. ``rdflib.Graph`` instance. TODO verify that this frees Cython pointers.
  134. """
  135. def __cinit__(
  136. self, Keyset keyset=None, store=None, set data=set(), **kwargs):
  137. """
  138. Initialize the graph with pre-existing data or by looking up a store.
  139. One of ``keyset``, or ``data`` can be provided. If more than
  140. one of these is provided, precedence is given in the mentioned order.
  141. If none of them is specified, an empty graph is initialized.
  142. :param rdflib.URIRef uri: The graph URI.
  143. This will serve as the subject for some queries.
  144. :param Keyset keyset: Keyset to create the graph from. Keys will be
  145. converted to set elements.
  146. :param lakesuperior.store.ldp_rs.LmdbTripleStore store: store to
  147. look up the keyset. Only used if ``keyset`` is specified. If not
  148. set, the environment store is used.
  149. :param set data: Initial data as a set of 3-tuples of RDFLib terms.
  150. :param tuple lookup: tuple of a 3-tuple of lookup terms, and a context.
  151. E.g. ``((URIRef('urn:ns:a'), None, None), URIRef('urn:ns:ctx'))``.
  152. Any and all elements may be ``None``.
  153. :param lmdbStore store: the store to look data up.
  154. """
  155. cdef:
  156. cc.HashSetConf terms_conf
  157. cc.HashSetConf trp_conf
  158. cc.hashset_conf_init(&terms_conf)
  159. terms_conf.load_factor = 0.85
  160. terms_conf.hash = &hash_ptr_passthrough # spookyhash_64?
  161. terms_conf.hash_seed = term_hash_seed32
  162. terms_conf.key_compare = &term_cmp_fn
  163. terms_conf.key_length = sizeof(void*)
  164. cc.hashset_conf_init(&trp_conf)
  165. trp_conf.load_factor = 0.75
  166. trp_conf.hash = &hash_ptr_passthrough # spookyhash_64?
  167. trp_conf.hash_seed = term_hash_seed32
  168. trp_conf.key_compare = &triple_cmp_fn
  169. trp_conf.key_length = sizeof(void*)
  170. cc.hashset_new_conf(&terms_conf, &self._terms)
  171. cc.hashset_new_conf(&trp_conf, &self._triples)
  172. self.store = store or env.app_globals.rdf_store
  173. self._pool = Pool()
  174. # Initialize empty data set.
  175. if keyset:
  176. # Populate with triples extracted from provided key set.
  177. self._data_from_keyset(keyset)
  178. elif data is not None:
  179. # Populate with provided Python set.
  180. for s, p, o in data:
  181. self._add_from_rdflib(s, p, o)
  182. def __dealloc__(self):
  183. """
  184. Free the triple pointers. TODO use a Cymem pool
  185. """
  186. free(self._triples)
  187. free(self._terms)
  188. @property
  189. def data(self):
  190. """
  191. Triple data as a Python set.
  192. :rtype: set
  193. """
  194. return self._data_as_set()
  195. cdef void _data_from_lookup(self, tuple trp_ptn, ctx=None) except *:
  196. """
  197. Look up triples in the triplestore and load them into ``data``.
  198. :param tuple lookup: 3-tuple of RDFlib terms or ``None``.
  199. :param LmdbTriplestore store: Reference to a LMDB triplestore. This
  200. is normally set to ``lakesuperior.env.app_globals.rdf_store``.
  201. """
  202. cdef:
  203. size_t i
  204. unsigned char spok[TRP_KLEN]
  205. with self.store.txn_ctx():
  206. keyset = self.store.triple_keys(trp_ptn, ctx)
  207. self.data_from_keyset(keyset)
  208. cdef void _data_from_keyset(self, Keyset data) except *:
  209. """Populate a graph from a Keyset."""
  210. cdef TripleKey spok
  211. while data.next(spok):
  212. self._add_from_spok(spok)
  213. cdef inline void _add_from_spok(self, TripleKey spok) except *:
  214. """
  215. Add a triple from a TripleKey of term keys.
  216. """
  217. cdef:
  218. SPOBuffer s_spo
  219. BufferTriple trp
  220. s_spo = <SPOBuffer>self._pool.alloc(3, sizeof(Buffer))
  221. self.store.lookup_term(spok, s_spo)
  222. self.store.lookup_term(spok + KLEN, s_spo + 1)
  223. self.store.lookup_term(spok + DBL_KLEN, s_spo + 2)
  224. self._add_triple(s_spo, s_spo + 1, s_spo + 2)
  225. cdef inline void _add_triple(
  226. self, BufferPtr ss, BufferPtr sp, BufferPtr so
  227. ) except *:
  228. """
  229. Add a triple from 3 (TPL) serialized terms.
  230. Each of the terms is added to the term set if not existing. The triple
  231. also is only added if not existing.
  232. """
  233. trp = <BufferTriple *>self._pool.alloc(1, sizeof(BufferTriple))
  234. logger.info('Inserting terms.')
  235. logger.info(f'ss addr: {<unsigned long>ss.addr}')
  236. logger.info(f'ss sz: {ss.sz}')
  237. #logger.info('ss:')
  238. #logger.info((<unsigned char *>ss.addr)[:ss.sz])
  239. print('Insert ss: @0x{:02x}'.format(<unsigned long>ss))
  240. cc.hashset_add_or_get(self._terms, <void **>&ss)
  241. print('Now ss is: @0x{:02x}'.format(<unsigned long>ss))
  242. logger.info('Insert sp')
  243. cc.hashset_add_or_get(self._terms, <void **>&sp)
  244. logger.info('Insert so')
  245. cc.hashset_add_or_get(self._terms, <void **>&so)
  246. logger.info('inserted terms.')
  247. cdef size_t terms_sz = cc.hashset_size(self._terms)
  248. logger.info('Terms set size: {terms_sz}')
  249. #cdef cc.HashSetIter ti
  250. #cdef Buffer *t
  251. #cc.hashset_iter_init(&ti, self._terms)
  252. #while calg.set_iter_has_more(&ti):
  253. # t = <Buffer *>calg.set_iter_next(&ti)
  254. trp.s = ss
  255. trp.p = sp
  256. trp.o = so
  257. r = cc.hashset_add(self._triples, trp)
  258. print('Insert triple result:')
  259. print(r)
  260. #cdef BufferTriple *tt
  261. #calg.set_iterate(self._triples, &ti)
  262. #while calg.set_iter_has_more(&ti):
  263. # tt = <BufferTriple *>calg.set_iter_next(&ti)
  264. cdef set _data_as_set(self):
  265. """
  266. Convert triple data to a Python set.
  267. :rtype: set
  268. """
  269. cdef:
  270. void *void_p
  271. cc.HashSetIter ti
  272. BufferTriple *trp
  273. term.Term s, p, o
  274. graph_set = set()
  275. cc.hashset_iter_init(&ti, self._triples)
  276. while cc.hashset_iter_next(&ti, &void_p) == cc.CC_OK:
  277. if void_p == NULL:
  278. logger.warn('Triple is NULL!')
  279. break
  280. trp = <BufferTriple *>void_p
  281. graph_set.add((
  282. term.deserialize_to_rdflib(trp.s),
  283. term.deserialize_to_rdflib(trp.p),
  284. term.deserialize_to_rdflib(trp.o),
  285. ))
  286. return graph_set
  287. # Basic set operations.
  288. def add(self, triple):
  289. """ Add one triple to the graph. """
  290. ss = <Buffer *>self._pool.alloc(1, sizeof(Buffer))
  291. sp = <Buffer *>self._pool.alloc(1, sizeof(Buffer))
  292. so = <Buffer *>self._pool.alloc(1, sizeof(Buffer))
  293. s, p, o = triple
  294. term.serialize_from_rdflib(s, ss, self._pool)
  295. term.serialize_from_rdflib(p, sp, self._pool)
  296. term.serialize_from_rdflib(o, so, self._pool)
  297. self._add_triple(ss, sp, so)
  298. def remove(self, item):
  299. """
  300. Remove one item from the graph.
  301. :param tuple item: A 3-tuple of RDFlib terms. Only exact terms, i.e.
  302. wildcards are not accepted.
  303. """
  304. self.data.remove(item)
  305. def __len__(self):
  306. """ Number of triples in the graph. """
  307. #return calg.set_num_entries(self._triples)
  308. return len(self.data)
  309. @use_data
  310. def __eq__(self, other):
  311. """ Equality operator between ``SimpleGraph`` instances. """
  312. return self.data == other
  313. def __repr__(self):
  314. """
  315. String representation of the graph.
  316. It provides the number of triples in the graph and memory address of
  317. the instance.
  318. """
  319. return (f'<{self.__class__.__name__} @{hex(id(self))} '
  320. f'length={len(self.data)}>')
  321. def __str__(self):
  322. """ String dump of the graph triples. """
  323. return str(self.data)
  324. @use_data
  325. def __sub__(self, other):
  326. """ Set subtraction. """
  327. return self.data - other
  328. @use_data
  329. def __isub__(self, other):
  330. """ In-place set subtraction. """
  331. self.data -= other
  332. return self
  333. @use_data
  334. def __and__(self, other):
  335. """ Set intersection. """
  336. return self.data & other
  337. @use_data
  338. def __iand__(self, other):
  339. """ In-place set intersection. """
  340. self.data &= other
  341. return self
  342. @use_data
  343. def __or__(self, other):
  344. """ Set union. """
  345. return self.data | other
  346. @use_data
  347. def __ior__(self, other):
  348. """ In-place set union. """
  349. self.data |= other
  350. return self
  351. @use_data
  352. def __xor__(self, other):
  353. """ Set exclusive intersection (XOR). """
  354. return self.data ^ other
  355. @use_data
  356. def __ixor__(self, other):
  357. """ In-place set exclusive intersection (XOR). """
  358. self.data ^= other
  359. return self
  360. def __contains__(self, item):
  361. """
  362. Whether the graph contains a triple.
  363. :rtype: boolean
  364. """
  365. return item in self.data
  366. def __iter__(self):
  367. """ Graph iterator. It iterates over the set triples. """
  368. return self.data.__iter__()
  369. # Slicing.
  370. def __getitem__(self, item):
  371. """
  372. Slicing function.
  373. It behaves similarly to `RDFLib graph slicing
  374. <https://rdflib.readthedocs.io/en/stable/utilities.html#slicing-graphs>`__
  375. """
  376. if isinstance(item, slice):
  377. s, p, o = item.start, item.stop, item.step
  378. return self._slice(s, p, o)
  379. else:
  380. raise TypeError(f'Wrong slice format: {item}.')
  381. cpdef void set(self, tuple trp) except *:
  382. """
  383. Set a single value for subject and predicate.
  384. Remove all triples matching ``s`` and ``p`` before adding ``s p o``.
  385. """
  386. if None in trp:
  387. raise ValueError(f'Invalid triple: {trp}')
  388. self.remove_triples((trp[0], trp[1], None))
  389. self.add(trp)
  390. cpdef void remove_triples(self, pattern) except *:
  391. """
  392. Remove triples by pattern.
  393. The pattern used is similar to :py:meth:`LmdbTripleStore.delete`.
  394. """
  395. s, p, o = pattern
  396. for match in self.lookup(s, p, o):
  397. logger.debug(f'Removing from graph: {match}.')
  398. self.data.remove(match)
  399. cpdef object as_rdflib(self):
  400. """
  401. Return the data set as an RDFLib Graph.
  402. :rtype: rdflib.Graph
  403. """
  404. gr = Graph()
  405. for trp in self.data:
  406. gr.add(trp)
  407. return gr
  408. def _slice(self, s, p, o):
  409. """
  410. Return terms filtered by other terms.
  411. This behaves like the rdflib.Graph slicing policy.
  412. """
  413. _data = self.data
  414. logger.debug(f'Slicing graph by: {s}, {p}, {o}.')
  415. if s is None and p is None and o is None:
  416. return _data
  417. elif s is None and p is None:
  418. return {(r[0], r[1]) for r in _data if r[2] == o}
  419. elif s is None and o is None:
  420. return {(r[0], r[2]) for r in _data if r[1] == p}
  421. elif p is None and o is None:
  422. return {(r[1], r[2]) for r in _data if r[0] == s}
  423. elif s is None:
  424. return {r[0] for r in _data if r[1] == p and r[2] == o}
  425. elif p is None:
  426. return {r[1] for r in _data if r[0] == s and r[2] == o}
  427. elif o is None:
  428. return {r[2] for r in _data if r[0] == s and r[1] == p}
  429. else:
  430. # all given
  431. return (s,p,o) in _data
  432. def lookup(self, s, p, o):
  433. """
  434. Look up triples by a pattern.
  435. This function converts RDFLib terms into the serialized format stored
  436. in the graph's internal structure and compares them bytewise.
  437. Any and all of the lookup terms can be ``None``.
  438. """
  439. cdef:
  440. void *void_p
  441. BufferTriple trp
  442. BufferTriple *trp_p
  443. cc.HashSetIter ti
  444. Buffer t1
  445. Buffer t2
  446. lookup_fn_t fn
  447. res = set()
  448. # Decide comparison logic outside the loop.
  449. if s is not None and p is not None and o is not None:
  450. # Return immediately if 3-term match is requested.
  451. term.serialize_from_rdflib(s, trp.s)
  452. term.serialize_from_rdflib(p, trp.p)
  453. term.serialize_from_rdflib(o, trp.o)
  454. if cc.hashset_contains(self._triples, &trp):
  455. res.add((s, p, o))
  456. return res
  457. elif s is not None:
  458. term.serialize_from_rdflib(s, &t1)
  459. if p is not None:
  460. fn = lookup_sp_cmp_fn
  461. term.serialize_from_rdflib(p, &t2)
  462. elif o is not None:
  463. fn = lookup_so_cmp_fn
  464. term.serialize_from_rdflib(o, &t2)
  465. else:
  466. fn = lookup_s_cmp_fn
  467. elif p is not None:
  468. term.serialize_from_rdflib(p, &t1)
  469. if o is not None:
  470. fn = lookup_po_cmp_fn
  471. term.serialize_from_rdflib(o, &t2)
  472. else:
  473. fn = lookup_p_cmp_fn
  474. elif o is not None:
  475. fn = lookup_o_cmp_fn
  476. term.serialize_from_rdflib(o, &t1)
  477. else:
  478. fn = lookup_none_cmp_fn
  479. # Iterate over serialized triples.
  480. cc.hashset_iter_init(&ti, self._triples)
  481. while cc.hashset_iter_next(&ti, &void_p) == cc.CC_OK:
  482. if void_p == NULL:
  483. trp_p = <BufferTriple *>void_p
  484. res.add((
  485. term.deserialize_to_rdflib(trp_p[0].s),
  486. term.deserialize_to_rdflib(trp_p[0].p),
  487. term.deserialize_to_rdflib(trp_p[0].o),
  488. ))
  489. return res
  490. cpdef set terms(self, str type):
  491. """
  492. Get all terms of a type: subject, predicate or object.
  493. :param str type: One of ``s``, ``p`` or ``o``.
  494. """
  495. i = 'spo'.index(type)
  496. return {r[i] for r in self.data}
  497. cdef class Imr(SimpleGraph):
  498. """
  499. In-memory resource data container.
  500. This is an extension of :py:class:`~SimpleGraph` that adds a subject URI to
  501. the data set and some convenience methods.
  502. An instance of this class can be converted to a ``rdflib.Resource``
  503. instance.
  504. Some set operations that produce a new object (``-``, ``|``, ``&``, ``^``)
  505. will create a new ``Imr`` instance with the same subject URI.
  506. """
  507. def __init__(self, uri, *args, **kwargs):
  508. """
  509. Initialize the graph with pre-existing data or by looking up a store.
  510. Either ``data``, or ``lookup`` *and* ``store``, can be provide.
  511. ``lookup`` and ``store`` have precedence. If none of them is specified,
  512. an empty graph is initialized.
  513. :param rdflib.URIRef uri: The graph URI.
  514. This will serve as the subject for some queries.
  515. :param set data: Initial data as a set of 3-tuples of RDFLib terms.
  516. :param tuple lookup: tuple of a 3-tuple of lookup terms, and a context.
  517. E.g. ``((URIRef('urn:ns:a'), None, None), URIRef('urn:ns:ctx'))``.
  518. Any and all elements may be ``None``.
  519. :param lmdbStore store: the store to look data up.
  520. """
  521. self.uri = str(uri)
  522. @property
  523. def identifier(self):
  524. """
  525. IMR URI. For compatibility with RDFLib Resource.
  526. :rtype: string
  527. """
  528. return self.uri
  529. @property
  530. def graph(self):
  531. """
  532. Return a SimpleGraph with the same data.
  533. :rtype: SimpleGraph
  534. """
  535. return SimpleGraph(self.data)
  536. def __repr__(self):
  537. """
  538. String representation of an Imr.
  539. This includes the subject URI, number of triples contained and the
  540. memory address of the instance.
  541. """
  542. return (f'<{self.__class__.__name__} @{hex(id(self))} uri={self.uri}, '
  543. f'length={len(self.data)}>')
  544. @use_data
  545. def __sub__(self, other):
  546. """
  547. Set difference. This creates a new Imr with the same subject URI.
  548. """
  549. return self.__class__(uri=self.uri, data=self.data - other)
  550. @use_data
  551. def __and__(self, other):
  552. """
  553. Set intersection. This creates a new Imr with the same subject URI.
  554. """
  555. return self.__class__(uri=self.uri, data=self.data & other)
  556. @use_data
  557. def __or__(self, other):
  558. """
  559. Set union. This creates a new Imr with the same subject URI.
  560. """
  561. return self.__class__(uri=self.uri, data=self.data | other)
  562. @use_data
  563. def __xor__(self, other):
  564. """
  565. Set exclusive OR (XOR). This creates a new Imr with the same subject
  566. URI.
  567. """
  568. return self.__class__(uri=self.uri, data=self.data ^ other)
  569. def __getitem__(self, item):
  570. """
  571. Supports slicing notation.
  572. """
  573. if isinstance(item, slice):
  574. s, p, o = item.start, item.stop, item.step
  575. return self._slice(s, p, o)
  576. elif isinstance(item, Node):
  577. # If a Node is given, return all values for that predicate.
  578. return {
  579. r[2] for r in self.data
  580. if r[0] == self.uri and r[1] == item}
  581. else:
  582. raise TypeError(f'Wrong slice format: {item}.')
  583. def value(self, p, strict=False):
  584. """
  585. Get an individual value.
  586. :param rdflib.termNode p: Predicate to search for.
  587. :param bool strict: If set to ``True`` the method raises an error if
  588. more than one value is found. If ``False`` (the default) only
  589. the first found result is returned.
  590. :rtype: rdflib.term.Node
  591. """
  592. values = self[p]
  593. if strict and len(values) > 1:
  594. raise RuntimeError('More than one value found for {}, {}.'.format(
  595. self.uri, p))
  596. for ret in values:
  597. return ret
  598. return None
  599. cpdef as_rdflib(self):
  600. """
  601. Return the IMR as a RDFLib Resource.
  602. :rtype: rdflib.Resource
  603. """
  604. gr = Graph()
  605. for trp in self.data:
  606. gr.add(trp)
  607. return gr.resource(identifier=self.uri)