-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackwards_chaining.py
78 lines (60 loc) · 2 KB
/
backwards_chaining.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class Backwards_Chaining():
def __init__(self,KB,query,symbols):
self.KB = KB
self.query = query
self.symbols = symbols
self.found_symbols = []
self.name = 'Backwards_Chaining'
#Gets symbol object from char
def get_symbol(self,char):
#Catch symbols masquerading as chars
try:
char.char = char.char
return char
#Gets symbol with matching char
except:
for symbol in self.symbols:
if symbol.char == char:
return symbol
def get_next_statement(self,current_char):
#Find statement that inferres current char, so right hand side
for statement in self.KB:
if statement.rightside == current_char and statement.visited == False:
return statement
#Recursion
def get_inferrer(self,sSymbol):
if sSymbol is not None and sSymbol.inferred != True:
#Find statement with query
current_statement = self.get_next_statement(sSymbol)
if current_statement is not None:
sSymbol.inferred_by = current_statement.leftside
current_statement.visited = True #Prevents duplication
self.found_symbols.insert(0,sSymbol)
if current_statement.leftside[0] == current_statement.rightside:
current_statement.rightside.inferred = True
return None
if len(sSymbol.inferred_by) == 0:
return None
for symbol in sSymbol.inferred_by:
self.get_inferrer(symbol)
else:
sSymbol.inferred = False
def set_inferred(self,sSymbol):
is_true = True
if len(sSymbol.inferred_by) == 0: #Symbols that are not inferred by anything
is_true = False
else:
for inferrer in sSymbol.inferred_by:
if inferrer.inferred == False:
is_true = False
break
sSymbol.inferred = is_true
def solve(self):
#Gets a chain of symbols and the statements that lead them there
self.get_inferrer(self.query)
#Implements logic to set them as true or false
for symbol in self.found_symbols:
self.set_inferred(symbol)
if self.query is None:
return None,None
return self.query.inferred,self.found_symbols