graph.pyx 25 KB

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