graph.pyx 26 KB

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