Algorithm Search⌘K

Algorithmadvanced

Reiter's hitting set tree

Also called HS-tree, Greiner HS-DAG.

Finds all minimal diagnoses as the minimal hitting sets of the conflict sets, with a breadth-first search tree whose edges are elements of conflicts.

Time
O(k · (k + m) · u) worst
Space
Θ(k · u) extra
Where
k = the number of nodes that the search creates; m = the number of distinct labels; u = the number of components
Properties
deterministic
Origin
Raymond Reiter, Russell Greiner, Barbara A. Smith, Ralph W. Wilkerson, 1987

This page is the diagnosis search tree. In consistency-based diagnosis, a diagnosis is a minimal set of components that, when assumed faulty, makes the observations consistent with the system description. Reiter (1987, Theorem 4.4) proved that the diagnoses are exactly the minimal hitting sets of the conflict sets. The hitting set page covers the set problem itself. This page covers the search that Reiter built on the theorem: a breadth-first tree that asks a consistency checker for one conflict at a time, never needs the whole list of conflicts, and stops at the minimal hitting sets. Reiter's rules for pruning the tree are wrong in some cases. Greiner, Smith and Wilkerson (1989) gave two examples where a diagnosis is lost, and replaced the tree by a directed acyclic graph, the HS-DAG, which they proved correct.

In plain words

A machine misbehaves, and a checker can tell you a group of parts that cannot all be working, called a conflict. The search starts with no suspects. It asks for a conflict and branches on each part in it: "suppose this part is broken". On each branch it asks again for a conflict that avoids the parts already suspected, and branches again. A branch ends when the suspects explain everything, and then they form a diagnosis. The search goes level by level, so small diagnoses come first, and a branch that contains a diagnosis already found is dropped. When the checker gives a large conflict and later a smaller one inside it, the search can cut the branches for the extra parts. The correction is about doing this cut safely.

The problem

The input is a finite set UU of components and a label oracle next\mathrm{next}. For a set h⊆Uh \subseteq U of suspected components, next(h)\mathrm{next}(h) returns nothing if hh hits every conflict, and otherwise a conflict L⊆UL \subseteq U with L∩h=∅L \cap h = \emptyset. In diagnosis, a conflict is a set CC of components such that the system description, the observations and the statements "cc is not abnormal" for all c∈Cc \in C are inconsistent together. The oracle needs only a consistency checker: next(h)\mathrm{next}(h) tests the components outside hh, and if they are inconsistent, it deletes components one at a time while the rest stays inconsistent. A conflict need not be minimal. For an explicit collection FF of sets, the oracle returns the first member of FF that is disjoint from hh.

The output is the set of all minimal hitting sets of the conflicts, that is, all minimal diagnoses. If the observations alone contradict the system description, the empty set is a conflict and there is no diagnosis. If nothing is wrong, the answer is the single empty diagnosis.

The algorithm

Each node nn stands for the set H(n)H(n) of the labels on the path from the root. A node is identified by H(n)H(n), so two paths with the same edge labels in a different order end at the same node. This is what makes the structure a DAG.

  1. HS-DAG(next) ▷ next(h): a conflict disjoint from h, or nothing
  2. 1create the root with H = ∅; labels ← an empty list
  3. 2level ← [root]
  4. 3while level is not empty do
  5. 4following ← []
  6. 5for each node n of level that still exists and has no status do
  7. 6if some checked node m has H(m) ⊊ H(n) then mark n closed; continue
  8. 7L ← the first S in labels with S ∩ H(n) = ∅, or nothing ▷ reuse a known conflict
  9. 8if L is nothing then
  10. 9L ← next(H(n))
  11. 10if L is nothing then mark n checked; continue ▷ H(n) is a diagnosis
  12. 11PRUNE(L); append L to labels
  13. 12if n was deleted by PRUNE then continue
  14. 13mark n labeled with L
  15. 14for each σ in L do
  16. 15c ← H(n) ∪ {σ}
  17. 16if no node has H = c then
  18. 17create the node c
  19. 18append c to following
  20. 19add an edge marked σ from n to c
  21. 20level ← following
  22. 21return the sets H(n) of the checked nodes
  23. PRUNE(Σ)
  24. 22for each node n' with a label S' ⊋ Σ do: relabel n' with Σ, remove its edges for the elements of S' ∖ Σ, and remove S' from labels
  25. 23delete every node that the root no longer reaches

Line L7 is Reiter's label reuse: a known conflict that avoids H(n)H(n) saves a call of the oracle, which is often a theorem prover. Line L6 is the closing rule: a node above a known diagnosis cannot lead to a minimal one. Lines L22 and L23 are the pruning step of Greiner, Smith and Wilkerson. In their version the collection FF is ordered and S′S' is swapped with Σ\Sigma in FF; removing S′S' from the list of labels has the same effect.

Example

This is the example in Figure 1 of Greiner, Smith and Wilkerson. The conflicts, in this order, are F={a,b},{b,c},{a,c},{b,d},{b}F = \{a,b\}, \{b,c\}, \{a,c\}, \{b,d\}, \{b\}. The minimal hitting sets must contain bb, and then one of aa or cc, so they are {a,b}\{a,b\} and {b,c}\{b,c\}.

level node HH result why
0 ∅\emptyset label {a,b}\{a,b\} the first conflict
1 {a}\{a\} label {b,c}\{b,c\} the first conflict that avoids aa
1 {b}\{b\} label {a,c}\{a,c\} its aa edge goes to the node {a,b}\{a,b\}, which already exists
2 {a,b}\{a,b\} checked it meets every conflict
2 {a,c}\{a,c\} label {b,d}\{b,d\}
2 {b,c}\{b,c\} checked it meets every conflict
3 {a,b,c}\{a,b,c\} closed it contains the diagnosis {a,b}\{a,b\}
3 {a,c,d}\{a,c,d\} label {b}\{b\}, deleted the new conflict {b}\{b\} prunes

The new label {b}\{b\} is a proper subset of the labels of the root, of {a}\{a\} and of {a,c}\{a,c\}. PRUNE gives all three the label {b}\{b\} and removes the edges for aa, cc and dd respectively. The root now reaches only {b}\{b\}, and through it {a,b}\{a,b\} and {b,c}\{b,c\}. The nodes {a}\{a\}, {a,c}\{a,c\}, {a,b,c}\{a,b,c\} and {a,c,d}\{a,c,d\} are deleted. The node {a,b}\{a,b\} stays, because its other parent {b}\{b\} stays. The result is {a,b}\{a,b\} and {b,c}\{b,c\}.

Reiter's original tree makes a separate node for each path. It closes the path b,ab, a because the path a,ba, b already gave the same set. Then the label {b}\{b\} cuts the aa edge of the root, and the path a,ba, b goes with it, so {a,b}\{a,b\} is lost. Figure 2 of the same paper shows a second error: with F={a,b},{a},{b}F = \{a,b\}, \{a\}, \{b\}, the root keeps its label {a,b}\{a,b\}, the label {b}\{b\} cuts its aa edge, and later the label {a}\{a\} cuts its bb edge. The tree returns nothing, but {a,b}\{a,b\} is a hitting set.

Correctness

The correctness proof has the details. Call a label valid if it contains a conflict, and note that a set hits every valid label exactly when it hits every conflict. The proof shows three invariants: every label is valid, every labeled node has an edge for each element of its current label, and every node is reachable from the root. PRUNE keeps them, because Σ⊊S′\Sigma \subsetneq S' is valid, avoids H(n′)H(n'), and its edges were already there. For completeness, take a minimal hitting set MM and walk from the root, always along an edge in M∩LM \cap L. The walk cannot stop at a closed node, because then a smaller hitting set would lie inside MM, so it ends at a checked node with H=MH = M. For soundness, a checked node nn whose H(n)H(n) is not minimal contains some minimal MM, and the node for MM is on an earlier level, so it was already checked when nn was tested at line L6. Reiter's tree breaks the invariants: a node closed in favour of a node that is later cut has no valid reason to be closed, and a node that keeps its old label after a cut no longer has an edge for each element of it.

Proof: The pruned HS-DAG returns exactly the minimal hitting setsfull

Let FF be a finite collection of finite sets. A set XX hits FF if X∩S≠∅X \cap S \neq \emptyset for every S∈FS \in F, and a hitting set is minimal if no proper subset of it hits FF. In a diagnosis problem, FF is the collection of conflict sets and the minimal hitting sets are the minimal diagnoses (Reiter 1987, Theorem 4.4). This file proves that the HS-DAG of Greiner, Smith and Wilkerson (1989), in the form of lines L1 to L23 on the main page, returns every minimal hitting set and nothing else.

Hypotheses on the label oracle

The algorithm asks a function next(h)\mathrm{next}(h) for a label. We assume three things.

  1. If hh hits FF, then next(h)\mathrm{next}(h) returns nothing.
  2. If hh does not hit FF, then next(h)\mathrm{next}(h) returns a set LL with L∩h=∅L \cap h = \emptyset and S⊆LS \subseteq L for some S∈FS \in F.
  3. Every label is a subset of one finite set UU.

Let L\mathcal{L} be the family of the sets that contain some member of FF. Every label that the oracle returns is in L\mathcal{L}.

Fact 0. A set XX hits every member of L\mathcal{L} if and only if XX hits FF.

Proof. F⊆LF \subseteq \mathcal{L}. Conversely, if XX hits FF and S⊆LS \subseteq L with S∈FS \in F, then X∩L⊇X∩S≠∅X \cap L \supseteq X \cap S \neq \emptyset. □\square

An explicit collection with the rule "the first member of FF that is disjoint from hh" satisfies the hypotheses, with U=⋃FU = \bigcup F. So does the diagnosis oracle that returns a conflict among the components outside hh, with UU the set of components.

The structure that the algorithm keeps

A node is identified by its set HH, so two paths with the same edge labels end at the same node. A node with ∣H∣=j|H| = j is at level jj. The algorithm processes the levels in increasing order (lines L3 to L20). While it processes level jj, it creates only nodes of level j+1j + 1 (line L17). Each node has a status: not yet processed, labeled, checked or closed. A node gets a status at most once (line L5).

We claim that the following invariants hold before and after each step.

  • (I1) Every label of a node, and every set in the list labels\mathit{labels}, is in L\mathcal{L}.
  • (I2) If a node nn has the label LL, then L∩H(n)=∅L \cap H(n) = \emptyset, and for each σ∈L\sigma \in L the node H(n)∪{σ}H(n) \cup \{\sigma\} exists and an edge marked σ\sigma goes from nn to it.
  • (I3) Every node that exists can be reached from the root.

Proof. At the start there is only the root, with no label. A label comes either from the list (line L7) or from the oracle (line L9). In both cases it is in L\mathcal{L} and is disjoint from H(n)H(n): the list is searched for a disjoint set, and the oracle returns a disjoint set by hypothesis 2. Lines L14 to L19 then create the edges and the children, so (I1) and (I2) hold for nn. The new children are reached through nn, so (I3) holds.

The pruning step (lines L22 and L23) takes a new label Σ\Sigma and a node n′n' with a label S′S' such that Σ⊊S′\Sigma \subsetneq S'. It gives n′n' the label Σ\Sigma and removes the edges for α∈S′∖Σ\alpha \in S' \setminus \Sigma. Then Σ∈L\Sigma \in \mathcal{L}, and Σ∩H(n′)⊆S′∩H(n′)=∅\Sigma \cap H(n') \subseteq S' \cap H(n') = \emptyset. The edges for the elements of Σ\Sigma were there before, because Σ⊆S′\Sigma \subseteq S', and they are kept. So (I1) and (I2) hold for n′n'. Next, the step deletes every node that the root no longer reaches. This gives (I3). It does not break (I2) for a node pp that stays: pp is reachable, so each child of pp is reachable through pp and stays. The list labels\mathit{labels} only loses sets and gains Σ\Sigma, so (I1) holds. □\square

Lemma 1 (every node is processed). When the algorithm stops, every node that exists has a status.

Proof. A node of level j+1j + 1 is created while level jj is processed, and it is put on the list of level j+1j + 1 (line L18). That list is processed in the next round. A node on it is skipped only if it does not exist at that moment, or if it already has a status. A node that is created again after a deletion is put on the list again, and the creation happens during the round of level jj, before the round of level j+1j + 1. So a node that exists at the end was on the list of its level when that round ran, it existed at that moment, and it got a status. □\square

Lemma 2 (checked nodes are hitting sets). If a node nn is checked, then H(n)H(n) hits FF.

Proof. A node is checked only when the oracle returns nothing (line L10). By hypothesis 2, the oracle returns a set whenever hh does not hit FF. □\square

Completeness

Lemma 3. When the algorithm stops, every minimal hitting set MM of FF is H(n)H(n) for some checked node nn that exists.

Proof. We walk down from the root along nodes n0,n1,…n_0, n_1, \ldots that exist at the end and have H(ni)⊆MH(n_i) \subseteq M. The root exists and H(n0)=∅⊆MH(n_0) = \emptyset \subseteq M. Take the current node nin_i. By Lemma 1 it has a status.

  • If nin_i is checked, then H(ni)H(n_i) hits FF by Lemma 2, and H(ni)⊆MH(n_i) \subseteq M. Since MM is minimal, H(ni)=MH(n_i) = M, and we are done.
  • If nin_i is closed, then at line L6 some checked node mm had H(m)⊊H(ni)⊆MH(m) \subsetneq H(n_i) \subseteq M. By Lemma 2, H(m)H(m) hits FF. This contradicts the minimality of MM. So this case cannot happen.
  • If nin_i has a label LL, then L∈LL \in \mathcal{L} by (I1), so M∩L≠∅M \cap L \neq \emptyset by Fact 0. Take σ∈M∩L\sigma \in M \cap L. By (I2), σ∉H(ni)\sigma \notin H(n_i), and the node ni+1=H(ni)∪{σ}n_{i+1} = H(n_i) \cup \{\sigma\} exists. Also H(ni+1)⊆MH(n_{i+1}) \subseteq M.

Each step makes HH larger by one element, and HH stays inside MM, which is finite. So the walk ends after at most ∣M∣|M| steps, and it can only end at a checked node with H=MH = M. □\square

Soundness

Lemma 4. When the algorithm stops, H(n)H(n) is a minimal hitting set for every checked node nn that exists.

Proof. By Lemma 2, H(n)H(n) hits FF. Suppose that it is not minimal. Then it contains a minimal hitting set M⊊H(n)M \subsetneq H(n). By Lemma 3, there is a checked node mm with H(m)=MH(m) = M that exists at the end. Its level ∣M∣|M| is smaller than the level ∣H(n)∣|H(n)| of nn.

Nodes of level ∣M∣|M| are created only in the round of level ∣M∣−1|M| - 1, and that round ends before the round of level ∣H(n)∣|H(n)| starts. So the node mm that exists at the end was created before nn was processed, and it was never deleted after that. It was processed, and became checked, in the round of level ∣M∣|M|, which also ended before nn was processed. So when nn was processed, mm existed, mm was checked, and H(m)⊊H(n)H(m) \subsetneq H(n). The test at line L6 then closes nn, and nn is not checked. This is a contradiction. □\square

Termination

By hypothesis 3, each H(n)H(n) is a subset of the finite set UU, because its elements come from labels. So there are at most ∣U∣+1|U| + 1 levels and at most 2∣U∣2^{|U|} nodes at any time. Each round processes a finite list. A node can be deleted and created again only within the round before its level, so each list is finite. The algorithm stops.

Theorem

Under hypotheses 1 to 3, the HS-DAG with the pruning step returns the set of all minimal hitting sets of FF, each once.

Proof. Lemma 3 and Lemma 4 show that the returned sets {H(n):n checked}\{H(n) : n \text{ checked}\} are exactly the minimal hitting sets. Each set appears once, because a node is identified by its set HH. ■\blacksquare

Remarks

Pruning is not needed for correctness. The proof does not use the pruning step except to check that it keeps (I1) to (I3). The step makes the DAG smaller when the oracle returns labels that are not minimal. Without it, the algorithm is the basic HS-DAG, and the theorem holds for it too. That is the case that Reiter stated without a proof, and that Greiner, Smith and Wilkerson proved as their Lemma 4.2.

Where Reiter's pruned tree breaks the invariants. Reiter's tree has no merging of equal nodes. Its rule 3(ii) closes a node when an earlier node has the same set HH. Its rule 3(iii) removes edges but keeps the old label. Each rule breaks one step of the proof.

  • With F={{a,b},{b,c},{a,c},{b,d},{b}}F = \{\{a,b\}, \{b,c\}, \{a,c\}, \{b,d\}, \{b\}\}, the node for the path b,ab, a is closed because the node for a,ba, b exists. Later the label {b}\{b\} prunes the aa edge of the root, and the node for a,ba, b goes with it. The walk of Lemma 3 for M={a,b}M = \{a, b\} then ends at a node that is closed for no valid reason, and {a,b}\{a, b\} is lost.
  • With F={{a,b},{a},{b}}F = \{\{a,b\}, \{a\}, \{b\}\}, the root keeps the label {a,b}\{a,b\}. The label {b}\{b\} removes its aa edge, and later the label {a}\{a\} removes its bb edge. The root then has no edges, but its label still claims {a,b}\{a, b\}. So (I2) fails, and the walk of Lemma 3 cannot leave the root. The tree returns no hitting set, but {a,b}\{a, b\} is one.

In the HS-DAG the first case cannot happen, because the two paths end at one node, which stays while any of its parents stays. The second case cannot happen, because the root takes the label {b}\{b\} and the later label {a}\{a\} is not a proper subset of it.

Complexity

Let kk be the number of nodes that the search creates, u=∣U∣u = |U| and mm the number of distinct labels. Each node is processed once. The closing test at line L6 scans the nodes in O(k⋅u)O(k \cdot u) time, and the reuse test at line L7 scans the labels in O(m⋅u)O(m \cdot u) time. Each call of PRUNE costs O(k⋅u)O(k \cdot u), and there is at most one per node. So the work outside the oracle is O(k⋅(k+m)⋅u)O(k \cdot (k + m) \cdot u), and the oracle is called at most kk times. The space is Θ(k⋅u)\Theta(k \cdot u). In diagnosis the oracle calls dominate: the deletion method makes up to u+1u + 1 consistency checks per conflict, and for a propositional system description each check is a SAT call.

The number of nodes kk is at least the number of minimal diagnoses, and that can be exponential: rr disjoint conflicts {ai,bi}\{a_i, b_i\} have 2r2^r minimal hitting sets. Enumerating minimal hitting sets with good bounds in terms of the output size is the minimal transversal enumeration problem. The HS-DAG is not built for that bound. Its strength is that it needs no list of conflicts in advance and calls the oracle only on the nodes it visits.

Properties

  • Sound and complete. The checked nodes are exactly the minimal hitting sets, also when the oracle returns conflicts that are not minimal.
  • Smallest first. The search goes level by level, so all diagnoses of size jj are found before any of size j+1j + 1. Stopping after level jj gives the diagnoses of size at most jj.
  • Lazy conflicts. Only the conflicts that the search asks for are computed, and each known conflict is reused when it avoids the current node.
  • Deterministic. With a deterministic oracle and a fixed order of the elements at line L14, the run is fixed.
  • Pruning is optional. Without lines L22 and L23 the algorithm is the basic HS-DAG and is still correct. Pruning only removes work when a later conflict is a proper subset of an earlier one. With minimal conflicts it never applies.

Variants and improvements

  • Basic HS-DAG. Drop the pruning step. Greiner, Smith and Wilkerson proved this version first (their Lemma 4.2); Reiter had stated the property without proof.
  • Minimal conflicts. If the oracle always returns minimal conflicts, no label is a proper subset of another, pruning never applies, and Reiter's tree and the HS-DAG give the same answer. In SAT terms, a minimal conflict is a minimal unsatisfiable subset of the health assumptions, and a minimal diagnosis is the complement of a maximal satisfiable subset, that is, a minimal correction subset.
  • Bounded search. Stop after a fixed level, or keep only diagnoses up to a given size, which is common when single and double faults are the main concern.
  • Wotawa's variant. Wotawa (2001) changed the way the tree is built to reduce the work for nodes that the HS-DAG would merge or close.
  • Conflicts from an ATMS. De Kleer and Williams (1987) computed the conflicts with an assumption-based truth maintenance system and generated the candidates from them in their General Diagnostic Engine.

When to use it

Use the HS-DAG when the conflicts are not given in advance but can be found by a consistency checker, and when you want the diagnoses in increasing size. This is the usual case in model-based diagnosis of circuits and of configuration or software models. If the full collection of sets is given and only one smallest hitting set is needed, an exact or approximate hitting set method fits better. If all minimal hitting sets of a large explicit collection are needed, look at minimal transversal enumeration.

Pitfalls

  • Reiter's pruning without relabeling. Cutting the extra edges of a node but keeping its old label can lose diagnoses, as in Figure 2. Relabel the node with the smaller conflict.
  • Closing on a duplicate in a tree. In a tree, closing a node because another node has the same set is safe only if that other node is never cut later. Merging the two into one node, as in the DAG, removes the problem.
  • Closing on equal sets. The closing test must use a proper subset. A node equal to a checked node is that node.
  • Depth-first search. The closing test relies on all smaller diagnoses being found first. A depth-first order can mark a non-minimal set as checked.
  • Inconsistent observations. If the system description and the observations are already inconsistent, the oracle returns the empty conflict, and the correct answer is "no diagnosis". Code that assumes every label has at least one element can loop or crash here.

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.

reiter_hs_tree.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reiter-hs-tree/. The authors are listed in prov/PCV2A8.jsonl.
"""Reiter's hitting set tree with the correction of Greiner, Smith and Wilkerson (1989).

hs_dag(next_label) is the HS-DAG of Greiner, Smith and Wilkerson. The caller
gives next_label(h): it returns a set that is disjoint from h and contains a
member of the conflict collection, or None when h hits every member. The
labels need not be minimal, but all of them must be subsets of one finite
set, so that the search stops. The result is the list of all minimal hitting
sets, sorted by size and then by their sorted elements. Elements must be
sortable, for example ints or strings.

minimal_hitting_sets(collection) runs hs_dag with the labels taken from an
explicit list of sets. diagnoses(components, consistent) runs it with the
conflicts computed on demand, as in Reiter's theory of diagnosis.

reiter_pruned_tree(collection) follows the pruning rules of Reiter (1987)
without the correction. It can lose minimal hitting sets, and it is here so
that the error can be shown.
"""

from collections import deque
from typing import Callable, Hashable, Iterable, List, Optional

Label = Optional[Iterable[Hashable]]

LABELED, CHECKED, CLOSED = "labeled", "checked", "closed"


class _Node:
    __slots__ = ("label", "status", "children")

    def __init__(self):
        self.label = None
        self.status = None
        self.children = {}


def _sort_key(s):
    return (len(s), sorted(s))


def hs_dag(next_label: Callable[[frozenset], Label]) -> List[frozenset]:
    """All minimal hitting sets, found with the pruned HS-DAG of Greiner, Smith and Wilkerson.

    Precondition: next_label meets the contract in the module comment. Cost:
    with k nodes, u elements and m labels, O(k (k + m) u) time outside the
    oracle, at most k oracle calls, and O(k u) space.
    """
    root = frozenset()
    nodes, labels = {root: _Node()}, []  # @line L1
    level = [root]  # @line L2
    while level:  # @line L3
        following = []  # @line L4
        for h in level:  # @line L5
            node = nodes.get(h)
            if node is None or node.status is not None:
                continue  # removed by a pruning step, or already processed
            if any(m < h and nodes[m].status == CHECKED for m in nodes):  # @line L6
                node.status = CLOSED
                continue
            label = next((s for s in labels if not (s & h)), None)  # @line L7
            if label is None:  # @line L8
                found = next_label(h)  # @line L9
                if found is None:  # @line L10
                    node.status = CHECKED
                    continue
                label = frozenset(found)
                if label & h:
                    raise ValueError("next_label returned a set that meets h")
                _prune(nodes, root, labels, label)  # @line L11
                labels.append(label)
                if h not in nodes:  # @line L12
                    continue
            node.label, node.status = label, LABELED  # @line L13
            for sigma in sorted(label):  # @line L14
                child = h | {sigma}  # @line L15
                if child not in nodes:  # @line L16
                    nodes[child] = _Node()  # @line L17
                    following.append(child)  # @line L18
                node.children[sigma] = child  # @line L19
        level = following  # @line L20
    return sorted((h for h, n in nodes.items() if n.status == CHECKED), key=_sort_key)  # @line L21


def _prune(nodes, root, labels, new):
    """Relabel each node whose label is a proper superset of new, and drop the nodes that are no longer reachable."""
    changed = False
    for node in nodes.values():  # @line L22
        if node.label is not None and new < node.label:
            for alpha in node.label - new:
                node.children.pop(alpha, None)
            node.label = new
            changed = True
    labels[:] = [s for s in labels if not new < s]
    if not changed:
        return
    seen = {root}  # @line L23
    stack = [root]
    while stack:
        for child in nodes[stack.pop()].children.values():
            if child not in seen:
                seen.add(child)
                stack.append(child)
    for h in [h for h in nodes if h not in seen]:
        del nodes[h]


def collection_labels(collection: Iterable[Iterable[Hashable]]) -> Callable[[frozenset], Optional[frozenset]]:
    """next_label for an explicit list of sets: the first member that is disjoint from h."""
    sets = [frozenset(s) for s in collection]

    def next_label(h):
        return next((s for s in sets if not (s & h)), None)

    return next_label


def minimal_hitting_sets(collection: Iterable[Iterable[Hashable]]) -> List[frozenset]:
    """All minimal hitting sets of a finite list of finite sets."""
    return hs_dag(collection_labels(collection))


def diagnoses(components: Iterable[Hashable], consistent: Callable[[frozenset], bool]) -> List[frozenset]:
    """All minimal diagnoses.

    consistent(ok) tells whether SD, OBS and the statements "c is not abnormal"
    for c in ok are consistent together. A subset of a consistent set must be
    consistent. Each conflict is found from the components outside h and then
    made minimal by deleting components one at a time.
    """
    comps = frozenset(components)

    def next_label(h):
        rest = comps - h
        if consistent(rest):
            return None
        conflict = set(rest)
        for c in sorted(rest):
            if not consistent(frozenset(conflict - {c})):
                conflict.discard(c)
        return frozenset(conflict)

    return hs_dag(next_label)


def reiter_pruned_tree(collection: Iterable[Iterable[Hashable]]) -> List[frozenset]:
    """Reiter's pruned HS-tree without the correction. It can lose minimal hitting sets."""
    sets = [frozenset(s) for s in collection]
    hs, label, status, children, alive = [frozenset()], [None], [None], [{}], [True]

    def kill(i):
        stack = [i]
        while stack:
            j = stack.pop()
            alive[j] = False
            stack.extend(children[j].values())

    def cut(i, keep):
        for alpha in label[i] - keep:
            if alpha in children[i]:
                kill(children[i].pop(alpha))

    queue = deque([0])
    while queue:
        i = queue.popleft()
        if not alive[i]:
            continue
        h = hs[i]
        others = [j for j in range(len(hs)) if j != i and alive[j]]
        if any(status[j] == CHECKED and hs[j] <= h for j in others):
            status[i] = CLOSED
            continue
        if any(j < i and hs[j] == h for j in others):
            status[i] = CLOSED
            continue
        s = next((label[j] for j in others if label[j] is not None and not (label[j] & h)), None)
        if s is None:
            s = next((t for t in sets if not (t & h)), None)
        if s is None:
            status[i] = CHECKED
            continue
        label[i], status[i] = s, LABELED
        for sigma in sorted(s):
            hs.append(h | {sigma})
            label.append(None)
            status.append(None)
            children.append({})
            alive.append(True)
            children[i][sigma] = len(hs) - 1
            queue.append(len(hs) - 1)
        for j in range(len(hs)):
            if j != i and alive[j] and label[j] is not None:
                if s < label[j]:
                    cut(j, s)
                elif label[j] < s and alive[i]:
                    cut(i, label[j])
    return sorted((hs[i] for i in range(len(hs)) if alive[i] and status[i] == CHECKED), key=_sort_key)
test_reiter_hs_tree.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reiter-hs-tree/. The authors are listed in prov/PCV2A8.jsonl.

import random
import unittest
from itertools import combinations

from reiter_hs_tree import (
    collection_labels,
    diagnoses,
    hs_dag,
    minimal_hitting_sets,
    reiter_pruned_tree,
)


def brute_force(collection):
    """The minimal hitting sets, by trying every subset of the union."""
    sets = [frozenset(s) for s in collection]
    universe = sorted(set().union(*sets)) if sets else []
    hitting = [
        frozenset(c)
        for k in range(len(universe) + 1)
        for c in combinations(universe, k)
        if all(set(c) & s for s in sets)
    ]
    minimal = [h for h in hitting if not any(o < h for o in hitting)]
    return sorted(minimal, key=lambda s: (len(s), sorted(s)))


def random_collection(rng):
    n = rng.randint(1, 7)
    count = rng.randint(0, 7)
    out = []
    for _ in range(count):
        size = rng.choice([1, 1, 2, 2, 3, 3, 4]) if rng.random() > 0.03 else 0
        out.append(set(rng.sample(range(n), min(size, n))))
    return out


def superset_labels(collection, universe, rng):
    """Returns a member disjoint from h with extra elements added, so that the labels are often not minimal."""
    sets = [frozenset(s) for s in collection]

    def next_label(h):
        free = [s for s in sets if not (s & h)]
        if not free:
            return None
        base = rng.choice(free)
        extra = [x for x in universe if x not in h and rng.random() < 0.4]
        return base | set(extra)

    return next_label


FIG1 = [{"a", "b"}, {"b", "c"}, {"a", "c"}, {"b", "d"}, {"b"}]
FIG2 = [{"a", "b"}, {"a"}, {"b"}]


class TestHSDAG(unittest.TestCase):
    def test_random_collections(self):
        rng = random.Random(1987)
        for _ in range(600):
            coll = random_collection(rng)
            self.assertEqual(minimal_hitting_sets(coll), brute_force(coll), coll)

    def test_order_does_not_matter(self):
        rng = random.Random(41)
        for _ in range(200):
            coll = random_collection(rng)
            shuffled = coll[:]
            rng.shuffle(shuffled)
            self.assertEqual(minimal_hitting_sets(shuffled), brute_force(coll))

    def test_labels_that_are_not_minimal(self):
        rng = random.Random(1989)
        for _ in range(600):
            coll = random_collection(rng)
            universe = sorted(set().union(*coll)) if coll else []
            universe += [99, 100]  # elements outside every conflict
            got = hs_dag(superset_labels(coll, universe, rng))
            self.assertEqual(got, brute_force(coll), coll)

    def test_edge_cases(self):
        self.assertEqual(minimal_hitting_sets([]), [frozenset()])
        self.assertEqual(minimal_hitting_sets([set()]), [])
        self.assertEqual(minimal_hitting_sets([{1}, set(), {2}]), [])
        self.assertEqual(minimal_hitting_sets([{1}, {1}]), [frozenset({1})])
        self.assertEqual(minimal_hitting_sets([{1, 2, 3}]), [frozenset({1}), frozenset({2}), frozenset({3})])

    def test_bad_label_is_rejected(self):
        with self.assertRaises(ValueError):
            hs_dag(lambda h: {1})


class TestReiterError(unittest.TestCase):
    def test_figure_1(self):
        expected = [frozenset("ab"), frozenset("bc")]
        self.assertEqual(brute_force(FIG1), expected)
        self.assertEqual(minimal_hitting_sets(FIG1), expected)
        self.assertEqual(reiter_pruned_tree(FIG1), [frozenset("bc")])

    def test_figure_2(self):
        self.assertEqual(minimal_hitting_sets(FIG2), [frozenset("ab")])
        self.assertEqual(reiter_pruned_tree(FIG2), [])

    def test_uncorrected_tree_on_minimal_conflicts(self):
        # With an antichain of conflicts no pruning step applies, and the uncorrected tree is right.
        rng = random.Random(7)
        for _ in range(300):
            coll = [frozenset(s) for s in random_collection(rng)]
            anti = [s for s in set(coll) if not any(o < s for o in coll)]
            self.assertEqual(reiter_pruned_tree(anti), brute_force(anti), anti)

    def test_collection_labels(self):
        nl = collection_labels(FIG1)
        self.assertEqual(nl(frozenset()), frozenset("ab"))
        self.assertEqual(nl(frozenset("acd")), frozenset("b"))
        self.assertIsNone(nl(frozenset("ab")))


class TestDiagnosis(unittest.TestCase):
    def polybox_consistent(self, ok):
        # Inputs A=3, B=2, C=2, D=3, E=3 and outputs F=10, G=12. A correct
        # multiplier fixes its output, a correct adder ties its inputs to the
        # observed output, and a faulty component imposes nothing.
        for y in range(-50, 60):
            if "M2" in ok and y != 6:
                continue
            xs = ({6} if "M1" in ok else set()) | ({10 - y} if "A1" in ok else set())
            zs = ({6} if "M3" in ok else set()) | ({12 - y} if "A2" in ok else set())
            if len(xs) <= 1 and len(zs) <= 1:
                return True
        return False

    def test_polybox(self):
        got = diagnoses(["M1", "M2", "M3", "A1", "A2"], self.polybox_consistent)
        expected = [frozenset({"A1"}), frozenset({"M1"}), frozenset({"A2", "M2"}), frozenset({"M2", "M3"})]
        self.assertEqual(got, expected)

    def test_inconsistent_observations(self):
        self.assertEqual(diagnoses(["x", "y"], lambda ok: False), [])

    def test_no_fault(self):
        self.assertEqual(diagnoses(["x", "y"], lambda ok: True), [frozenset()])

    def test_random_conflict_systems(self):
        rng = random.Random(32)
        for _ in range(200):
            coll = [frozenset(s) for s in random_collection(rng)]
            comps = sorted(set().union(*coll)) if coll else []
            comps += [99]  # a component in no conflict

            def consistent(ok, coll=coll):
                return not any(s <= ok for s in coll)

            self.assertEqual(diagnoses(comps, consistent), brute_force(coll), coll)


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

History

Reiter (1987) set out the consistency-based theory of diagnosis, proved that diagnoses are minimal hitting sets of the conflict sets, and gave the HS-tree with label reuse, closing and pruning. In the same issue of Artificial Intelligence, de Kleer and Williams (1987) described the General Diagnostic Engine, which finds conflicts with an ATMS. Greiner, Smith and Wilkerson (1989) showed that Reiter's pruning can lose diagnoses, gave the HS-DAG with relabeling, and proved it correct. Wotawa (2001) published a later variant of the construction.

References

  1. Raymond Reiter, A theory of diagnosis from first principles, Artificial Intelligence 32(1), 57 to 95 (1987), Theorem 4.4 (diagnoses are the minimal hitting sets of the conflict sets) and Section 4 (the HS-tree and its pruning rules)
  2. Russell Greiner, Barbara A. Smith and Ralph W. Wilkerson, A correction to the algorithm in Reiter's theory of diagnosis, Artificial Intelligence 41(1), 79 to 88 (1989), Figures 1 and 2 (the lost diagnoses), the HS-DAG algorithm, Theorem 4.1 and Lemma 4.2
  3. Johan de Kleer and Brian C. Williams, Diagnosing multiple faults, Artificial Intelligence 32(1), 97 to 130 (1987), the polybox example, and conflicts found with an assumption-based truth maintenance system
  4. Franz Wotawa, A variant of Reiter's hitting-set algorithm, Information Processing Letters 79(1), 45 to 51 (2001), the variant of the tree construction

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