Algorithm Search⌘K

Algorithmadvanced

Diagnoser automaton

Also called Sampath diagnoser.

Builds an automaton over the observable events whose states are sets of plant states with fault labels. It detects faults online and tests diagnosability by a search for indeterminate cycles.

Time
O(2^(n 2^m) n^4 16^m q) worst
Space
O(2^(n 2^m) n^4 16^m q) extra
Where
m = the number of fault types; n = the number of states of the plant; q = the number of observable events
Properties
deterministicexactoffline
Origin
Meera Sampath, Raja Sengupta, Stéphane Lafortune, Kasim Sinnamohideen, Demosthenis Teneketzis, 1995

The diagnoser of a partially observed discrete-event system is a deterministic automaton that reads only the observable events. Each of its states is the set of all pairs (plant state, faults so far) that agree with what has been observed. A state whose pairs all carry a fault of type FF says "FF has certainly occurred". A state where some pairs carry FF and some do not says "uncertain". Online, the diagnoser runs next to the plant and reports a fault as soon as it is certain. Offline, Sampath, Sengupta, Lafortune, Sinnamohideen and Teneketzis (1995) used it to decide diagnosability: the plant is diagnosable exactly when the diagnoser has no indeterminate cycle, a cycle along which a faulty and a fault-free explanation stay together forever. The construction is a subset construction over the plant states with fault labels, so it can have exponentially many states. The twin plant test answers the offline question in polynomial time, but it does not give an online detector.

In plain words

You watch a machine, but some of its events are hidden from you, and a fault is one of the hidden events. After each event you see, you write down every place the machine could be in now, and for each place whether a fault has happened on the way there. If every entry says "fault", you raise the alarm. If none does, all is well. If some do and some do not, you wait.

Do this once for every sequence of observations you could ever see, and you get a finite machine: the diagnoser. To learn whether you will always reach a verdict, look for a loop in which a "fault" entry and a "no fault" entry can follow each other forever. If there is such a loop, some faults are never found. If there is none, every fault is found after a bounded wait.

The problem

The input is a deterministic plant G=(X,Σ,δ,x0)G = (X, \Sigma, \delta, x_0), the observable events Σo\Sigma_o, and a map from each fault event to its fault type. Fault events are unobservable, and there are mm types. A label ℓ\ell is a set of fault types, and ℓ(s)\ell(s) is the set of types of the fault events in ss. The natural projection PP erases the unobservable events.

The first output is the diagnoser: the reachable part of the deterministic automaton over Σo\Sigma_o whose state after the observed word yy is

Q(y)={(δ(x0,s),ℓ(s)):s∈L(G), P(s)=y, s=ε or s ends with an observable event}.Q(y) = \{(\delta(x_0, s), \ell(s)) : s \in L(G),\ P(s) = y,\ s = \varepsilon \text{ or } s \text{ ends with an observable event}\}.

The second output, for a chosen type FF, is the answer to: is FF diagnosable? The test assumes, as Sampath et al. do, that GG has no cycle of unobservable events.

For a pair p=(x,ℓ)p = (x, \ell) and an event σ∈Σo\sigma \in \Sigma_o, MOVES(p)[σ](p)[\sigma] is the set of pairs (δ(x,uσ),ℓ∪ℓ(uσ))(\delta(x, u\sigma), \ell \cup \ell(u\sigma)) over all unobservable strings uu such that uσu\sigma is defined at xx. It is computed by a search over pairs.

The algorithm

  1. DIAGNOSER(G, Σo, faults)
  2. 1q0 ← {(x0, ∅)}
  3. 2states ← {q0}; queue ← [q0]
  4. 3while queue is not empty do
  5. 4q ← pop the front of queue
  6. 5for each σ in Σo do
  7. 6r ← ∅
  8. 7for each pair p in q do r ← r ∪ MOVES(p)[σ]
  9. 8if r ≠ ∅ then δd(q, σ) ← r; if r is not in states then add r to states and to queue
  10. 9return (q0, states, δd)
  11. DIAGNOSABLE(G, Σo, faults, F)
  12. 10D ← DIAGNOSER(G, Σo, faults)
  13. 11T ← the triples (q, a, b) with q a state of D, a and b pairs in q, F in the label of a and F not in the label of b
  14. 12for each (q, a, b) in T, σ in Σo with δd(q, σ) defined, a' in MOVES(a)[σ], b' in MOVES(b)[σ] with F not in the label of b' do add the edge (q, a, b) → (δd(q, σ), a', b')
  15. 13return true if the graph on T has no cycle, else false

Lines L1 to L9 are a breadth-first subset construction over pairs. Line L7 follows the unobservable events, collects the fault types they carry into the label, and stops at the next observable event σ\sigma. So a diagnoser state lists the plant states that are entered by an observable event, not those in the middle of an unobservable run. Line L8 keeps only nonempty sets: an observation that the plant cannot produce has no transition.

Lines L10 to L13 are the test. A triple (q,a,b)(q, a, b) says that, after the same observation, a faulty explanation aa and a fault-free explanation bb are both possible. An edge of line L12 extends both explanations by the same observable event, and keeps the second one fault-free. A cycle of triples is an indeterminate cycle: two explanations, one with the fault and one without, that can go on forever with the same observation. Line L13 uses Kahn's algorithm, as in topological sort: remove nodes with in-degree 0 until none is left, and report a cycle if some node remains.

Example

The plant has states 0 to 4, initial state 0, and transitions 0→a10 \xrightarrow{a} 1, 1→u21 \xrightarrow{u} 2, 2→b02 \xrightarrow{b} 0, 1→f31 \xrightarrow{f} 3, 3→b43 \xrightarrow{b} 4 and 4→c44 \xrightarrow{c} 4. The events aa, bb and cc are observable, and ff is the fault, of type FF. A pair (x,ℓ)(x, \ell) is written xNxN if the label is empty and xFxF otherwise. The table shows lines L4 to L8, with the events in the order aa, bb, cc, and only the events where rr is not empty.

step qq at L4 σ\sigma at L5 rr at L7 line L8 verdict on rr
1 {0N}\{0N\} aa {1N}\{1N\} new state normal
2 {1N}\{1N\} bb {0N,4F}\{0N, 4F\} new state uncertain
3 {0N,4F}\{0N, 4F\} aa {1N}\{1N\} known normal
3 {0N,4F}\{0N, 4F\} cc {4F}\{4F\} new state FF certain
4 {4F}\{4F\} cc {4F}\{4F\} known FF certain

At step 2, MOVES((1,∅))[b]((1, \emptyset))[b] follows uu to 2N2N and then bb to 0N0N, and it follows ff to 3F3F and then bb to 4F4F. The diagnoser has 4 states and 5 transitions. Online, after the observation abab it is uncertain, and after abcabc it reports the fault.

For the test, line L11 finds one triple, ({0N,4F},4F,0N)(\{0N, 4F\}, 4F, 0N). Line L12 adds no edge from it: on aa, the pair 4F4F has no move, and on cc, the pair 0N0N has none. The graph has no cycle, so FF is diagnosable.

Now change the plant after the fault to 3→b43 \xrightarrow{b} 4, 4→a54 \xrightarrow{a} 5 and 5→b45 \xrightarrow{b} 4, with aa and bb observable. The diagnoser is {0N}→a{1N}→b{0N,4F}→a{1N,5F}→b{0N,4F}\{0N\} \xrightarrow{a} \{1N\} \xrightarrow{b} \{0N, 4F\} \xrightarrow{a} \{1N, 5F\} \xrightarrow{b} \{0N, 4F\}. The triples ({0N,4F},4F,0N)(\{0N, 4F\}, 4F, 0N) and ({1N,5F},5F,1N)(\{1N, 5F\}, 5F, 1N) form a cycle, so FF is not diagnosable: the faulty run af(ba)kaf(ba)^k and the normal run (aub)ka(aub)^k a look the same forever. The tests of the implementation check both plants and compare the diagnoser states with a brute force enumeration of strings.

Correctness

By induction on the observed word, the state that lines L1 to L9 reach on yy is exactly Q(y)Q(y): line L7 extends every explanation of yy by an unobservable run and the event σ\sigma, and every explanation of yσy\sigma arises this way. There are at most 2n2m2^{n 2^m} sets of pairs, so the construction stops.

For the test: a cycle of triples gives, by the meaning of the states, a faulty string and a fault-free string with the same projection that can both be pumped around the cycle. So the delay after the fault is unbounded and FF is not diagnosable. Conversely, if FF is not diagnosable, there are arbitrarily long continuations after a fault with a fault-free twin. Because there is no unobservable cycle, a long continuation has many observable events, so it gives a long path of triples, and a path longer than the number of triples repeats one. The full proof is in the correctness proof.

Proof: The diagnoser holds the exact state estimate, and the indeterminate cycle test decides diagnosabilityfull

Setting. The plant GG is a deterministic automaton with state set XX, initial state x0x_0 and alphabet Σ=Σo∪Σuo\Sigma = \Sigma_o \cup \Sigma_{uo}, where Σo\Sigma_o is the set of observable events. The fault events are unobservable, and each one has a fault type. The label ℓ(s)\ell(s) of a string ss is the set of fault types of the fault events in ss. Labels only grow along a string. PP is the natural projection that erases the unobservable events. For a pair p=(x,ℓ)p = (x, \ell) and σ∈Σo\sigma \in \Sigma_o, MOVES(p)[σ](p)[\sigma] is the set of pairs (δ(x,uσ),ℓ∪ℓ(uσ))(\delta(x, u\sigma), \ell \cup \ell(u\sigma)) over all u∈Σuo∗u \in \Sigma_{uo}^* with uσu\sigma defined at xx. The function computes it by a search over pairs, so it stops even if GG has a cycle of unobservable events.

For y∈Σo∗y \in \Sigma_o^* let

Q(y)={(δ(x0,s),ℓ(s)):s∈L(G), P(s)=y, s=ε or s ends with an observable event}.Q(y) = \{(\delta(x_0, s), \ell(s)) : s \in L(G),\ P(s) = y,\ s = \varepsilon \text{ or } s \text{ ends with an observable event}\}.

Lemma 1 (meaning of a state). For each y∈Σo∗y \in \Sigma_o^*: if Q(y)≠∅Q(y) \neq \emptyset, the diagnoser reaches the state Q(y)Q(y) on yy. If Q(y)=∅Q(y) = \emptyset, the diagnoser has no run on yy.

Proof. By induction on ∣y∣|y|. For y=εy = \varepsilon, only s=εs = \varepsilon qualifies, so Q(ε)={(x0,∅)}Q(\varepsilon) = \{(x_0, \emptyset)\}, which is the state of line L1. Assume the claim for yy, and let σ∈Σo\sigma \in \Sigma_o. A string s′s' that qualifies for yσy\sigma ends with σ\sigma. Write s′=suσs' = s u \sigma, where ss is the longest prefix of s′s' before the last σ\sigma that is empty or ends with an observable event. Then ss qualifies for yy, u∈Σuo∗u \in \Sigma_{uo}^*, and the pair of s′s' is in MOVES(p)[σ](p)[\sigma] for the pair pp of ss. Conversely, each pair in MOVES(p)[σ](p)[\sigma] for p∈Q(y)p \in Q(y) is the pair of such a string suσs u \sigma. So Q(yσ)Q(y\sigma) is the union of MOVES(p)[σ](p)[\sigma] over p∈Q(y)p \in Q(y). This is the set that lines L6 and L7 build from the state Q(y)Q(y). Line L8 adds the transition exactly when the set is not empty. If Q(y)=∅Q(y) = \emptyset, then Q(yσ)=∅Q(y\sigma) = \emptyset as well, and there is no run. ■\blacksquare

Theorem (construction). Lines L1 to L9 stop, and they return the part of the diagnoser that is reachable from Q(ε)Q(\varepsilon).

Proof. A state is a set of pairs (x,ℓ)(x, \ell) with x∈Xx \in X and ℓ\ell a set of fault types. With mm fault types there are ∣X∣2m|X| 2^m pairs, so at most 2∣X∣2m2^{|X| 2^m} states. Each state enters the queue once, so the loop of line L3 stops. By Lemma 1, each transition that line L8 adds is a transition of the diagnoser, and the search adds every transition from every reached state. ■\blacksquare

The test. Fix a fault type FF. Lines L11 and L12 build the graph TT. Its nodes are the triples (q,a,b)(q, a, b) with qq a reached diagnoser state, a,b∈qa, b \in q, FF in the label of aa and FF not in the label of bb. There is an edge from (q,a,b)(q, a, b) to (q′,a′,b′)(q', a', b') if q′=δd(q,σ)q' = \delta_d(q, \sigma), a′∈a' \in MOVES(a)[σ](a)[\sigma], b′∈b' \in MOVES(b)[σ](b)[\sigma] and FF is not in the label of b′b', for some σ∈Σo\sigma \in \Sigma_o. Then a′,b′∈q′a', b' \in q', and FF is in the label of a′a', because labels only grow.

The type FF is diagnosable if there is an integer NN with this property: for every s∈L(G)s \in L(G) that ends with a fault event of type FF and every tt with st∈L(G)st \in L(G) and ∣t∣≥N|t| \ge N, every w∈L(G)w \in L(G) with P(w)=P(st)P(w) = P(st) has a fault event of type FF.

Theorem (test). Assume that GG has no cycle of unobservable events. Then FF is diagnosable if and only if TT has no cycle. Line L13 returns this answer.

Proof that a cycle gives no diagnosability. Let (q,a,b)(q, a, b) be a node on a cycle with the observable word σ1⋯σk\sigma_1 \cdots \sigma_k, k≥1k \ge 1. By Lemma 1 there is yy with q=Q(y)q = Q(y), a string sas_a for aa and a string sbs_b for bb, both with projection yy. sas_a has a fault of type FF, and sbs_b has none. Each edge of the cycle extends the strings by uσiu\sigma_i and vσiv\sigma_i with u,v∈Σuo∗u, v \in \Sigma_{uo}^*. One turn around the cycle brings a=(xa,ℓa)a = (x_a, \ell_a) back to itself, so it gives a string cac_a from xax_a to xax_a with P(ca)=σ1⋯σkP(c_a) = \sigma_1 \cdots \sigma_k and ∣ca∣≥1|c_a| \ge 1. In the same way it gives cbc_b from xbx_b to xbx_b with P(cb)=P(ca)P(c_b) = P(c_a), and cbc_b has no fault of type FF, because the label of bb does not get FF. Let ss be the prefix of sas_a that ends with its first fault event of type FF, and write sa=srs_a = s r. For every NN, take t=rcaNt = r c_a^N and w=sbcbNw = s_b c_b^N. Then st∈L(G)st \in L(G), ∣t∣≥N|t| \ge N, w∈L(G)w \in L(G), P(w)=y P(ca)N=P(st)P(w) = y\,P(c_a)^N = P(st), and ww has no fault of type FF. So no NN works.

Proof that no cycle gives diagnosability. Let MM be the number of nodes of TT, and N=(M+2)∣X∣N = (M + 2)|X|. Take ss, tt and ww as in the definition, with ∣t∣≥N|t| \ge N, and assume that ww has no fault of type FF. Because GG has no cycle of unobservable events, a run of unobservable events visits each state at most once, so it has at most ∣X∣−1|X| - 1 events. So if tt has jj observable events, ∣t∣≤j+(j+1)(∣X∣−1)|t| \le j + (j + 1)(|X| - 1), and j≥(∣t∣−∣X∣+1)/∣X∣>Mj \ge (|t| - |X| + 1)/|X| > M. Let y0=P(s)y_0 = P(s), let σ1,…,σj\sigma_1, \ldots, \sigma_j be the observable events of tt, and let yi=y0σ1⋯σiy_i = y_0 \sigma_1 \cdots \sigma_i. For 1≤i≤j1 \le i \le j, let αi\alpha_i be the prefix of stst that ends with σi\sigma_i, and βi\beta_i the prefix of ww that ends with its (∣y0∣+i)(|y_0| + i)-th observable event. Both qualify for yiy_i, so their pairs aia_i and bib_i are in Q(yi)Q(y_i). αi\alpha_i contains ss, so FF is in the label of aia_i, and FF is not in the label of bib_i. So (Q(yi),ai,bi)(Q(y_i), a_i, b_i) is a node of TT, and by the definition of MOVES there is an edge from node ii to node i+1i + 1. This is a path with j>Mj > M nodes in a graph with MM nodes, so a node repeats, and TT has a cycle. This contradicts the assumption, so every such ww has a fault of type FF.

Line L13 runs Kahn's algorithm. It removes nodes of in-degree 0 until none is left, and it removes all nodes if and only if the graph has no cycle. ■\blacksquare

The first part of the proof does not use the assumption on unobservable cycles. The second part uses it to turn the length of tt into a number of observable events. Neither part uses the assumption of Sampath et al. that L(G)L(G) is live.

Cost. TT has at most D (∣X∣2m)2D\,(|X| 2^m)^2 nodes, where DD is the number of diagnoser states, and each node has at most ∣Σo∣(∣X∣2m)2|\Sigma_o| (|X| 2^m)^2 edges. So the test is polynomial in the size of the diagnoser, and the diagnoser can be exponential in ∣X∣|X|.

Complexity

The model is the word RAM with hashing. Let n=∣X∣n = |X|, mm the number of fault types and q=∣Σo∣q = |\Sigma_o|. There are n2mn 2^m pairs.

  • The diagnoser has at most D≤2n2mD \le 2^{n 2^m} states. With MOVES cached per pair, one transition at lines L6 and L7 costs O(n24m)O(n^2 4^m) set operations, so lines L1 to L9 take O(D q n24m)O(D\,q\,n^2 4^m) time.
  • Line L11 makes at most D n24mD\,n^2 4^m triples, and line L12 gives each at most q n24mq\,n^2 4^m edges. Kahn's algorithm is linear in the size of this graph. So lines L10 to L13 take O(D q n416m)O(D\,q\,n^4 16^m) time and space.

With D≤2n2mD \le 2^{n 2^m} this is the bound in the front matter. The bound on DD is the bound of the subset construction. Observers of automata can be exponential in nn, so this growth does occur. In practice, mm is small, but DD can still grow exponentially in nn. Online, a precomputed diagnoser takes O(1)O(1) time per observed event. Without precomputation, one step of lines L6 and L7 on the current state takes O(n24m)O(n^2 4^m) set operations for the observed σ\sigma, and memory for one state.

Properties

  • Exact. The diagnoser state is the exact set of explanations, not an approximation.
  • Deterministic. The diagnoser is deterministic, even though the plant with its unobservable events is not, seen through the projection.
  • Online use. It reports a fault of type FF at the first observation after which every explanation carries FF. No observer that uses only the observations can report it earlier without the risk of a false alarm.
  • Several fault types at once. One diagnoser serves all mm types. The test of lines L10 to L13 runs once per type.
  • Exponential size. Its size is the main cost. The diagnosability test alone does not need it; see the twin plant.

Variants and improvements

  • Twin plant and verifier. Jiang, Huang, Chandra and Kumar (2001) and Yoo and Lafortune (2002) test diagnosability without the diagnoser, on a product of the plant with itself, in polynomial time. See twin plant diagnosability test.
  • On-the-fly diagnoser. Keep only the current state and compute the next one when an event is observed. This avoids the exponential precomputation, at the cost of the work of line L7 at each step.
  • Decentralized diagnosis. Several local diagnosers, each with its own observable events, report to a coordinator. Diagnosability then becomes a joint condition on all of them.
  • Stochastic diagnosis. With probabilities on the transitions, the state becomes a probability distribution over pairs, as in the forward algorithm of a hidden Markov model, and a fault is reported when its probability passes a threshold.
  • Observer. Without fault labels, the same construction is the observer of the plant, used for state estimation and for checking observability properties.

When to use it

Use the diagnoser when you need an online fault detector and the plant is small enough that the set of explanations stays manageable. It also gives the offline verdict and a readable reason for it. If you only need to know whether the plant is diagnosable, use the twin plant test, which is polynomial. If the plant is large, run the diagnoser on the fly instead of building it in advance.

Pitfalls

  • Testing for a cycle of uncertain states instead of triples (line L11). A cycle of uncertain diagnoser states does not prove that the fault is not diagnosable. In the plant 1→a11 \xrightarrow{a} 1, 1→f51 \xrightarrow{f} 5, 5→a25 \xrightarrow{a} 2, 2→b62 \xrightarrow{b} 6, 6→b66 \xrightarrow{b} 6 with aa and bb observable, the diagnoser state {1N,2F}\{1N, 2F\} has an aa self-loop and is uncertain. But the fault is diagnosable: the faulty explanation 2F2F cannot follow aa, so it does not stay on that loop, and the first bb reveals the fault. The triples of line L11 track which explanation stays on the cycle, and there the graph has no cycle. The tests check this plant.
  • Cutting the unobservable runs short at line L7. MOVES must follow unobservable runs of any length before the observable event, and add the fault types of the whole run to the label. If it follows at most one unobservable event, it loses the explanations where two hidden events come in a row, such as a fault and then another hidden event. If it does not record the fault types along the run, every label stays empty and the diagnoser never reports a fault.
  • Letting the fault-free explanation become faulty at line L12. An edge must keep FF out of the label of b′b'. If bb may pick up a fault, two faulty explanations can form a cycle, and the test says "not diagnosable" for a diagnosable plant.
  • Unobservable cycles (line L13). The equivalence needs a plant without a cycle of unobservable events. In the plant 0→b00 \xrightarrow{b} 0, 0→f10 \xrightarrow{f} 1, 1→u11 \xrightarrow{u} 1 with only bb observable, the plant can loop on uu forever after the fault and no observation ever comes, so the fault is not diagnosable. But the state 1F1F is never entered by an observable event, so it is in no diagnoser state, line L11 finds no triple, and line L13 answers "diagnosable". Check the assumption first, for example with a cycle search on the unobservable transitions.
  • The size of the diagnoser. Lines L1 to L9 can produce exponentially many states. Do not build the diagnoser only to answer the offline question.

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.

diagnoser_automaton.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diagnoser-automaton/. The authors are listed in prov/8VN8F2.jsonl.

"""The diagnoser of Sampath et al. (1995) for a partially observed automaton.

The plant G is a dict with the keys "init" and "delta" (a dict that maps
(state, event) to the next state). `observable` is the set of observable
events. `faults` maps each fault event to its fault type; fault events must
be unobservable. A label is a frozenset of fault types; the empty label is
"normal".

diagnoser(g, observable, faults) returns {"init", "states", "delta"}. A
diagnoser state is a frozenset of pairs (x, label). After an observed word
y, the state holds exactly the pairs (state of G, faults so far) of the
strings s of L(G) with P(s) = y that end with an observable event (or s is
empty and y is empty). This needs no cycle of unobservable events in G.

diagnosable(g, observable, faults, kind) decides diagnosability for one
fault type by a search for an indeterminate cycle: a cycle in the graph of
triples (diagnoser state, a pair with the fault, a pair without it).

Cost: the diagnoser has at most 2^(|X| 2^m) states for |X| states of G and
m fault types. Each diagnoser transition costs O(|X|^2 4^m) set operations
after the moves of every pair are cached.
"""

from collections import deque
from typing import Hashable, Iterable

Pair = tuple
Label = frozenset


def out_edges(delta: dict) -> dict:
    out: dict = {}
    for (q, e), r in delta.items():
        out.setdefault(q, {})[e] = r
    return out


def moves(out: dict, pair: Pair, observable: set, faults: dict) -> dict:
    """For a pair (x, label), map each observable event sigma to the set of pairs reached by u sigma, u unobservable."""
    result: dict = {}
    seen = {pair}
    stack = [pair]
    while stack:
        x, label = stack.pop()
        for e, y in out.get(x, {}).items():
            if e in observable:
                result.setdefault(e, set()).add((y, label))
            else:
                nxt = (y, label | {faults[e]} if e in faults else label)
                if nxt not in seen:
                    seen.add(nxt)
                    stack.append(nxt)
    return result


class _Moves:
    """Cache of moves() for one plant."""

    def __init__(self, g: dict, observable: Iterable, faults: dict):
        self.out = out_edges(g["delta"])
        self.observable = set(observable)
        self.faults = dict(faults)
        self.cache: dict = {}

    def __call__(self, pair: Pair) -> dict:
        if pair not in self.cache:
            self.cache[pair] = moves(self.out, pair, self.observable, self.faults)
        return self.cache[pair]


def diagnoser(g: dict, observable: Iterable, faults: dict) -> dict:
    """The diagnoser automaton of g, built on the reachable diagnoser states."""
    mv = _Moves(g, observable, faults)
    events = sorted(mv.observable, key=repr)
    q0 = frozenset({(g["init"], Label())})  # @line L1
    states = {q0}
    delta = {}
    queue = deque([q0])  # @line L2
    while queue:  # @line L3
        q = queue.popleft()  # @line L4
        for sigma in events:  # @line L5
            nxt: set = set()  # @line L6
            for pair in q:  # @line L7
                nxt |= mv(pair).get(sigma, set())
            if nxt:  # @line L8
                r = frozenset(nxt)
                delta[(q, sigma)] = r
                if r not in states:
                    states.add(r)
                    queue.append(r)
    return {"init": q0, "states": states, "delta": delta}  # @line L9


def verdict(q: frozenset, kind: Hashable) -> str:
    """'F' if every pair of q has the fault type, 'N' if none has it, else 'uncertain'."""
    has = [kind in label for _, label in q]
    if all(has):
        return "F"
    if not any(has):
        return "N"
    return "uncertain"


def observe(d: dict, word: Iterable) -> frozenset:
    """The diagnoser state after the observed word, or None if the word cannot be observed."""
    q = d["init"]
    for sigma in word:
        q = d["delta"].get((q, sigma))
        if q is None:
            return None
    return q


def has_cycle(nodes: set, succ: dict) -> bool:
    """Kahn's algorithm: True if the graph on nodes has a cycle."""
    indeg = {v: 0 for v in nodes}
    for v in nodes:
        for w in succ.get(v, ()):
            indeg[w] += 1
    queue = deque(v for v in nodes if indeg[v] == 0)
    removed = 0
    while queue:
        v = queue.popleft()
        removed += 1
        for w in succ.get(v, ()):
            indeg[w] -= 1
            if indeg[w] == 0:
                queue.append(w)
    return removed < len(nodes)


def diagnosable(g: dict, observable: Iterable, faults: dict, kind: Hashable) -> bool:
    """True if the fault type `kind` is diagnosable: no indeterminate cycle in the diagnoser."""
    mv = _Moves(g, observable, faults)
    d = diagnoser(g, observable, faults)  # @line L10
    nodes = set()
    for q in d["states"]:  # @line L11
        for a in q:
            for b in q:
                if kind in a[1] and kind not in b[1]:
                    nodes.add((q, a, b))
    succ: dict = {}
    for q, a, b in nodes:  # @line L12
        for sigma in mv.observable:
            r = d["delta"].get((q, sigma))
            if r is None:
                continue
            for a2 in mv(a).get(sigma, ()):
                for b2 in mv(b).get(sigma, ()):
                    if kind not in b2[1]:
                        succ.setdefault((q, a, b), []).append((r, a2, b2))
    return not has_cycle(nodes, succ)  # @line L13


def has_uncertain_cycle(g: dict, observable: Iterable, faults: dict, kind: Hashable) -> bool:
    """True if the diagnoser has a cycle of uncertain states. If False, the fault type is diagnosable; True proves nothing."""
    d = diagnoser(g, observable, faults)
    nodes = {q for q in d["states"] if verdict(q, kind) == "uncertain"}
    succ: dict = {}
    for (q, _), r in d["delta"].items():
        if q in nodes and r in nodes:
            succ.setdefault(q, []).append(r)
    return has_cycle(nodes, succ)
test_diagnoser_automaton.py 186 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diagnoser-automaton/. The authors are listed in prov/8VN8F2.jsonl.

import itertools
import random

from diagnoser_automaton import diagnosable, diagnoser, has_uncertain_cycle, observe, verdict

N = frozenset()
F = frozenset({"F"})


def plant(edges, init=0):
    return {"init": init, "delta": {(x, e): y for x, e, y in edges}}


# The worked example of the page: the normal cycle a u b, and a fault after a.
EXAMPLE = plant([(0, "a", 1), (1, "u", 2), (2, "b", 0), (1, "f", 3), (3, "b", 4), (4, "c", 4)])
# Diagnosable, but the diagnoser has a cycle of uncertain states.
UNCERTAIN = plant([(1, "a", 1), (1, "f", 5), (5, "a", 2), (2, "b", 6), (6, "b", 6)], init=1)
# Not diagnosable: after the fault the plant shows a b a b ... as the normal plant does.
AMBIGUOUS = plant([(0, "a", 1), (1, "u", 2), (2, "b", 0), (1, "f", 3), (3, "b", 4), (4, "a", 5), (5, "b", 4)])


def brute_states(g, observable, faults, max_obs):
    """Group the strings of L(G) that end with an observable event (or are empty) by their projection."""
    out = {}
    for (x, e), y in g["delta"].items():
        out.setdefault(x, []).append((e, y))
    groups = {(): {(g["init"], N)}}
    stack = [(g["init"], N, ())]
    while stack:
        x, label, obs = stack.pop()
        for e, y in out.get(x, []):
            if e in observable:
                if len(obs) < max_obs:
                    groups.setdefault(obs + (e,), set()).add((y, label))
                    stack.append((y, label, obs + (e,)))
            else:
                stack.append((y, label | {faults[e]} if e in faults else label, obs))
    return groups


def oracle_verifier(g, observable, fault_events):
    """An independent twin plant: a cycle of states (x, faulty, y) with the flag set means not diagnosable."""
    out = {}
    for (x, e), y in g["delta"].items():
        out.setdefault(x, {})[e] = y
    start = (g["init"], False, g["init"])
    seen = {start}
    stack = [start]
    succ = {}
    while stack:
        x, f, y = v = stack.pop()
        nxt = []
        for e, x2 in out.get(x, {}).items():
            if e not in observable:
                nxt.append((x2, f or e in fault_events, y))
            elif e in out.get(y, {}):
                nxt.append((x2, f, out[y][e]))
        for e, y2 in out.get(y, {}).items():
            if e not in observable and e not in fault_events:
                nxt.append((x, f, y2))
        succ[v] = nxt
        for w in nxt:
            if w not in seen:
                seen.add(w)
                stack.append(w)
    nodes = {v for v in seen if v[1]}
    color = {}
    for root in nodes:
        if root in color:
            continue
        color[root] = 1
        it = [(root, iter(succ[root]))]
        while it:
            v, children = it[-1]
            for w in children:
                if w not in nodes:
                    continue
                if color.get(w) == 1:
                    return False
                if w not in color:
                    color[w] = 1
                    it.append((w, iter(succ[w])))
                    break
            else:
                color[v] = 2
                it.pop()
    return True


def random_plant(rng, n, observable, unobservable):
    edges = {}
    for x in range(n):
        for e in observable:
            if rng.random() < 0.45:
                edges[(x, e)] = rng.randrange(n)
        for e in unobservable:
            if x < n - 1 and rng.random() < 0.35:
                edges[(x, e)] = rng.randrange(x + 1, n)
        if not any(k[0] == x for k in edges):
            edges[(x, rng.choice(observable))] = rng.randrange(n)
    return {"init": 0, "delta": edges}


def test_page_example():
    d = diagnoser(EXAMPLE, {"a", "b", "c"}, {"f": "F"})
    q0 = frozenset({(0, N)})
    q1 = frozenset({(1, N)})
    q2 = frozenset({(0, N), (4, F)})
    q3 = frozenset({(4, F)})
    assert d["states"] == {q0, q1, q2, q3}
    assert d["delta"] == {(q0, "a"): q1, (q1, "b"): q2, (q2, "a"): q1, (q2, "c"): q3, (q3, "c"): q3}
    assert [verdict(q, "F") for q in (q0, q1, q2, q3)] == ["N", "N", "uncertain", "F"]
    assert observe(d, "abababc") == q3
    assert observe(d, "aa") is None
    assert diagnosable(EXAMPLE, {"a", "b", "c"}, {"f": "F"}, "F")


def test_uncertain_cycle_but_diagnosable():
    d = diagnoser(UNCERTAIN, {"a", "b"}, {"f": "F"})
    assert len(d["states"]) == 3
    assert has_uncertain_cycle(UNCERTAIN, {"a", "b"}, {"f": "F"}, "F")
    assert diagnosable(UNCERTAIN, {"a", "b"}, {"f": "F"}, "F")


def test_not_diagnosable():
    assert not diagnosable(AMBIGUOUS, {"a", "b"}, {"f": "F"}, "F")
    d = diagnoser(AMBIGUOUS, {"a", "b"}, {"f": "F"})
    assert verdict(observe(d, "abababab"), "F") == "uncertain"


def test_no_fault_event():
    g = plant([(0, "a", 1), (1, "u", 0)])
    d = diagnoser(g, {"a"}, {})
    assert all(verdict(q, "F") == "N" for q in d["states"])
    assert diagnosable(g, {"a"}, {}, "F")


def test_two_fault_types():
    g = plant([(0, "f1", 1), (0, "f2", 2), (1, "a", 3), (2, "a", 4), (3, "b", 3), (4, "c", 4)])
    faults = {"f1": 1, "f2": 2}
    d = diagnoser(g, {"a", "b", "c"}, faults)
    q = observe(d, "a")
    assert q == frozenset({(3, frozenset({1})), (4, frozenset({2}))})
    assert verdict(q, 1) == "uncertain" and verdict(observe(d, "ab"), 1) == "F"
    assert diagnosable(g, {"a", "b", "c"}, faults, 1) and diagnosable(g, {"a", "b", "c"}, faults, 2)


def test_states_against_brute_force():
    rng = random.Random(11)
    observable = ["a", "b"]
    for _ in range(300):
        g = random_plant(rng, 4, observable, ["u", "f"])
        d = diagnoser(g, set(observable), {"f": "F"})
        groups = brute_states(g, set(observable), {"f": "F"}, 4)
        for k in range(5):
            for word in itertools.product(observable, repeat=k):
                q = observe(d, word)
                if word in groups:
                    assert q == frozenset(groups[word])
                else:
                    assert q is None


def test_random_against_twin_plant():
    rng = random.Random(5)
    observable = ["a", "b"]
    counts = [0, 0]
    for _ in range(600):
        g = random_plant(rng, 4, observable, ["u", "f"])
        got = diagnosable(g, set(observable), {"f": "F"}, "F")
        assert got == oracle_verifier(g, set(observable), {"f"})
        counts[got] += 1
    assert min(counts) >= 50


def test_random_two_types_against_twin_plant():
    rng = random.Random(8)
    observable = ["a", "b"]
    faults = {"f": 1, "g": 2}
    for _ in range(300):
        g = random_plant(rng, 4, observable, ["f", "g", "u"])
        for kind, events in ((1, {"f"}), (2, {"g"})):
            assert diagnosable(g, set(observable), faults, kind) == oracle_verifier(g, set(observable), events)

History

Sampath, Sengupta, Lafortune, Sinnamohideen and Teneketzis introduced diagnosability and the diagnoser in the IEEE Transactions on Automatic Control in 1995, with the condition that the diagnoser has no indeterminate cycle. In 1996 the same group described the use of the diagnoser for fault detection in physical systems in the IEEE Transactions on Control Systems Technology. Because the diagnoser can be exponential, Jiang, Huang, Chandra and Kumar (2001) and Yoo and Lafortune (2002) gave polynomial tests on a product of the plant with itself. The diagnoser stays the standard online detector.

References

  1. M. Sampath, R. Sengupta, S. Lafortune, K. Sinnamohideen and D. Teneketzis, Diagnosability of discrete-event systems, IEEE Transactions on Automatic Control 40(9), 1995, pages 1555 to 1575, the construction of the diagnoser and the necessary and sufficient condition for diagnosability in terms of indeterminate cycles
  2. M. Sampath, R. Sengupta, S. Lafortune, K. Sinnamohideen and D. C. Teneketzis, Failure diagnosis using discrete-event models, IEEE Transactions on Control Systems Technology 4(2), 1996, pages 105 to 124, the use of the diagnoser for online fault detection
  3. Christos G. Cassandras and Stéphane Lafortune, Introduction to Discrete Event Systems, third edition, Springer, 2021, Chapter 2, Languages and Automata (observers and diagnosers)

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