comparison service/reasoning/inference.py @ 1089:cb7fa2f30df9

rules become simple-looking again; fix the ambiguity in memory after loading them. Ignore-this: e8788fe6e9c8738671bc1f8910a906c refactor all rule/inference code to one module; all escaping/unescaping to another. darcs-hash:dd0d4538341f23cf7a524cfdc51d03fe1db5ebab
author drewp <drewp@bigasterisk.com>
date Sun, 08 May 2016 02:58:25 -0700
parents 6ab5238fc049
children 3b61c0dfaaef
comparison
equal deleted inserted replaced
1088:0f6128740000 1089:cb7fa2f30df9
1 """ 1 """
2 see ./reasoning for usage 2 see ./reasoning for usage
3 """ 3 """
4 4
5 import sys 5 import sys, os
6 try: 6 try:
7 from rdflib.Graph import Graph 7 from rdflib.Graph import Graph
8 except ImportError: 8 except ImportError:
9 from rdflib import Graph 9 from rdflib import Graph
10
11 from rdflib.parser import StringInputSource
10 12
11 sys.path.append("/my/proj/room/fuxi/build/lib.linux-x86_64-2.6") 13 sys.path.append("/my/proj/room/fuxi/build/lib.linux-x86_64-2.6")
12 from FuXi.Rete.Util import generateTokenSet 14 from FuXi.Rete.Util import generateTokenSet
13 from FuXi.Rete import ReteNetwork 15 from FuXi.Rete import ReteNetwork
14 from rdflib import plugin 16 from FuXi.Rete.RuleStore import N3RuleStore
17
18 from rdflib import plugin, Namespace
15 from rdflib.store import Store 19 from rdflib.store import Store
20
21 sys.path.append('../../../ffg/ffg')
22 import evtiming
23
24 from escapeoutputstatements import escapeOutputStatements
25 ROOM = Namespace("http://projects.bigasterisk.com/room/")
26
27 _rulesCache = (None, None, None, None)
28 @evtiming.serviceLevel.timed('readRules')
29 def readRules(rulesPath, outputPatterns):
30 """
31 returns (rulesN3, ruleGraph)
32
33 This includes escaping certain statements in the output
34 (implied) subgraaphs so they're not confused with input
35 statements.
36 """
37 global _rulesCache
38 mtime = os.path.getmtime(rulesPath)
39 key = (rulesPath, mtime)
40 if _rulesCache[:2] == key:
41 _, _, rulesN3, expandedN3 = _rulesCache
42 else:
43 rulesN3 = open(rulesPath).read() # for web display
44
45 plainGraph = Graph()
46 plainGraph.parse(StringInputSource(rulesN3),
47 format='n3') # for inference
48 escapeOutputStatements(plainGraph, outputPatterns=outputPatterns)
49 expandedN3 = plainGraph.serialize(format='n3')
50 _rulesCache = key + (rulesN3, expandedN3)
51
52 # the rest needs to happen each time since inference is
53 # consuming the ruleGraph somehow
54 ruleStore = N3RuleStore()
55 ruleGraph = Graph(ruleStore)
56
57 ruleGraph.parse(StringInputSource(expandedN3), format='n3')
58 log.debug('%s rules' % len(ruleStore.rules))
59 return rulesN3, ruleGraph
16 60
17 def infer(graph, rules): 61 def infer(graph, rules):
18 """ 62 """
19 returns new graph of inferred statements 63 returns new graph of inferred statements
20 """ 64 """