Algorithm Search⌘K

Algorithmintro

Forward chaining

Also called data-driven inference.

Start from the known facts, find each rule whose conditions all match facts, add its conclusion, and repeat until no rule adds a new fact or the goal appears.

Time
O(r m a n^m) worst
Space
O(a n) extra
Where
a = the largest arity of a fact; m = the largest number of conditions in a rule; n = the number of facts in the least model; r = the number of rules
Properties
deterministicmonotone
Origin
Allen Newell, Herbert A. Simon, 1972

Forward chaining is the inference method of data-driven rule systems. It starts from the facts in a working memory, finds every rule whose conditions all match facts, adds the conclusion of each such rule as a new fact, and repeats until no rule gives a new fact or a goal fact appears. This page treats it in the setting of production systems and expert systems: rules with pattern variables, a working memory that grows, and the set of matching rule instances (the conflict set) that the system must find again after each change. The propositional case, with its linear-time counter algorithm, is on Horn-SAT forward chaining. The database view, with relations and rounds of joins, is on semi-naive evaluation. The goal-directed opposite is backward chaining.

In plain words

You have a list of things you know and a list of rules of the form "if these things are true, then that thing is true too". Go through what you know. Each time a rule has all of its "if" parts in your list, write its "then" part at the end of the list, unless it is there already. Each new entry can make more rules apply, so you keep going until nothing new comes out. The list you end with holds everything that the rules let you conclude, and nothing more. If you only want to know one thing, you can stop as soon as it appears. The order in which you use the rules does not change the final list, as long as the rules only add things.

The problem

A fact is a ground atom p(c1,…,ck)p(c_1, \ldots, c_k). A rule is a definite clause h←b1,…,bmh \leftarrow b_1, \ldots, b_m whose atoms may contain variables. The rule is safe when each variable of hh occurs in some bjb_j. For a finite set PP of safe rules and a finite set FF of facts, the immediate consequence operator is

T(I)=F∪{hθ:(h←b1,…,bm)∈P, θ ground, b1θ,…,bmθ∈I}.T(I) = F \cup \{ h\theta : (h \leftarrow b_1, \ldots, b_m) \in P,\ \theta \text{ ground},\ b_1\theta, \ldots, b_m\theta \in I \}.

TT is monotone, so it has a least fixed point M=⋃k≥0Tk(∅)M = \bigcup_{k \ge 0} T^k(\emptyset), the least model of P∪FP \cup F. A ground atom gg follows from P∪FP \cup F exactly when g∈Mg \in M. This is the semantics of a Datalog program, and of a Horn clause set in the propositional case.

The task is to compute MM, or to decide whether g∈Mg \in M for a goal gg. Each match of a rule against facts is an instantiation (ρ,θ)(\rho, \theta); the set of instantiations whose head is new is the conflict set of the rule system.

The algorithm

The working memory WW holds the facts found so far and the agenda QQ holds the facts that have not yet been used to match rules. Each new fact is used once: it is matched against each condition of each rule, and the other conditions are joined with the facts already in WW.

  1. FORWARD-CHAIN(P, F, g) ▷ rules P, facts F, goal g (or none)
  2. 1W ← ∅, Q ← an empty queue
  3. 2for each fact f of F, and each head f of a rule of P with an empty body do
  4. 3if f ∉ W then
  5. 4add f to W and to the end of Q; if f = g then return true
  6. 5while Q is not empty do
  7. 6f ← remove the first fact of Q
  8. 7for each rule h ← b_1, …, b_m of P and each i in 1 .. m do
  9. 8if b_i matches f with the binding β then
  10. 9for each extension θ of β that matches every b_j with j ≠ i to a fact of W do
  11. 10if hθ ∉ W then
  12. 11add hθ to W and to the end of Q; if hθ = g then return true
  13. 12return false

When the call returns false, WW is the least model. Line L9 is a join: it binds the variables of the other conditions one condition at a time, the way a nested loop join does. A rule system with conflict resolution collects the instantiations of lines L9 to L11 into a conflict set and fires them one at a time in the order that its conflict resolution strategy gives.

Example

Take the rules

R1:ancestor(x,y)←parent(x,y)R2:ancestor(x,z)←parent(x,y),ancestor(y,z)\begin{aligned} R_1 &: \mathit{ancestor}(x, y) \leftarrow \mathit{parent}(x, y) \\ R_2 &: \mathit{ancestor}(x, z) \leftarrow \mathit{parent}(x, y), \mathit{ancestor}(y, z) \end{aligned}

and the facts parent(ann,bob)\mathit{parent}(\mathit{ann}, \mathit{bob}) and parent(bob,cat)\mathit{parent}(\mathit{bob}, \mathit{cat}), with no goal.

step fact taken from QQ matches new facts
1 parent(ann,bob)\mathit{parent}(\mathit{ann}, \mathit{bob}) R1R_1; R2R_2 condition 1, but no ancestor(bob,z)\mathit{ancestor}(\mathit{bob}, z) in WW yet ancestor(ann,bob)\mathit{ancestor}(\mathit{ann}, \mathit{bob})
2 parent(bob,cat)\mathit{parent}(\mathit{bob}, \mathit{cat}) R1R_1; R2R_2 condition 1, but no ancestor(cat,z)\mathit{ancestor}(\mathit{cat}, z) ancestor(bob,cat)\mathit{ancestor}(\mathit{bob}, \mathit{cat})
3 ancestor(ann,bob)\mathit{ancestor}(\mathit{ann}, \mathit{bob}) R2R_2 condition 2 with y=anny = \mathit{ann}, but no parent(x,ann)\mathit{parent}(x, \mathit{ann}) none
4 ancestor(bob,cat)\mathit{ancestor}(\mathit{bob}, \mathit{cat}) R2R_2 condition 2 with y=boby = \mathit{bob}, joined with parent(ann,bob)\mathit{parent}(\mathit{ann}, \mathit{bob}) ancestor(ann,cat)\mathit{ancestor}(\mathit{ann}, \mathit{cat})
5 ancestor(ann,cat)\mathit{ancestor}(\mathit{ann}, \mathit{cat}) R2R_2 condition 2 with y=anny = \mathit{ann}, no partner none

The agenda is empty after step 5, and WW holds the two parent facts and three ancestor facts, which is the least model. With the goal ancestor(bob,cat)\mathit{ancestor}(\mathit{bob}, \mathit{cat}) the run stops in step 2, after two rule firings.

Correctness

The correctness proof shows three facts. Every fact in WW is in MM (soundness, by induction on the order of addition). Each fact enters the agenda at most once, so the run stops. When the agenda is empty, WW is closed under every ground rule instance: for an instance whose body facts are all in WW, look at the body fact that left the agenda last; at that moment the other body facts were in WW, so line L9 found the instance. A closed set that contains FF contains MM, so W=MW = M. The proof uses no property of the agenda order, so any order of the queue and of the rules gives the same MM.

Proof: Forward chaining computes the least model of a definite rule setfull

Let PP be a finite set of safe definite rules h←b1,…,bmh \leftarrow b_1, \ldots, b_m over a finite set of constants, and let FF be a finite set of ground facts. A ground instance ρθ\rho\theta of a rule ρ\rho replaces each variable by a constant. The immediate consequence operator is T(I)=F∪{hθ:(h←b1,…,bm)∈P, b1θ,…,bmθ∈I}T(I) = F \cup \{ h\theta : (h \leftarrow b_1, \ldots, b_m) \in P,\ b_1\theta, \ldots, b_m\theta \in I \}. A set II of ground atoms is a model when T(I)⊆IT(I) \subseteq I. The least model MM is the intersection of all models; by the Knaster-Tarski theorem it is the least fixed point of TT, and M=⋃k≥0Tk(∅)M = \bigcup_{k \ge 0} T^k(\emptyset) because TT is monotone and the set of ground atoms is finite.

We use the procedure FORWARD-CHAIN of the page. WW is the working memory and QQ is the agenda. The procedure adds a fact to WW and to the end of QQ in one step (line L4 or L11), and only when the fact is not in WW yet. Nothing is ever removed from WW.

Lemma 1 (soundness)

At every moment, W⊆MW \subseteq M.

Proof. By induction on the order in which facts enter WW. A fact of FF, or the head of a rule with an empty body, is in T(∅)⊆MT(\emptyset) \subseteq M. Any other fact enters WW at line L11 as hθh\theta, where θ\theta matches every body pattern bjb_j to a fact bjθb_j\theta that is in WW at that moment. By the induction hypothesis each bjθ∈Mb_j\theta \in M, so hθ∈T(M)=Mh\theta \in T(M) = M. □\square

Lemma 2 (termination)

The procedure stops after at most ∣M∣|M| iterations of the main loop.

Proof. Each fact enters QQ only when it enters WW, and so at most once. Each iteration removes one fact from QQ. By Lemma 1 at most ∣M∣|M| facts enter WW, and MM is finite because a safe rule only puts constants of its body facts or of the rule itself into its head. Each iteration does finite work, because the join at line L9 ranges over the finite set WW. □\square

Lemma 3 (closure)

If the main loop ends because QQ is empty, then T(W)⊆WT(W) \subseteq W.

Proof. F⊆WF \subseteq W by line L4. Take a rule ρ=(h←b1,…,bm)\rho = (h \leftarrow b_1, \ldots, b_m) and a ground instance θ\theta with b1θ,…,bmθ∈Wb_1\theta, \ldots, b_m\theta \in W. If m=0m = 0, then hh is ground and line L4 put it in WW. Otherwise each bjθb_j\theta entered QQ when it entered WW, and since QQ is now empty, each was removed from QQ at line L6. Let ff be the one of these facts that was removed last, and let ii be an index with biθ=fb_i\theta = f. When ff was removed, every other bjθb_j\theta was either removed earlier, and so already in WW, or equal to ff, which entered WW before it entered QQ. Since WW only grows, all of them stay in WW during that iteration. The pattern bib_i matches ff with the restriction of θ\theta to the variables of bib_i (line L8), and the join at line L9 enumerates every extension of this binding that matches the other patterns to facts of WW, so it reaches θ\theta restricted to the variables of ρ\rho. Line L11 then puts hθh\theta in WW, or hθh\theta was in WW already. □\square

Theorem

FORWARD-CHAIN(P,F,g)(P, F, g) stops. It returns true exactly when g∈Mg \in M. When it returns false, the final WW equals MM.

Proof. The procedure stops by Lemma 2. If it returns true, then g∈W⊆Mg \in W \subseteq M by Lemma 1. Otherwise the loop ended with QQ empty, so WW is a model by Lemma 3. Since MM is the least model, M⊆WM \subseteq W, and with Lemma 1, W=MW = M. The procedure checks every fact as it enters WW (lines L4 and L11), so g∉W=Mg \notin W = M. ■\blacksquare

Remark on the order of the agenda

The proof uses only the facts that each fact enters QQ once and that the loop runs until QQ is empty. So the result is the same for a queue, a stack or any other order of QQ, and for any order of the rules. This is the reason why conflict resolution does not change the result of a production system whose rules only add facts. It changes the result as soon as rules can delete facts or stop the run, as in the production system model.

Complexity

Each of the nn facts of MM leaves the agenda once. For each such fact, each of the rr rules and each of its at most mm conditions, the join at line L9 tries at most nm−1n^{m-1} tuples of facts, and each match costs O(a)O(a). The total time is O(r m a nm)O(r\, m\, a\, n^m), and the space for WW and QQ is O(a n)O(a\, n).

For a fixed rule set, nn is at most the number of ground atoms over the cc constants of the input, which is polynomial in cc. So the data complexity, with the rules fixed, is polynomial, and deciding g∈Mg \in M is P-complete. In combined complexity, with the rules part of the input, nn can be exponential in the size of the rules, and the problem is EXPTIME-complete; the Datalog evaluation page gives the results. Even one rule application is hard in combined complexity: finding the matches of a single rule body is the conjunctive query problem, which is NP-complete. In the propositional case there are no variables, and the counter method of Horn-SAT forward chaining runs in time linear in the size of the rules.

Properties

  • Monotone. Facts are only added. Each fact in WW stays true for the rest of the run.
  • Order independent. For definite rules, the final WW does not depend on the order of the agenda or of the rules. This fails as soon as rules can delete facts, as in OPS5.
  • Complete for ground goals. Every atom of the least model is found, so every ground atom that follows from the rules is derived.
  • Not goal directed. Without a goal, the run computes every consequence, including the many that are not relevant to a question.

Variants and improvements

  • Counter based propositional chaining. Keep for each rule the number of body atoms not yet true, and fire the rule when the counter reaches zero. This is Horn-SAT forward chaining, linear in the input size.
  • Semi-naive evaluation. Work in rounds and join only with at least one fact from the last round. This is the same idea as the agenda, in the language of relations; see semi-naive evaluation.
  • Incremental matching. A production system keeps the conflict set between cycles and updates it after each change of the working memory. The Rete algorithm stores partial matches in a network; the TREAT algorithm stores only the matches of single conditions and recomputes the joins.
  • Goal-directed bottom-up evaluation. The magic sets rewriting adds conditions so that forward chaining only derives facts relevant to a query.
  • Rules with actions. In OPS5 and CLIPS a rule can also remove or modify facts. The run is then a sequence of recognize-act cycles, and the conflict resolution strategy decides the result.

When to use it

Use forward chaining when new data arrives and the system must react to it, as in monitoring, configuration and business rule systems. It also fits when most consequences of the facts are needed anyway, or when there are many possible goals. Use backward chaining when there is one question and most of the rules are irrelevant to it.

Pitfalls

  • Unsafe rules. A head variable that is not in the body gives infinitely many or non-ground conclusions. Reject such rules, as the implementation does.
  • Function symbols. With terms such as s(x)s(x) the least model can be infinite and the run does not stop. Forward chaining as given here is for function-free rules.
  • Duplicate work. Without the agenda, a naive loop that rematches every rule against the whole memory after each new fact repeats the old matches again and again.
  • Join order. The join at line L9 is cheap or expensive depending on the order of the conditions. A condition that binds no variable of the others makes a cross product.
  • Negation. A rule with a negated condition cannot fire safely before all facts that the condition depends on are known. Use a stratified order, or a semantics such as the well-founded semantics.

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.

forward_chaining.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Forward chaining for the page https://algorithm.tamnd.com/forward-chaining/. The authors are listed in prov/.
"""Forward chaining over definite rules with variables, driven by an agenda of new facts.

A fact is a tuple of constants, for example ("parent", "ann", "bob"). A pattern
is a tuple of the same shape in which a term may be a variable, a string that
starts with "?". A rule is (name, body, head): body is a tuple of patterns and
head is one pattern. Each variable of the head must occur in the body (a safe
rule). A rule with an empty body must have a ground head; it is a fact.

forward_chain(rules, facts, goal) returns (found, memory, fired):
- found is True when goal is in the least model (always False when goal is None),
- memory is the set of facts derived so far (the whole least model when the
  run does not stop early at the goal),
- fired is the list of (rule name, new fact) in the order the rules added them.
"""

from collections import deque


def is_var(term):
    return isinstance(term, str) and term.startswith("?")


def match(pattern, fact, binding):
    """Extend binding so that pattern equals fact, or return None."""
    if len(pattern) != len(fact):
        return None
    out = dict(binding)
    for p, f in zip(pattern, fact):
        if is_var(p):
            if p in out:
                if out[p] != f:
                    return None
            else:
                out[p] = f
        elif p != f:
            return None
    return out


def substitute(pattern, binding):
    return tuple(binding[t] if is_var(t) else t for t in pattern)


def check_safe(rules):
    for name, body, head in rules:
        body_vars = {t for p in body for t in p if is_var(t)}
        head_vars = {t for t in head if is_var(t)}
        if not head_vars <= body_vars:
            raise ValueError(f"rule {name} is not safe")


def _joins(body, skip, binding, memory):
    """All extensions of binding that match every body pattern except index skip to facts in memory."""
    rest = [p for j, p in enumerate(body) if j != skip]

    def go(k, b):
        if k == len(rest):
            yield b
            return
        for fact in list(memory):
            b2 = match(rest[k], fact, b)
            if b2 is not None:
                yield from go(k + 1, b2)

    yield from go(0, binding)


def forward_chain(rules, facts, goal=None):
    check_safe(rules)
    memory, agenda = set(), deque()  # @line L1
    fired = []

    def add(fact, name):
        memory.add(fact)
        agenda.append(fact)
        if name is not None:
            fired.append((name, fact))
        return fact == goal

    start = [(tuple(head), name) for name, body, head in rules if not body] + [(tuple(f), None) for f in facts]
    for f, name in start:  # @line L2
        if f not in memory:  # @line L3
            if add(f, name):  # @line L4
                return True, memory, fired
    while agenda:  # @line L5
        f = agenda.popleft()  # @line L6
        for name, body, head in rules:  # @line L7
            for i, pattern in enumerate(body):
                b = match(pattern, f, {})  # @line L8
                if b is None:
                    continue
                for full in _joins(body, i, b, memory):  # @line L9
                    new = substitute(head, full)
                    if new not in memory:  # @line L10
                        if add(new, name):  # @line L11
                            return True, memory, fired
    return False, memory, fired  # @line L12
test_forward_chaining.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/forward-chaining/. The authors are listed in prov/.

import random
import unittest
from itertools import combinations, product

from forward_chaining import forward_chain, is_var, match, substitute


def ground(rules, facts):
    """Every ground instance of every rule over the constants that occur in the input."""
    consts = set()
    for _, body, head in rules:
        for p in list(body) + [head]:
            consts.update(t for t in p[1:] if not is_var(t))
    for f in facts:
        consts.update(f[1:])
    consts = sorted(consts)
    out = [(tuple(f), ()) for f in facts]
    for _, body, head in rules:
        vs = sorted({t for p in body for t in p if is_var(t)} | {t for t in head if is_var(t)})
        for values in product(consts, repeat=len(vs)):
            b = dict(zip(vs, values))
            out.append((substitute(head, b), tuple(substitute(p, b) for p in body)))
    return out


def least_model_brute(ground_rules):
    """The least model of a ground definite program: the smallest subset of the Herbrand base closed under every rule."""
    base = sorted({h for h, _ in ground_rules} | {a for _, body in ground_rules for a 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 ground_rules if all(a in s for a in body)):
                return s
    raise AssertionError("the full base is always a model")


def random_propositional(rng, n_atoms, n_rules):
    names = [("p" + str(i),) for i in range(n_atoms)]
    rules = []
    for r in range(n_rules):
        head = rng.choice(names)
        body = tuple(rng.sample(names, rng.randint(0, min(3, n_atoms))))
        rules.append(("r" + str(r), body, head))
    facts = [f for f in names if rng.random() < 0.15]
    return rules, facts


def random_first_order(rng):
    """Two constants and the predicates p/1, q/1, e/2, so the Herbrand base has 2 + 2 + 4 = 8 atoms."""
    consts = ["a", "b"]
    preds = [("p", 1), ("q", 1), ("e", 2)]
    vars_ = ["?x", "?y"]

    def pattern():
        name, arity = rng.choice(preds)
        return (name,) + tuple(rng.choice(vars_ + consts) for _ in range(arity))

    rules = []
    for r in range(rng.randint(1, 5)):
        body = tuple(pattern() for _ in range(rng.randint(1, 3)))
        body_vars = sorted({t for p in body for t in p if is_var(t)})
        name, arity = rng.choice(preds)
        head = (name,) + tuple(rng.choice(body_vars + consts) for _ in range(arity))
        rules.append(("r" + str(r), body, head))
    facts = []
    for name, arity in preds:
        for args in product(consts, repeat=arity):
            if rng.random() < 0.2:
                facts.append((name,) + args)
    return rules, facts


class TestForwardChaining(unittest.TestCase):
    def test_match(self):
        self.assertEqual(match(("e", "?x", "?x"), ("e", "a", "a"), {}), {"?x": "a"})
        self.assertIsNone(match(("e", "?x", "?x"), ("e", "a", "b"), {}))
        self.assertIsNone(match(("e", "?x"), ("e", "a", "b"), {}))

    def test_page_example(self):
        rules = [
            ("R1", (("parent", "?x", "?y"),), ("ancestor", "?x", "?y")),
            ("R2", (("parent", "?x", "?y"), ("ancestor", "?y", "?z")), ("ancestor", "?x", "?z")),
        ]
        facts = [("parent", "ann", "bob"), ("parent", "bob", "cat")]
        found, memory, fired = forward_chain(rules, facts)
        self.assertFalse(found)
        self.assertEqual(
            fired,
            [
                ("R1", ("ancestor", "ann", "bob")),
                ("R1", ("ancestor", "bob", "cat")),
                ("R2", ("ancestor", "ann", "cat")),
            ],
        )
        self.assertEqual(len(memory), 5)
        found, _, fired = forward_chain(rules, facts, goal=("ancestor", "bob", "cat"))
        self.assertTrue(found)
        self.assertEqual(len(fired), 2)

    def test_unsafe_rule(self):
        with self.assertRaises(ValueError):
            forward_chain([("bad", (("p", "?x"),), ("q", "?y"))], [])

    def test_random_propositional(self):
        rng = random.Random(20261115)
        for _ in range(400):
            rules, facts = random_propositional(rng, rng.randint(1, 10), rng.randint(0, 14))
            _, memory, fired = forward_chain(rules, facts)
            expected = least_model_brute(ground(rules, facts))
            self.assertEqual(memory, expected)
            self.assertEqual(len(fired), len({f for _, f in fired}))
            for atom in [("p" + str(i),) for i in range(10)]:
                found, _, _ = forward_chain(rules, facts, goal=atom)
                self.assertEqual(found, atom in expected)

    def test_random_first_order(self):
        rng = random.Random(7)
        for _ in range(300):
            rules, facts = random_first_order(rng)
            _, memory, _ = forward_chain(rules, facts)
            self.assertEqual(memory, least_model_brute(ground(rules, facts)))


if __name__ == "__main__":
    unittest.main()

History

Post (1943) defined canonical systems, the first formal systems built from productions. Newell and Simon (1972) used production systems that fire forward from the data in working memory as models of human problem solving, and OPS5 (Forgy 1981) and its successors made forward chaining the standard control method of rule-based expert systems. In logic programming the same computation is bottom-up evaluation, the least fixed point construction of van Emden and Kowalski (1976). Dowling and Gallier (1984) gave the linear-time propositional algorithm.

References

  1. Stuart Russell and Peter Norvig, Artificial Intelligence, A Modern Approach, third edition, Prentice Hall (2010), Chapter 7 (forward chaining for propositional definite clauses) and Chapter 9 (forward chaining with variables)
  2. Allen Newell and Herbert A. Simon, Human Problem Solving, Prentice-Hall (1972), the chapters on production systems
  3. Lee Brownston, Robert Farrell, Elaine Kant and Nancy Martin, Programming Expert Systems in OPS5, Addison-Wesley (1985), the chapters on the recognize-act cycle and forward chaining in OPS5
  4. William F. Dowling and Jean H. Gallier, Linear-time algorithms for testing the satisfiability of propositional Horn formulae, Journal of Logic Programming 1(3), 267 to 284 (1984), the linear-time forward algorithm for the propositional case

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example