-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackwardChainingAlgorithm.py
77 lines (57 loc) · 2.86 KB
/
backwardChainingAlgorithm.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
from propositionalSymbol import PropositionalSymbol
from clause import Clause
class BCAlgorithm:
def __init__(self):
self.foundSymbols = []
self.outputSymbols = []
self.inferred = {}
def backwardChainingEntails(self, kb, symbols, query):
self.inferred = {symbol: False for symbol in symbols}
self.foundSymbols = [clause.right.symbol for clause in kb if
clause.operator is None and clause.left is None]
if self.infer(kb, query, []):
return True
return False
def infer(self, kb, query, explored):
if (isinstance(query, Clause)):
query = query.right
if query.symbol in self.foundSymbols:
if query.symbol not in self.outputSymbols:
self.foundSymbols.append(query.symbol)
self.outputSymbols.append(query.symbol)
return True
for clause in kb:
if (not isinstance(clause.right, PropositionalSymbol)):
# Check if the right hand side of the sentence contain the symbol in the query
if clause.right.right == query:
# Get all the symbols on the left hand side of the setence
leftHandSymbols = []
leftHandSymbols.append(clause.left.right)
premises = clause.left
while premises.left is not None:
premises = premises.left
leftHandSymbols.append(premises.right)
# Check if the left hand side symbols of the sentence is true in KB
trueSymbolCount = 0
for premise in leftHandSymbols:
if (isinstance(premise, Clause)):
premise = premise.right
if premise == query:
break
if premise.symbol in explored:
if self.inferred[premise.symbol] == False:
break
else:
explored.append(premise.symbol)
self.inferred[premise.symbol] = self.infer(
kb, premise, explored.copy())
if (self.inferred[premise.symbol] == False):
break
trueSymbolCount += 1
# Check if all the symbols in the left hand side is true
if trueSymbolCount == len(leftHandSymbols):
if query.symbol not in self.foundSymbols:
self.foundSymbols.append(query.symbol)
self.outputSymbols.append(query.symbol)
return True
return False