I'm looking for the algorithm of backward and forward chaining to implement it with Python. I looked on the internet, but I didn't find too much. I looked in Wikipedia too but I just found some rules and I didn't find the algorithms.
Forward-chaining inference engines can be implemented relatively easily in Python. This is a list of inference rules:
mammal(A) ==> vertebrate(A).
vertebrate(A) ==> animal(A).
vertebrate(A),flying(A) ==> bird(A).
vertebrate("duck").
flying("duck").
mammal("cat").
These rules can be translated into Python:
global facts
global is_changed
is_changed = True
facts = [["vertebrate","duck"],["flying","duck"],["mammal","cat"]]
def assert_fact(fact):
global facts
global is_changed
if not fact in facts:
facts += [fact]
is_changed = True
while is_changed:
is_changed = False
for A1 in facts:
if A1[0] == "mammal":
assert_fact(["vertebrate",A1[1]])
if A1[0] == "vertebrate":
assert_fact(["animal",A1[1]])
if A1[0] == "vertebrate" and ["flying",A1[1]] in facts:
assert_fact(["bird",A1[1]])
print(facts)
From the initial set of facts, the inference engine generates this list:
[['vertebrate', 'duck'], ['flying', 'duck'], ['mammal', 'cat'], ['animal', 'duck'], ['bird', 'duck'], ['vertebrate', 'cat'], ['animal', 'cat']]