Algorithm Search⌘K

Algorithmresearch

Twin plant diagnosability test

Also called verifier for diagnosability.

Tests diagnosability in polynomial time. It runs a faulty and a fault-free copy of the plant in step on the observable events and searches for a cycle where the copies never separate.

Time
O(n^2 q) worst
Space
O(n^2 q) extra
Where
n = the number of states of the plant; q = the number of events
Properties
deterministicexactoffline
Origin
Shengbing Jiang, Zhongdong Huang, Vigyan Chandra, Ratnesh Kumar, Tae Sic Yoo, Stéphane Lafortune, 2001

The twin plant test decides whether a fault of a partially observed discrete-event system is diagnosable, in time polynomial in the size of the plant. It runs two copies of the plant side by side. The first copy may take the fault and remembers in a flag that it did. The second copy never takes the fault. The copies move alone on unobservable events and together on observable events, so they always show the same observation. A cycle of states where the flag is set is a way for a faulty run and a fault-free run to look the same forever, so the fault is not diagnosable. If there is no such cycle, it is. Jiang, Huang, Chandra and Kumar (2001) gave the first polynomial test of this kind, and Yoo and Lafortune (2002) gave the verifier automaton. The diagnoser of Sampath et al. answers the same question, but it can be exponentially large.

In plain words

You want to know whether a hidden fault always shows itself after a while. Imagine two copies of the machine. One is allowed to break, and the other is not. You make them produce the same visible events, step by step, while each may also do hidden events on its own.

If the broken copy and the healthy copy can go on forever and still look the same, then an observer can never be sure that the fault happened, and the fault is not diagnosable. If every such game ends, because sooner or later the broken copy does something the healthy copy cannot match, then the fault is diagnosable. Both copies have only as many positions as the machine, so the pairs of positions are few, and the search is fast.

The problem

The input is a deterministic plant G=(X,Σ,δ,x0)G = (X, \Sigma, \delta, x_0), the observable events Σo\Sigma_o and the set ΣF⊆Σ∖Σo\Sigma_F \subseteq \Sigma \setminus \Sigma_o of fault events of one type FF. As in Sampath et al. (1995), GG has no cycle of unobservable events. The output is true if FF is diagnosable: there is NN such that, for every string s∈L(G)s \in L(G) that ends with a fault of type FF and every continuation tt with ∣t∣≥N|t| \ge N, every w∈L(G)w \in L(G) with P(w)=P(st)P(w) = P(st) contains a fault of type FF. Here PP is the natural projection onto Σo∗\Sigma_o^*. For several fault types, run the test once per type, and treat the other fault events as ordinary unobservable events.

The algorithm

GNG_N is GG without its fault transitions. A verifier state is a triple (x,f,y)(x, f, y): xx is the state of copy 1, ff is the flag "copy 1 has taken a fault", and yy is the state of copy 2.

  1. TWIN-PLANT(G, Σo, ΣF)
  2. 1G_N ← G without the transitions labeled by events of ΣF
  3. 2v0 ← (x0, false, x0); states ← {v0}; queue ← [v0]
  4. 3while queue is not empty do
  5. 4(x, f, y) ← pop the front of queue
  6. 5for each unobservable e defined at x in G do add the edge to (δ(x, e), f or e ∈ ΣF, y)
  7. 6for each unobservable e defined at y in G_N do add the edge to (x, f, δ_N(y, e))
  8. 7for each observable e defined at x in G and at y in G_N do add the edge to (δ(x, e), f, δ_N(y, e))
  9. 8add each new target of lines L5 to L7 to states and to queue
  10. 9W ← the states with f = true
  11. 10return true if the graph restricted to W has no cycle, else false

Lines L2 to L8 are a breadth-first search of the product of GG and GNG_N that is synchronized only on observable events. Each path from v0v_0 is a pair of runs, of GG and of GNG_N, with the same projection, and the flag tells whether the first run has a fault. Line L10 runs Kahn's algorithm on WW, as in topological sort: it removes flagged states of in-degree 0 until none is left, and a cycle remains if and only if some state remains. The test of Yoo and Lafortune labels the states of both copies and looks for a cycle where the labels differ. The version here keeps copy 2 fault-free from the start, so one flag is enough.

Example

The plant has states 0 to 5 and the transitions 0→a10 \xrightarrow{a} 1, 1→u21 \xrightarrow{u} 2, 2→b02 \xrightarrow{b} 0 (the normal cycle), 1→f31 \xrightarrow{f} 3 (the fault), 3→b43 \xrightarrow{b} 4, 4→a54 \xrightarrow{a} 5 and 5→b45 \xrightarrow{b} 4. The events aa and bb are observable, and uu and ff are not. The table lists the verifier states in the order of the search, with the flag written N or F. A label (e,−)(e, -) is a move of copy 1 alone, (−,e)(-, e) of copy 2 alone, and (e,e)(e, e) a joint move.

order state line edges
1 (0,N,0)(0, N, 0) L7 (a,a)→(1,N,1)(a, a) \to (1, N, 1)
2 (1,N,1)(1, N, 1) L5, L6 (u,−)→(2,N,1)(u, -) \to (2, N, 1); (f,−)→(3,F,1)(f, -) \to (3, F, 1); (−,u)→(1,N,2)(-, u) \to (1, N, 2)
3 (2,N,1)(2, N, 1) L6 (−,u)→(2,N,2)(-, u) \to (2, N, 2)
4 (3,F,1)(3, F, 1) L6 (−,u)→(3,F,2)(-, u) \to (3, F, 2)
5 (1,N,2)(1, N, 2) L5 (u,−)→(2,N,2)(u, -) \to (2, N, 2); (f,−)→(3,F,2)(f, -) \to (3, F, 2)
6 (2,N,2)(2, N, 2) L7 (b,b)→(0,N,0)(b, b) \to (0, N, 0)
7 (3,F,2)(3, F, 2) L7 (b,b)→(4,F,0)(b, b) \to (4, F, 0)
8 (4,F,0)(4, F, 0) L7 (a,a)→(5,F,1)(a, a) \to (5, F, 1)
9 (5,F,1)(5, F, 1) L6 (−,u)→(5,F,2)(-, u) \to (5, F, 2)
10 (5,F,2)(5, F, 2) L7 (b,b)→(4,F,0)(b, b) \to (4, F, 0)

The verifier has 10 states and 13 edges. Line L9 gives the 5 flagged states (3,F,1)(3, F, 1), (3,F,2)(3, F, 2), (4,F,0)(4, F, 0), (5,F,1)(5, F, 1) and (5,F,2)(5, F, 2). Kahn's algorithm at line L10 removes (3,F,1)(3, F, 1) and then (3,F,2)(3, F, 2), and stops. The cycle (4,F,0)→(5,F,1)→(5,F,2)→(4,F,0)(4, F, 0) \to (5, F, 1) \to (5, F, 2) \to (4, F, 0) remains, so the fault is not diagnosable. The cycle gives a witness: copy 1 runs afba(ba)kafba(ba)^k and copy 2 runs auba(uba)kauba(uba)^k. Both show abab⋯abab\cdots, the first has the fault and the second has not, for every kk.

If instead the plant ends with 3→b43 \xrightarrow{b} 4 and 4→c44 \xrightarrow{c} 4, with cc observable, the verifier has 8 states and 10 edges. The flagged state (4,F,0)(4, F, 0) has no edge, because copy 1 can only do cc and copy 2 can only do aa. There is no flagged cycle, and the fault is diagnosable. The tests of the implementation check both plants, and compare the test with the diagnoser and with the test of Jiang et al. on 600 random plants.

Correctness

Paths of the verifier from v0v_0 correspond to pairs (s,s′)(s, s') with s∈L(G)s \in L(G), s′∈L(GN)s' \in L(G_N) and P(s)=P(s′)P(s) = P(s'), and the flag of the end state is set if and only if ss has a fault. The flag never goes back to false. If the flagged states have a cycle, follow a path to it and pump the cycle: this gives faulty strings with arbitrarily long continuations after the fault and a fault-free twin with the same projection. So FF is not diagnosable. The run of copy 1 on the cycle must be nonempty for this, and it is, because copy 2 alone has no cycle of unobservable events. If the flagged states have no cycle, every path inside WW has fewer than ∣W∣|W| edges. A continuation tt after a fault, with a fault-free twin, gives a path in WW with at least ∣t∣|t| edges, one for each event of copy 1. So N=∣W∣≤n2N = |W| \le n^2 is a valid delay bound, and FF is diagnosable. The full proof is in the correctness proof.

Proof: The verifier has a cycle of flagged states if and only if the fault is not diagnosablefull

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}. ΣF⊆Σuo\Sigma_F \subseteq \Sigma_{uo} is the set of fault events of the type under test. PP erases the unobservable events. The fault type is diagnosable if there is an integer NN such that for every s∈L(G)s \in L(G) that ends with an event of ΣF\Sigma_F, every tt with st∈L(G)st \in L(G) and ∣t∣≥N|t| \ge N, and every w∈L(G)w \in L(G) with P(w)=P(st)P(w) = P(st), the string ww has an event of ΣF\Sigma_F.

Lines L1 to L8 build the verifier VV. Its states are triples (x,f,y)(x, f, y) with x,y∈Xx, y \in X and a flag ff. Its edges are:

  • L5: (x,f,y)→(x′,f∨[e∈ΣF],y)(x, f, y) \to (x', f \lor [e \in \Sigma_F], y) for e∈Σuoe \in \Sigma_{uo} with δ(x,e)=x′\delta(x, e) = x' (copy 1 moves alone);
  • L6: (x,f,y)→(x,f,y′)(x, f, y) \to (x, f, y') for e∈Σuo∖ΣFe \in \Sigma_{uo} \setminus \Sigma_F with δ(y,e)=y′\delta(y, e) = y' (copy 2 moves alone);
  • L7: (x,f,y)→(x′,f,y′)(x, f, y) \to (x', f, y') for e∈Σoe \in \Sigma_o with δ(x,e)=x′\delta(x, e) = x' and δ(y,e)=y′\delta(y, e) = y' (both move).

Each edge carries the event of copy 1 (or nothing) and the event of copy 2 (or nothing). For a path π\pi, let s1(π)s_1(\pi) and s2(π)s_2(\pi) be the two strings of these events.

Lemma 1 (paths and string pairs). (a) If π\pi is a path from v0=(x0,0,x0)v_0 = (x_0, 0, x_0) to (x,f,y)(x, f, y), then s1=s1(π)s_1 = s_1(\pi) and s2=s2(π)s_2 = s_2(\pi) are in L(G)L(G), δ(x0,s1)=x\delta(x_0, s_1) = x, δ(x0,s2)=y\delta(x_0, s_2) = y, P(s1)=P(s2)P(s_1) = P(s_2), s2s_2 has no event of ΣF\Sigma_F, and f=1f = 1 if and only if s1s_1 has an event of ΣF\Sigma_F. (b) Conversely, for s1,s2∈L(G)s_1, s_2 \in L(G) with P(s1)=P(s2)P(s_1) = P(s_2) and no event of ΣF\Sigma_F in s2s_2, there is a path π\pi from v0v_0 with s1(π)=s1s_1(\pi) = s_1 and s2(π)=s2s_2(\pi) = s_2.

Proof. (a) By induction on the length of π\pi; each kind of edge keeps every claim true. (b) Write s1=u0σ1u1⋯σkuks_1 = u_0 \sigma_1 u_1 \cdots \sigma_k u_k and s2=u0′σ1u1′⋯σkuk′s_2 = u_0' \sigma_1 u_1' \cdots \sigma_k u_k' with ui,ui′∈Σuo∗u_i, u_i' \in \Sigma_{uo}^*. The path does u0u_0 with edges L5, then u0′u_0' with edges L6, then σ1\sigma_1 with an edge L7, and so on. Each edge exists because the strings are in L(G)L(G) and ui′u_i' has no event of ΣF\Sigma_F. ■\blacksquare

Lemma 2. The flag never goes from 1 to 0. So a cycle of VV through a flagged state has only flagged states.

Proof. The three kinds of edges keep the flag or set it. ■\blacksquare

Theorem. Assume that GG has no cycle of unobservable events. The fault type is diagnosable if and only if the flagged states WW (line L9) of VV contain no cycle. Line L10 returns this answer.

Proof that a flagged cycle gives no diagnosability. Let π\pi be a path from v0v_0 to a flagged state vv, and cc a cycle from vv to vv. If s1(c)s_1(c) were empty, every edge of cc would be of kind L6, and the states yy along cc would form a cycle of unobservable events in GG. So s1(c)≠εs_1(c) \neq \varepsilon. For each kk, the path πck\pi c^k gives by Lemma 1 the strings p1c1kp_1 c_1^k and p2c2kp_2 c_2^k, with pi=si(π)p_i = s_i(\pi) and ci=si(c)c_i = s_i(c). They are in L(G)L(G) and have the same projection. The second one has no event of ΣF\Sigma_F, and the first one has one, because vv is flagged. Let ss be the prefix of p1p_1 that ends with its first event of ΣF\Sigma_F, and p1=srp_1 = s r. Then t=rc1kt = r c_1^k has ∣t∣≥k|t| \ge k, and w=p2c2kw = p_2 c_2^k breaks the condition. As kk is arbitrary, no NN works.

Proof that no flagged cycle gives diagnosability. Let N=∣W∣N = |W|; note ∣W∣≤∣X∣2|W| \le |X|^2. Take ss, tt and ww as in the definition with ∣t∣≥N|t| \ge N, and assume that ww has no event of ΣF\Sigma_F. By Lemma 1(b), there is a path π\pi from v0v_0 with s1(π)=sts_1(\pi) = st and s2(π)=ws_2(\pi) = w. Each event of stst is on its own edge of π\pi. After the edge of the last event of ss, the flag is 1, and by Lemma 2 it stays 1. The events of tt come after this edge, on ∣t∣|t| more edges. So π\pi has a part of at least ∣t∣≥∣W∣|t| \ge |W| edges, that is at least ∣W∣+1|W| + 1 states, all in WW. A state repeats, so WW contains a cycle. This contradicts the assumption. So every such ww has an event of ΣF\Sigma_F, and the fault type is diagnosable with the delay bound N=∣W∣≤∣X∣2N = |W| \le |X|^2.

Line L10 runs Kahn's algorithm on the graph that VV induces on WW. It removes all states of WW if and only if this graph has no cycle. ■\blacksquare

Only the first part uses the assumption on unobservable cycles. Without it, a cycle of kind L6 edges alone can make the test answer "not diagnosable" for a diagnosable plant.

Termination and cost. There are at most 2∣X∣22|X|^2 triples, and the search of lines L3 to L8 puts each one in the queue once, so it stops. A state has at most ∣Σuo∣|\Sigma_{uo}| edges of kind L5, ∣Σuo∣|\Sigma_{uo}| of kind L6 and ∣Σo∣|\Sigma_o| of kind L7, so at most 2∣Σ∣2|\Sigma| edges. The search and Kahn's algorithm each take O(∣X∣2∣Σ∣)O(|X|^2 |\Sigma|) dict operations. ■\blacksquare

Complexity

The model is the word RAM with hashing. Let n=∣X∣n = |X| and q=∣Σ∣q = |\Sigma|.

  • The verifier has at most 2n22 n^2 states: nn choices for each copy and two values of the flag.
  • Each state has at most 2q2q edges: lines L5 and L7 together take at most one edge per event of copy 1, and line L6 at most one per event of copy 2. So there are at most 4n2q4 n^2 q edges.
  • Lines L2 to L8 and Kahn's algorithm at line L10 are linear in the size of the verifier.

The total is O(n2q)O(n^2 q) time and space. This bound is derived on this page for the program above. The abstract of Jiang et al. (2001) says that their test is of fourth order in the number of states of the plant and linear in the number of failure types. Their test first builds a nondeterministic automaton over the observable events, which can have many more transitions than GG, and then takes its product with itself. For mm fault types, the version here runs mm times, so it is also linear in mm.

Properties

  • Exact. It decides diagnosability, under the assumption on unobservable cycles.
  • Polynomial. Unlike the diagnoser, its size is at most quadratic in nn.
  • Witness. A flagged cycle, with a path to it, gives a faulty run and a fault-free run with the same projection, of any length. The implementation returns one.
  • Delay bound. If the fault is diagnosable, the number of flagged states bounds the detection delay: N=∣W∣≤n2N = |W| \le n^2 events after the fault.
  • Offline only. It does not give an online detector. For that, use the diagnoser.

Variants and improvements

  • Jiang et al. (2001). First replace GG by its observable reduction: a nondeterministic automaton over Σo\Sigma_o whose states are pairs (state, fault label) and whose transitions jump over unobservable runs. Then build the product of two copies, synchronized on all events, and look for a cycle of states where the two labels differ. The implementation has this test as a second function, and the tests check that it agrees.
  • Yoo and Lafortune (2002). The verifier keeps the unobservable moves of both copies, as here, and labels both. It avoids the observable reduction, and so the extra transitions it can have.
  • Several fault types. One flag per type gives 2m2^m copies of each pair. One run per type keeps the size at 2n22 n^2.
  • Other properties. A twin product of the same kind checks the observability of a language, which also asks about two runs with the same observation.
  • Search for strongly connected components. Instead of Kahn's algorithm, compute the strongly connected components of WW; a cycle exists if one has more than one state or a self-loop. Both are linear, as other cycle detection methods are.

When to use it

Use it when you need to know whether a plant is diagnosable, and the plant has many states. It is the method of choice for this offline question. If you also need an online detector, build the diagnoser for a small plant, or run it on the fly. Check first that the plant has no cycle of unobservable events.

Pitfalls

  • Unobservable cycles (lines L6 and L10). With a cycle of unobservable events, copy 2 can loop alone while copy 1 waits in a flagged state. That is a flagged cycle, and line L10 answers "not diagnosable" even when the fault is diagnosable. In the plant 0→f10 \xrightarrow{f} 1, 1→a11 \xrightarrow{a} 1, 0→u20 \xrightarrow{u} 2, 2→u22 \xrightarrow{u} 2, 2→b22 \xrightarrow{b} 2 with aa and bb observable, every run after the fault shows aa, and no fault-free run does, so the fault is diagnosable. But copy 2 loops on uu at state 2 while copy 1 waits at state 1, and the test says no. A test of the implementation checks this case. Check the assumption first.
  • Letting copy 2 take the fault (line L1). If copy 2 runs GG instead of GNG_N, the flag no longer means "faulty against fault-free". Two faulty runs then give flagged cycles, and the test reports diagnosable plants as not diagnosable.
  • Looking for a flagged state instead of a flagged cycle (line L10). Every reachable fault gives a flagged state at once, since the other copy can always wait. Only a cycle shows that the ambiguity can last forever.
  • Synchronizing the unobservable events (lines L5 and L6). If both copies had to make the same unobservable move, the verifier would miss fault-free twins that use other hidden events, such as uu against ff in the example, and it would answer "diagnosable" too often.

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.

twin_plant.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/twin-plant-diagnosability-test/. The authors are listed in prov/4TC48W.jsonl.

"""The twin plant (verifier) test of diagnosability.

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 and `faults` is the set of fault events of the fault type under test.
Fault events are unobservable. G must have no cycle of unobservable events.

The verifier runs two copies of G. Copy 1 is the full plant and records in
a flag whether a fault has happened. Copy 2 is the plant without the fault
transitions. The copies move alone on unobservable events and together on
observable events, so both always have the same observation. G is
diagnosable for `faults` if and only if the verifier has no cycle of states
whose flag is set (Yoo and Lafortune 2002; Jiang et al. 2001 use a similar
product of the observable reduction of G).

Cost: at most 2 |X|^2 verifier states, each with at most 2 |Sigma| outgoing
edges, for |X| states and an alphabet of size |Sigma|. So there are at most
4 |X|^2 |Sigma| edges, and the test takes O(|X|^2 |Sigma|) dict operations.
"""

from collections import deque
from typing import Iterable, Optional


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


def build_verifier(g: dict, observable: Iterable, faults: Iterable):
    """Return (v0, states, edges); edges[v] is a list of (w, (event of copy 1, event of copy 2))."""
    obs, flt = set(observable), set(faults)
    out = out_edges(g["delta"])
    normal = {y: {e: z for e, z in d.items() if e not in flt} for y, d in out.items()}  # @line L1
    v0 = (g["init"], False, g["init"])  # @line L2
    states = {v0}
    edges: dict = {}
    queue = deque([v0])
    while queue:  # @line L3
        v = queue.popleft()  # @line L4
        x, flag, y = v
        succ = []
        for e, x2 in out.get(x, {}).items():
            if e not in obs:
                succ.append(((x2, flag or e in flt, y), (e, None)))  # @line L5
        for e, y2 in normal.get(y, {}).items():
            if e not in obs:
                succ.append(((x, flag, y2), (None, e)))  # @line L6
        for e, x2 in out.get(x, {}).items():
            if e in obs and e in normal.get(y, {}):
                succ.append(((x2, flag, normal[y][e]), (e, e)))  # @line L7
        edges[v] = succ
        for w, _ in succ:  # @line L8
            if w not in states:
                states.add(w)
                queue.append(w)
    return v0, states, edges


def _kahn_remaining(nodes: set, edges: dict) -> set:
    """The nodes that Kahn's algorithm cannot remove; empty if and only if the graph on nodes has no cycle."""
    indeg = {v: 0 for v in nodes}
    for v in nodes:
        for w, _ in edges.get(v, ()):
            if w in nodes:
                indeg[w] += 1
    queue = deque(v for v in nodes if indeg[v] == 0)
    left = set(nodes)
    while queue:
        v = queue.popleft()
        left.discard(v)
        for w, _ in edges.get(v, ()):
            if w in nodes:
                indeg[w] -= 1
                if indeg[w] == 0:
                    queue.append(w)
    return left


def diagnosable(g: dict, observable: Iterable, faults: Iterable) -> bool:
    """True if G is diagnosable for the given fault events."""
    v0, states, edges = build_verifier(g, observable, faults)
    w = {v for v in states if v[1]}  # @line L9
    return not _kahn_remaining(w, edges)  # @line L10


def witness(g: dict, observable: Iterable, faults: Iterable) -> Optional[tuple]:
    """If G is not diagnosable, return (p1, c1, p2, c2): copy 1 runs p1 c1 c1 ..., copy 2 runs p2 c2 c2 ...

    p1 c1^k is in L(G) and holds a fault, p2 c2^k is in L(G) and holds none, and both have the same
    projection for every k. Return None if G is diagnosable.
    """
    v0, states, edges = build_verifier(g, observable, faults)
    w = {v for v in states if v[1]}
    left = _kahn_remaining(w, edges)
    if not left:
        return None
    pred: dict = {}
    for v in left:
        for u, lab in edges.get(v, ()):
            if u in left:
                pred.setdefault(u, (v, lab))
    v = next(iter(left))
    seen: dict = {}
    while v not in seen:
        seen[v] = len(seen)
        v = pred[v][0]
    start = v
    cycle = []
    while True:
        u, lab = pred[v]
        cycle.append(lab)
        v = u
        if v == start:
            break
    cycle.reverse()
    parent = {v0: None}
    queue = deque([v0])
    while queue:
        u = queue.popleft()
        if u == start:
            break
        for x, lab in edges.get(u, ()):
            if x not in parent:
                parent[x] = (u, lab)
                queue.append(x)
    path = []
    u = start
    while parent[u] is not None:
        u, lab = parent[u]
        path.append(lab)
    path.reverse()

    def part(labels, i):
        return tuple(lab[i] for lab in labels if lab[i] is not None)

    return part(path, 0), part(cycle, 0), part(path, 1), part(cycle, 1)


def diagnosable_jiang(g: dict, observable: Iterable, faults: Iterable) -> bool:
    """The test of Jiang et al. (2001): a product of two labelled copies of the observable reduction of G."""
    obs, flt = set(observable), set(faults)
    out = out_edges(g["delta"])

    def jumps(pair):
        res: dict = {}
        seen = {pair}
        stack = [pair]
        while stack:
            x, f = stack.pop()
            for e, y in out.get(x, {}).items():
                if e in obs:
                    res.setdefault(e, set()).add((y, f))
                elif (y, f or e in flt) not in seen:
                    seen.add((y, f or e in flt))
                    stack.append((y, f or e in flt))
        return res

    cache: dict = {}
    start = ((g["init"], False), (g["init"], False))
    states = {start}
    edges: dict = {}
    queue = deque([start])
    while queue:
        a, b = v = queue.popleft()
        for p in (a, b):
            if p not in cache:
                cache[p] = jumps(p)
        succ = []
        for e, targets in cache[a].items():
            for a2 in targets:
                for b2 in cache[b].get(e, ()):
                    succ.append(((a2, b2), e))
        edges[v] = succ
        for w, _ in succ:
            if w not in states:
                states.add(w)
                queue.append(w)
    amb = {v for v in states if v[0][1] != v[1][1]}
    return not _kahn_remaining(amb, edges)
test_twin_plant_diagnosability_test.py 198 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/twin-plant-diagnosability-test/. The authors are listed in prov/4TC48W.jsonl.

import random

from twin_plant_diagnosability_test import build_verifier, diagnosable, diagnosable_jiang, witness


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


# The worked example of the page: normal cycle a u b; after the fault the plant repeats b a.
AMBIGUOUS = plant([(0, "a", 1), (1, "u", 2), (2, "b", 0), (1, "f", 3), (3, "b", 4), (4, "a", 5), (5, "b", 4)])
# The same plant, but after the fault it shows c forever.
DIAGNOSABLE = plant([(0, "a", 1), (1, "u", 2), (2, "b", 0), (1, "f", 3), (3, "b", 4), (4, "c", 4)])
# Diagnosable, although its 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)


def run(g, s):
    q = g["init"]
    for e in s:
        q = g["delta"].get((q, e))
        if q is None:
            return None
    return q


def oracle_diagnoser(g, observable, fault_events):
    """Independent test by the diagnoser of Sampath et al.: no indeterminate cycle means diagnosable."""
    out = {}
    for (x, e), y in g["delta"].items():
        out.setdefault(x, {})[e] = y
    memo = {}

    def jumps(pair):
        if pair in memo:
            return memo[pair]
        res = {}
        seen = {pair}
        stack = [pair]
        while stack:
            x, f = stack.pop()
            for e, y in out.get(x, {}).items():
                if e in observable:
                    res.setdefault(e, set()).add((y, f))
                else:
                    p = (y, f or e in fault_events)
                    if p not in seen:
                        seen.add(p)
                        stack.append(p)
        memo[pair] = res
        return res

    q0 = frozenset({(g["init"], False)})
    dstates, dnext, stack = {q0}, {}, [q0]
    while stack:
        q = stack.pop()
        for e in observable:
            r = set()
            for p in q:
                r |= jumps(p).get(e, set())
            if r:
                r = frozenset(r)
                dnext[(q, e)] = r
                if r not in dstates:
                    dstates.add(r)
                    stack.append(r)
    nodes = {(q, a, b) for q in dstates for a in q for b in q if a[1] and not b[1]}
    succ = {v: [] for v in nodes}
    for q, a, b in nodes:
        for e in observable:
            if (q, e) in dnext:
                for a2 in jumps(a).get(e, ()):
                    for b2 in jumps(b).get(e, ()):
                        if not b2[1]:
                            succ[(q, a, b)].append((dnext[(q, e)], a2, b2))
    indeg = {v: 0 for v in nodes}
    for v in nodes:
        for w in succ[v]:
            indeg[w] += 1
    ready = [v for v in nodes if indeg[v] == 0]
    gone = 0
    while ready:
        v = ready.pop()
        gone += 1
        for w in succ[v]:
            indeg[w] -= 1
            if indeg[w] == 0:
                ready.append(w)
    return gone == len(nodes)


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 check_witness(g, observable, faults, wit, reps=4):
    p1, c1, p2, c2 = wit
    assert len(c1) >= 1
    for k in range(reps):
        s1, s2 = p1 + c1 * k, p2 + c2 * k
        assert run(g, s1) is not None and run(g, s2) is not None
        assert any(e in faults for e in s1)
        assert not any(e in faults for e in s2)
        assert [e for e in s1 if e in observable] == [e for e in s2 if e in observable]
        tail = s1[min(i for i, e in enumerate(s1) if e in faults) + 1:]
        assert len(tail) >= k * len(c1)


def test_page_example_not_diagnosable():
    obs = {"a", "b", "c"}
    v0, states, edges = build_verifier(AMBIGUOUS, obs, {"f"})
    assert v0 == (0, False, 0)
    assert len(states) == 10
    assert sum(len(x) for x in edges.values()) == 13
    assert {v for v in states if v[1]} == {(3, True, 1), (3, True, 2), (4, True, 0), (5, True, 1), (5, True, 2)}
    assert not diagnosable(AMBIGUOUS, obs, {"f"})
    wit = witness(AMBIGUOUS, obs, {"f"})
    assert wit == (("a", "f", "b", "a"), ("b", "a"), ("a", "u", "b", "a"), ("u", "b", "a"))
    check_witness(AMBIGUOUS, obs, {"f"}, wit)
    v0, states, edges = build_verifier(DIAGNOSABLE, obs, {"f"})
    assert len(states) == 8 and sum(len(x) for x in edges.values()) == 10
    assert edges[(4, True, 0)] == []


def test_unobservable_cycle_breaks_the_test():
    # Pitfall: with an unobservable cycle in the normal part, copy 2 can loop alone while copy 1 waits after the fault.
    g = plant([(0, "f", 1), (0, "u", 2), (2, "u", 2), (1, "a", 1), (2, "b", 2)])
    v0, states, edges = build_verifier(g, {"a", "b"}, {"f"})
    assert ((1, True, 2), (None, "u")) in edges[(1, True, 2)]
    assert not diagnosable(g, {"a", "b"}, {"f"})
    # Yet every long run after the fault shows a and every normal run shows only b, so the fault is diagnosable.


def test_page_example_diagnosable():
    obs = {"a", "b", "c"}
    assert diagnosable(DIAGNOSABLE, obs, {"f"})
    assert witness(DIAGNOSABLE, obs, {"f"}) is None
    assert diagnosable_jiang(DIAGNOSABLE, obs, {"f"})
    assert not diagnosable_jiang(AMBIGUOUS, obs, {"f"})


def test_uncertain_diagnoser_cycle_is_diagnosable():
    assert diagnosable(UNCERTAIN, {"a", "b"}, {"f"})


def test_no_fault_and_fault_free_plant():
    g = plant([(0, "a", 1), (1, "u", 0)])
    assert diagnosable(g, {"a"}, set())
    assert diagnosable(g, {"a"}, {"f"})


def test_fault_without_observation_after_it():
    g = plant([(0, "a", 0), (0, "f", 1), (1, "a", 1)])
    assert not diagnosable(g, {"a"}, {"f"})
    check_witness(g, {"a"}, {"f"}, witness(g, {"a"}, {"f"}))


def test_random_against_diagnoser_and_jiang():
    rng = random.Random(17)
    observable = ["a", "b"]
    counts = [0, 0]
    for _ in range(600):
        g = random_plant(rng, 4, observable, ["u", "f"])
        got = diagnosable(g, set(observable), {"f"})
        assert got == oracle_diagnoser(g, set(observable), {"f"})
        assert got == diagnosable_jiang(g, set(observable), {"f"})
        if not got:
            check_witness(g, set(observable), {"f"}, witness(g, set(observable), {"f"}))
        counts[got] += 1
    assert min(counts) >= 50


def test_verifier_size_bound():
    rng = random.Random(23)
    for _ in range(200):
        n = rng.randrange(2, 7)
        g = random_plant(rng, n, ["a", "b", "c"], ["u", "f"])
        v0, states, edges = build_verifier(g, {"a", "b", "c"}, {"f"})
        assert len(states) <= 2 * n * n
        assert all(len(x) <= 5 + 2 for x in edges.values())
        assert sum(len(x) for x in edges.values()) <= 4 * n * n * 5
        flagged = [v for v in states if v[1]]
        assert len(flagged) <= n * n
        # The flag never goes back to False, so a cycle through a flagged state stays flagged.
        assert all(not v[1] or all(w[1] for w, _ in edges[v]) for v in states)
twin_plant_diagnosability_test.py 15 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/twin-plant-diagnosability-test/. The authors are listed in prov/4TC48W.jsonl.

"""The twin plant diagnosability test. The code is in twin_plant.py; this
module re-exports it under the name of the page (a file name ending in _test
is read as a test file by some tools, so the implementation itself lives in
twin_plant.py)."""

from twin_plant import (  # noqa: F401
    build_verifier,
    diagnosable,
    diagnosable_jiang,
    out_edges,
    witness,
)

History

Sampath, Sengupta, Lafortune, Sinnamohideen and Teneketzis defined diagnosability in 1995 and tested it with the diagnoser, which can be exponential in the number of plant states. Jiang, Huang, Chandra and Kumar showed in 2001, in the IEEE Transactions on Automatic Control, that a product of the plant with itself decides diagnosability in polynomial time. Yoo and Lafortune published the verifier in 2002 in the same journal. The name twin plant is common in the literature for this kind of product.

References

  1. S. Jiang, Z. Huang, V. Chandra and R. Kumar, A polynomial algorithm for testing diagnosability of discrete-event systems, IEEE Transactions on Automatic Control 46(8), 2001, pages 1318 to 1321, the product of the plant with itself and the test for ambiguous cycles; the abstract gives the order of the complexity
  2. T.-S. Yoo and S. Lafortune, Polynomial-time verification of diagnosability of partially observed discrete-event systems, IEEE Transactions on Automatic Control 47(9), 2002, pages 1491 to 1495, the verifier automaton and its cycle condition
  3. 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 definition of diagnosability and its assumptions

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