Algorithm Search⌘K

Algorithmadvanced

TREAT algorithm

Also called Miranker TREAT.

A production system matcher that keeps only the matches of single conditions and the conflict set, joins each new element with the other conditions, and deletes by a scan of the conflict set.

Time
O(r m a n^(m-1)) worst
Space
O(r m n + k) extra
Where
a = the largest arity of an element; k = the number of instantiations in the conflict set; 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
Daniel P. Miranker, 1987

TREAT is a match algorithm for production systems, proposed by Miranker as an alternative to the Rete algorithm. Both keep the conflict set up to date while the working memory changes. Rete stores every partial match of every prefix of the conditions of a rule in beta memories. TREAT stores only the alpha memories, the elements that match each single condition, and the conflict set itself. When an element is inserted, TREAT joins it with the alpha memories of the other conditions of each rule that it touches. When an element is deleted, TREAT removes the instantiations that hold it from the conflict set, with no join at all. So TREAT does more work on inserts and less on deletes, and it uses much less memory.

In plain words

A rule system needs to know, after every change to its facts, which rules can fire with which facts. TREAT keeps two things: for each condition of each rule, the list of facts that fit that condition alone, and the list of complete matches. When a new fact arrives, it is put in the lists of the conditions it fits. Then, for each rule and each such condition, TREAT looks for complete matches that use the new fact there, by pairing it with facts from the lists of the other conditions. When a fact is removed, TREAT takes it out of the lists and drops every complete match that uses it. Nothing in between is saved, so nothing in between has to be cleaned up.

The problem

The setting is the same as for Rete. A working memory element (WME) is a ground tuple. A rule is ρ:c1,…,cm⇒actions\rho: c_1, \ldots, c_m \Rightarrow \text{actions} with condition patterns ckc_k. 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 such that ckθ=wkc_k\theta = w_k for every kk. The conflict set is the set of pairs (ρ,(w1,…,wm))(\rho, (w_1, \ldots, w_m)) over all rules. The task is to keep the conflict set correct after each insert or delete of one element. This page treats positive conditions only.

The algorithm

Each condition has an alpha memory, keyed by the condition with its variables renamed by first occurrence, so that equal conditions of different rules share it. It holds the elements that pass the constant tests and the equality tests within the condition.

  1. INSERT(w)
  2. 1for each alpha memory α whose tests w passes do
  3. 2add w to α
  4. 3for each rule ρ with the conditions c_1, …, c_m do
  5. 4for each i such that the alpha memory of c_i received w do
  6. 5for each binding θ with c_i θ = w and, for each j ≠ i, c_j θ = w_j for an element w_j of the alpha memory of c_j, where w_j ≠ w for j < i do
  7. 6add (ρ, (w_1, …, w_m)) to the conflict set, with w_i = w
  8. DELETE(w)
  9. 7remove w from every alpha memory
  10. 8for each instantiation in the conflict set that holds w do
  11. 9remove it from the conflict set

Line L5 is a seeded join: it starts from the binding that ww gives at position ii and binds the other conditions one at a time, as a nested loop join does. The rule wj≠ww_j \ne w for j<ij < i makes each new instantiation come from the first position where ww occurs, so an element that matches two conditions of one rule does not make the same instantiation twice. Miranker's condition membership adds a flag for each rule that says whether every alpha memory of the rule is non-empty; line L4 can skip a rule whose flag is off.

Example

Take the two rules of the Rete example,

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}

and the elements goal(g1)\mathit{goal}(g_1), block(b1,red)\mathit{block}(b_1, \mathit{red}), block(b2,red)\mathit{block}(b_2, \mathit{red}), block(b3,blue)\mathit{block}(b_3, \mathit{blue}) and on(b1,table)\mathit{on}(b_1, \mathit{table}), inserted in this order. TREAT has the same 4 alpha memories as Rete, and the conflict set holds (R1,(goal(g1),block(b1,red),on(b1,table)))(R_1, (\mathit{goal}(g_1), \mathit{block}(b_1, \mathit{red}), \mathit{on}(b_1, \mathit{table}))).

change seeds join work conflict set change
insert clear(b2)\mathit{clear}(b_2) R2R_2 at position 3, binding b=b2b = b_2 goal memory: g1g_1; block memory: b1b_1 fails the test b=b2b = b_2, b2b_2 passes add the instantiation of R2R_2
delete block(b1,red)\mathit{block}(b_1, \mathit{red}) none none remove the instantiation of R1R_1
insert block(b1,red)\mathit{block}(b_1, \mathit{red}) R1R_1 and R2R_2 at position 2, binding b=b1b = b_1 R1R_1: goal g1g_1, then on: on(b1,table)\mathit{on}(b_1, \mathit{table}) passes; R2R_2: goal g1g_1, then clear: clear(b2)\mathit{clear}(b_2) fails add the instantiation of R1R_1 again

Rete would answer the first insert from its stored tokens for goal,block\mathit{goal}, \mathit{block}, and would answer the delete by removing two tokens. TREAT recomputes the join of the goal and block memories, and needs no tokens at all.

Correctness

The correctness proof keeps the invariant that each alpha memory holds exactly the elements that pass its tests and that the conflict set holds exactly the instantiations, each once. After an insert, the new instantiations are those that contain ww. Each has a first position pp where ww occurs; the seeded join at pp produces it once, and the seeded join at any later position ii with wi=ww_i = w rejects it, because wp=ww_p = w with p<ip < i. A delete removes exactly the instantiations that hold ww.

Proof: TREAT keeps the conflict set exact, with each instantiation made oncefull

Fix a set of rules with positive conditions. For a working memory WW, an instantiation of a rule ρ=c1,…,cm\rho = c_1, \ldots, c_m is a tuple (w1,…,wm)(w_1, \ldots, w_m) of elements of WW with one binding θ\theta such that ckθ=wkc_k\theta = w_k for every 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 of WW that match π\pi alone;
  • (C) the conflict set holds exactly the pairs (ρ,u)(\rho, u) where uu is an instantiation of ρ\rho in WW, each once.

Both hold for the empty memory.

Lemma 1 (the seeded join)

Let (A) hold for W′=W∪{w}W' = W \cup \{w\}. For a rule ρ\rho and a position ii, line L5 enumerates, each exactly once, the instantiations (w1,…,wm)(w_1, \ldots, w_m) of ρ\rho in W′W' with wi=ww_i = w and wj≠ww_j \ne w for all j<ij < i.

Proof. The join binds the positions j≠ij \ne i one at a time and tries each element of the alpha memory of cjc_j, extending the binding with the test of cjc_j; this is a depth-first enumeration of all tuples of candidates, so each tuple is reached at most once. An element that matches cjc_j under some binding also passes the alpha test of cjc_j, since the alpha pattern is cjc_j with its variables renamed by first occurrence. So by (A) every element of W′W' that can stand at position jj is in the alpha memory. The test of each step succeeds exactly when the chosen elements so far have a common binding. So the leaves are exactly the instantiations with ww at position ii, minus those that the rule wj≠ww_j \ne w for j<ij < i excludes. □\square

Lemma 2 (insert)

Let w∉Ww \notin W. After INSERT(w)(w) the invariant holds for W′=W∪{w}W' = W \cup \{w\}.

Proof. Lines L1 and L2 make (A) hold. The instantiations in W′W' are the old ones, which are still in the conflict set, and the new ones, which contain ww. Take a new instantiation u=(w1,…,wm)u = (w_1, \ldots, w_m) of ρ\rho and let pp be the first position with wp=ww_p = w. The element ww matches cpc_p, so the alpha memory of cpc_p received ww, and line L4 runs the join with i=pi = p. By Lemma 1 this join yields uu once. A join with i≠pi \ne p does not yield uu: if wi≠ww_i \ne w, then uu does not have ww at position ii; if wi=ww_i = w, then i>pi > p, and wp=ww_p = w breaks the rule for the positions before ii. No join yields a tuple that is not an instantiation, or one without ww. So each new instantiation is added once, and nothing else is added. □\square

Lemma 3 (delete)

Let w∈Ww \in W. After DELETE(w)(w) the invariant holds for W′=W∖{w}W' = W \setminus \{w\}.

Proof. Line L7 makes (A) hold. The instantiations in W′W' are the instantiations in WW that do not contain ww. Lines L8 and L9 remove exactly the others. □\square

Theorem

After every sequence of inserts and deletes, the conflict set equals the set of all instantiations of the rules in the current working memory, and no instantiation was added twice.

Proof. By induction on the length of the sequence, with Lemmas 2 and 3. An insert of an element of WW or a delete of an element not in WW changes nothing. ■\blacksquare

Remark

The rule "wj≠ww_j \ne w for j<ij < i" is what makes each instantiation appear once when ww matches two conditions of the same rule. Without it, the rule q(x,y),q(y,x)q(x, y), q(y, x) and the insert of q(a,a)q(a, a) would add the pair (q(a,a),q(a,a))(q(a, a), q(a, a)) twice, once for each seed position.

Complexity

An insert runs, for each rule and each position whose alpha memory received ww, a join over the m−1m - 1 other alpha memories. The search tree of one join has O(nm−1)O(n^{m-1}) nodes and each test costs O(a)O(a), so an insert costs O(r m a nm−1)O(r\, m\, a\, n^{m-1}) time in the worst case. A delete scans the conflict set in O(k m)O(k\, m) time, or takes time proportional to the instantiations it removes when each element keeps a list of its instantiations. The extra space is the alpha memories, O(r m n)O(r\, m\, n), plus the conflict set, O(k)O(k). Rete in the worst case stores O(r m nm)O(r\, m\, n^m) tokens.

As for Rete, these are combined complexity bounds, and the match problem is NP-complete when the rules are part of the input. The speed comparison with Rete is a measurement: Miranker (1987) ran both on five OPS5 programs and found TREAT faster, often by more than half. The result depends on the programs, on how often they delete elements, and on the two implementations; Doorenbos (1995) argued, from his own measurements, that on very large learned rule sets the stored state of Rete is worth its cost.

Properties

  • Incremental. The conflict set is kept between changes; only alpha memories are kept besides it.
  • Little state. The memory is linear in the working memory, plus the conflict set.
  • Cheap deletes. A delete needs no join, only the removal of the instantiations that hold the element.
  • Repeated joins. The same partial match is computed again on each insert that needs it.
  • Exact. The conflict set equals the result of a full rematch after each change, with no duplicates.

Variants and improvements

  • Condition membership. Skip the joins of a rule while one of its alpha memories is empty. Miranker describes this as a part of TREAT; the implementation here does without it, since its join stops at the first empty memory.
  • Join order. Order the other conditions of a seeded join by the size of their alpha memories, or by the variables they share with the seed, to keep the search tree small.
  • Negated conditions. An insert that matches a negated condition removes the instantiations that it blocks; a delete that matches a negated condition needs a seeded join for the instantiations that it unblocks.
  • Gator networks. Hanson and Hasan generalized Rete and TREAT to networks that store an optimized choice of partial matches.
  • Lazy matching. LEAPS computes only the instantiation that conflict resolution would pick next, not the whole conflict set.

When to use it

Use TREAT when memory is limited, when facts are often deleted or modified, or when the rules have conditions with large alpha memories that would make large beta memories in Rete. Use Rete when the same partial matches are needed in many cycles and memory is not the limit. Both give the same conflict set, so the choice affects only the cost.

Pitfalls

  • Double counting. When an element matches two conditions of one rule, only the first position may seed the instantiation; without the rule wj≠ww_j \ne w for j<ij < i the conflict set gets duplicates.
  • Join order. A seeded join that binds an unrelated condition first makes a cross product.
  • Delete cost. Without an index from elements to instantiations, each delete scans the whole conflict set.
  • Reading the speed claim as a bound. TREAT is faster on the programs that Miranker measured; on programs that reuse long partial matches, Rete can be faster.

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.

treat_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# The TREAT match algorithm for the page https://algorithm.tamnd.com/treat-algorithm/. The authors are listed in prov/.
"""The TREAT match algorithm: alpha memories and the conflict set, with no beta memories.

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 is the tuple of WMEs, one for each condition in order, that match
the conditions with one consistent binding. The conflict set is the set of
pairs (rule name, tuple of WMEs).

Treat(rules) keeps one alpha memory for each condition pattern, shared by the
conditions that differ only in the names of their variables, and the conflict
set. insert(w) joins w, as the element of each condition that it matches, with
the alpha memories of the other conditions. delete(w) removes from the conflict
set the instantiations that hold w. No partial match is stored between changes.
"""


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."""
    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 Treat:
    def __init__(self, rules):
        self.alpha = {}
        self.rules = []
        self.memory = set()
        self.conflict = {}
        self.partial_matches = 0  # the number of consistent partial bindings that joins have built
        self.duplicates = 0
        for name, conditions in rules:
            if not conditions:
                raise ValueError(f"rule {name} has no condition")
            keys = [canonical(c) for c in conditions]
            for k in keys:
                self.alpha.setdefault(k, set())
            self.rules.append((name, [tuple(c) for c in conditions], keys))

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

    def _seeded_join(self, conditions, keys, i, w):
        """Every instantiation whose element at position i is w and whose elements before i are not w."""
        order = [j for j in range(len(conditions)) if j != i]
        chosen = [None] * len(conditions)
        chosen[i] = w

        def go(k, b):
            if k == len(order):
                yield tuple(chosen), b
                return
            j = order[k]
            for v in list(self.alpha[keys[j]]):
                if j < i and v == w:
                    continue
                b2 = match(conditions[j], v, b)
                if b2 is not None:
                    self.partial_matches += 1
                    chosen[j] = v
                    yield from go(k + 1, b2)

        b0 = match(conditions[i], w, {})
        if b0 is not None:
            self.partial_matches += 1
            yield from go(0, b0)

    def insert(self, w):
        w = tuple(w)
        if w in self.memory:
            return
        self.memory.add(w)
        hit = set()
        for key, items in self.alpha.items():  # @line L1
            if match(key, w, {}) is not None:
                items.add(w)  # @line L2
                hit.add(key)
        for name, conditions, keys in self.rules:  # @line L3
            for i, key in enumerate(keys):
                if key not in hit:  # @line L4
                    continue
                for wmes, binding in self._seeded_join(conditions, keys, i, w):  # @line L5
                    inst = (name, wmes)
                    if inst in self.conflict:
                        self.duplicates += 1
                    self.conflict[inst] = binding  # @line L6

    def delete(self, w):
        w = tuple(w)
        if w not in self.memory:
            return
        self.memory.discard(w)
        for items in self.alpha.values():  # @line L7
            items.discard(w)
        for inst in [x for x in self.conflict if w in x[1]]:  # @line L8
            del self.conflict[inst]  # @line L9
test_treat_algorithm.py 87 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/treat-algorithm/. The authors are listed in prov/.

import random
import unittest
from itertools import product

from treat_algorithm import Treat, 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))

    return [("r" + str(r), [condition() for _ in range(rng.randint(1, 4))]) for r in range(rng.randint(1, 5))]


class TestTreat(unittest.TestCase):
    def test_page_example(self):
        rules = [
            ("R1", [("goal", "?g"), ("block", "?b", "red"), ("on", "?b", "?t")]),
            ("R2", [("goal", "?g"), ("block", "?b", "red"), ("clear", "?b")]),
        ]
        m = Treat(rules)
        self.assertEqual(len(m.alpha), 4)
        for w in [("goal", "g1"), ("block", "b1", "red"), ("block", "b2", "red"), ("block", "b3", "blue"), ("on", "b1", "table"), ("clear", "b2")]:
            m.insert(w)
        r2 = ("R2", (("goal", "g1"), ("block", "b2", "red"), ("clear", "b2")))
        self.assertEqual(m.conflict_set(), {("R1", (("goal", "g1"), ("block", "b1", "red"), ("on", "b1", "table"))), r2})
        before = m.partial_matches
        m.delete(("block", "b1", "red"))
        self.assertEqual(m.conflict_set(), {r2})
        self.assertEqual(m.partial_matches, before)  # a delete does no join

    def test_same_wme_in_two_conditions(self):
        m = Treat([("loop", [("q", "?x", "?y"), ("q", "?y", "?x")])])
        m.insert(("q", "a", "a"))
        self.assertEqual(m.conflict_set(), {("loop", (("q", "a", "a"), ("q", "a", "a")))})
        m.insert(("q", "a", "b"))
        m.insert(("q", "b", "a"))
        self.assertEqual(len(m.conflict_set()), 3)
        self.assertEqual(m.duplicates, 0)

    def test_random_against_naive(self):
        rng = random.Random(20261115)
        for _ in range(150):
            rules = random_rules(rng)
            m = Treat(rules)
            memory = set()
            for _ in range(40):
                w = rng.choice(ALL_WMES)
                if w in memory and rng.random() < 0.5:
                    memory.discard(w)
                    m.delete(w)
                else:
                    memory.add(w)
                    m.insert(w)
                self.assertEqual(m.conflict_set(), naive_conflict_set(rules, memory))
                self.assertEqual(m.duplicates, 0)
                for key, items in m.alpha.items():
                    self.assertEqual(items, {w for w in memory if match(key, w, {}) is not None})


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

History

Miranker developed TREAT at Columbia University in the mid-1980s, as part of the DADO project on parallel production systems, and presented it at AAAI-87 with measurements on five OPS5 programs. His thesis appeared as a book in 1990. Later work combined the two ideas: Gator networks (Hanson and Hasan, 1993) choose which partial matches to store, and LEAPS (Miranker and others, 1990) matches lazily.

References

  1. Daniel P. Miranker, TREAT: A better match algorithm for AI production systems, Proceedings of the Sixth National Conference on Artificial Intelligence (AAAI-87), volume 1, 42 to 47 (1987), the description of the algorithm, condition membership, and the comparison with Rete on five OPS5 programs
  2. 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 network that TREAT is compared with
  3. Robert B. Doorenbos, Production Matching for Large Learning Systems, PhD thesis, Carnegie Mellon University, technical report CMU-CS-95-113 (1995), the discussion of TREAT and of the trade-off between storing and recomputing partial matches

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