Beispiel #1
0
    def makeRuleGraph(self):
        self.ruleStore = N3RuleStore()

        class NullDispatcher(object):
            def dispatch(self, *args):
                pass

        self.ruleStore.dispatcher = NullDispatcher()
        self.ruleGraph = Graph(self.ruleStore)
        self.ruleGraph.parse('commandRules.n3', format='n3')  # for inference
Beispiel #2
0
 def setUp(self):
     from FuXi.Rete.RuleStore import N3RuleStore
     from FuXi.Rete import ReteNetwork
     from FuXi.Rete.Util import generateTokenSet
     self.testGraph = Graph()
     self.ruleStore = N3RuleStore()
     self.ruleGraph = Graph(self.ruleStore)
     self.ruleGraph.parse(StringIO(testN3), format='n3')
     self.testGraph.parse(StringIO(testN3), format='n3')
     self.closureDeltaGraph = Graph()
     self.network = ReteNetwork(self.ruleStore,
                                initialWorkingMemory=generateTokenSet(
                                    self.testGraph),
                                inferredTarget=self.closureDeltaGraph,
                                nsMap={})
Beispiel #3
0
def HornFromN3(n3Source, additionalBuiltins=None):
    """
    Takes the path or URL of a N3 document, and a mapping from predicates
    to functions that implement any builtins found in the N3 document
    """
    from FuXi.Rete.RuleStore import SetupRuleStore, N3RuleStore
    if isinstance(n3Source, ConjunctiveGraph):
        store = N3RuleStore(additionalBuiltins=additionalBuiltins)
        for ctx in n3Source.contexts():
            for s, p, o in ctx:
                store.add((s, p, o), ctx)
    else:
        store, graph = SetupRuleStore(n3Source,
                                      additionalBuiltins=additionalBuiltins)
    store._finalize()
    return Ruleset(n3Rules=store.rules, nsMapping=store.nsMgr)
Beispiel #4
0
 def testExistentials(self):
     store = plugin.get('IOMemory', Store)()
     store.open('')
     ruleStore = N3RuleStore()
     ruleGraph = Graph(ruleStore)
     ruleGraph.parse(StringIO(N3_PROGRAM), format='n3')
     factGraph = Graph(store)
     factGraph.parse(StringIO(N3_FACTS), format='n3')
     deltaGraph = Graph(store)
     network = ReteNetwork(ruleStore,
                           initialWorkingMemory=generateTokenSet(factGraph),
                           inferredTarget=deltaGraph)
     inferenceCount = 0
     for inferredFact in network.inferredFacts.subjects(
             predicate=RDF.type,
             object=URIRef('http://example.com/#Inference')):
         inferenceCount = inferenceCount + 1
     print(network.inferredFacts.serialize(format='n3'))
     self.failUnless(inferenceCount > 1,
                     'Each rule firing should introduce a new BNode!')
Beispiel #5
0
 def test_n3rulestore_basic(self):
     s = N3RuleStore()
     g = Graph(s)
     g.parse(data=src, format='n3')
     s._finalize()
     assert len([
         pred for subj, pred, obj in s.facts
         if pred == 'http://metacognition.info/FuXi/test#relatedTo'
     ]) == 1, len([
         pred for subj, pred, obj in s.facts
         if pred == 'http://metacognition.info/FuXi/test#relatedTo'
     ])
     assert len(s.rules) == 1, len(s.rules)
     assert len(s.rules[0][RULE_LHS]) == 4, len(s.rules[0][RULE_LHS])
     assert len(s.rules[0][RULE_RHS]) == 5, len(s.rules[0][RULE_RHS])
     assert s.rules[0][RULE_LHS][
         1] == "(rdflib.term.Variable('X'), rdflib.term.URIRef('http://metacognition.info/FuXi/test#prop1'), rdflib.term.Variable('M'))", s.rules[
             0][RULE_LHS][1]
     assert s.rules[0][RULE_LHS][
         -1] == "<http://www.w3.org/2000/10/swap/math#equalTo>(?N, 3)", s.rules[
             0][RULE_LHS][-1]
Beispiel #6
0
def readRules(rulesPath, outputPatterns):
    """
    returns (rulesN3, ruleStore)

    This includes escaping certain statements in the output
    (implied) subgraaphs so they're not confused with input
    statements.
    """
    global _rulesCache

    with STATS.readRules.time():
        mtime = os.path.getmtime(rulesPath)
        key = (rulesPath, mtime)
        if _rulesCache[:2] == key:
            _, _, rulesN3, ruleStore = _rulesCache
        else:
            rulesN3 = open(rulesPath).read()  # for web display

            ruleStore = N3RuleStore()
            _loadAndEscape(ruleStore, rulesN3, outputPatterns)
            log.debug('%s rules' % len(ruleStore.rules))

            _rulesCache = key + (rulesN3, ruleStore)
        return rulesN3, ruleStore
Beispiel #7
0
def main():
    from optparse import OptionParser

    parser = OptionParser()
    parser.add_option(
        '--stdin',
        type="choice",
        choices=['xml', 'trix', 'n3', 'nt', 'rdfa'],
        help='Parse RDF from STDIN (useful for piping) with given format')
    parser.add_option('-x',
                      '--xml',
                      action='append',
                      help='Append to the list of RDF/XML documents to parse')
    parser.add_option('-t',
                      '--trix',
                      action='append',
                      help='Append to the list of TriX documents to parse')
    parser.add_option('-n',
                      '--n3',
                      action='append',
                      help='Append to the list of N3 documents to parse')
    parser.add_option('--nt',
                      action='append',
                      help='Append to the list of NT documents to parse')
    parser.add_option('-a',
                      '--rdfa',
                      action='append',
                      help='Append to the list of RDFa documents to parse')

    parser.add_option(
        '-o',
        '--output',
        type="choice",
        choices=['n3', 'xml', 'pretty-xml', 'TriX', 'turtle', 'nt'],
        help='Format of the final serialized RDF graph')

    parser.add_option(
        '-m',
        '--ns',
        action='append',
        help='Register a namespace binding (QName prefix to a base URI)')

    parser.add_option(
        '-r',
        '--rules',
        action='append',
        help='Append to the list of fact files to use to perform reasoning')
    parser.add_option(
        '-i',
        '--inferred',
        help='URI to use for the graph containing any inferred triples')

    parser.set_defaults(xml=[],
                        trix=[],
                        n3=[],
                        nt=[],
                        rdfa=[],
                        ns=[],
                        output='n3')

    (options, args) = parser.parse_args()

    store = plugin.get(RDFLIB_STORE, Store)()
    store.open(RDFLIB_CONNECTION)

    namespace_manager = NamespaceManager(Graph())
    for prefixDef in options.ns:
        prefix, uri = prefixDef.split('=')
        namespace_manager.bind(prefix, uri, override=False)

    factGraph = ConjunctiveGraph(store)
    for graphRef in options.xml:
        factGraph.parse(graphRef,
                        publicID=Uri.OsPathToUri(graphRef),
                        format='xml')
    for graphRef in options.trix:
        factGraph.parse(graphRef,
                        publicID=Uri.OsPathToUri(graphRef),
                        format='trix')
    for graphRef in options.n3:
        factGraph.parse(graphRef,
                        publicID=Uri.OsPathToUri(graphRef),
                        format='n3')
    for graphRef in options.nt:
        factGraph.parse(graphRef,
                        publicID=Uri.OsPathToUri(graphRef),
                        format='nt')
    for graphRef in options.rdfa:
        factGraph.parse(graphRef,
                        publicID=Uri.OsPathToUri(graphRef),
                        format='rdfa')
    if options.stdin:
        factGraph.parse(sys.stdin, format=options.stdin)

    if options.inferred and len(options.rules) > 0:
        inferredURI = URIRef(options.inferred)
        ruleStore = N3RuleStore()
        ruleGraph = Graph(ruleStore)
        for ruleFile in options.rules:
            ruleGraph.parse(ruleFile, format='n3')
        tokenSet = generateTokenSet(factGraph)
        deltaGraph = Graph(store=factGraph.store, identifier=inferredURI)
        network = ReteNetwork(ruleStore, inferredTarget=deltaGraph)
        network.feedFactsToAdd(tokenSet)

    print factGraph.serialize(destination=None,
                              format=options.output,
                              base=None)
    store.rollback()