Algorithm Search⌘K

Algorithmadvanced

Supervision based on place invariants

Also called SBPI, Petri net controller by place invariants.

Enforces linear marking constraints L mu <= b on a Petri net by adding one monitor place per constraint, with incidence -L D and initial marking b - L mu0. No reachability graph is built.

Time
O(c n q) worst
Space
O(n q + c q) extra
Where
c = the number of constraints; n = the number of places; q = the number of transitions
Properties
deterministicexactofflineiterative
Origin
Katerina Yamalidou, John O. Moody, Michael D. Lemmon, Panos J. Antsaklis, 1996

Supervision based on place invariants (SBPI) builds a supervisor for a Petri net that must keep its marking μ\mu inside a set of linear constraints Lμ≤bL \mu \le b. For each constraint it adds one monitor place to the net. The arcs of the monitor places come from the product −LD-L D, where DD is the incidence matrix of the plant, and their initial tokens are b−Lμ0b - L \mu_0. The construction makes Lμ+μc=bL \mu + \mu_c = b a place invariant of the closed loop, so the constraint holds on every reachable marking. When the supervisor can disable and observe every transition, the closed loop blocks a firing only if that firing would break a constraint, so the supervisor is maximally permissive. The method needs one matrix product and never builds the reachability graph. This is the main difference from the automaton approach of supervisory control theory, where the supremal controllable sublanguage is computed on the full state space.

In plain words

A factory is modeled as a network of places that hold tokens, and of events that move tokens when they occur. Some combinations of tokens are not allowed, for example two robots in the same work cell, or more than three parts in a buffer. Each rule of this kind says that a weighted count of tokens must stay below a limit. The method adds one new place for each rule. This new place holds the "spare capacity" of the rule. An event that uses up capacity must first take tokens from the new place, and an event that frees capacity puts tokens back. When the new place is empty, the events that need it cannot occur. Because the new place always holds the exact spare capacity, it stops exactly the events that would break the rule, and nothing more.

The problem

Input: a Petri net with nn places and qq transitions, given by nonnegative integer matrices Pre,Post∈Nn×q\mathrm{Pre}, \mathrm{Post} \in \mathbb{N}^{n \times q} (Preit\mathrm{Pre}_{it} is the weight of the arc from place ii to transition tt, and Postit\mathrm{Post}_{it} the weight of the arc from tt to ii), an initial marking μ0∈Nn\mu_0 \in \mathbb{N}^n, an integer matrix L∈Zc×nL \in \mathbb{Z}^{c \times n} and an integer vector b∈Zcb \in \mathbb{Z}^c.

The incidence matrix is D=Post−PreD = \mathrm{Post} - \mathrm{Pre}. Transition tt is enabled at μ\mu if μ≥Pre⋅t\mu \ge \mathrm{Pre}_{\cdot t} entrywise, and firing it gives μ+D⋅t\mu + D_{\cdot t}. This is the notation of the petri-net page, with μ\mu for the marking.

Output: cc monitor places, given by Prec,Postc∈Nc×q\mathrm{Pre}_c, \mathrm{Post}_c \in \mathbb{N}^{c \times q} and an initial marking μc,0∈Nc\mu_{c,0} \in \mathbb{N}^c, such that in the closed loop (the plant with the monitor places added):

  1. every reachable marking satisfies Lμ≤bL \mu \le b, and
  2. a firing sequence can fire in the closed loop if and only if it can fire in the plant and every marking along it satisfies Lμ≤bL \mu \le b.

If Lμ0≰bL \mu_0 \not\le b, no supervisor exists, and the output is a report of this fact. Condition 2 assumes that the supervisor can disable and observe every transition; the section on variants treats uncontrollable and unobservable transitions.

The algorithm

  1. SBPI(Pre, Post, mu0, L, b)
  2. 1D ← Post - Pre ▷ n by q incidence matrix of the plant
  3. 2D_c ← -L·D ▷ c by q, one row per monitor place
  4. 3mu_c0 ← b - L·mu0 ▷ the spare capacity of each constraint
  5. 4if some entry of mu_c0 < 0 then report "mu0 breaks L mu ≤ b"
  6. 5Pre_c ← max(0, -D_c); Post_c ← max(0, D_c) ▷ entrywise
  7. 6return (Pre_c, Post_c, mu_c0)

Line L1 forms the incidence matrix. Line L2 gives the change of each monitor place when each transition fires: it is minus the change of the constrained count LμL \mu. Line L3 gives the initial tokens of the monitors: the slack of each constraint at μ0\mu_0. A negative slack means that the initial marking is already illegal (line L4). Line L5 turns the signed incidence into arcs: a negative entry becomes an arc from the monitor to the transition, and a positive entry becomes an arc from the transition to the monitor. The monitors have no self-loops.

The closed loop is the plant with the rows of Prec\mathrm{Pre}_c and Postc\mathrm{Post}_c added below Pre\mathrm{Pre} and Post\mathrm{Post}, and with the initial marking (μ0,μc,0)(\mu_0, \mu_{c,0}).

Example

Mutual exclusion of two processes. Process 1 cycles p1→t1→p2→t2→p1p_1 \to t_1 \to p_2 \to t_2 \to p_1, and process 2 cycles p3→t3→p4→t4→p3p_3 \to t_3 \to p_4 \to t_4 \to p_3. Places p2p_2 and p4p_4 are the critical sections. The initial marking is μ0=(1,0,1,0)\mu_0 = (1, 0, 1, 0): both processes are idle. The rule is that at most one process is in its critical section: μ2+μ4≤1\mu_2 + \mu_4 \le 1, so L=[0 1 0 1]L = [0\ 1\ 0\ 1] and b=1b = 1.

Line Result
L1 D=[−11001−10000−11001−1]D = \begin{bmatrix} -1 & 1 & 0 & 0 \\ 1 & -1 & 0 & 0 \\ 0 & 0 & -1 & 1 \\ 0 & 0 & 1 & -1 \end{bmatrix}, columns t1,t2,t3,t4t_1, t_2, t_3, t_4
L2 LD=[1 −1 1 −1]L D = [1\ {-1}\ 1\ {-1}], so Dc=[−1 1 −1 1]D_c = [-1\ 1\ {-1}\ 1]
L3 μc,0=1−(0+0)=1\mu_{c,0} = 1 - (0 + 0) = 1
L4 1≥01 \ge 0, so the initial marking is legal
L5 Prec=[1 0 1 0]\mathrm{Pre}_c = [1\ 0\ 1\ 0] (arcs to t1t_1 and t3t_3), Postc=[0 1 0 1]\mathrm{Post}_c = [0\ 1\ 0\ 1] (arcs from t2t_2 and t4t_4)

The monitor place is the classic binary semaphore: entering a critical section takes its token, and leaving gives it back. The reachable markings, written (μ1,μ2,μ3,μ4∣μc)(\mu_1, \mu_2, \mu_3, \mu_4 \mid \mu_c), are:

Marking Plant Closed loop Enabled in the closed loop
(1,0,1,0∣1)(1, 0, 1, 0 \mid 1) reachable reachable t1t_1, t3t_3
(0,1,1,0∣0)(0, 1, 1, 0 \mid 0) reachable reachable t2t_2 (t3t_3 is blocked by the empty monitor)
(1,0,0,1∣0)(1, 0, 0, 1 \mid 0) reachable reachable t4t_4 (t1t_1 is blocked)
(0,1,0,1)(0, 1, 0, 1) reachable not reachable

The plant reaches 4 markings and the closed loop reaches 3. The only removed marking is the one that breaks the rule, and the only blocked firings are t3t_3 from the second marking and t1t_1 from the third, which lead to it. The invariant μ2+μ4+μc=1\mu_2 + \mu_4 + \mu_c = 1 holds in every row.

Correctness

The key fact is that Lμ+μc=bL \mu + \mu_c = b is a place invariant of the closed loop: when tt fires, LμL \mu changes by LD⋅tL D_{\cdot t} and μc\mu_c changes by −LD⋅t-L D_{\cdot t}, and the sum starts at bb by line L3. Since a marking is never negative, μc≥0\mu_c \ge 0 gives Lμ≤bL \mu \le b. For maximal permissiveness, look at one monitor jj and one transition tt. If (Dc)jt<0(D_c)_{jt} < 0, the monitor enables tt exactly when μc,j+(Dc)jt≥0\mu_{c,j} + (D_c)_{jt} \ge 0, and by the invariant this is Lj(μ+D⋅t)≤bjL_j(\mu + D_{\cdot t}) \le b_j. If (Dc)jt≥0(D_c)_{jt} \ge 0, the monitor never blocks tt, and the firing cannot raise LjμL_j \mu. So the closed loop allows tt exactly when the plant allows it and the next marking is legal. An induction on the firing sequence completes the proof. The full proof, with the conditions for uncontrollable and unobservable transitions, is in proofs/correctness.md.

Proof: The monitor places enforce L mu <= b, and they block only the firings that would break itfull

Let the plant be a Petri net with nn places and qq transitions, with nonnegative integer matrices Pre,Post∈Nn×q\mathrm{Pre}, \mathrm{Post} \in \mathbb{N}^{n \times q} and incidence matrix D=Post−PreD = \mathrm{Post} - \mathrm{Pre}. A marking is μ∈Nn\mu \in \mathbb{N}^n. Transition tt is enabled at μ\mu if μ≥Pre⋅t\mu \ge \mathrm{Pre}_{\cdot t} (entrywise), and firing it gives μ′=μ+D⋅t\mu' = \mu + D_{\cdot t}. The specification is Lμ≤bL \mu \le b with L∈Zc×nL \in \mathbb{Z}^{c \times n} and b∈Zcb \in \mathbb{Z}^c, and the initial marking μ0\mu_0 satisfies Lμ0≤bL \mu_0 \le b.

The algorithm adds cc monitor places with incidence Dc=−LDD_c = -L D, arcs Prec=max⁡(0,−Dc)\mathrm{Pre}_c = \max(0, -D_c) and Postc=max⁡(0,Dc)\mathrm{Post}_c = \max(0, D_c) (entrywise), and initial marking μc,0=b−Lμ0\mu_{c,0} = b - L \mu_0. The closed loop is the net with places (μ,μc)(\mu, \mu_c) and the matrices Pre\mathrm{Pre} and Post\mathrm{Post} stacked on Prec\mathrm{Pre}_c and Postc\mathrm{Post}_c.

Note that Postc−Prec=Dc\mathrm{Post}_c - \mathrm{Pre}_c = D_c, because max⁡(0,x)−max⁡(0,−x)=x\max(0, x) - \max(0, -x) = x for every integer xx, and that no monitor place has both an input arc and an output arc with the same transition.

Lemma 1: the place invariant

Every marking (μ,μc)(\mu, \mu_c) that is reachable in the closed loop satisfies Lμ+μc=bL \mu + \mu_c = b.

Proof. By induction on the length of the firing sequence. At the start, Lμ0+μc,0=Lμ0+b−Lμ0=bL \mu_0 + \mu_{c,0} = L \mu_0 + b - L \mu_0 = b. If tt fires at (μ,μc)(\mu, \mu_c), the new marking is (μ+D⋅t,μc+(Dc)⋅t)(\mu + D_{\cdot t}, \mu_c + (D_c)_{\cdot t}), and

L(μ+D⋅t)+μc+(Dc)⋅t=Lμ+μc+LD⋅t−LD⋅t=b.□L(\mu + D_{\cdot t}) + \mu_c + (D_c)_{\cdot t} = L \mu + \mu_c + L D_{\cdot t} - L D_{\cdot t} = b. \qquad \square

In the terms of the petri-net page, the vector y=(Lj,ej)y = (L_j, e_j) is a place invariant of the closed loop for each row jj: yT[D;Dc]=LjD−LjD=0y^T [D; D_c] = L_j D - L_j D = 0.

Lemma 2: the constraint holds

Every reachable closed-loop marking satisfies Lμ≤bL \mu \le b.

Proof. Markings of a Petri net are nonnegative, so μc≥0\mu_c \ge 0, and Lemma 1 gives Lμ=b−μc≤bL \mu = b - \mu_c \le b. □\square

Lemma 3: the enabling rule of the closed loop

Let (μ,μc)(\mu, \mu_c) be reachable in the closed loop. Then tt is enabled in the closed loop if and only if tt is enabled at μ\mu in the plant and L(μ+D⋅t)≤bL(\mu + D_{\cdot t}) \le b.

Proof. In the closed loop, tt is enabled if and only if μ≥Pre⋅t\mu \ge \mathrm{Pre}_{\cdot t} and μc≥(Prec)⋅t\mu_c \ge (\mathrm{Pre}_c)_{\cdot t}. The first condition is plant enabling. Take one monitor jj and write d=(Dc)jt=−LjD⋅td = (D_c)_{jt} = -L_j D_{\cdot t}.

  • If d<0d < 0, the monitor condition is μc,j≥−d\mu_{c,j} \ge -d, that is μc,j+d≥0\mu_{c,j} + d \ge 0. By Lemma 1, μc,j=bj−Ljμ\mu_{c,j} = b_j - L_j \mu, so the condition is bj−Ljμ−LjD⋅t≥0b_j - L_j \mu - L_j D_{\cdot t} \ge 0, that is Lj(μ+D⋅t)≤bjL_j(\mu + D_{\cdot t}) \le b_j.
  • If d≥0d \ge 0, there is no arc from monitor jj to tt, so the monitor condition always holds. The constraint also holds: Lj(μ+D⋅t)=Ljμ−d≤Ljμ≤bjL_j(\mu + D_{\cdot t}) = L_j \mu - d \le L_j \mu \le b_j by Lemma 2.

So in both cases the condition of monitor jj is equivalent to Lj(μ+D⋅t)≤bjL_j(\mu + D_{\cdot t}) \le b_j, and the claim follows by taking all jj. □\square

Theorem: maximal permissiveness

Let RR be the set of plant markings that can be reached from μ0\mu_0 by a firing sequence whose markings all satisfy Lμ≤bL \mu \le b (the legal reachable set). Then the projection of the closed-loop reachable set on the plant places is exactly RR. More strongly, a firing sequence σ\sigma can fire in the closed loop if and only if it can fire in the plant and every marking along it satisfies Lμ≤bL \mu \le b.

Proof. By induction on the length of σ\sigma, with the claim that after σ\sigma the closed loop is at (μ,b−Lμ)(\mu, b - L\mu), where μ\mu is the plant marking after σ\sigma. The empty sequence is the base case. For the step, let σ\sigma satisfy the claim and add tt. By Lemma 3, tt fires in the closed loop after σ\sigma if and only if it fires in the plant and the new plant marking satisfies the constraint. The new plant part is μ+D⋅t\mu + D_{\cdot t} in both nets, and Lemma 1 fixes the monitor part as b−L(μ+D⋅t)b - L(\mu + D_{\cdot t}). □\square

Any supervisor that observes and can disable all transitions and enforces Lμ≤bL \mu \le b must disable tt at every reachable μ\mu with L(μ+D⋅t)≰bL(\mu + D_{\cdot t}) \not\le b. By Lemma 3 the monitors disable exactly these firings and no other. So no supervisor of this kind allows a larger set of sequences: the monitor solution is maximally permissive.

Uncontrollable and unobservable transitions

Suppose some transitions are uncontrollable (the supervisor cannot disable them) or unobservable (the supervisor does not see them fire).

  • If (LD)⋅t≤0(L D)_{\cdot t} \le 0, then (Dc)⋅t≥0(D_c)_{\cdot t} \ge 0, so (Prec)⋅t=0(\mathrm{Pre}_c)_{\cdot t} = 0. No monitor arc leads into tt, so the monitors never disable tt, and they may treat it as uncontrollable.
  • If (LD)⋅t=0(L D)_{\cdot t} = 0, then (Dc)⋅t=0(D_c)_{\cdot t} = 0, so no monitor arc touches tt. The monitor marking does not depend on whether tt fired, and tt may be unobservable.

These are the sufficient conditions of Moody and Antsaklis (1998). When they fail, the monitor built from (L,b)(L, b) is not admissible. A common repair is to replace the constraint by a stricter one L′μ≤b′L' \mu \le b' that implies Lμ≤bL \mu \le b on the reachable markings and meets the conditions; the result may then be less permissive than the best admissible supervisor.

Termination and cost

The algorithm has no loop with a data-dependent bound. Line L1 takes nqnq subtractions. Line L2 computes the c×qc \times q matrix −LD-L D with cnqc n q multiplications and additions. Line L3 takes cnc n operations, and lines L4 and L5 take cc and cqc q operations. The total is O(cnq)O(c n q) word operations, with integers that fit in a word when the entries of LL, bb, DD and μ0\mu_0 are bounded by a constant. The output has 2cq+c2 c q + c integers.

Complexity

The model is the word RAM, with nn places, qq transitions and cc constraints, and with integer entries of Pre\mathrm{Pre}, Post\mathrm{Post}, LL, bb and μ0\mu_0 that fit in a word.

  • Line L1: nqn q subtractions.
  • Line L2: the product of a c×nc \times n matrix by an n×qn \times q matrix, cnqc n q multiplications and additions.
  • Lines L3 to L5: cn+c+2cqc n + c + 2 c q operations.

The total is O(cnq)O(c n q) time in the worst case. The extra space is O(nq)O(n q) for DD and O(cq)O(c q) for the monitor arcs. The bound is in the size of the net, not in the size of its reachability graph. The reachability graph of a bounded net can have a number of markings exponential in nn (the state explosion problem), and for an unbounded net it is infinite. Methods that work on the reachability graph, such as the supremal controllable sublanguage on an automaton model, pay that size. The tests on this page build the reachability graph only to check the result.

Properties

  • Exact. All arithmetic is on integers, and the output is the unique monitor with incidence −LD-L D.
  • Maximally permissive when every transition is controllable and observable (proofs/correctness.md).
  • Correct for any net, bounded or not, and for any initial marking that satisfies the constraints. The proof uses only the firing rule and the invariant, not the reachability set.
  • The supervisor is itself a Petri net, so the closed loop can be analyzed with the same tools as the plant, for example invariant checking.
  • The method does not ensure liveness or deadlock freedom. The closed loop can deadlock in a legal marking.

Variants and improvements

  • Uncontrollable transitions. If (LD)⋅t≤0(L D)_{\cdot t} \le 0, the monitor has no arc into tt, so it never needs to disable tt. When this fails for some uncontrollable tt, the constraint is not admissible as written. Moody and Antsaklis (1998) transform it into a stricter constraint L′μ≤b′L' \mu \le b' that implies the original one and is admissible. The result may then be less permissive than the best admissible supervisor.
  • Unobservable transitions. If (LD)⋅t=0(L D)_{\cdot t} = 0, the monitor has no arc at tt at all, so it does not need to see tt fire. The same transformation handles the other cases.
  • Generalized mutual exclusion constraints. Giua, DiCesare and Silva (1992) called the constraints Lμ≤bL \mu \le b generalized mutual exclusion constraints (GMECs) and used monitor places for them. They also studied when a set of such constraints is equivalent to a smaller one.
  • Liveness. Deadlock prevention by monitors, for example with siphons, is a separate problem. It adds further constraints and is not part of this method. See deadlock for the general notion.

When to use it

Use it when the specification is a set of linear inequalities on the marking: mutual exclusion, buffer capacities, resource counts. It works without the reachability graph, so it scales to nets whose state space is too large to enumerate. When the specification is a regular language or an arbitrary set of forbidden states, it does not apply directly; use the automaton methods of supervisory control theory instead. When some transitions are uncontrollable, check the condition (LD)⋅t≤0(L D)_{\cdot t} \le 0 first.

Pitfalls

  • Wrong sign on line L2. Writing Dc=LDD_c = L D gives a monitor that gains tokens when the constrained count grows. The invariant is then $L \mu - \mu_c = $ constant, which bounds nothing. The correct line is Dc=−LDD_c = -L D.
  • Skipping line L4. If Lμ0≤bL \mu_0 \le b fails, line L3 gives a negative initial marking, which is not a marking. No supervisor can make an illegal initial state legal, and the code must report it.
  • Uncontrollable transitions with an arc from a monitor. Line L5 creates an arc from monitor jj into tt whenever (LD)jt>0(L D)_{jt} > 0. If tt is uncontrollable, the supervisor cannot honor this arc. Check the condition from the section on variants before you use the monitor.
  • Building arcs from L⋅PreL \cdot \mathrm{Pre} and L⋅PostL \cdot \mathrm{Post} separately. A transition that both takes and gives tokens in the constrained count then gets a self-loop on the monitor, and the monitor blocks it even when the net change is zero. Line L5 builds the arcs from the net change DcD_c, which gives the maximally permissive monitor.
  • Expecting liveness. The mutual exclusion example stays live, but in general the closed loop can deadlock. Check deadlock freedom separately.

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.

supervision_based_on_place_invariants.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/supervision-based-on-place-invariants/. The authors are listed in prov/131GMK.jsonl.

"""Supervision based on place invariants (Yamalidou, Moody, Lemmon and Antsaklis 1996).

A Petri net has n places and q transitions. Pre[i][t] is the weight of the arc
from place i to transition t, Post[i][t] the weight of the arc from t to i, and
D = Post - Pre is the incidence matrix. A marking mu is a vector of n
nonnegative integers. Transition t is enabled at mu if mu >= Pre[:, t]; firing
it gives mu + D[:, t].

The specification is c linear constraints L mu <= b, with L an integer c by n
matrix and b an integer vector. The supervisor adds one monitor place per
constraint, with incidence D_c = -L D and initial marking mu_c0 = b - L mu0.
Then L mu + mu_c = b is a place invariant of the closed loop, so mu_c >= 0
gives L mu <= b. When every transition is controllable and observable, the
closed loop blocks a firing only if the firing would break a constraint, so it
is maximally permissive.

All arithmetic is on Python integers, so the result is exact.
"""

from collections import deque

__all__ = [
    "incidence",
    "monitor_places",
    "closed_loop",
    "is_admissible",
    "enabled",
    "fire",
    "reachable_markings",
]


def _shape(pre, post):
    n = len(pre)
    if n == 0 or len(post) != n:
        raise ValueError("Pre and Post must have the same number of rows (places)")
    q = len(pre[0])
    for row in list(pre) + list(post):
        if len(row) != q:
            raise ValueError("Pre and Post must have the same number of columns (transitions)")
        for a in row:
            if not isinstance(a, int) or a < 0:
                raise ValueError("arc weights must be nonnegative integers")
    return n, q


def incidence(pre, post):
    """Return D = Post - Pre, an n by q integer matrix."""
    n, q = _shape(pre, post)
    return [[post[i][t] - pre[i][t] for t in range(q)] for i in range(n)]


def monitor_places(pre, post, mu0, L, b):
    """Return (Pre_c, Post_c, mu_c0) for the constraints L mu <= b.

    Pre_c and Post_c are c by q: row j holds the arcs of monitor place j.
    Raise ValueError if the initial marking mu0 breaks a constraint, because
    then no monitor marking can be nonnegative.
    """
    n, q = _shape(pre, post)
    if len(mu0) != n or any(m < 0 for m in mu0):
        raise ValueError("mu0 must hold n nonnegative integers")
    if any(len(row) != n for row in L) or len(b) != len(L):
        raise ValueError("L must be c by n and b must hold c integers")
    c = len(L)
    D = incidence(pre, post)  # @line L1
    Dc = [[-sum(L[j][i] * D[i][t] for i in range(n)) for t in range(q)] for j in range(c)]  # @line L2
    muc0 = [b[j] - sum(L[j][i] * mu0[i] for i in range(n)) for j in range(c)]  # @line L3
    if any(m < 0 for m in muc0):  # @line L4
        raise ValueError("the initial marking breaks the constraint L mu0 <= b")
    pre_c = [[max(0, -Dc[j][t]) for t in range(q)] for j in range(c)]  # @line L5
    post_c = [[max(0, Dc[j][t]) for t in range(q)] for j in range(c)]  # @line L5
    return pre_c, post_c, muc0  # @line L6


def closed_loop(pre, post, mu0, L, b):
    """Return (Pre', Post', mu0') of the plant with the monitor places appended."""
    pre_c, post_c, muc0 = monitor_places(pre, post, mu0, L, b)
    return ([list(r) for r in pre] + pre_c, [list(r) for r in post] + post_c, list(mu0) + muc0)


def is_admissible(pre, post, L, uncontrollable=(), unobservable=()):
    """Check the conditions of Moody and Antsaklis for the monitor of L mu <= b.

    The monitor never needs to block an uncontrollable transition t when
    (L D)[:, t] <= 0, and it never needs to see an unobservable transition t
    when (L D)[:, t] = 0. Return True when both conditions hold.
    """
    n, q = _shape(pre, post)
    D = incidence(pre, post)
    LD = [[sum(row[i] * D[i][t] for i in range(n)) for t in range(q)] for row in L]
    for t in uncontrollable:
        if any(LD[j][t] > 0 for j in range(len(L))):
            return False
    for t in unobservable:
        if any(LD[j][t] != 0 for j in range(len(L))):
            return False
    return True


def enabled(pre, mu, t):
    """True if transition t is enabled at marking mu."""
    return all(mu[i] >= pre[i][t] for i in range(len(pre)))


def fire(pre, post, mu, t):
    """Return the marking after firing the enabled transition t at mu."""
    if not enabled(pre, mu, t):
        raise ValueError("transition is not enabled")
    return tuple(mu[i] - pre[i][t] + post[i][t] for i in range(len(pre)))


def reachable_markings(pre, post, mu0, allowed=None, limit=100000):
    """Breadth-first search of the reachability graph.

    allowed(mu) -> bool restricts the search to markings where it is True (the
    initial marking must be allowed). Return the set of reached markings as
    tuples. Raise RuntimeError if more than limit markings are found, since an
    unbounded net has an infinite reachability set.
    """
    q = len(pre[0])
    start = tuple(mu0)
    if allowed is not None and not allowed(start):
        return set()
    seen = {start}
    todo = deque([start])
    while todo:
        mu = todo.popleft()
        for t in range(q):
            if enabled(pre, mu, t):
                nxt = fire(pre, post, mu, t)
                if nxt not in seen and (allowed is None or allowed(nxt)):
                    seen.add(nxt)
                    if len(seen) > limit:
                        raise RuntimeError("too many markings; the net may be unbounded")
                    todo.append(nxt)
    return seen
test_supervision_based_on_place_invariants.py 211 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/supervision-based-on-place-invariants/. The authors are listed in prov/131GMK.jsonl.

import itertools
import random

import pytest

from supervision_based_on_place_invariants import (
    closed_loop,
    enabled,
    fire,
    incidence,
    is_admissible,
    monitor_places,
    reachable_markings,
)

# Two cyclic processes p1 -> t1 -> p2 -> t2 -> p1 and p3 -> t3 -> p4 -> t4 -> p3.
# p2 and p4 are the critical sections. The constraint mu(p2) + mu(p4) <= 1 is
# mutual exclusion.
PRE = [
    [1, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 1, 0],
    [0, 0, 0, 1],
]
POST = [
    [0, 1, 0, 0],
    [1, 0, 0, 0],
    [0, 0, 0, 1],
    [0, 0, 1, 0],
]
MU0 = [1, 0, 1, 0]
L_MUTEX = [[0, 1, 0, 1]]
B_MUTEX = [1]


def lin(L, mu):
    return [sum(a * x for a, x in zip(row, mu)) for row in L]


def legal(L, b):
    return lambda mu: all(v <= bj for v, bj in zip(lin(L, mu), b))


def random_conservative_net(rng, n, q):
    """Each transition moves k tokens, so the total number of tokens is constant."""
    pre = [[0] * q for _ in range(n)]
    post = [[0] * q for _ in range(n)]
    for t in range(q):
        k = rng.randint(1, 2)
        for _ in range(k):
            pre[rng.randrange(n)][t] += 1
            post[rng.randrange(n)][t] += 1
    return pre, post


def random_case(rng):
    n = rng.randint(2, 5)
    q = rng.randint(2, 5)
    pre, post = random_conservative_net(rng, n, q)
    mu0 = [0] * n
    for _ in range(rng.randint(1, 4)):
        mu0[rng.randrange(n)] += 1
    c = rng.randint(1, 2)
    L = [[rng.randint(-1, 2) for _ in range(n)] for _ in range(c)]
    b = [v + rng.randint(0, 2) for v in lin(L, mu0)]
    return pre, post, mu0, L, b


def test_incidence_of_the_example():
    assert incidence(PRE, POST) == [
        [-1, 1, 0, 0],
        [1, -1, 0, 0],
        [0, 0, -1, 1],
        [0, 0, 1, -1],
    ]


def test_mutual_exclusion_monitor_is_a_semaphore():
    pre_c, post_c, muc0 = monitor_places(PRE, POST, MU0, L_MUTEX, B_MUTEX)
    # D_c = -L D = [-1, 1, -1, 1]: the monitor feeds t1 and t3, and t2 and t4 give the token back.
    assert pre_c == [[1, 0, 1, 0]]
    assert post_c == [[0, 1, 0, 1]]
    assert muc0 == [1]


def test_example_reachability_counts():
    plant = reachable_markings(PRE, POST, MU0)
    assert plant == {(1, 0, 1, 0), (0, 1, 1, 0), (1, 0, 0, 1), (0, 1, 0, 1)}
    pre2, post2, mu2 = closed_loop(PRE, POST, MU0, L_MUTEX, B_MUTEX)
    cl = reachable_markings(pre2, post2, mu2)
    assert cl == {(1, 0, 1, 0, 1), (0, 1, 1, 0, 0), (1, 0, 0, 1, 0)}


def test_infeasible_initial_marking_is_rejected():
    with pytest.raises(ValueError):
        monitor_places(PRE, POST, [0, 1, 0, 1], L_MUTEX, B_MUTEX)


def test_bad_input_is_rejected():
    with pytest.raises(ValueError):
        incidence([[1, -1]], [[0, 0]])
    with pytest.raises(ValueError):
        monitor_places(PRE, POST, MU0, [[1, 1]], [1])


def test_random_nets_match_restricted_reachability_graph():
    rng = random.Random(20240611)
    checked = 0
    for _ in range(300):
        pre, post, mu0, L, b = random_case(rng)
        n = len(pre)
        pre2, post2, mu2 = closed_loop(pre, post, mu0, L, b)
        cl = reachable_markings(pre2, post2, mu2)
        projected = {m[:n] for m in cl}
        target = reachable_markings(pre, post, mu0, allowed=legal(L, b))
        assert projected == target
        for m in cl:
            mu, muc = m[:n], m[n:]
            # the place invariant L mu + mu_c = b holds on every reachable marking
            assert [v + w for v, w in zip(lin(L, mu), muc)] == list(b)
            assert all(w >= 0 for w in muc)
        checked += len(cl)
    assert checked > 500


def test_maximal_permissiveness_on_every_legal_marking():
    rng = random.Random(7)
    for _ in range(200):
        pre, post, mu0, L, b = random_case(rng)
        n, q = len(pre), len(pre[0])
        pre2, post2, mu2 = closed_loop(pre, post, mu0, L, b)
        ok = legal(L, b)
        for m in reachable_markings(pre2, post2, mu2):
            mu = m[:n]
            for t in range(q):
                plant_allows = enabled(pre, mu, t) and ok(fire(pre, post, mu, t))
                assert enabled(pre2, m, t) == plant_allows


def test_all_firing_sequences_up_to_length_8():
    rng = random.Random(99)
    for _ in range(25):
        pre, post, mu0, L, b = random_case(rng)
        n, q = len(pre), len(pre[0])
        if q > 3:
            pre = [row[:3] for row in pre]
            post = [row[:3] for row in post]
            q = 3
        pre2, post2, mu2 = closed_loop(pre, post, mu0, L, b)
        ok = legal(L, b)
        for length in range(9):
            for seq in itertools.product(range(q), repeat=length):
                mu, m = tuple(mu0), tuple(mu2)
                plant_ok, cl_ok = True, True
                for t in seq:
                    if plant_ok and enabled(pre, mu, t):
                        mu = fire(pre, post, mu, t)
                        plant_ok = ok(mu)
                    else:
                        plant_ok = False
                    if cl_ok and enabled(pre2, m, t):
                        m = fire(pre2, post2, m, t)
                    else:
                        cl_ok = False
                assert plant_ok == cl_ok
                if cl_ok:
                    assert m[:n] == mu


def test_admissibility_with_uncontrollable_transitions():
    # t2 and t4 leave the critical sections. They only lower L mu, so they may be uncontrollable.
    assert is_admissible(PRE, POST, L_MUTEX, uncontrollable=[1, 3])
    pre_c, _, _ = monitor_places(PRE, POST, MU0, L_MUTEX, B_MUTEX)
    assert pre_c[0][1] == 0 and pre_c[0][3] == 0
    # t1 enters a critical section. If it is uncontrollable the monitor cannot block it.
    assert not is_admissible(PRE, POST, L_MUTEX, uncontrollable=[0])
    # t2 changes L mu, so it must be observed.
    assert not is_admissible(PRE, POST, L_MUTEX, unobservable=[1])


def test_admissible_monitor_never_blocks_uncontrollable_transitions():
    rng = random.Random(4242)
    found = 0
    for _ in range(400):
        pre, post, mu0, L, b = random_case(rng)
        q = len(pre[0])
        unc = [t for t in range(q) if rng.random() < 0.5]
        if not is_admissible(pre, post, L, uncontrollable=unc):
            continue
        found += 1
        pre_c, _, _ = monitor_places(pre, post, mu0, L, b)
        for t in unc:
            assert all(row[t] == 0 for row in pre_c)
    assert found > 20


def test_bounded_buffer_capacity():
    # producer t0 puts an item in the buffer p0, consumer t1 takes it; p1 and p2 are idle places.
    pre = [[0, 1], [1, 0], [0, 0]]
    post = [[1, 0], [1, 0], [0, 0]]
    mu0 = [0, 1, 0]
    # the plant buffer is unbounded; the monitor keeps mu(p0) <= 3
    pre2, post2, mu2 = closed_loop(pre, post, mu0, [[1, 0, 0]], [3])
    cl = reachable_markings(pre2, post2, mu2)
    assert {m[0] for m in cl} == {0, 1, 2, 3}
    assert all(m[0] + m[3] == 3 for m in cl)
    with pytest.raises(RuntimeError):
        reachable_markings(pre, post, mu0, limit=50)

History

Petri nets with place invariants were a standard analysis tool by the 1980s (Murata 1989). Giua, DiCesare and Silva (1992) used monitor places to enforce generalized mutual exclusion constraints on nets with uncontrollable transitions. Yamalidou, Moody, Lemmon and Antsaklis presented the construction from place invariants at the 33rd IEEE CDC in 1994 and in Automatica in 1996. They derived the monitor incidence Dc=−LDD_c = -L D from the invariant equation and showed that the result is maximally permissive. Moody and Antsaklis (1998) collected the method, its extensions to uncontrollable and unobservable transitions, and the constraint transformations in a book.

References

  1. Katerina Yamalidou, John Moody, Michael Lemmon and Panos Antsaklis, Feedback control of Petri nets based on place invariants, Automatica 32(1), 15-28, 1996, the monitor place construction D_c = -L D and mu_c0 = b - L mu0, and its maximal permissiveness; the conference version is in Proc. 33rd IEEE CDC, 1994, 3104-3109
  2. Alessandro Giua, Frank DiCesare and Manuel Silva, Generalized mutual exclusion constraints on nets with uncontrollable transitions, Proc. IEEE International Conference on Systems, Man and Cybernetics, Chicago, 974-979, 1992, generalized mutual exclusion constraints and their monitor places
  3. John O. Moody and Panos J. Antsaklis, Supervisory Control of Discrete Event Systems Using Petri Nets, Kluwer Academic Publishers, 1998, the place invariant method and the admissibility conditions for uncontrollable and unobservable transitions
  4. Tadao Murata, Petri nets, properties, analysis and applications, Proceedings of the IEEE 77(4), 541-580, 1989, the incidence matrix, the state equation and place invariants (S-invariants)
  5. Christos G. Cassandras and Stéphane Lafortune, Introduction to Discrete Event Systems, third edition, Springer, 2021, the chapter on Petri nets and the chapter on supervisory control

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