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
- Model
- Word RAM
- Properties
- deterministicincremental
- Evidence
- Proof sketchCode in 1 languages
- 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 with condition patterns . An instantiation of in the working memory is a tuple of elements of with one binding such that for every . The conflict set is the set of pairs 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.
INSERT(w)- 1
for each alpha memory α whose tests w passes do - 2
add w to α - 3
for each rule ρ with the conditions c_1, …, c_m do - 4
for each i such that the alpha memory of c_i received w do - 5
for 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 - 6
add (ρ, (w_1, …, w_m)) to the conflict set, with w_i = w DELETE(w)- 7
remove w from every alpha memory - 8
for each instantiation in the conflict set that holds w do - 9
remove it from the conflict set
Line L5 is a seeded join: it starts from the binding that gives at position and binds the other conditions one at a time, as a nested loop join does. The rule for makes each new instantiation come from the first position where 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,
and the elements , , , and , inserted in this order. TREAT has the same 4 alpha memories as Rete, and the conflict set holds .
| change | seeds | join work | conflict set change |
|---|---|---|---|
| insert | at position 3, binding | goal memory: ; block memory: fails the test , passes | add the instantiation of |
| delete | none | none | remove the instantiation of |
| insert | and at position 2, binding | : goal , then on: passes; : goal , then clear: fails | add the instantiation of again |
Rete would answer the first insert from its stored tokens for , 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 . Each has a first position where occurs; the seeded join at produces it once, and the seeded join at any later position with rejects it, because with . A delete removes exactly the instantiations that hold .
Proof: TREAT keeps the conflict set exact, with each instantiation made oncefull
Fix a set of rules with positive conditions. For a working memory , an instantiation of a rule is a tuple of elements of with one binding such that for every . We use the procedures INSERT and DELETE of the page.
Invariant. For the current working memory :
- (A) each alpha memory with pattern holds exactly the elements of that match alone;
- (C) the conflict set holds exactly the pairs where is an instantiation of in , each once.
Both hold for the empty memory.
Lemma 1 (the seeded join)
Let (A) hold for . For a rule and a position , line L5 enumerates, each exactly once, the instantiations of in with and for all .
Proof. The join binds the positions one at a time and tries each element of the alpha memory of , extending the binding with the test of ; this is a depth-first enumeration of all tuples of candidates, so each tuple is reached at most once. An element that matches under some binding also passes the alpha test of , since the alpha pattern is with its variables renamed by first occurrence. So by (A) every element of that can stand at position 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 at position , minus those that the rule for excludes.
Lemma 2 (insert)
Let . After INSERT the invariant holds for .
Proof. Lines L1 and L2 make (A) hold. The instantiations in are the old ones, which are still in the conflict set, and the new ones, which contain . Take a new instantiation of and let be the first position with . The element matches , so the alpha memory of received , and line L4 runs the join with . By Lemma 1 this join yields once. A join with does not yield : if , then does not have at position ; if , then , and breaks the rule for the positions before . No join yields a tuple that is not an instantiation, or one without . So each new instantiation is added once, and nothing else is added.
Lemma 3 (delete)
Let . After DELETE the invariant holds for .
Proof. Line L7 makes (A) hold. The instantiations in are the instantiations in that do not contain . Lines L8 and L9 remove exactly the others.
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 or a delete of an element not in changes nothing.
Remark
The rule " for " is what makes each instantiation appear once when matches two conditions of the same rule. Without it, the rule and the insert of would add the pair twice, once for each seed position.
Complexity
An insert runs, for each rule and each position whose alpha memory received , a join over the other alpha memories. The search tree of one join has nodes and each test costs , so an insert costs time in the worst case. A delete scans the conflict set in 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, , plus the conflict set, . Rete in the worst case stores 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 for 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.
# 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
- 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
- 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
- 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.
| 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 YM9BB7 Edit this page History Report an error Markdown