예제 #1
0
def get_conjunctivegraph(quads):
    cg = ConjunctiveGraph()
#     for (c, s, p, o) in quads:
#         cg.default_context = Graph(store=cg.store, identifier=c)
#         cg.add((s, p, o))
    cg.addN([(s, p, o, Graph(store=cg.store, identifier=c)) for (c, s, p, o) in quads])
    return cg
예제 #2
0
파일: inference.py 프로젝트: drewp/homeauto
def infer(graph: ConjunctiveGraph, rules: ConjunctiveGraph):
    """
    returns new graph of inferred statements.
    """
    log.info(
        f'Begin inference of graph len={len(graph)} with rules len={len(rules)}:'
    )

    workingSet = ConjunctiveGraph()
    workingSet.addN(graph.quads())

    implied = ConjunctiveGraph()

    delta = 1
    while delta > 0:
        delta = -len(implied)

        for r in rules:
            if r[1] == LOG['implies']:
                containsSetup = all(st in workingSet for st in r[0])
                if containsSetup:
                    log.info(f'  Rule {r[0]} -> present={containsSetup}')
                    for st in r[0]:
                        log.info(
                            f'     {st[0].n3()} {st[1].n3()} {st[2].n3()}')

                    log.info(f'  ...implies {len(r[2])} statements')
                if containsSetup:
                    for st in r[2]:
                        workingSet.add(st)
                        implied.add(st)
            else:
                log.info(f'  {r}')
        delta += len(implied)
        log.info(f'  this inference round added {delta} more implied stmts')
    log.info(f'{len(implied)} stmts implied:')
    for st in implied:
        log.info(f'  {st}')
    return implied

    # based on fuxi/tools/rdfpipe.py
    target = Graph()
    tokenSet = generateTokenSet(graph)
    with _dontChangeRulesStore(rules):
        network = ReteNetwork(rules, inferredTarget=target)
        network.feedFactsToAdd(tokenSet)

    return target
예제 #3
0
    def testSerialize(self):

      s1 = URIRef('store:1')
      r1 = URIRef('resource:1')
      r2 = URIRef('resource:2')

      label = URIRef('predicate:label')

      g1 = Graph(identifier = s1)
      g1.add((r1, label, Literal("label 1", lang="en")))
      g1.add((r1, label, Literal("label 2")))

      s2 = URIRef('store:2')
      g2 = Graph(identifier = s2)
      g2.add((r2, label, Literal("label 3")))

      g = ConjunctiveGraph()
      for s,p,o in g1.triples((None, None, None)):
        g.addN([(s,p,o,g1)])
      for s,p,o in g2.triples((None, None, None)):
        g.addN([(s,p,o,g2)])
      r3 = URIRef('resource:3')
      g.add((r3, label, Literal(4)))
      
      
      r = g.serialize(format='trix')
      g3 = ConjunctiveGraph()
      from StringIO import StringIO

      g3.parse(StringIO(r), format='trix')

      for q in g3.quads((None,None,None)):
        # TODO: Fix once getGraph/getContext is in conjunctive graph
        if isinstance(q[3].identifier, URIRef): 
          tg=Graph(store=g.store, identifier=q[3].identifier)
        else:
          # BNode, this is a bit ugly
          # we cannot match the bnode to the right graph automagically
          # here I know there is only one anonymous graph, 
          # and that is the default one, but this is not always the case
          tg=g.default_context
        self.assertTrue(q[0:3] in tg)
예제 #4
0
파일: main.py 프로젝트: nfusionz/whyis
        def get_entity_sparql(entity):
            try:
                statements = self.db.query('''select distinct ?s ?p ?o ?g where {
    hint:Query hint:optimizer "Runtime" .
            ?np np:hasAssertion?|np:hasProvenance?|np:hasPublicationInfo? ?g;
                np:hasPublicationInfo ?pubinfo;
                np:hasAssertion ?assertion;

            {graph ?np { ?np sio:isAbout ?e.}}
            UNION
            {graph ?assertion { ?e ?p ?o.}}
            graph ?g { ?s ?p ?o }
        }''',initBindings={'e':entity}, initNs=self.NS.prefixes)
                result = ConjunctiveGraph()
                result.addN(statements)
            except Exception as e:
                print(str(e), entity)
                raise e
            #print result.serialize(format="trig")
            return result.resource(entity)
예제 #5
0
    def testSerialize(self):

        s1 = URIRef('store:1')
        r1 = URIRef('resource:1')
        r2 = URIRef('resource:2')

        label = URIRef('predicate:label')

        g1 = Graph(identifier=s1)
        g1.add((r1, label, Literal("label 1", lang="en")))
        g1.add((r1, label, Literal("label 2")))

        s2 = URIRef('store:2')
        g2 = Graph(identifier=s2)
        g2.add((r2, label, Literal("label 3")))

        g = ConjunctiveGraph()
        for s, p, o in g1.triples((None, None, None)):
            g.addN([(s, p, o, g1)])
        for s, p, o in g2.triples((None, None, None)):
            g.addN([(s, p, o, g2)])
        r3 = URIRef('resource:3')
        g.add((r3, label, Literal(4)))

        r = g.serialize(format='trix')
        g3 = ConjunctiveGraph()
        from StringIO import StringIO

        g3.parse(StringIO(r), format='trix')

        for q in g3.quads((None, None, None)):
            # TODO: Fix once getGraph/getContext is in conjunctive graph
            if isinstance(q[3].identifier, URIRef):
                tg = Graph(store=g.store, identifier=q[3].identifier)
            else:
                # BNode, this is a bit ugly
                # we cannot match the bnode to the right graph automagically
                # here I know there is only one anonymous graph,
                # and that is the default one, but this is not always the case
                tg = g.default_context
            self.assertTrue(q[0:3] in tg)