Algorithm Search⌘K

Algorithmcore

Rete algorithm

Also called Rete network, Forgy's Rete.

Compile the rule conditions into a network that stores the partial matches, so each change of working memory updates the conflict set without matching all rules again.

Time
O(r m a n^m) worst
Space
O(r m n^m) extra
Where
a = the largest arity of an element; m = the largest number of conditions in a rule; n = the number of elements in working memory; r = the number of rules
Properties
deterministicincremental
Origin
Charles L. Forgy, 1982

The Rete algorithm solves the match step of a production system: after each change to the working memory, find the conflict set, the set of all instantiations of all rules. A plain forward chaining loop matches every rule against the whole memory again in each cycle. Rete compiles the conditions of all rules into one network. Alpha memories hold the working memory elements that pass the tests of a single condition, and join nodes hold the partial matches (tokens) of the first ii conditions of a rule. A change to working memory then only flows through the nodes that it touches. Rules that share conditions share the nodes. Forgy designed it for OPS5, and the commercial rule engines that came later use variants of it.

In plain words

A rule system checks its rules after every small change to its facts. Most of the work it did in the last check is still valid, because only one fact changed. Rete keeps that work. For each condition it keeps the list of facts that fit the condition. For each rule it keeps the groups of facts that fit its first condition, its first two conditions, and so on. A new fact is checked only against the lists it can join, and the new groups that it makes are passed on to the next condition. When a fact is removed, the groups that hold it are removed. Two rules that start with the same conditions share these lists. The cost is memory: the saved groups can be many.

The problem

A working memory element (WME) is a ground tuple, such as block(b1,red)\mathit{block}(b_1, \mathit{red}). A rule has the form

ρ:c1,…,cm⇒actions,\rho: c_1, \ldots, c_m \Rightarrow \text{actions},

where each condition ckc_k is a pattern with variables. An instantiation of ρ\rho in the working memory WW is a tuple (w1,…,wm)(w_1, \ldots, w_m) of elements of WW with one binding θ\theta of the variables such that ckθ=wkc_k\theta = w_k for each kk. The conflict set CS(W)CS(W) is the set of pairs (ρ,(w1,…,wm))(\rho, (w_1, \ldots, w_m)) over all rules.

The task is incremental: given the rules once, and then a sequence of changes, each of which inserts or deletes one element, keep CS(W)CS(W) correct after each change. This page treats positive conditions only. Finding even one instantiation of one rule is the conjunctive query problem, which is NP-complete in combined complexity, so the incremental task cannot have a polynomial worst case in the size of the rules either.

The algorithm

The network is built from the rules before the first change. Each condition gets an alpha memory, keyed by the condition with its variables renamed by first occurrence, so that on(x,y)\mathit{on}(x, y) and on(b,t)\mathit{on}(b, t) share one memory. It holds the WMEs that pass the constant tests of the condition and the equality tests between its own variables. Each prefix c1,…,cic_1, \ldots, c_i of a rule gets a join node at depth ii, whose parent is the node of c1,…,ci−1c_1, \ldots, c_{i-1}; rules with equal prefixes share the nodes. The join node reads the alpha memory of cic_i and keeps a beta memory of tokens, one for each match of c1,…,cic_1, \ldots, c_i. The node of the full condition list of a rule is its production node. A token records its parent token, its WME and its children, and each WME records its tokens, for removal.

  1. INSERT(w)
  2. 1for each alpha memory α whose tests w passes do
  3. 2add w to α
  4. 3sort the join nodes that read these alpha memories by depth, deepest first
  5. 4for each such join node j do RIGHT-ACTIVATE(j, w)
  6. RIGHT-ACTIVATE(j, w) ▷ a new element arrives from the alpha side
  7. 5for each token t in the beta memory of the parent of j (the empty token if j has depth 1) do
  8. 6if the condition of j matches w with a binding that extends the binding of t then
  9. 7MAKE-TOKEN(j, t, w)
  10. MAKE-TOKEN(j, t, w)
  11. 8add the token t + w to the beta memory of j, link it to t and to w; if j is the production node of a rule ρ then add (ρ, t + w) to the conflict set; for each child c of j do LEFT-ACTIVATE(c, t + w)
  12. LEFT-ACTIVATE(c, t) ▷ a new token arrives from the parent side
  13. 9for each element w in the alpha memory of c do
  14. 10if the condition of c matches w with a binding that extends the binding of t then
  15. 11MAKE-TOKEN(c, t, w)
  16. DELETE(w)
  17. 12remove w from every alpha memory
  18. 13for each token t that records w do
  19. 14remove t and all its descendants from their beta memories, and their instantiations from the conflict set

Line L3 is needed when one element can match two conditions of the same rule. Deepest first, the deeper node joins ww with the old tokens of its parent before the shallower node adds new tokens there, so no match is made twice. Deletion by the token tree (lines L13 and L14) is the tree-based removal of Doorenbos; Forgy's original network sent a delete token through the same joins as an insert.

Example

Two rules share their first two conditions:

R1:goal(g),block(b,red),on(b,t)⇒…R2:goal(g),block(b,red),clear(b)⇒…\begin{aligned} R_1 &: \mathit{goal}(g), \mathit{block}(b, \mathit{red}), \mathit{on}(b, t) \Rightarrow \ldots \\ R_2 &: \mathit{goal}(g), \mathit{block}(b, \mathit{red}), \mathit{clear}(b) \Rightarrow \ldots \end{aligned}

The network has 4 alpha memories, for goal(⋅)\mathit{goal}(\cdot), block(⋅,red)\mathit{block}(\cdot, \mathit{red}), on(⋅,⋅)\mathit{on}(\cdot, \cdot) and clear(⋅)\mathit{clear}(\cdot), and 4 join nodes: J1J_1 for goal\mathit{goal}, J2J_2 for goal,block\mathit{goal}, \mathit{block}, and the production nodes J3J_3 of R1R_1 and J4J_4 of R2R_2, both children of J2J_2.

insert alpha memory join activity new tokens
goal(g1)\mathit{goal}(g_1) goal J1J_1 joins with the empty token [g1][g_1] at J1J_1
block(b1,red)\mathit{block}(b_1, \mathit{red}) block red J2J_2 joins with [g1][g_1]; J3J_3 and J4J_4 find empty alpha memories [g1,b1][g_1, b_1] at J2J_2
block(b2,red)\mathit{block}(b_2, \mathit{red}) block red as before [g1,b2][g_1, b_2] at J2J_2
block(b3,blue)\mathit{block}(b_3, \mathit{blue}) none the constant test red\mathit{red} rejects it none
on(b1,table)\mathit{on}(b_1, \mathit{table}) on J3J_3 joins with the two tokens of J2J_2; only b=b1b = b_1 is consistent [g1,b1,on][g_1, b_1, \mathit{on}] at J3J_3, an instantiation of R1R_1
clear(b2)\mathit{clear}(b_2) clear J4J_4 joins with the two tokens of J2J_2; only b=b2b = b_2 is consistent [g1,b2,clear][g_1, b_2, \mathit{clear}] at J4J_4, an instantiation of R2R_2

The network now holds 5 tokens, and the conflict set holds one instantiation of each rule. Deleting block(b1,red)\mathit{block}(b_1, \mathit{red}) removes the token [g1,b1][g_1, b_1] and its child at J3J_3, so 3 tokens and the instantiation of R2R_2 remain. No join runs for the delete.

Correctness

The correctness proof shows an invariant: each alpha memory holds exactly the elements that pass its tests, each join node holds exactly one token for each match of its prefix, and the conflict set holds exactly the matches of the production nodes. For an insert, a new match gets its token at the first position where the new element occurs, by the right activation of that node, and then by left activations down the chain; the deepest-first order rules out a second copy. For a delete, the matches that contain the element are exactly the tokens that record it and their descendants.

Proof: The Rete network keeps exactly the partial matches and the conflict setfull

Fix a set of rules with positive conditions and the network that Rete builds for them. A join node jj stands for a prefix c1,…,cic_1, \ldots, c_i of the conditions of one or more rules; ii is the depth of jj (counted from 1 in this proof), and for i>1i > 1 its parent is the node of c1,…,ci−1c_1, \ldots, c_{i-1}. For a working memory WW, a match of jj is a tuple (w1,…,wi)(w_1, \ldots, w_i) of elements of WW such that one binding θ\theta of the variables makes ckθ=wkc_k\theta = w_k for all kk. We use the procedures INSERT and DELETE of the page.

Invariant. For the current working memory WW:

  • (A) each alpha memory with pattern π\pi holds exactly the elements w∈Ww \in W that match π\pi alone;
  • (B) the beta memory of each join node jj holds exactly one token for each match of jj, and the token records the tuple and its binding;
  • (C) the conflict set holds exactly the pairs (ρ,t)(\rho, t) where tt is a match of the last join node of the rule ρ\rho.

The invariant holds for the empty memory, since all memories and the conflict set are empty. (C) follows from (B), because a token at a node with productions adds or removes its instantiations at the same moment as the token is made or removed. So we prove that INSERT and DELETE keep (A) and (B).

Lemma 1 (a join step)

Let tt be a token for a match (w1,…,wi−1)(w_1, \ldots, w_{i-1}) of the parent of jj with binding θ\theta, and let ww be an element. The test of lines L6 and L10 succeeds exactly when (w1,…,wi−1,w)(w_1, \ldots, w_{i-1}, w) is a match of jj, and then it returns the binding of that match.

Proof. The test extends θ\theta so that cic_i equals ww. It fails exactly when a constant of cic_i differs from ww, or a variable already bound in θ\theta, or bound earlier in cic_i, gets two values. These are the conditions for a common binding of c1,…,cic_1, \ldots, c_i. □\square

The alpha test of line L1 uses cic_i with its variables renamed by first occurrence. It accepts a superset of the elements that pass the join test with any parent binding, so taking the candidates of the join from the alpha memory loses no match.

Lemma 2 (insert)

Let w∉Ww \notin W and W′=W∪{w}W' = W \cup \{w\}. After INSERT(w)(w), invariant (B) holds for W′W', and no token is made twice.

Proof. Lines L1 and L2 make (A) hold for W′W' before any join runs. The matches of jj for W′W' are the old matches, which keep their tokens, and the new matches, which contain ww. Take a new match u=(w1,…,wi)u = (w_1, \ldots, w_i) of a node jj, and let pp be the first position with wp=ww_p = w. Let jpj_p be the ancestor of jj at depth pp (or jj itself when p=ip = i), and jp−1j_{p-1} its parent.

uu gets a token. The prefix (w1,…,wp−1)(w_1, \ldots, w_{p-1}) does not contain ww, so it was a match of jp−1j_{p-1} before the insert and has an old token (for p=1p = 1 the root token plays this part). The node jpj_p reads an alpha memory that received ww, so line L4 right-activates it. Line L3 sorts the nodes by depth, deepest first, and a token made by a join only goes down to deeper nodes. So when jpj_p is right-activated, nothing has added a token to jp−1j_{p-1} yet, and its memory holds exactly the old matches. By Lemma 1, the right activation makes a token for (w1,…,wp)(w_1, \ldots, w_p). Each new token at a node is passed at once to each child node (line L8), and the left activation of lines L9 to L11 joins it with the whole alpha memory of the child, which already holds ww and every other element of W′W'. By induction on k=p,…,ik = p, \ldots, i, a token for (w1,…,wk)(w_1, \ldots, w_k) is made at depth kk.

uu gets only one token. Each token is made either by a right activation, from an old parent token and the element ww in the last position, or by a left activation, from a new parent token and one element of the alpha memory. Consider the tokens for (w1,…,wk)(w_1, \ldots, w_k) for k≥pk \ge p. At depth pp, a left activation would need a new token for (w1,…,wp−1)(w_1, \ldots, w_{p-1}), which does not exist since that tuple does not contain ww. So the only token at depth pp is the one that the single right activation of jpj_p made with the old parent token. For k>pk > p the parent tuple (w1,…,wk−1)(w_1, \ldots, w_{k-1}) contains ww, so it is new. If wk=ww_k = w, the node jkj_k was right-activated before jpj_p, at a time when the memory of jk−1j_{k-1} held no new token, so the right activation made no token for uu's prefix. So a token for (w1,…,wk)(w_1, \ldots, w_k) comes only from the left activation by the unique new parent token, and that left activation meets wkw_k once in the alpha memory. By induction, uu gets exactly one token.

No other token is made. By Lemma 1, every token that the joins make is a match for W′W', and it contains ww, since right activations put ww last and left activations start from a new parent token. □\square

Lemma 3 (delete)

Let w∈Ww \in W and W′=W∖{w}W' = W \setminus \{w\}. After DELETE(w)(w), invariants (A) and (B) hold for W′W'.

Proof. Line L12 makes (A) hold. A token for (w1,…,wi)(w_1, \ldots, w_i) is the child of the token for (w1,…,wi−1)(w_1, \ldots, w_{i-1}), and it records wiw_i. So the tokens whose tuple contains ww are exactly the tokens that record ww and their descendants, and lines L13 and L14 remove exactly these. The matches for W′W' are the matches for WW that do not contain ww, and each of them kept its one token. □\square

Theorem

After every sequence of inserts and deletes, the conflict set of the network equals the set of all instantiations of the rules in the current working memory, with no duplicates.

Proof. By induction on the length of the sequence, with Lemmas 2 and 3 for the step and (C) for the conflict set. An insert of an element that is in WW already, or a delete of an element that is not, changes nothing. ■\blacksquare

Why the order of line L3 matters

Take the rule with the conditions q(x,y)q(x, y) and q(y,x)q(y, x), and insert q(a,a)q(a, a). It enters both alpha memories. If the node of depth 1 runs first, it makes the token (q(a,a))(q(a, a)), and the left activation of the node of depth 2 makes (q(a,a),q(a,a))(q(a, a), q(a, a)). If the node of depth 2 is right-activated after that, it finds the new parent token and makes the same pair again. Deepest first, the node of depth 2 runs while its parent memory is still empty, and the pair is made once.

Complexity

The costs depend on the data much more than on the number of rules. An insert costs the size of the parent memories of the join nodes that ww reaches, plus, for each new token, the size of the alpha memories of the child nodes. A delete costs the number of tokens that it removes when the token lists are linked lists. In the worst case a join node at depth ii holds up to nin^i tokens, so one change can cost O(r m a nm)O(r\, m\, a\, n^m) time and the network can hold O(r m nm)O(r\, m\, n^m) tokens: the same order as matching every rule again, with more memory. This is the combined complexity; the match problem itself is NP-complete when the rules are part of the input, and for fixed rules (data complexity) the cost is polynomial in nn.

The advantage of Rete is a measured one. Forgy's measurements of OPS programs found that most of their run time went into the match, and that a typical cycle changes few elements, so the saved state removes most of the work. Doorenbos (1995) measured the basic algorithm and his extensions on learning systems with more than a hundred thousand rules. These are results on particular programs, not bounds.

Properties

  • Incremental. The state between cycles holds every partial match, and each change does work only for the matches it creates or destroys.
  • State saving. The memory can be much larger than the working memory: the price of the speed.
  • Sharing. Equal conditions share alpha memories, and equal prefixes share join nodes. The order of the conditions in a rule decides how much is shared and how large the beta memories are.
  • Exact. The conflict set after each change is the same as a full rematch gives, with no duplicates.

Variants and improvements

  • Negated conditions. A negative node keeps, for each token, the count of the elements that match the negated condition, and passes the token on only while the count is zero. This page does not implement it.
  • Hashed memories. Index alpha and beta memories by the values of the join variables, so a join reads only the consistent partners, as in a hash join.
  • Rete/UL. Doorenbos added unlinking of nodes whose memory is empty and other changes, so that very large learned rule sets do not slow each change.
  • TREAT. The TREAT algorithm of Miranker keeps no beta memories and recomputes the joins after each insert, trading time on inserts for memory and cheap deletes.
  • Later designs. Rete II and Rete-NT (Forgy's commercial versions), LEAPS (lazy matching) and Gator networks (which choose the join structure by cost) all change which partial matches are stored.

When to use it

Use Rete when many rules are matched again and again against a working memory that changes a little in each cycle, as in OPS5, CLIPS, Jess and Drools. The saved state pays off when the same partial matches are needed in many cycles. Use TREAT when memory is short or when elements are often removed, and use a plain query when the rules are run once over static data.

Pitfalls

  • Cross products. A rule whose first conditions share no variables makes beta memories with the product of their alpha memories. Order the conditions so that each one joins with the earlier ones.
  • Duplicate tokens. When an element can match two conditions of a rule, right activations must run deepest first, or the same match is made twice.
  • Modify as delete plus insert. A change to an element in OPS5 is a delete and an insert, so the tokens of the element are removed and made again.
  • Memory growth. The number of tokens can grow as nmn^m, and a few bad rules can fill the memory.

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.

rete_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# The Rete match algorithm for the page https://algorithm.tamnd.com/rete-algorithm/. The authors are listed in prov/.
"""The Rete match algorithm, with alpha memories, shared join nodes and tree-based removal.

A working memory element (WME) is a tuple of constants. A condition is a
pattern: a tuple in which a term may be a variable, a string that starts with
"?". A rule is (name, conditions), with one or more positive conditions. An
instantiation of a rule is the tuple of WMEs, one for each condition in order,
that match the conditions with one consistent binding of the variables. The
conflict set is the set of pairs (rule name, tuple of WMEs).

Rete(rules) builds the network. insert(w) and delete(w) change the working
memory, which is a set, and keep the conflict set up to date.

- An alpha memory holds the WMEs that pass the tests of one condition alone:
  its constants and the equalities between its own variables. Conditions that
  differ only in the names of their variables share one alpha memory.
- A join node stands for a prefix c_1, ..., c_i of the conditions of a rule.
  Rules with the same prefix share the node. Its beta memory holds tokens: the
  partial matches of the prefix.
- A token records its parent token, its WME and its children, and each WME
  records the tokens that hold it, so a delete removes exactly the tokens that
  contain the WME, without a new match.
"""


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


def match(pattern, wme, binding):
    """Extend binding so that pattern equals wme, or return None."""
    if len(pattern) != len(wme):
        return None
    out = dict(binding)
    for p, f in zip(pattern, wme):
        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 canonical(pattern):
    """Rename the variables of a pattern by their first occurrence: ("p", "?x", "?x") becomes ("p", "?0", "?0")."""
    names = {}
    out = []
    for t in pattern:
        if is_var(t):
            names.setdefault(t, "?" + str(len(names)))
            out.append(names[t])
        else:
            out.append(t)
    return tuple(out)


class AlphaMemory:
    def __init__(self, pattern):
        self.pattern = pattern
        self.items = set()
        self.successors = []  # the join nodes that read this memory


class Token:
    __slots__ = ("parent", "wme", "binding", "node", "children", "wmes")

    def __init__(self, parent, wme, binding, node):
        self.parent = parent
        self.wme = wme
        self.binding = binding
        self.node = node
        self.children = []
        self.wmes = () if parent is None else parent.wmes + (wme,)


class JoinNode:
    def __init__(self, parent, alpha, condition, depth):
        self.parent = parent  # None for the first condition
        self.alpha = alpha
        self.condition = condition
        self.depth = depth
        self.tokens = []  # the beta memory
        self.children = []
        self.productions = []


class Rete:
    def __init__(self, rules):
        self.alpha = {}
        self.joins = {}
        self.root = Token(None, None, {}, None)
        self.memory = set()
        self.conflict = {}
        self.wme_tokens = {}
        self.tokens_made = 0
        self.duplicates = 0
        for name, conditions in rules:
            if not conditions:
                raise ValueError(f"rule {name} has no condition")
            node = None
            for i, c in enumerate(conditions):
                key = tuple(conditions[: i + 1])
                if key not in self.joins:
                    am = self.alpha.setdefault(canonical(c), AlphaMemory(canonical(c)))
                    nn = JoinNode(node, am, tuple(c), i)
                    am.successors.append(nn)
                    if node is not None:
                        node.children.append(nn)
                    self.joins[key] = nn
                node = self.joins[key]
            node.productions.append(name)

    def conflict_set(self):
        return set(self.conflict)

    def _make_token(self, parent, wme, binding, node):
        t = Token(parent, wme, binding, node)  # @line L8
        self.tokens_made += 1
        node.tokens.append(t)
        parent.children.append(t)
        self.wme_tokens.setdefault(wme, []).append(t)
        for name in node.productions:
            key = (name, t.wmes)
            if key in self.conflict:
                self.duplicates += 1
            self.conflict[key] = t.binding
        for child in node.children:
            self._left_activate(child, t)

    def _left_activate(self, node, token):
        for w in list(node.alpha.items):  # @line L9
            b = match(node.condition, w, token.binding)  # @line L10
            if b is not None:
                self._make_token(token, w, b, node)  # @line L11

    def _right_activate(self, node, w):
        parents = [self.root] if node.parent is None else list(node.parent.tokens)
        for t in parents:  # @line L5
            b = match(node.condition, w, t.binding)  # @line L6
            if b is not None:
                self._make_token(t, w, b, node)  # @line L7

    def insert(self, w):
        w = tuple(w)
        if w in self.memory:
            return
        self.memory.add(w)
        targets = []
        for am in self.alpha.values():  # @line L1
            if match(am.pattern, w, {}) is not None:
                am.items.add(w)  # @line L2
                targets.extend(am.successors)
        targets.sort(key=lambda n: -n.depth)  # @line L3
        for node in targets:  # @line L4
            self._right_activate(node, w)

    def _delete_token(self, t):
        while t.children:
            self._delete_token(t.children[-1])
        t.node.tokens.remove(t)
        t.parent.children.remove(t)
        self.wme_tokens[t.wme].remove(t)
        for name in t.node.productions:
            self.conflict.pop((name, t.wmes), None)

    def delete(self, w):
        w = tuple(w)
        if w not in self.memory:
            return
        self.memory.discard(w)
        for am in self.alpha.values():  # @line L12
            am.items.discard(w)
        for t in list(self.wme_tokens.get(w, [])):  # @line L13
            if t.node is not None and t in t.node.tokens:
                self._delete_token(t)  # @line L14
        self.wme_tokens.pop(w, None)

    def token_count(self):
        return sum(len(n.tokens) for n in self.joins.values())
test_rete_algorithm.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rete-algorithm/. The authors are listed in prov/.

import random
import unittest
from itertools import product

from rete_algorithm import Rete, canonical, match

CONSTS = ["a", "b", "c"]
PREDS = [("p", 1), ("q", 2), ("r", 2)]
VARS = ["?x", "?y", "?z"]
ALL_WMES = [(name,) + args for name, arity in PREDS for args in product(CONSTS, repeat=arity)]


def naive_conflict_set(rules, memory):
    """Rematch every rule against the whole working memory."""
    out = set()
    for name, conditions in rules:
        def go(k, b, chosen):
            if k == len(conditions):
                out.add((name, tuple(chosen)))
                return
            for w in memory:
                b2 = match(conditions[k], w, b)
                if b2 is not None:
                    go(k + 1, b2, chosen + [w])
        go(0, {}, [])
    return out


def random_rules(rng):
    def condition():
        name, arity = rng.choice(PREDS)
        return (name,) + tuple(rng.choice(VARS + VARS + CONSTS) for _ in range(arity))

    rules = []
    first = [condition() for _ in range(2)]
    for r in range(rng.randint(1, 5)):
        conds = [rng.choice(first)] if rng.random() < 0.5 else []  # shared prefixes
        conds += [condition() for _ in range(rng.randint(1, 3))]
        rules.append(("r" + str(r), conds))
    return rules


class TestRete(unittest.TestCase):
    def test_canonical(self):
        self.assertEqual(canonical(("q", "?y", "?y")), ("q", "?0", "?0"))
        self.assertEqual(canonical(("q", "?x", "b")), canonical(("q", "?z", "b")))

    def test_page_example(self):
        rules = [
            ("R1", [("goal", "?g"), ("block", "?b", "red"), ("on", "?b", "?t")]),
            ("R2", [("goal", "?g"), ("block", "?b", "red"), ("clear", "?b")]),
        ]
        net = Rete(rules)
        self.assertEqual(len(net.alpha), 4)
        self.assertEqual(len(net.joins), 4)
        for w in [("goal", "g1"), ("block", "b1", "red"), ("block", "b2", "red"), ("block", "b3", "blue"), ("on", "b1", "table"), ("clear", "b2")]:
            net.insert(w)
        self.assertEqual(
            net.conflict_set(),
            {
                ("R1", (("goal", "g1"), ("block", "b1", "red"), ("on", "b1", "table"))),
                ("R2", (("goal", "g1"), ("block", "b2", "red"), ("clear", "b2"))),
            },
        )
        self.assertEqual(net.token_count(), 5)
        net.delete(("block", "b1", "red"))
        self.assertEqual(net.conflict_set(), {("R2", (("goal", "g1"), ("block", "b2", "red"), ("clear", "b2")))})
        self.assertEqual(net.token_count(), 3)

    def test_same_wme_in_two_conditions(self):
        rules = [("loop", [("q", "?x", "?y"), ("q", "?y", "?x")])]
        net = Rete(rules)
        net.insert(("q", "a", "a"))
        self.assertEqual(net.conflict_set(), {("loop", (("q", "a", "a"), ("q", "a", "a")))})
        self.assertEqual(net.duplicates, 0)
        net.delete(("q", "a", "a"))
        self.assertEqual(net.conflict_set(), set())
        self.assertEqual(net.token_count(), 0)

    def test_random_against_naive(self):
        rng = random.Random(20261115)
        for _ in range(150):
            rules = random_rules(rng)
            net = Rete(rules)
            memory = set()
            for _ in range(40):
                w = rng.choice(ALL_WMES)
                if w in memory and rng.random() < 0.5:
                    memory.discard(w)
                    net.delete(w)
                else:
                    memory.add(w)
                    net.insert(w)
                self.assertEqual(net.memory, memory)
                self.assertEqual(net.conflict_set(), naive_conflict_set(rules, memory))
                self.assertEqual(net.duplicates, 0)
            for w in list(memory):
                net.delete(w)
            self.assertEqual(net.conflict_set(), set())
            self.assertEqual(net.token_count(), 0)
            self.assertTrue(all(not am.items for am in net.alpha.values()))


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

History

Forgy developed the network match at Carnegie-Mellon in the 1970s, for the OPS family of production system languages, described it in his 1979 thesis, and published the full algorithm in Artificial Intelligence in 1982. OPS5 (1981) made it widely known. Miranker (1987) proposed TREAT as a lighter alternative. Doorenbos (1995) gave the now standard description with tree-based removal and the Rete/UL extensions. CLIPS, Jess and Drools use Rete variants.

References

  1. Charles L. Forgy, Rete: A fast algorithm for the many pattern/many object pattern match problem, Artificial Intelligence 19(1), 17 to 37 (1982), the description of the pattern and data representations, the network and its node types, and the operations of the matcher
  2. Robert B. Doorenbos, Production Matching for Large Learning Systems, PhD thesis, Carnegie Mellon University, technical report CMU-CS-95-113 (1995), the chapter on the basic Rete algorithm (alpha memories, beta memories, join nodes and tree-based removal)
  3. Charles L. Forgy, OPS5 User's Manual, technical report CMU-CS-81-135, Carnegie-Mellon University (1981), the description of the recognize-act cycle that the matcher serves
  4. Lee Brownston, Robert Farrell, Elaine Kant and Nancy Martin, Programming Expert Systems in OPS5, Addison-Wesley (1985), the parts on the Rete match and on writing efficient OPS5 programs

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