graph.pyx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. import logging
  2. from functools import wraps
  3. from rdflib import Graph, URIRef
  4. from rdflib.term import Node
  5. from lakesuperior import env
  6. from libc.string cimport memcpy
  7. from libc.stdlib cimport free
  8. from cymem.cymem cimport Pool
  9. cimport lakesuperior.cy_include.collections as cc
  10. cimport lakesuperior.model.graph.callbacks as cb
  11. from lakesuperior.model.base cimport Buffer, buffer_dump
  12. from lakesuperior.model.graph cimport term
  13. from lakesuperior.model.graph.triple cimport BufferTriple
  14. from lakesuperior.model.structures.hash cimport term_hash_seed32
  15. logger = logging.getLogger(__name__)
  16. cdef class SimpleGraph:
  17. """
  18. Fast and simple implementation of a graph.
  19. Most functions should mimic RDFLib's graph with less overhead. It uses
  20. the same funny but functional slicing notation.
  21. A SimpleGraph can be instantiated from a store lookup. This makes it
  22. possible to use a Keyset to perform initial filtering via identity by key,
  23. then the filtered Keyset can be converted into a set of meaningful terms.
  24. An instance of this class can also be converted to and from a
  25. ``rdflib.Graph`` instance.
  26. """
  27. def __cinit__(self, set data=set(), *args, **kwargs):
  28. """
  29. Initialize the graph, optionally with Python data.
  30. :param set data: Initial data as a set of 3-tuples of RDFLib terms.
  31. """
  32. cdef:
  33. cc.HashSetConf terms_conf, trp_conf
  34. self.term_cmp_fn = cb.term_cmp_fn
  35. self.trp_cmp_fn = cb.trp_cmp_fn
  36. cc.hashset_conf_init(&terms_conf)
  37. terms_conf.load_factor = 0.85
  38. terms_conf.hash = cb.term_hash_fn
  39. terms_conf.hash_seed = term_hash_seed32
  40. terms_conf.key_compare = self.term_cmp_fn
  41. terms_conf.key_length = sizeof(Buffer*)
  42. cc.hashset_conf_init(&trp_conf)
  43. trp_conf.load_factor = 0.75
  44. trp_conf.hash = cb.trp_hash_fn
  45. trp_conf.hash_seed = term_hash_seed32
  46. trp_conf.key_compare = self.trp_cmp_fn
  47. trp_conf.key_length = sizeof(BufferTriple)
  48. cc.hashset_new_conf(&terms_conf, &self._terms)
  49. cc.hashset_new_conf(&trp_conf, &self._triples)
  50. self.pool = Pool()
  51. # Initialize empty data set.
  52. if data:
  53. # Populate with provided Python set.
  54. self.add(data)
  55. def __dealloc__(self):
  56. """
  57. Free the triple pointers.
  58. """
  59. free(self._triples)
  60. free(self._terms)
  61. ## PROPERTIES ##
  62. @property
  63. def data(self):
  64. """
  65. Triple data as a Python generator.
  66. :rtype: generator
  67. """
  68. cdef:
  69. void *void_p
  70. cc.HashSetIter ti
  71. Buffer* ss
  72. Buffer* sp
  73. Buffer* so
  74. cc.hashset_iter_init(&ti, self._triples)
  75. while cc.hashset_iter_next(&ti, &void_p) != cc.CC_ITER_END:
  76. trp = <BufferTriple *>void_p
  77. yield (
  78. term.deserialize_to_rdflib(trp.s),
  79. term.deserialize_to_rdflib(trp.p),
  80. term.deserialize_to_rdflib(trp.o),
  81. )
  82. @property
  83. def stored_terms(self):
  84. """
  85. All terms in the graph with their memory address.
  86. For debugging purposes.
  87. """
  88. cdef:
  89. cc.HashSetIter it
  90. void *cur
  91. terms = set()
  92. cc.hashset_iter_init(&it, self._terms)
  93. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  94. s_term = <Buffer*>cur
  95. terms.add((f'0x{<size_t>cur:02x}', term.deserialize_to_rdflib(s_term)))
  96. return terms
  97. ## MAGIC METHODS ##
  98. def __len__(self):
  99. """ Number of triples in the graph. """
  100. return cc.hashset_size(self._triples)
  101. def __eq__(self, other):
  102. """ Equality operator between ``SimpleGraph`` instances. """
  103. return len(self ^ other) == 0
  104. def __repr__(self):
  105. """
  106. String representation of the graph.
  107. It provides the number of triples in the graph and memory address of
  108. the instance.
  109. """
  110. return (
  111. f'<{self.__class__.__name__} @{hex(id(self))} '
  112. f'length={len(self)}>'
  113. )
  114. def __str__(self):
  115. """ String dump of the graph triples. """
  116. return str(self.data)
  117. def __add__(self, other):
  118. """ Alias for set-theoretical union. """
  119. return self.union_(other)
  120. def __iadd__(self, other):
  121. """ Alias for in-place set-theoretical union. """
  122. self.ip_union(other)
  123. return self
  124. def __sub__(self, other):
  125. """ Set-theoretical subtraction. """
  126. return self.subtraction(other)
  127. def __isub__(self, other):
  128. """ In-place set-theoretical subtraction. """
  129. self.ip_subtraction(other)
  130. return self
  131. def __and__(self, other):
  132. """ Set-theoretical intersection. """
  133. return self.intersection(other)
  134. def __iand__(self, other):
  135. """ In-place set-theoretical intersection. """
  136. self.ip_intersection(other)
  137. return self
  138. def __or__(self, other):
  139. """ Set-theoretical union. """
  140. return self.union_(other)
  141. def __ior__(self, other):
  142. """ In-place set-theoretical union. """
  143. self.ip_union(other)
  144. return self
  145. def __xor__(self, other):
  146. """ Set-theoretical exclusive disjunction (XOR). """
  147. return self.xor(other)
  148. def __ixor__(self, other):
  149. """ In-place set-theoretical exclusive disjunction (XOR). """
  150. self.ip_xor(other)
  151. return self
  152. def __contains__(self, trp):
  153. """
  154. Whether the graph contains a triple.
  155. :rtype: boolean
  156. """
  157. cdef:
  158. Buffer ss, sp, so
  159. BufferTriple btrp
  160. btrp.s = &ss
  161. btrp.p = &sp
  162. btrp.o = &so
  163. s, p, o = trp
  164. term.serialize_from_rdflib(s, &ss)
  165. term.serialize_from_rdflib(p, &sp)
  166. term.serialize_from_rdflib(o, &so)
  167. return self.trp_contains(&btrp)
  168. def __iter__(self):
  169. """ Graph iterator. It iterates over the set triples. """
  170. yield from self.data
  171. # Slicing.
  172. def __getitem__(self, item):
  173. """
  174. Slicing function.
  175. It behaves similarly to `RDFLib graph slicing
  176. <https://rdflib.readthedocs.io/en/stable/utilities.html#slicing-graphs>`__
  177. """
  178. if isinstance(item, slice):
  179. s, p, o = item.start, item.stop, item.step
  180. return self._slice(s, p, o)
  181. else:
  182. raise TypeError(f'Wrong slice format: {item}.')
  183. def __hash__(self):
  184. return 23465
  185. ## BASIC PYTHON-ACCESSIBLE SET OPERATIONS ##
  186. def terms_by_type(self, type):
  187. """
  188. Get all terms of a type: subject, predicate or object.
  189. :param str type: One of ``s``, ``p`` or ``o``.
  190. """
  191. i = 'spo'.index(type)
  192. return {r[i] for r in self.data}
  193. def add(self, trp):
  194. """
  195. Add triples to the graph.
  196. :param iterable triples: iterable of 3-tuple triples.
  197. """
  198. cdef size_t cur = 0, trp_cur = 0
  199. trp_ct = len(trp)
  200. term_buf = <Buffer*>self.pool.alloc(3 * trp_ct, sizeof(Buffer))
  201. trp_buf = <BufferTriple*>self.pool.alloc(trp_ct, sizeof(BufferTriple))
  202. for s, p, o in trp:
  203. term.serialize_from_rdflib(s, term_buf + cur, self.pool)
  204. term.serialize_from_rdflib(p, term_buf + cur + 1, self.pool)
  205. term.serialize_from_rdflib(o, term_buf + cur + 2, self.pool)
  206. (trp_buf + trp_cur).s = term_buf + cur
  207. (trp_buf + trp_cur).p = term_buf + cur + 1
  208. (trp_buf + trp_cur).o = term_buf + cur + 2
  209. self.add_triple(trp_buf + trp_cur)
  210. trp_cur += 1
  211. cur += 3
  212. def len_terms(self):
  213. """ Number of terms in the graph. """
  214. return cc.hashset_size(self._terms)
  215. def remove(self, pattern):
  216. """
  217. Remove triples by pattern.
  218. The pattern used is similar to :py:meth:`LmdbTripleStore.delete`.
  219. """
  220. self._match_ptn_callback(
  221. pattern, self, cb.del_trp_callback, NULL
  222. )
  223. ## CYTHON-ACCESSIBLE BASIC METHODS ##
  224. cdef SimpleGraph empty_copy(self):
  225. """
  226. Create an empty copy carrying over some key properties.
  227. Override in subclasses to accommodate for different init properties.
  228. """
  229. return self.__class__()
  230. cpdef union_(self, SimpleGraph other):
  231. """
  232. Perform set union resulting in a new SimpleGraph instance.
  233. TODO Allow union of multiple graphs at a time.
  234. :param SimpleGraph other: The other graph to merge.
  235. :rtype: SimpleGraph
  236. :return: A new SimpleGraph instance.
  237. """
  238. cdef:
  239. void *cur
  240. cc.HashSetIter it
  241. BufferTriple *trp
  242. new_gr = self.empty_copy()
  243. for gr in (self, other):
  244. cc.hashset_iter_init(&it, gr._triples)
  245. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  246. bt = <BufferTriple*>cur
  247. new_gr.add_triple(bt, True)
  248. return new_gr
  249. cdef void ip_union(self, SimpleGraph other) except *:
  250. """
  251. Perform an in-place set union that adds triples to this instance
  252. TODO Allow union of multiple graphs at a time.
  253. :param SimpleGraph other: The other graph to merge.
  254. :rtype: void
  255. """
  256. cdef:
  257. void *cur
  258. cc.HashSetIter it
  259. cc.hashset_iter_init(&it, other._triples)
  260. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  261. bt = <BufferTriple*>cur
  262. self.add_triple(bt, True)
  263. cpdef intersection(self, SimpleGraph other):
  264. """
  265. Graph intersection.
  266. :param SimpleGraph other: The other graph to intersect.
  267. :rtype: SimpleGraph
  268. :return: A new SimpleGraph instance.
  269. """
  270. cdef:
  271. void *cur
  272. cc.HashSetIter it
  273. new_gr = self.empty_copy()
  274. cc.hashset_iter_init(&it, self._triples)
  275. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  276. bt = <BufferTriple*>cur
  277. if other.trp_contains(bt):
  278. new_gr.add_triple(bt, True)
  279. return new_gr
  280. cdef void ip_intersection(self, SimpleGraph other) except *:
  281. """
  282. In-place graph intersection.
  283. Triples not in common with another graph are removed from the current
  284. one.
  285. :param SimpleGraph other: The other graph to intersect.
  286. :rtype: void
  287. """
  288. cdef:
  289. void *cur
  290. cc.HashSetIter it
  291. cc.hashset_iter_init(&it, self._triples)
  292. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  293. bt = <BufferTriple*>cur
  294. if not other.trp_contains(bt):
  295. self.remove_triple(bt)
  296. cpdef subtraction(self, SimpleGraph other):
  297. """
  298. Graph set-theoretical subtraction.
  299. Create a new graph with the triples of this graph minus the ones in
  300. common with the other graph.
  301. :param SimpleGraph other: The other graph to subtract to this.
  302. :rtype: SimpleGraph
  303. :return: A new SimpleGraph instance.
  304. """
  305. cdef:
  306. void *cur
  307. cc.HashSetIter it
  308. new_gr = self.empty_copy()
  309. cc.hashset_iter_init(&it, self._triples)
  310. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  311. bt = <BufferTriple*>cur
  312. if not other.trp_contains(bt):
  313. new_gr.add_triple(bt, True)
  314. return new_gr
  315. cdef void ip_subtraction(self, SimpleGraph other) except *:
  316. """
  317. In-place graph subtraction.
  318. Triples in common with another graph are removed from the current one.
  319. :param SimpleGraph other: The other graph to intersect.
  320. :rtype: void
  321. """
  322. cdef:
  323. void *cur
  324. cc.HashSetIter it
  325. cc.hashset_iter_init(&it, self._triples)
  326. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  327. bt = <BufferTriple*>cur
  328. if other.trp_contains(bt):
  329. self.remove_triple(bt)
  330. cpdef xor(self, SimpleGraph other):
  331. """
  332. Graph Exclusive disjunction (XOR).
  333. :param SimpleGraph other: The other graph to perform XOR with.
  334. :rtype: SimpleGraph
  335. :return: A new SimpleGraph instance.
  336. """
  337. cdef:
  338. void *cur
  339. cc.HashSetIter it
  340. BufferTriple* bt
  341. new_gr = self.empty_copy()
  342. # Add triples in this and not in other.
  343. cc.hashset_iter_init(&it, self._triples)
  344. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  345. bt = <BufferTriple*>cur
  346. if not other.trp_contains(bt):
  347. new_gr.add_triple(bt, True)
  348. # Other way around.
  349. cc.hashset_iter_init(&it, other._triples)
  350. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  351. bt = <BufferTriple*>cur
  352. if not self.trp_contains(bt):
  353. new_gr.add_triple(bt, True)
  354. return new_gr
  355. cdef void ip_xor(self, SimpleGraph other) except *:
  356. """
  357. In-place graph XOR.
  358. Triples in common with another graph are removed from the current one,
  359. and triples not in common will be added from the other one.
  360. :param SimpleGraph other: The other graph to perform XOR with.
  361. :rtype: void
  362. """
  363. cdef:
  364. void *cur
  365. cc.HashSetIter it
  366. # TODO This could be more efficient to stash values in a simple
  367. # array, but how urgent is it to improve an in-place XOR?
  368. SimpleGraph tmp = SimpleGraph()
  369. # Add *to the tmp graph* triples in other graph and not in this graph.
  370. cc.hashset_iter_init(&it, other._triples)
  371. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  372. bt = <BufferTriple*>cur
  373. if not self.trp_contains(bt):
  374. tmp.add_triple(bt)
  375. # Remove triples in common.
  376. cc.hashset_iter_init(&it, self._triples)
  377. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  378. bt = <BufferTriple*>cur
  379. if other.trp_contains(bt):
  380. self.remove_triple(bt)
  381. self |= tmp
  382. cdef inline BufferTriple* store_triple(self, const BufferTriple* strp):
  383. """
  384. Store triple data in the graph.
  385. Normally, raw data underlying the triple and terms are only referenced
  386. by pointers. If the destination data are garbage collected before the
  387. graph is, segfaults are bound to happen.
  388. This method copies the data to the graph's memory pool, so they are
  389. managed with the lifecycle of the graph.
  390. Note that this method stores items regardless of whether thwy are
  391. duplicate or not, so there may be some duplication.
  392. """
  393. cdef:
  394. BufferTriple* dtrp = <BufferTriple*>self.pool.alloc(
  395. 1, sizeof(BufferTriple)
  396. )
  397. Buffer* spo = <Buffer*>self.pool.alloc(3, sizeof(Buffer))
  398. if not dtrp:
  399. raise MemoryError()
  400. if not spo:
  401. raise MemoryError()
  402. dtrp.s = spo
  403. dtrp.p = spo + 1
  404. dtrp.o = spo + 2
  405. spo[0].addr = self.pool.alloc(strp.s.sz, 1)
  406. spo[0].sz = strp.s.sz
  407. spo[1].addr = self.pool.alloc(strp.p.sz, 1)
  408. spo[1].sz = strp.p.sz
  409. spo[2].addr = self.pool.alloc(strp.o.sz, 1)
  410. spo[2].sz = strp.o.sz
  411. if not spo[0].addr or not spo[1].addr or not spo[2].addr:
  412. raise MemoryError()
  413. memcpy(dtrp.s.addr, strp.s.addr, strp.s.sz)
  414. memcpy(dtrp.p.addr, strp.p.addr, strp.p.sz)
  415. memcpy(dtrp.o.addr, strp.o.addr, strp.o.sz)
  416. return dtrp
  417. cdef inline void add_triple(
  418. self, const BufferTriple* trp, bint copy=False
  419. ) except *:
  420. """
  421. Add a triple from 3 (TPL) serialized terms.
  422. Each of the terms is added to the term set if not existing. The triple
  423. also is only added if not existing.
  424. :param BufferTriple* trp: The triple to add.
  425. :param bint copy: if ``True``, the triple and term data will be
  426. allocated and copied into the graph memory pool.
  427. """
  428. if copy:
  429. trp = self.store_triple(trp)
  430. cc.hashset_add(self._terms, trp.s)
  431. cc.hashset_add(self._terms, trp.p)
  432. cc.hashset_add(self._terms, trp.o)
  433. if cc.hashset_add(self._triples, trp) != cc.CC_OK:
  434. raise RuntimeError('Error inserting triple in graph.')
  435. cdef int remove_triple(self, const BufferTriple* btrp) except -1:
  436. """
  437. Remove one triple from the graph.
  438. """
  439. return cc.hashset_remove(self._triples, btrp, NULL)
  440. cdef bint trp_contains(self, const BufferTriple* btrp):
  441. cdef:
  442. cc.HashSetIter it
  443. void* cur
  444. cc.hashset_iter_init(&it, self._triples)
  445. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  446. if self.trp_cmp_fn(cur, btrp) == 0:
  447. return True
  448. return False
  449. cpdef void set(self, tuple trp) except *:
  450. """
  451. Set a single value for subject and predicate.
  452. Remove all triples matching ``s`` and ``p`` before adding ``s p o``.
  453. """
  454. if None in trp:
  455. raise ValueError(f'Invalid triple: {trp}')
  456. self.remove((trp[0], trp[1], None))
  457. self.add((trp,))
  458. def as_rdflib(self):
  459. """
  460. Return the data set as an RDFLib Graph.
  461. :rtype: rdflib.Graph
  462. """
  463. gr = Graph()
  464. for trp in self.data:
  465. gr.add(trp)
  466. return gr
  467. def _slice(self, s, p, o):
  468. """
  469. Return terms filtered by other terms.
  470. This behaves like the rdflib.Graph slicing policy.
  471. """
  472. # If no terms are unbound, check for containment.
  473. if s is not None and p is not None and o is not None: # s p o
  474. return (s, p, o) in self
  475. # If some terms are unbound, do a lookup.
  476. res = self.lookup((s, p, o))
  477. if s is not None:
  478. if p is not None: # s p ?
  479. return {r[2] for r in res}
  480. if o is not None: # s ? o
  481. return {r[1] for r in res}
  482. # s ? ?
  483. return {(r[1], r[2]) for r in res}
  484. if p is not None:
  485. if o is not None: # ? p o
  486. return {r[0] for r in res}
  487. # ? p ?
  488. return {(r[0], r[2]) for r in res}
  489. if o is not None: # ? ? o
  490. return {(r[0], r[1]) for r in res}
  491. # ? ? ?
  492. return res
  493. def lookup(self, pattern):
  494. """
  495. Look up triples by a pattern.
  496. This function converts RDFLib terms into the serialized format stored
  497. in the graph's internal structure and compares them bytewise.
  498. Any and all of the lookup terms msy be ``None``.
  499. :rtype: SimpleGraph
  500. "return: New SimpleGraph instance with matching triples.
  501. """
  502. cdef:
  503. void* cur
  504. BufferTriple trp
  505. SimpleGraph res_gr = SimpleGraph()
  506. self._match_ptn_callback(pattern, res_gr, cb.add_trp_callback, NULL)
  507. return res_gr
  508. cdef void _match_ptn_callback(
  509. self, pattern, SimpleGraph gr,
  510. lookup_callback_fn_t callback_fn, void* ctx=NULL
  511. ) except *:
  512. """
  513. Execute an arbitrary function on a list of triples matching a pattern.
  514. The arbitrary function is appied to each triple found in the current
  515. graph, and to a discrete graph that can be the current graph itself
  516. or a different one.
  517. """
  518. cdef:
  519. void* cur
  520. Buffer t1, t2
  521. Buffer ss, sp, so
  522. BufferTriple trp
  523. BufferTriple* trp_p
  524. lookup_fn_t cmp_fn
  525. cc.HashSetIter it
  526. s, p, o = pattern
  527. # Decide comparison logic outside the loop.
  528. if s is not None and p is not None and o is not None:
  529. # Shortcut for 3-term match.
  530. trp.s = &ss
  531. trp.p = &sp
  532. trp.o = &so
  533. term.serialize_from_rdflib(s, trp.s, self.pool)
  534. term.serialize_from_rdflib(p, trp.p, self.pool)
  535. term.serialize_from_rdflib(o, trp.o, self.pool)
  536. if cc.hashset_contains(self._triples, &trp):
  537. callback_fn(gr, &trp, ctx)
  538. return
  539. if s is not None:
  540. term.serialize_from_rdflib(s, &t1)
  541. if p is not None:
  542. cmp_fn = cb.lookup_sp_cmp_fn
  543. term.serialize_from_rdflib(p, &t2)
  544. elif o is not None:
  545. cmp_fn = cb.lookup_so_cmp_fn
  546. term.serialize_from_rdflib(o, &t2)
  547. else:
  548. cmp_fn = cb.lookup_s_cmp_fn
  549. elif p is not None:
  550. term.serialize_from_rdflib(p, &t1)
  551. if o is not None:
  552. cmp_fn = cb.lookup_po_cmp_fn
  553. term.serialize_from_rdflib(o, &t2)
  554. else:
  555. cmp_fn = cb.lookup_p_cmp_fn
  556. elif o is not None:
  557. cmp_fn = cb.lookup_o_cmp_fn
  558. term.serialize_from_rdflib(o, &t1)
  559. else:
  560. cmp_fn = cb.lookup_none_cmp_fn
  561. # Iterate over serialized triples.
  562. cc.hashset_iter_init(&it, self._triples)
  563. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  564. trp_p = <BufferTriple*>cur
  565. if cmp_fn(trp_p, &t1, &t2):
  566. callback_fn(gr, trp_p, ctx)
  567. cdef class Imr(SimpleGraph):
  568. """
  569. In-memory resource data container.
  570. This is an extension of :py:class:`~SimpleGraph` that adds a subject URI to
  571. the data set and some convenience methods.
  572. An instance of this class can be converted to a ``rdflib.Resource``
  573. instance.
  574. Some set operations that produce a new object (``-``, ``|``, ``&``, ``^``)
  575. will create a new ``Imr`` instance with the same subject URI.
  576. """
  577. def __init__(self, uri, *args, **kwargs):
  578. """
  579. Initialize the graph with pre-existing data or by looking up a store.
  580. Either ``data``, or ``lookup`` *and* ``store``, can be provide.
  581. ``lookup`` and ``store`` have precedence. If none of them is specified,
  582. an empty graph is initialized.
  583. :param rdflib.URIRef uri: The graph URI.
  584. This will serve as the subject for some queries.
  585. :param args: Positional arguments inherited from
  586. ``SimpleGraph.__init__``.
  587. :param kwargs: Keyword arguments inherited from
  588. ``SimpleGraph.__init__``.
  589. """
  590. self.id = str(uri)
  591. #super().__init(*args, **kwargs)
  592. def __repr__(self):
  593. """
  594. String representation of an Imr.
  595. This includes the subject URI, number of triples contained and the
  596. memory address of the instance.
  597. """
  598. return (f'<{self.__class__.__name__} @{hex(id(self))} id={self.id}, '
  599. f'length={len(self)}>')
  600. def __getitem__(self, item):
  601. """
  602. Supports slicing notation.
  603. """
  604. if isinstance(item, slice):
  605. s, p, o = item.start, item.stop, item.step
  606. return self._slice(s, p, o)
  607. elif isinstance(item, Node):
  608. # If a Node is given, return all values for that predicate.
  609. return self._slice(self.uri, item, None)
  610. else:
  611. raise TypeError(f'Wrong slice format: {item}.')
  612. @property
  613. def uri(self):
  614. """
  615. Get resource identifier as a RDFLib URIRef.
  616. :rtype: rdflib.URIRef.
  617. """
  618. return URIRef(self.id)
  619. cdef Imr empty_copy(self):
  620. """
  621. Create an empty instance carrying over some key properties.
  622. """
  623. return self.__class__(uri=self.id)
  624. def value(self, p, strict=False):
  625. """
  626. Get an individual value.
  627. :param rdflib.termNode p: Predicate to search for.
  628. :param bool strict: If set to ``True`` the method raises an error if
  629. more than one value is found. If ``False`` (the default) only
  630. the first found result is returned.
  631. :rtype: rdflib.term.Node
  632. """
  633. # TODO use slice.
  634. values = {trp[2] for trp in self.lookup((self.uri, p, None))}
  635. if strict and len(values) > 1:
  636. raise RuntimeError('More than one value found for {}, {}.'.format(
  637. self.id, p))
  638. for ret in values:
  639. return ret
  640. return None
  641. cpdef as_rdflib(self):
  642. """
  643. Return the IMR as a RDFLib Resource.
  644. :rtype: rdflib.Resource
  645. """
  646. gr = Graph()
  647. for trp in self.data:
  648. gr.add(trp)
  649. return gr.resource(identifier=self.uri)