graph.pyx 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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.cy_include cimport spookyhash as sph
  13. from lakesuperior.model.graph cimport term
  14. from lakesuperior.store.ldp_rs.lmdb_triplestore cimport (
  15. KLEN, DBL_KLEN, TRP_KLEN, TripleKey)
  16. from lakesuperior.model.structures.hash cimport term_hash_seed32
  17. from lakesuperior.model.structures.keyset cimport Keyset
  18. from lakesuperior.model.base cimport Buffer
  19. from lakesuperior.model.graph.triple cimport BufferTriple
  20. from lakesuperior.model.structures.hash cimport hash64
  21. cdef extern from 'spookyhash_api.h':
  22. uint64_t spookyhash_64(const void *input, size_t input_size, uint64_t seed)
  23. logger = logging.getLogger(__name__)
  24. cdef int term_cmp_fn(const void* key1, const void* key2):
  25. """
  26. Compare function for two Buffer objects.
  27. :rtype: int
  28. :return: 0 if the byte streams are the same, another integer otherwise.
  29. """
  30. b1 = <Buffer *>key1
  31. b2 = <Buffer *>key2
  32. if b1.sz != b2.sz:
  33. logger.info(f'Sizes differ: {b1.sz} != {b2.sz}. Return 1.')
  34. return 1
  35. cdef int cmp = memcmp(b1.addr, b2.addr, b1.sz)
  36. logger.info(f'term memcmp: {cmp}')
  37. return cmp
  38. cdef int trp_lit_cmp_fn(const void* key1, const void* key2):
  39. """
  40. Compare function for two triples in a set.
  41. s, p, o byte data are compared literally.
  42. :rtype: int
  43. :return: 0 if all three terms point to byte-wise identical data in both
  44. triples.
  45. """
  46. t1 = <BufferTriple *>key1
  47. t2 = <BufferTriple *>key2
  48. diff = (
  49. term_cmp_fn(t1.o, t2.o) or
  50. term_cmp_fn(t1.s, t2.s) or
  51. term_cmp_fn(t1.p, t2.p)
  52. )
  53. logger.info(f'Triples match: {not(diff)}')
  54. return diff
  55. cdef int trp_cmp_fn(const void* key1, const void* key2):
  56. """
  57. Compare function for two triples in a 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. :rtype: int
  62. :return: 0 if the addresses of all terms are the same, 1 otherwise.
  63. """
  64. t1 = <BufferTriple *>key1
  65. t2 = <BufferTriple *>key2
  66. cdef int is_not_equal = (
  67. t1.s.addr != t2.s.addr or
  68. t1.p.addr != t2.p.addr or
  69. t1.o.addr != t2.o.addr
  70. )
  71. logger.info(f'Triples match: {not(is_not_equal)}')
  72. return is_not_equal
  73. cdef bint graph_eq_fn(SimpleGraph g1, SimpleGraph g2):
  74. """
  75. Compare 2 graphs for equality.
  76. Note that this returns the opposite value than the triple and term
  77. compare functions: 1 (True) if equal, 0 (False) if not.
  78. """
  79. cdef:
  80. void* el
  81. cc.HashSetIter it
  82. cc.hashset_iter_init(&it, g1._triples)
  83. while cc.hashset_iter_next(&it, &el) != cc.CC_ITER_END:
  84. if cc.hashset_contains(g2._triples, el):
  85. return False
  86. return True
  87. cdef size_t term_hash_fn(const void* key, int l, uint32_t seed):
  88. """
  89. Hash function for serialized terms (:py:class:`Buffer` objects)
  90. """
  91. return <size_t>spookyhash_64((<Buffer*>key).addr, (<Buffer*>key).sz, seed)
  92. cdef size_t trp_lit_hash_fn(const void* key, int l, uint32_t seed):
  93. """
  94. Hash function for sets of (serialized) triples.
  95. This function concatenates the literal terms of the triple as bytes
  96. and computes their hash.
  97. """
  98. trp = <BufferTriple*>key
  99. seed64 = <uint64_t>seed
  100. seed_dummy = seed64
  101. cdef sph.spookyhash_context ctx
  102. sph.spookyhash_context_init(&ctx, seed64, seed_dummy)
  103. sph.spookyhash_update(&ctx, trp.s.addr, trp.s.sz)
  104. sph.spookyhash_update(&ctx, trp.s.addr, trp.p.sz)
  105. sph.spookyhash_update(&ctx, trp.s.addr, trp.o.sz)
  106. sph.spookyhash_final(&ctx, &seed64, &seed_dummy)
  107. return <size_t>seed64
  108. cdef size_t trp_hash_fn(const void* key, int l, uint32_t seed):
  109. """
  110. Hash function for sets of (serialized) triples.
  111. This function computes the hash of the concatenated pointer values in the
  112. s, p, o members of the triple. The triple structure is treated as a byte
  113. string. This is safe in spite of byte-wise struct evaluation being a
  114. frowned-upon practice (due to padding issues), because it is assumed that
  115. the input value is always the same type of structure.
  116. """
  117. return <size_t>spookyhash_64(key, l, seed)
  118. cdef size_t hash_ptr_passthrough(const void* key, int l, uint32_t seed):
  119. """
  120. No-op function that takes a pointer and does *not* hash it.
  121. The pointer value is used as the "hash".
  122. """
  123. return <size_t>key
  124. cdef inline bint lookup_none_cmp_fn(
  125. const BufferTriple *trp, const Buffer *t1, const Buffer *t2
  126. ):
  127. """
  128. Dummy callback for queries with all parameters unbound.
  129. This function always returns ``True``
  130. """
  131. return True
  132. cdef inline bint lookup_s_cmp_fn(
  133. const BufferTriple *trp, const Buffer *t1, const Buffer *t2
  134. ):
  135. """
  136. Lookup callback compare function for a given s in a triple.
  137. The function returns ``True`` if ``t1`` matches the first term.
  138. ``t2`` is not used and is declared only for compatibility with the
  139. other interchangeable functions.
  140. """
  141. return term_cmp_fn(t1, trp[0].s)
  142. cdef inline bint lookup_p_cmp_fn(
  143. const BufferTriple *trp, const Buffer *t1, const Buffer *t2
  144. ):
  145. return term_cmp_fn(t1, trp[0].p)
  146. cdef inline bint lookup_o_cmp_fn(
  147. const BufferTriple *trp, const Buffer *t1, const Buffer *t2
  148. ):
  149. return term_cmp_fn(t1, trp[0].o)
  150. cdef inline bint lookup_sp_cmp_fn(
  151. const BufferTriple *trp, const Buffer *t1, const Buffer *t2
  152. ):
  153. return (
  154. term_cmp_fn(t1, trp[0].s)
  155. and term_cmp_fn(t2, trp[0].p))
  156. cdef inline bint lookup_so_cmp_fn(
  157. const BufferTriple *trp, const Buffer *t1, const Buffer *t2
  158. ):
  159. return (
  160. term_cmp_fn(t1, trp[0].s)
  161. and term_cmp_fn(t2, trp[0].o))
  162. cdef inline bint lookup_po_cmp_fn(
  163. const BufferTriple *trp, const Buffer *t1, const Buffer *t2
  164. ):
  165. return (
  166. term_cmp_fn(t1, trp[0].p)
  167. and term_cmp_fn(t2, trp[0].o))
  168. cdef class SimpleGraph:
  169. """
  170. Fast and simple implementation of a graph.
  171. Most functions should mimic RDFLib's graph with less overhead. It uses
  172. the same funny but functional slicing notation.
  173. A SimpleGraph can be instantiated from a store lookup or obtained from a
  174. :py:class:`lakesuperior.store.keyset.Keyset`. This makes it possible to use
  175. a Keyset to perform initial filtering via identity by key, then the
  176. filtered Keyset can be converted into a set of meaningful terms.
  177. An instance of this class can also be converted to and from a
  178. ``rdflib.Graph`` instance.
  179. """
  180. def __cinit__(
  181. self, lookup=None, Keyset keyset=None, store=None,
  182. set data=set(), *args, **kwargs
  183. ):
  184. """
  185. Initialize the graph with pre-existing data or by looking up a store.
  186. One of ``keyset``, or ``data`` can be provided. If more than
  187. one of these is provided, precedence is given in the mentioned order.
  188. If none of them is specified, an empty graph is initialized.
  189. :param rdflib.URIRef uri: The graph URI.
  190. This will serve as the subject for some queries.
  191. :param Keyset keyset: Keyset to create the graph from. Keys will be
  192. converted to set elements.
  193. :param lakesuperior.store.ldp_rs.LmdbTripleStore store: store to
  194. look up the keyset. It is used if ``keyset`` is specified on init
  195. or if the :py:meth:`_data_from_keyset` or
  196. :py:meth:`_data_from_lookup` methods are used later. If not
  197. set, the environment store is used.
  198. :param set data: Initial data as a set of 3-tuples of RDFLib terms.
  199. :param tuple lookup: tuple of a 3-tuple of lookup terms, and a context.
  200. E.g. ``((URIRef('urn:ns:a'), None, None), URIRef('urn:ns:ctx'))``.
  201. Any and all elements may be ``None``.
  202. :param lmdbStore store: the store to look data up.
  203. """
  204. cdef:
  205. cc.HashSetConf terms_conf, trp_conf
  206. self.term_cmp_fn = &term_cmp_fn
  207. self.trp_cmp_fn = &trp_lit_cmp_fn
  208. cc.hashset_conf_init(&terms_conf)
  209. terms_conf.load_factor = 0.85
  210. terms_conf.hash = &term_hash_fn
  211. terms_conf.hash_seed = term_hash_seed32
  212. terms_conf.key_compare = self.term_cmp_fn
  213. terms_conf.key_length = sizeof(Buffer*)
  214. cc.hashset_conf_init(&trp_conf)
  215. trp_conf.load_factor = 0.75
  216. trp_conf.hash = &trp_lit_hash_fn
  217. trp_conf.hash_seed = term_hash_seed32
  218. trp_conf.key_compare = self.trp_cmp_fn
  219. trp_conf.key_length = sizeof(BufferTriple)
  220. cc.hashset_new_conf(&terms_conf, &self._terms)
  221. cc.hashset_new_conf(&trp_conf, &self._triples)
  222. self.store = store or env.app_globals.rdf_store
  223. self._pool = Pool()
  224. # Initialize empty data set.
  225. if keyset:
  226. # Populate with triples extracted from provided key set.
  227. self._data_from_keyset(keyset)
  228. elif data:
  229. # Populate with provided Python set.
  230. self.add(data)
  231. elif lookup:
  232. # Populate via store lookup.
  233. spo = lookup[:3]
  234. # If lookup has 4 elements, it's a spoc.
  235. c = lookup[3] if len(lookup) > 3 else None
  236. self._data_from_lookup(spo, c)
  237. def __dealloc__(self):
  238. """
  239. Free the triple pointers.
  240. """
  241. free(self._triples)
  242. free(self._terms)
  243. @property
  244. def data(self):
  245. """
  246. Triple data as a Python set.
  247. :rtype: set
  248. """
  249. return self._to_pyset()
  250. @property
  251. def terms(self):
  252. return self._get_terms()
  253. # # # BASIC SET OPERATIONS # # #
  254. def add(self, trp):
  255. """
  256. Add triples to the graph.
  257. :param iterable triples: Set, list or tuple of 3-tuple triples.
  258. """
  259. cdef size_t cur = 0, trp_cur = 0
  260. trp_ct = len(trp)
  261. term_buf = <Buffer*>self._pool.alloc(3 * trp_ct, sizeof(Buffer))
  262. trp_buf = <BufferTriple*>self._pool.alloc(trp_ct, sizeof(BufferTriple))
  263. for s, p, o in trp:
  264. term.serialize_from_rdflib(s, term_buf + cur, self._pool)
  265. term.serialize_from_rdflib(p, term_buf + cur + 1, self._pool)
  266. term.serialize_from_rdflib(o, term_buf + cur + 2, self._pool)
  267. (trp_buf + trp_cur).s = term_buf + cur
  268. (trp_buf + trp_cur).p = term_buf + cur + 1
  269. (trp_buf + trp_cur).o = term_buf + cur + 2
  270. self._add_triple(trp_buf + trp_cur)
  271. trp_cur += 1
  272. cur += 3
  273. def len_terms(self):
  274. """ Number of triples in the graph. """
  275. return cc.hashset_size(self._terms)
  276. def remove(self, trp):
  277. """
  278. Remove one item from the graph.
  279. :param tuple item: A 3-tuple of RDFlib terms. Only exact terms, i.e.
  280. wildcards are not accepted.
  281. """
  282. cdef:
  283. Buffer ss, sp, so
  284. BufferTriple trp_buf
  285. term.serialize_from_rdflib(trp[0], &ss, self._pool)
  286. term.serialize_from_rdflib(trp[1], &sp, self._pool)
  287. term.serialize_from_rdflib(trp[2], &so, self._pool)
  288. trp_buf.s = &ss
  289. trp_buf.p = &sp
  290. trp_buf.o = &so
  291. self._remove_triple(&trp_buf)
  292. def __len__(self):
  293. """ Number of triples in the graph. """
  294. return cc.hashset_size(self._triples)
  295. def __eq__(self, other):
  296. """ Equality operator between ``SimpleGraph`` instances. """
  297. return len(self ^ other) == 0
  298. def __repr__(self):
  299. """
  300. String representation of the graph.
  301. It provides the number of triples in the graph and memory address of
  302. the instance.
  303. """
  304. return (
  305. f'<{self.__class__.__name__} @{hex(id(self))} '
  306. f'length={len(self.data)}>'
  307. )
  308. def __str__(self):
  309. """ String dump of the graph triples. """
  310. return str(self.data)
  311. def __add__(self, other):
  312. """ Alias for set-theoretical union. """
  313. return self.union_(other)
  314. def __iadd__(self, other):
  315. """ Alias for in-place set-theoretical union. """
  316. self.ip_union(other)
  317. return self
  318. def __sub__(self, other):
  319. """ Set-theoretical subtraction. """
  320. return self.subtraction(other)
  321. def __isub__(self, other):
  322. """ In-place set-theoretical subtraction. """
  323. self.ip_subtraction(other)
  324. return self
  325. def __and__(self, other):
  326. """ Set-theoretical intersection. """
  327. return self.intersection(other)
  328. def __iand__(self, other):
  329. """ In-place set-theoretical intersection. """
  330. self.ip_intersection(other)
  331. return self
  332. def __or__(self, other):
  333. """ Set-theoretical union. """
  334. return self.union_(other)
  335. def __ior__(self, other):
  336. """ In-place set-theoretical union. """
  337. self.ip_union(other)
  338. return self
  339. def __xor__(self, other):
  340. """ Set-theoretical exclusive disjunction (XOR). """
  341. return self.xor(other)
  342. def __ixor__(self, other):
  343. """ In-place set-theoretical exclusive disjunction (XOR). """
  344. self.ip_xor(other)
  345. return self
  346. def __contains__(self, trp):
  347. """
  348. Whether the graph contains a triple.
  349. :rtype: boolean
  350. """
  351. cdef:
  352. Buffer ss, sp, so
  353. BufferTriple btrp
  354. btrp.s = &ss
  355. btrp.p = &sp
  356. btrp.o = &so
  357. s, p, o = trp
  358. term.serialize_from_rdflib(s, &ss)
  359. term.serialize_from_rdflib(p, &sp)
  360. term.serialize_from_rdflib(o, &so)
  361. return self._trp_contains(&btrp)
  362. def __iter__(self):
  363. """ Graph iterator. It iterates over the set triples. """
  364. raise NotImplementedError()
  365. # Slicing.
  366. def __getitem__(self, item):
  367. """
  368. Slicing function.
  369. It behaves similarly to `RDFLib graph slicing
  370. <https://rdflib.readthedocs.io/en/stable/utilities.html#slicing-graphs>`__
  371. """
  372. if isinstance(item, slice):
  373. s, p, o = item.start, item.stop, item.step
  374. return self._slice(s, p, o)
  375. else:
  376. raise TypeError(f'Wrong slice format: {item}.')
  377. def __hash__(self):
  378. return 23465
  379. # Cython counterparts to basic methods.
  380. cdef SimpleGraph empty_copy(self):
  381. """
  382. Create an empty copy carrying over some key properties.
  383. Override in subclasses to accommodate for different init properties.
  384. """
  385. with self.store.txn_ctx():
  386. return self.__class__(store=self.store)
  387. cpdef union_(self, SimpleGraph other):
  388. """
  389. Perform set union resulting in a new SimpleGraph instance.
  390. TODO Allow union of multiple graphs at a time.
  391. :param SimpleGraph other: The other graph to merge.
  392. :rtype: SimpleGraph
  393. :return: A new SimpleGraph instance.
  394. """
  395. cdef:
  396. void *cur
  397. cc.HashSetIter it
  398. BufferTriple *trp
  399. new_gr = self.empty_copy()
  400. for gr in (self, other):
  401. cc.hashset_iter_init(&it, gr._triples)
  402. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  403. bt = <BufferTriple*>cur
  404. new_gr._add_triple(bt)
  405. return new_gr
  406. cdef void ip_union(self, SimpleGraph other) except *:
  407. """
  408. Perform an in-place set union that adds triples to this instance
  409. TODO Allow union of multiple graphs at a time.
  410. :param SimpleGraph other: The other graph to merge.
  411. :rtype: void
  412. """
  413. cdef:
  414. void *cur
  415. cc.HashSetIter it
  416. cc.hashset_iter_init(&it, other._triples)
  417. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  418. bt = <BufferTriple*>cur
  419. self._add_triple(bt)
  420. cpdef intersection(self, SimpleGraph other):
  421. """
  422. Graph intersection.
  423. :param SimpleGraph other: The other graph to intersect.
  424. :rtype: SimpleGraph
  425. :return: A new SimpleGraph instance.
  426. """
  427. cdef:
  428. void *cur
  429. cc.HashSetIter it
  430. new_gr = self.empty_copy()
  431. cc.hashset_iter_init(&it, self._triples)
  432. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  433. bt = <BufferTriple*>cur
  434. #print('Checking: <0x{:02x}> <0x{:02x}> <0x{:02x}>'.format(
  435. # <size_t>bt.s, <size_t>bt.p, <size_t>bt.o))
  436. if other._trp_contains(bt):
  437. #print('Adding.')
  438. new_gr._add_triple(bt)
  439. return new_gr
  440. cdef void ip_intersection(self, SimpleGraph other) except *:
  441. """
  442. In-place graph intersection.
  443. Triples not in common with another graph are removed from the current
  444. one.
  445. :param SimpleGraph other: The other graph to intersect.
  446. :rtype: void
  447. """
  448. cdef:
  449. void *cur
  450. cc.HashSetIter it
  451. cc.hashset_iter_init(&it, self._triples)
  452. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  453. bt = <BufferTriple*>cur
  454. if not other._trp_contains(bt):
  455. self._remove_triple(bt)
  456. cpdef subtraction(self, SimpleGraph other):
  457. """
  458. Graph set-theoretical subtraction.
  459. Create a new graph with the triples of this graph minus the ones in
  460. common with the other graph.
  461. :param SimpleGraph other: The other graph to subtract to this.
  462. :rtype: SimpleGraph
  463. :return: A new SimpleGraph instance.
  464. """
  465. cdef:
  466. void *cur
  467. cc.HashSetIter it
  468. new_gr = self.empty_copy()
  469. cc.hashset_iter_init(&it, self._triples)
  470. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  471. bt = <BufferTriple*>cur
  472. #print('Checking: <0x{:02x}> <0x{:02x}> <0x{:02x}>'.format(
  473. # <size_t>bt.s, <size_t>bt.p, <size_t>bt.o))
  474. if not other._trp_contains(bt):
  475. #print('Adding.')
  476. new_gr._add_triple(bt)
  477. return new_gr
  478. cdef void ip_subtraction(self, SimpleGraph other) except *:
  479. """
  480. In-place graph subtraction.
  481. Triples in common with another graph are removed from the current one.
  482. :param SimpleGraph other: The other graph to intersect.
  483. :rtype: void
  484. """
  485. cdef:
  486. void *cur
  487. cc.HashSetIter it
  488. cc.hashset_iter_init(&it, self._triples)
  489. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  490. bt = <BufferTriple*>cur
  491. if other._trp_contains(bt):
  492. self._remove_triple(bt)
  493. cpdef xor(self, SimpleGraph other):
  494. """
  495. Graph Exclusive disjunction (XOR).
  496. :param SimpleGraph other: The other graph to perform XOR with.
  497. :rtype: SimpleGraph
  498. :return: A new SimpleGraph instance.
  499. """
  500. cdef:
  501. void *cur
  502. cc.HashSetIter it
  503. BufferTriple* bt
  504. new_gr = self.empty_copy()
  505. # Add triples in this and not in other.
  506. cc.hashset_iter_init(&it, self._triples)
  507. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  508. bt = <BufferTriple*>cur
  509. if not other._trp_contains(bt):
  510. new_gr._add_triple(bt)
  511. # Other way around.
  512. cc.hashset_iter_init(&it, other._triples)
  513. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  514. bt = <BufferTriple*>cur
  515. if not self._trp_contains(bt):
  516. new_gr._add_triple(bt)
  517. return new_gr
  518. cdef void ip_xor(self, SimpleGraph other) except *:
  519. """
  520. In-place graph XOR.
  521. Triples in common with another graph are removed from the current one,
  522. and triples not in common will be added from the other one.
  523. :param SimpleGraph other: The other graph to perform XOR with.
  524. :rtype: void
  525. """
  526. cdef:
  527. void *cur
  528. cc.HashSetIter it
  529. # TODO This could be more efficient to stash values in a simple
  530. # array, but how urgent is it to improve an in-place XOR?
  531. SimpleGraph tmp = SimpleGraph()
  532. # Add *to the tmp graph* triples in other graph and not in this graph.
  533. cc.hashset_iter_init(&it, other._triples)
  534. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  535. bt = <BufferTriple*>cur
  536. if not self._trp_contains(bt):
  537. tmp._add_triple(bt)
  538. # Remove triples in common.
  539. cc.hashset_iter_init(&it, self._triples)
  540. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  541. bt = <BufferTriple*>cur
  542. if other._trp_contains(bt):
  543. print(self._remove_triple(bt))
  544. self |= tmp
  545. cdef void _data_from_lookup(self, tuple trp_ptn, ctx=None) except *:
  546. """
  547. Look up triples in the triplestore and load them into ``data``.
  548. :param tuple lookup: 3-tuple of RDFlib terms or ``None``.
  549. :param LmdbTriplestore store: Reference to a LMDB triplestore. This
  550. is normally set to ``lakesuperior.env.app_globals.rdf_store``.
  551. """
  552. cdef:
  553. size_t i
  554. unsigned char spok[TRP_KLEN]
  555. with self.store.txn_ctx():
  556. keyset = self.store.triple_keys(trp_ptn, ctx)
  557. self._data_from_keyset(keyset)
  558. cdef void _data_from_keyset(self, Keyset data) except *:
  559. """Populate a graph from a Keyset."""
  560. cdef TripleKey spok
  561. while data.next(spok):
  562. self._add_from_spok(spok)
  563. cdef inline void _add_from_spok(self, TripleKey spok) except *:
  564. """
  565. Add a triple from a TripleKey of term keys.
  566. """
  567. s_spo = <SPOBuffer>self._pool.alloc(3, sizeof(Buffer))
  568. print('SPO: {}'.format((<unsigned char*>spok)[:TRP_KLEN]))
  569. self.store.lookup_term(spok, s_spo)
  570. self.store.lookup_term(spok + KLEN, s_spo + 1)
  571. self.store.lookup_term(spok + DBL_KLEN, s_spo + 2)
  572. trp = <BufferTriple *>self._pool.alloc(1, sizeof(BufferTriple))
  573. trp.s = s_spo
  574. trp.p = s_spo + 1
  575. trp.o = s_spo + 2
  576. self._add_triple(trp)
  577. cdef inline void _add_triple(self, BufferTriple* trp) except *:
  578. """
  579. Add a triple from 3 (TPL) serialized terms.
  580. Each of the terms is added to the term set if not existing. The triple
  581. also is only added if not existing.
  582. """
  583. logger.info('Inserting terms.')
  584. cc.hashset_add(self._terms, trp.s)
  585. cc.hashset_add(self._terms, trp.p)
  586. cc.hashset_add(self._terms, trp.o)
  587. logger.info('inserted terms.')
  588. logger.info(f'Terms set size: {cc.hashset_size(self._terms)}')
  589. cdef size_t trp_sz = cc.hashset_size(self._triples)
  590. logger.info(f'Triples set size before adding: {trp_sz}')
  591. r = cc.hashset_add(self._triples, trp)
  592. #print('Insert triple result:')
  593. #print(r)
  594. trp_sz = cc.hashset_size(self._triples)
  595. logger.info(f'Triples set size after adding: {trp_sz}')
  596. cdef:
  597. cc.HashSetIter ti
  598. void *cur
  599. cdef int _remove_triple(self, BufferTriple* btrp) except -1:
  600. """
  601. Remove one triple from the graph.
  602. """
  603. return cc.hashset_remove(self._triples, btrp, NULL)
  604. cdef bint _trp_contains(self, BufferTriple* btrp):
  605. cdef:
  606. cc.HashSetIter it
  607. void* cur
  608. cc.hashset_iter_init(&it, self._triples)
  609. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  610. if self.trp_cmp_fn(cur, btrp) == 0:
  611. return True
  612. return False
  613. cdef _get_terms(self):
  614. """
  615. Get all terms in the graph.
  616. """
  617. cdef:
  618. cc.HashSetIter it
  619. void *cur
  620. terms = [] # This is intentionally a list to spot issues with the set.
  621. cc.hashset_iter_init(&it, self._terms)
  622. while cc.hashset_iter_next(&it, &cur) != cc.CC_ITER_END:
  623. s_term = <Buffer*>cur
  624. terms.append((f'0x{<size_t>cur:02x}', term.deserialize_to_rdflib(s_term)))
  625. return terms
  626. cdef set _to_pyset(self):
  627. """
  628. Convert triple data to a Python set.
  629. :rtype: set
  630. """
  631. cdef:
  632. void *void_p
  633. cc.HashSetIter ti
  634. term.Term s, p, o
  635. graph_set = set()
  636. # Looping over an empty HashSet results in a segfault. Exit early in
  637. # that case.
  638. #if not cc.hashset_size(self._triples):
  639. # return graph_set
  640. cc.hashset_iter_init(&ti, self._triples)
  641. while cc.hashset_iter_next(&ti, &void_p) != cc.CC_ITER_END:
  642. if void_p == NULL:
  643. logger.warn('Triple is NULL!')
  644. break
  645. trp = <BufferTriple *>void_p
  646. graph_set.add((
  647. term.deserialize_to_rdflib(trp.s),
  648. term.deserialize_to_rdflib(trp.p),
  649. term.deserialize_to_rdflib(trp.o),
  650. ))
  651. return graph_set
  652. cpdef void set(self, tuple trp) except *:
  653. """
  654. Set a single value for subject and predicate.
  655. Remove all triples matching ``s`` and ``p`` before adding ``s p o``.
  656. """
  657. if None in trp:
  658. raise ValueError(f'Invalid triple: {trp}')
  659. self.remove_triples((trp[0], trp[1], None))
  660. self.add((trp,))
  661. cpdef void remove_triples(self, pattern) except *:
  662. """
  663. Remove triples by pattern.
  664. The pattern used is similar to :py:meth:`LmdbTripleStore.delete`.
  665. """
  666. s, p, o = pattern
  667. for match in self.lookup(s, p, o):
  668. logger.debug(f'Removing from graph: {match}.')
  669. self.data.remove(match)
  670. cpdef object as_rdflib(self):
  671. """
  672. Return the data set as an RDFLib Graph.
  673. :rtype: rdflib.Graph
  674. """
  675. gr = Graph()
  676. for trp in self.data:
  677. gr.add(trp)
  678. return gr
  679. def _slice(self, s, p, o):
  680. """
  681. Return terms filtered by other terms.
  682. This behaves like the rdflib.Graph slicing policy.
  683. """
  684. _data = self.data
  685. logger.debug(f'Slicing graph by: {s}, {p}, {o}.')
  686. if s is None and p is None and o is None:
  687. return _data
  688. elif s is None and p is None:
  689. return {(r[0], r[1]) for r in _data if r[2] == o}
  690. elif s is None and o is None:
  691. return {(r[0], r[2]) for r in _data if r[1] == p}
  692. elif p is None and o is None:
  693. return {(r[1], r[2]) for r in _data if r[0] == s}
  694. elif s is None:
  695. return {r[0] for r in _data if r[1] == p and r[2] == o}
  696. elif p is None:
  697. return {r[1] for r in _data if r[0] == s and r[2] == o}
  698. elif o is None:
  699. return {r[2] for r in _data if r[0] == s and r[1] == p}
  700. else:
  701. # all given
  702. return (s,p,o) in _data
  703. def lookup(self, s, p, o):
  704. """
  705. Look up triples by a pattern.
  706. This function converts RDFLib terms into the serialized format stored
  707. in the graph's internal structure and compares them bytewise.
  708. Any and all of the lookup terms can be ``None``.
  709. """
  710. cdef:
  711. void *void_p
  712. BufferTriple trp
  713. BufferTriple *trp_p
  714. cc.HashSetIter ti
  715. Buffer t1
  716. Buffer t2
  717. lookup_fn_t fn
  718. res = set()
  719. # Decide comparison logic outside the loop.
  720. if s is not None and p is not None and o is not None:
  721. # Return immediately if 3-term match is requested.
  722. term.serialize_from_rdflib(s, trp.s, self._pool)
  723. term.serialize_from_rdflib(p, trp.p, self._pool)
  724. term.serialize_from_rdflib(o, trp.o, self._pool)
  725. if cc.hashset_contains(self._triples, &trp):
  726. res.add((s, p, o))
  727. return res
  728. elif s is not None:
  729. term.serialize_from_rdflib(s, &t1)
  730. if p is not None:
  731. fn = lookup_sp_cmp_fn
  732. term.serialize_from_rdflib(p, &t2)
  733. elif o is not None:
  734. fn = lookup_so_cmp_fn
  735. term.serialize_from_rdflib(o, &t2)
  736. else:
  737. fn = lookup_s_cmp_fn
  738. elif p is not None:
  739. term.serialize_from_rdflib(p, &t1)
  740. if o is not None:
  741. fn = lookup_po_cmp_fn
  742. term.serialize_from_rdflib(o, &t2)
  743. else:
  744. fn = lookup_p_cmp_fn
  745. elif o is not None:
  746. fn = lookup_o_cmp_fn
  747. term.serialize_from_rdflib(o, &t1)
  748. else:
  749. fn = lookup_none_cmp_fn
  750. # Iterate over serialized triples.
  751. cc.hashset_iter_init(&ti, self._triples)
  752. while cc.hashset_iter_next(&ti, &void_p) != cc.CC_ITER_END:
  753. if void_p == NULL:
  754. trp_p = <BufferTriple *>void_p
  755. res.add((
  756. term.deserialize_to_rdflib(trp_p[0].s),
  757. term.deserialize_to_rdflib(trp_p[0].p),
  758. term.deserialize_to_rdflib(trp_p[0].o),
  759. ))
  760. return res
  761. #cpdef set terms(self, str type):
  762. # """
  763. # Get all terms of a type: subject, predicate or object.
  764. # :param str type: One of ``s``, ``p`` or ``o``.
  765. # """
  766. # i = 'spo'.index(type)
  767. # return {r[i] for r in self.data}
  768. cdef class Imr(SimpleGraph):
  769. """
  770. In-memory resource data container.
  771. This is an extension of :py:class:`~SimpleGraph` that adds a subject URI to
  772. the data set and some convenience methods.
  773. An instance of this class can be converted to a ``rdflib.Resource``
  774. instance.
  775. Some set operations that produce a new object (``-``, ``|``, ``&``, ``^``)
  776. will create a new ``Imr`` instance with the same subject URI.
  777. """
  778. def __init__(self, uri, *args, **kwargs):
  779. """
  780. Initialize the graph with pre-existing data or by looking up a store.
  781. Either ``data``, or ``lookup`` *and* ``store``, can be provide.
  782. ``lookup`` and ``store`` have precedence. If none of them is specified,
  783. an empty graph is initialized.
  784. :param rdflib.URIRef uri: The graph URI.
  785. This will serve as the subject for some queries.
  786. :param args: Positional arguments inherited from
  787. ``SimpleGraph.__init__``.
  788. :param kwargs: Keyword arguments inherited from
  789. ``SimpleGraph.__init__``.
  790. """
  791. self.uri = str(uri)
  792. #super().__init(*args, **kwargs)
  793. @property
  794. def identifier(self):
  795. """
  796. IMR URI. For compatibility with RDFLib Resource.
  797. :rtype: string
  798. """
  799. return self.uri
  800. @property
  801. def graph(self):
  802. """
  803. Return a SimpleGraph with the same data.
  804. :rtype: SimpleGraph
  805. """
  806. raise NotImplementedError() # TODO
  807. def __repr__(self):
  808. """
  809. String representation of an Imr.
  810. This includes the subject URI, number of triples contained and the
  811. memory address of the instance.
  812. """
  813. return (f'<{self.__class__.__name__} @{hex(id(self))} uri={self.uri}, '
  814. f'length={len(self.data)}>')
  815. def __getitem__(self, item):
  816. """
  817. Supports slicing notation.
  818. """
  819. if isinstance(item, slice):
  820. s, p, o = item.start, item.stop, item.step
  821. return self._slice(s, p, o)
  822. elif isinstance(item, Node):
  823. # If a Node is given, return all values for that predicate.
  824. return {
  825. r[2] for r in self.data
  826. if r[0] == self.uri and r[1] == item}
  827. else:
  828. raise TypeError(f'Wrong slice format: {item}.')
  829. cdef Imr empty_copy(self):
  830. """
  831. Create an empty instance carrying over some key properties.
  832. """
  833. with self.store.txn_ctx():
  834. return self.__class__(uri=self.uri, store=self.store)
  835. def value(self, p, strict=False):
  836. """
  837. Get an individual value.
  838. :param rdflib.termNode p: Predicate to search for.
  839. :param bool strict: If set to ``True`` the method raises an error if
  840. more than one value is found. If ``False`` (the default) only
  841. the first found result is returned.
  842. :rtype: rdflib.term.Node
  843. """
  844. values = self[p]
  845. if strict and len(values) > 1:
  846. raise RuntimeError('More than one value found for {}, {}.'.format(
  847. self.uri, p))
  848. for ret in values:
  849. return ret
  850. return None
  851. cpdef as_rdflib(self):
  852. """
  853. Return the IMR as a RDFLib Resource.
  854. :rtype: rdflib.Resource
  855. """
  856. gr = Graph()
  857. for trp in self.data:
  858. gr.add(trp)
  859. return gr.resource(identifier=self.uri)