Algorithmintro
Backward chaining
Also called goal-driven inference.
Start from the goal, pick a rule that concludes it, and prove the conditions of that rule as subgoals in the same way, depth first, until every subgoal is a known fact.
- Solves
- Horn-SAT
- Time
- O(s^(n+1)) worstO(1) best
- Space
- O(n) extra
- Where
- n = the number of atoms; s = the total number of atom occurrences in the rules
- Model
- Word RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Edward H. Shortliffe, 1976
Backward chaining is the inference method of goal-driven rule systems. To prove a goal, it picks a rule whose conclusion is the goal and proves the conditions of the rule as new goals, depth first and from left to right, until each open goal is a known fact. This page treats it as the control method of rule-based expert systems such as MYCIN, on propositional rules: it adds a loop check on the goal stack and memo tables for proved and failed goals, and it shows the cost of the search. With variables and unification the same search is SLD resolution, the proof procedure of Prolog, and the page on it gives the first-order theory. The propositional decision problem itself is Horn-SAT, which forward chaining solves in linear time.
In plain words
You want to know one thing, and you have rules of the form "if these things are true, then that thing is true". Look for a rule whose "then" part is the thing you want. Its "if" parts become new questions, and you answer each of them the same way. A question that is a known fact is answered at once. If a rule fails, try the next rule for the same question. Keep a list of the questions that you are working on now. If a question comes back while you are still working on it, do not start it again, or you go around in a circle forever. Write down the answers you found, so that you do not do the same work twice.
The problem
The input is a finite set of propositional definite rules , where a fact is a rule with , and a goal atom . The semantics is the least model of : the least set of atoms that contains the head of each rule whose body atoms it contains, or for the immediate consequence operator . The task is to decide whether , which is the same as deciding that the Horn clause set is unsatisfiable. This is a P-complete problem that has a linear-time algorithm; backward chaining is chosen for its focus on the goal, not for its worst case.
The algorithm
The procedure is depth-first search over the rules. is the stack of goals that are open now, and is the position of on , from at the bottom. A call returns a truth value and , the smallest depth of a stack atom that a loop check met during the call, or .
BACKWARD-CHAIN(P, g)- 1
proved ← ∅, failed ← ∅, S ← an empty stack - 2
return the truth value of PROVE(g) PROVE(a)- 3
if a ∈ proved then return (true, ∞) - 4
if a ∈ failed then return (false, ∞) - 5
if a is on S at depth d then return (false, d) ▷ loop check - 6
k ← the size of S; push a on S; low ← ∞ - 7
for each rule a ← b_1, …, b_m of P, in order do - 8
for j ← 1 to m do - 9
(ok, c) ← PROVE(b_j); low ← min(low, c) - 10
if not ok then continue with the next rule at L7 - 11
pop a from S; add a to proved; return (true, ∞) - 12
pop a from S - 13
if low ≥ k then add a to failed; return (false, ∞) ▷ the failure did not use the stack below a - 14
return (false, low) ▷ the failure used a goal below a: do not store it
Line L13 stores a failure only when no loop check below hit a goal that was open before . A failure that line L14 reports depends on the current stack: the same atom can be provable when it is asked from another place. MYCIN added one more case to line L7: when no rule concludes a goal that is marked askable, ask the user.
Example
The rules, in this order, are , , , , , , and the fact .
| step | call | stack before the call | what happens |
|---|---|---|---|
| 1 | PROVE | empty | push at depth 0, try |
| 2 | PROVE | push at depth 1, try | |
| 3 | PROVE | loop check: is at depth 1, return (false, 1) | |
| 4 | back in | no rule left, : store as failed | |
| 5 | PROVE | rule ; push at depth 1, try | |
| 6 | PROVE | loop check: is at depth 0, return (false, 0) | |
| 7 | PROVE | rule ; is a fact: store as proved | |
| 8 | back in | store as proved | |
| 9 | PROVE | push , rule , PROVE is a memo hit, store as proved | |
| 10 | back in | empty | store as proved; the answer is true |
In step 6 the call for meets , a goal that was open before it. If had then failed, line L14 would not have stored the failure, since could still follow from by another rule of .
Correctness
The correctness proof shows an invariant: every atom in proved is in , no atom in failed is in , and a call that returns has no proof tree that avoids the stack atoms at depth or more. A proof tree of least size has no atom twice on one path, so the loop check of line L5 loses no proof. When , the set of avoided atoms is empty, so the atom is not in and line L13 may store it. The top call starts with the empty stack, so it returns true exactly when . The stack holds distinct atoms, so the search stops.
Proof: Backward chaining with a loop check and memo tables decides the least modelfull
Let be a finite set of propositional definite rules (a fact has ) and let be its least model. We use the procedure of the page: PROVE works with a goal stack , a set proved and a set failed, and returns a pair . The depth of an atom on is its position, counted from at the bottom.
Proof trees
A proof tree for is a finite tree whose root carries , in which a node with atom has children for some rule of . An atom is in exactly when it has a proof tree; this is the usual reading of by induction on . For a set of atoms, is -provable when it has a proof tree in which no node carries an atom of . So exactly when is -provable, and an atom of is never -provable.
Lemma 1. If is -provable, then has a proof tree that avoids and in which no atom occurs twice on one path from the root.
Proof. Take an -avoiding proof tree of least size. If an atom occurs at a node and again at a node below , replace the subtree at by the subtree at . The result is a smaller -avoiding proof tree, a contradiction.
Invariant
Lemma 2. At every moment, proved and failed . Each call PROVE that returns has . Each call that returns has the property that is not -provable for , where is the stack at the time of the call.
Proof. By induction on the number of calls that have returned. Take a call PROVE with stack , , and assume the claim for all calls that returned before it.
-
Line L3: proved .
-
Line L4: failed, so , so is not -provable for any .
-
Line L5: at depth , the result is , and , so is not -provable.
-
Line L11: the rule had all inner calls return true, so each by the induction hypothesis, and . Adding to proved keeps the invariant.
-
Lines L12 to L14: every rule of had an inner call PROVE that returned with . That call ran with the stack plus on top, at depth . By the induction hypothesis is not -provable, where is the set of atoms of at depth at least .
Let be the value that the call returns: when (line L13) and otherwise (line L14). Let be the set of atoms of at depth at least . In both cases : if , then and ; if , then and holds only atoms of at depth at least , and maybe .
Assume that is -provable. By Lemma 1 it has an -avoiding proof tree in which does not occur below the root. The root uses some rule , and the subtree of each avoids . So the failed of that rule is -provable, a contradiction. So is not -provable.
When , , so , and line L13 keeps the invariant when it adds to failed.
Termination
Lemma 3. Every call stops, and the stack never holds more than atoms, where is the number of atoms of .
Proof. Line L6 pushes only after line L5 found that is not on , so the atoms on are distinct and the recursion depth is at most . Each call makes at most one inner call for each body atom of each rule of . So the tree of calls is finite.
Theorem
BACKWARD-CHAIN stops, and it returns true exactly when . This holds also when the memo tables are kept from earlier goals.
Proof. The run stops by Lemma 3. The top call runs with the empty stack. If it returns true, by Lemma 2. If it returns , then is not -provable for , so . Lemma 2 does not depend on the content of the memo tables at the start, only on the invariant, which holds for the empty tables and is kept by every call.
Why a failure under a loop is not stored
If line L14 stored as failed, the invariant would break. In the program , , , , the call PROVE inside PROVE meets on the stack and fails with . But , because through . The procedure stores nothing for , and a later query for succeeds.
Complexity
The stack holds at most distinct atoms, so the recursion depth is at most , and each call makes at most one inner call for each atom occurrence in the rules of its goal. So the number of calls is at most , and the extra space is for the stack and the memo tables. The worst case is exponential. In the rules for all among atoms, with no facts, every failure meets a goal deeper in the stack, so line L14 stores nothing, and the search walks every simple path from . The number of calls is at least ; the implementation makes 11743 calls for . A goal that is a fact is decided in time.
The problem has better algorithms. Forward chaining with counters decides in time linear in the size of . SLG resolution (tabling) keeps the goal-directed search but stores answers in tables, which makes it polynomial. With variables, the question whether an atom follows from a Datalog program is EXPTIME-complete in combined complexity; see Datalog evaluation.
Properties
- Goal directed. Only rules that can help with the goal, or with its subgoals, are ever looked at.
- Sound and complete for propositional definite rules, with the loop check. Without it, the search does not stop on a rule such as .
- Order dependent cost. The answer does not depend on the order of the rules or of the body atoms, but the number of calls does.
- Explainable. The stack at each moment is a chain of reasons, which is why MYCIN could answer the user's question "why do you ask this?".
Variants and improvements
- Variables. Rules with variables need unification, and the search becomes SLD resolution. Prolog uses it with leftmost selection and without a loop check, so it can run forever on left-recursive rules.
- Tabling. SLG resolution stores the answers of each subgoal and suspends a goal that loops, in place of failing it. This removes the exponential repetition and also handles negation with the well-founded semantics.
- Negation as failure. A condition succeeds when the proof of fails finitely; see negation as failure.
- Askable facts. MYCIN and EMYCIN asked the user for the value of a goal that no rule concludes, and combined the answers with certainty factors.
- Bottom-up with goal focus. The magic sets rewriting lets forward chaining compute only the facts that a backward search would need.
When to use it
Use backward chaining when there is one question, or a few, and most of the rules are irrelevant to it, as in diagnosis and consultation systems that ask the user for data only when a rule needs it. Use forward chaining when new data must trigger all of its consequences, or when the worst case matters.
Pitfalls
- No loop check. A left-recursive rule such as makes a plain depth-first search run forever.
- Storing every failure. A failure that met an open goal is only a failure for the current stack. Storing it as a plain failure makes the search incomplete, as the program , , , shows: fails inside , but .
- Repeated work. Without memo tables the same subgoal is proved again in every place where it occurs, and even with them the loop case can be exponential.
- Asking too much. In a consultation system the order of the rules decides which questions the user sees and in which order.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Backward chaining for the page https://algorithm.tamnd.com/backward-chaining/. The authors are listed in prov/.
"""Backward chaining over propositional definite rules, with a loop check and memo tables.
A rule is (head, body): head is an atom and body is a tuple of atoms. A fact is
a rule with an empty body. Atoms are any hashable values. The search proves a
goal depth first: to prove an atom, try its rules in the given order and prove
the body atoms from left to right. An atom that is already on the current goal
stack is not tried again (the loop check). Atoms that were proved are stored.
An atom whose failure did not depend on an atom of the stack above it is stored
as failed; other failures are not stored, because the same atom can succeed
later from another stack.
BackwardChainer(rules).prove(goal) returns True exactly when goal is in the
least model. The field calls counts the calls of the inner procedure.
"""
INF = float("inf")
class BackwardChainer:
def __init__(self, rules):
self.rules = {}
for head, body in rules:
self.rules.setdefault(head, []).append(tuple(body))
self.proved = set() # @line L1
self.failed = set()
self.depth = {} # the atoms on the goal stack, with their depths
self.calls = 0
self.trace = []
def prove(self, goal):
return self._prove(goal)[0] # @line L2
def _prove(self, a):
"""Return (ok, low): low is the smallest stack depth of an atom that a loop check met, or INF."""
self.calls += 1
if a in self.proved: # @line L3
self.trace.append(("memo true", a))
return True, INF
if a in self.failed: # @line L4
self.trace.append(("memo false", a))
return False, INF
if a in self.depth: # @line L5
self.trace.append(("loop", a))
return False, self.depth[a]
k = len(self.depth) # @line L6
self.depth[a] = k
low = INF
for body in self.rules.get(a, []): # @line L7
ok = True
for b in body: # @line L8
ok, c = self._prove(b) # @line L9
low = min(low, c)
if not ok: # @line L10
break
if ok:
del self.depth[a] # @line L11
self.proved.add(a)
self.trace.append(("proved", a))
return True, INF
del self.depth[a] # @line L12
if low >= k: # @line L13
self.failed.add(a)
self.trace.append(("failed", a))
return False, INF
self.trace.append(("failed for now", a))
return False, low # @line L14
def backward_chain(rules, goal):
"""True exactly when goal follows from the definite rules."""
return BackwardChainer(rules).prove(goal)
test_backward_chaining.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/backward-chaining/. The authors are listed in prov/.
import random
import unittest
from itertools import combinations
from backward_chaining import BackwardChainer, backward_chain
def least_model_brute(rules):
"""The smallest set of atoms that is closed under every rule, by brute force over all subsets."""
base = sorted({h for h, _ in rules} | {b for _, body in rules for b in body})
assert len(base) <= 12
for k in range(len(base) + 1):
for subset in combinations(base, k):
s = set(subset)
if all(h in s for h, body in rules if all(b in s for b in body)):
return s
raise AssertionError("the full base is always closed")
def random_rules(rng, n_atoms, n_rules):
rules = []
for _ in range(n_rules):
head = rng.randrange(n_atoms)
body = tuple(rng.choice(range(n_atoms)) for _ in range(rng.choice([0, 1, 1, 2, 2, 3])))
rules.append((head, body))
return rules
def complete_graph(n):
"""a_i <- a_j for every i != j, and no facts: nothing is provable."""
return [(i, (j,)) for i in range(n) for j in range(n) if i != j]
class TestBackwardChaining(unittest.TestCase):
def test_page_example(self):
rules = [("g", ("d",)), ("d", ("d",)), ("g", ("a", "b")), ("a", ("g",)), ("a", ("c",)), ("b", ("a",)), ("c", ())]
bc = BackwardChainer(rules)
self.assertTrue(bc.prove("g"))
self.assertEqual(
bc.trace,
[
("loop", "d"),
("failed", "d"),
("loop", "g"),
("proved", "c"),
("proved", "a"),
("memo true", "a"),
("proved", "b"),
("proved", "g"),
],
)
self.assertEqual(bc.failed, {"d"})
self.assertFalse(bc.prove("d"))
def test_conditional_failure_is_not_stored(self):
# From the goal g, q fails because its only route goes back to g, which is on the stack.
# Later q is asked again from the top and must succeed through g.
rules = [("g", ("q",)), ("g", ("s",)), ("q", ("g",)), ("s", ())]
bc = BackwardChainer(rules)
self.assertTrue(bc.prove("g"))
self.assertNotIn("q", bc.failed)
self.assertTrue(bc.prove("q"))
def test_random_against_least_model(self):
rng = random.Random(20261115)
for _ in range(600):
n = rng.randint(1, 9)
rules = random_rules(rng, n, rng.randint(0, 14))
m = least_model_brute(rules)
shared = BackwardChainer(rules)
for a in range(n):
self.assertEqual(backward_chain(rules, a), a in m)
self.assertEqual(shared.prove(a), a in m)
self.assertTrue(shared.proved <= m)
self.assertFalse(shared.failed & m)
self.assertEqual(shared.depth, {})
def test_complete_graph_is_exponential(self):
counts = []
for n in range(2, 8):
bc = BackwardChainer(complete_graph(n))
self.assertFalse(bc.prove(0))
counts.append(bc.calls)
self.assertEqual(counts, [3, 11, 49, 261, 1631, 11743])
for n, c in zip(range(2, 8), counts):
f = 1
for i in range(2, n):
f *= i
self.assertGreaterEqual(c, f)
if __name__ == "__main__":
unittest.main()
History
Goal-directed search over rules goes back to the early theorem provers and to Kowalski's procedural reading of Horn clauses (1974), the base of Prolog. Shortliffe's MYCIN (1976) made backward chaining the control method of medical expert systems, and EMYCIN made it a shell for other domains; Buchanan and Shortliffe (1984) collect the work. Tabled resolution, which removes the repeated work, came in the 1990s with SLG resolution of Chen and Warren.
References
- Stuart Russell and Peter Norvig, Artificial Intelligence, A Modern Approach, third edition, Prentice Hall (2010), Chapter 7 (backward chaining for propositional definite clauses) and Chapter 9 (backward chaining with variables and logic programming)
- Bruce G. Buchanan and Edward H. Shortliffe (eds.), Rule-Based Expert Systems, The MYCIN Experiments of the Stanford Heuristic Programming Project, Addison-Wesley (1984), the chapters on the MYCIN consultation program and its goal-directed control
- John W. Lloyd, Foundations of Logic Programming, second edition, Springer (1987), the chapters on SLD resolution, the least Herbrand model and the soundness and completeness of SLD resolution
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 3214H5 Edit this page History Report an error Markdown