Algorithm Search⌘K

Techniqueresearch

Event-triggered control

Also called event-based control.

Updates the control only when a state-dependent condition says the error has grown too large, so it uses less communication than periodic sampling.

Event-triggered control is a way to implement a feedback law u=−Kxu = -Kx (or any u=k(x)u = k(x)) on a digital platform without a fixed sampling period. The controller holds the last computed input. It measures the state, compares it with the state used for the last update, and computes and sends a new input only when the difference is too large compared with the state. Tabuada (2007) gave the standard trigger ∥x(tk)−x(t)∥≥σ∥x(t)∥\|x(t_k) - x(t)\| \ge \sigma \|x(t)\|, proved asymptotic stability when the closed loop is input-to-state stable with respect to the measurement error, and proved a positive lower bound on the time between two events. The aim is fewer updates, and so less traffic on a shared network, less computation, and less energy in a wireless sensor, than a sampled-data loop with a fixed period that must be short enough for the worst case.

In plain words

A thermostat that reads the room every second, and sends a command every second, wastes most of its messages: the room barely changes. A better rule is to send a new command only when the room has changed enough since the last command. "Enough" is measured relative to how far the room is from the target. Far from the target, small changes do not matter. Close to the target, the rule asks for more care.

The rule must keep the feedback working, and it must not ask for updates infinitely often in a finite time. For a linear plant with a good feedback, both hold: there is a proof that the state goes to the target, and a proof that two updates are never closer than a fixed time.

When it applies

  • A feedback that works when continuous. You need a law u=k(x)u = k(x) that stabilizes the plant without sampling, and an ISS Lyapunov function: V′≤−a(∥x∥)+g(∥e∥)V' \le -a(\|x\|) + g(\|e\|) for the loop x′=f(x,k(x+e))x' = f(x, k(x + e)), with ee the measurement error and aa, gg class-K functions. For linear systems with a Hurwitz A−BKA - BK, V=xTPxV = x^T P x with (A−BK)TP+P(A−BK)=−Q(A - BK)^T P + P(A - BK) = -Q works (see Lyapunov equation).
  • Cheap monitoring, expensive updates. The trigger must be checked often, at the sensor, while the costly part (computing, sending, actuating) happens only at events. If checking costs as much as updating, there is little to gain.
  • A cost of communication. The method pays off on shared networks, wireless links and processors that run many tasks. On a dedicated wired loop, periodic sampling is simpler and easier to analyze.

The template

The plant is x′=Ax+Bux' = Ax + Bu, the law is u=−Kxu = -Kx, and the trigger uses the Euclidean norm. The code checks the trigger after each step of a fixed-step Runge-Kutta solver, as a sensor that samples fast would.

  1. EVENT-TRIGGERED-LOOP(A, B, K, x0, sigma, T, dt)
  2. 1xhat ← x0
  3. 2u ← -K xhat
  4. for t ← dt, 2 dt, ..., T do
  5. 3x ← one step of x' = A x + B u from x, with u held
  6. 4e ← ||xhat - x||
  7. 5if e >= sigma ||x|| then
  8. 6xhat ← x
  9. 7u ← -K xhat

Theorem (Tabuada 2007, the linear case). Let Acl=A−BKA_{cl} = A - BK be Hurwitz, Q≻0Q \succ 0 and AclTP+PAcl=−QA_{cl}^T P + P A_{cl} = -Q. With the error e=x^−xe = \hat x - x, the loop between events is x′=Aclx−BKex' = A_{cl} x - BKe, so V=xTPxV = x^T P x has V′=−xTQx−2xTPBKeV' = -x^T Q x - 2x^T PBKe. The trigger keeps ∥e∥≤σ∥x∥\|e\| \le \sigma\|x\|, so

V′≤−(λmin⁡(Q)−2σ∥PBK∥2)∥x∥2,V' \le -\big(\lambda_{\min}(Q) - 2\sigma\|PBK\|_2\big)\|x\|^2,

and every σ<σˉ=λmin⁡(Q)/(2∥PBK∥2)\sigma < \bar\sigma = \lambda_{\min}(Q) / (2\|PBK\|_2) makes the origin globally exponentially stable. With α=∥Acl∥2\alpha = \|A_{cl}\|_2 and β=∥BK∥2\beta = \|BK\|_2, the ratio y=∥e∥/∥x∥y = \|e\| / \|x\| starts at 00 at each event and obeys y′≤(α+βy)(1+y)y' \le (\alpha + \beta y)(1 + y). So it needs at least

τ∗=1α−βln⁡α(1+σ)α+βσ\tau^* = \frac{1}{\alpha - \beta}\ln\frac{\alpha(1 + \sigma)}{\alpha + \beta\sigma}

to reach σ\sigma (and σ/(α(1+σ))\sigma / (\alpha(1 + \sigma)) if α=β\alpha = \beta). Every two events are at least τ∗\tau^* apart, so there is no Zeno behavior. The derivations are in the correctness proof. Note that τ∗\tau^* is a lower bound for all states, so a periodic loop with the period τ∗\tau^* is also stable; the gain of the trigger is that the actual gaps are usually much longer.

Classic examples

An unstable plant of order 2. Take A=(01−23)A = \begin{pmatrix} 0 & 1 \\ -2 & 3 \end{pmatrix}, B=(0,1)TB = (0, 1)^T and K=(−1,4)K = (-1, 4), that is u=x1−4x2u = x_1 - 4x_2. Then Acl=(01−1−1)A_{cl} = \begin{pmatrix} 0 & 1 \\ -1 & -1 \end{pmatrix}, which is Hurwitz. With Q=IQ = I, the Lyapunov equation gives exactly P=(3/21/21/21)P = \begin{pmatrix} 3/2 & 1/2 \\ 1/2 & 1 \end{pmatrix}. PBK=(−1/22−14)PBK = \begin{pmatrix} -1/2 & 2 \\ -1 & 4 \end{pmatrix} has rank 1, so ∥PBK∥2=21.25=4.6098\|PBK\|_2 = \sqrt{21.25} = 4.6098, and σˉ=0.10847\bar\sigma = 0.10847. Also α=∥Acl∥2=1.6180\alpha = \|A_{cl}\|_2 = 1.6180 (the golden ratio) and β=∥BK∥2=17=4.1231\beta = \|BK\|_2 = \sqrt{17} = 4.1231. For σ=0.05\sigma = 0.05, τ∗=0.028396\tau^* = 0.028396. A simulation from x0=(1,0)x_0 = (1, 0) for 10 seconds, with the trigger checked every 0.0010.001 seconds, gives 218 events, counting the one at t=0t = 0. The gaps are between 0.0300.030 and 0.0790.079, and ∥x(10)∥=0.0034\|x(10)\| = 0.0034. A periodic loop with the guaranteed period τ∗\tau^* would need about 352 updates in the same time. These numbers are measurements of one run; the tests check them, and they also check the bound τ∗\tau^* and the decrease of the state on random stable loops.

Lebesgue sampling. Åström and Bernhardsson (2002) compared periodic sampling (Riemann) with sampling when the signal crosses a level (Lebesgue) for a first order stochastic system. With the same mean rate of samples, the event-based scheme gave a smaller variance of the state in their analysis. This paper started much of the later interest.

Send-on-delta sensors. A sensor that transmits only when its reading has moved by more than a fixed amount uses an absolute trigger ∥e∥≥δ\|e\| \ge \delta. The loop then converges only to a neighborhood of the origin, whose size depends on δ\delta, but the time between events stays bounded below even with disturbances.

Variations

  • Mixed trigger. ∥e∥≥σ∥x∥+δ\|e\| \ge \sigma\|x\| + \delta adds an absolute part. It gives practical stability (convergence to a ball of size of order δ\delta), and Borgers and Heemels (2014) showed that such triggers keep a positive time between events when disturbances act, which a purely relative trigger can lose.
  • Dynamic trigger. Girard (2015) adds an internal variable η\eta with η′=−γ(η)+σa(∥x∥)−g(∥e∥)\eta' = -\gamma(\eta) + \sigma a(\|x\|) - g(\|e\|) and triggers when η+θ(σa(∥x∥)−g(∥e∥))≤0\eta + \theta(\sigma a(\|x\|) - g(\|e\|)) \le 0, for a parameter θ>0\theta > 0. The trigger then uses the margin that the decrease of VV has saved, and the events come less often.
  • Periodic event-triggered control. Check the trigger only at the instants of a fixed fast period, as the template does. Then the time between events is at least that period by construction, and stability can be checked with linear matrix inequalities on the sampled model (Heemels, Johansson and Tabuada 2012).
  • Self-triggered control. At each event, compute the time of the next one from the current state and the model, so the sensor need not monitor the state between events. The times are more conservative than with event triggering.
  • The loop as a hybrid system. The closed loop flows between events and jumps at events, when x^\hat x takes the value of xx. So it is a hybrid automaton with one location, the guard ∥e∥≥σ∥x∥\|e\| \ge \sigma\|x\| and a reset of x^\hat x. Unlike a timed automaton, its flow is a general linear differential equation, so the analysis uses Lyapunov functions, not a finite quotient.
  • Output feedback and networks. With only an output measured, or with several sensors that trigger separately, the triggers and the proofs need more care; Heemels, Johansson and Tabuada (2012) survey the results.

Pitfalls

  • Threshold too large (line L5). For σ≥σˉ\sigma \ge \bar\sigma the Lyapunov argument fails, and the loop may diverge. σˉ\bar\sigma depends on QQ and on the norm; it is a sufficient bound, not the true limit.
  • The state at the origin (line L5). With a purely relative trigger, σ∥x∥=0\sigma\|x\| = 0 at the origin, so a measured state that is exactly zero, or noise near zero, makes the trigger fire at every check. Add an absolute part δ\delta in practice.
  • Disturbances and noise. The bound τ∗\tau^* is for the nominal plant. With disturbances, a relative trigger can give events that come arbitrarily close together; this is the event-separation problem studied by Borgers and Heemels (2014).
  • Delays. The theorem assumes that the update is instantaneous. Communication and computation delays add an error that the trigger does not see; the threshold must leave a margin for them.
  • Checking period (line L3). A trigger checked every Δt\Delta t can fire up to Δt\Delta t late, so ∥e∥\|e\| can exceed σ∥x∥\sigma\|x\| for a short time. Make Δt\Delta t small compared with τ∗\tau^*, or use the periodic event-triggered analysis.
  • Comparing with the wrong baseline. Compare the number of events with the longest period that keeps the periodic loop stable, not with τ∗\tau^*, which is a conservative bound.

Code

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.

ctlmat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and polynomial routines for the control pages.

Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
  right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
  [1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
  every entry is an int or a Fraction, so the result is exact. With float or
  complex entries they compute in floating point.
- transpose does not conjugate complex entries.

Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
  infinity norm at most 1/2 and the series stops when a term is below
  2^-60 times the sum. For matrices that are not far from normal the relative
  error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
  well conditioned polynomial come out with a relative error near 1e-12 (the
  tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
  grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
  fourfold root. For real coefficients the output is closed under
  conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
  1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
  be positive.

This file holds no algorithm of a control page.
"""

import cmath
import math
from fractions import Fraction

__all__ = [
    "zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
    "dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
    "trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
    "polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]


def _is_exact(v):
    return isinstance(v, (int, Fraction))


def _all_exact(*mats):
    for m in mats:
        for row in m:
            if isinstance(row, list):
                for v in row:
                    if not _is_exact(v):
                        return False
            elif not _is_exact(row):
                return False
    return True


def _to_fraction(a):
    return [[Fraction(v) for v in row] for row in a]


def _shape(a):
    return len(a), (len(a[0]) if a else 0)


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None), with int entries."""
    if m is None:
        m = n
    return [[0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix, with int entries."""
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]


def add(a, b):
    """Return a + b."""
    if _shape(a) != _shape(b):
        raise ValueError("add: shapes differ")
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def sub(a, b):
    """Return a - b."""
    if _shape(a) != _shape(b):
        raise ValueError("sub: shapes differ")
    return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def scale(c, a):
    """Return the scalar c times the matrix a."""
    return [[c * x for x in row] for row in a]


def mul(a, b):
    """Return the matrix product a b."""
    n, k = _shape(a)
    k2, m = _shape(b)
    if k != k2:
        raise ValueError("mul: inner dimensions differ")
    bt = list(zip(*b)) if b else []
    out = []
    for row in a:
        out_row = []
        for col in bt:
            s = 0
            for x, y in zip(row, col):
                s += x * y
            out_row.append(s)
        out.append(out_row)
    return out


def transpose(a):
    """Return the transpose of a (no complex conjugation)."""
    return [list(col) for col in zip(*a)]


def matvec(a, x):
    """Return the vector a x, for a flat list x."""
    if a and len(a[0]) != len(x):
        raise ValueError("matvec: dimensions differ")
    out = []
    for row in a:
        s = 0
        for v, w in zip(row, x):
            s += v * w
        out.append(s)
    return out


def dot(x, y):
    """Return sum of x_i y_i (no complex conjugation)."""
    if len(x) != len(y):
        raise ValueError("dot: lengths differ")
    s = 0
    for v, w in zip(x, y):
        s += v * w
    return s


def _sym_eigvals(s):
    """Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
    n = len(s)
    a = [list(map(float, row)) for row in s]
    for _ in range(100):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        diag = sum(a[i][i] ** 2 for i in range(n))
        if off <= 1e-30 * max(diag, 1e-300):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - sn * akq
                    a[k][q] = sn * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - sn * aqk
                    a[q][k] = sn * apk + c * aqk
    return [a[i][i] for i in range(n)]


def norm2(x):
    """Return the 2-norm.

    For a flat vector this is the Euclidean norm. For a matrix it is the
    induced 2-norm (the largest singular value), computed from the
    eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
    the same singular values. The result is a float.
    """
    if not x:
        return 0.0
    if not isinstance(x[0], list):
        return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
    if any(isinstance(v, complex) for row in x for v in row):
        re = [[complex(v).real for v in row] for row in x]
        im = [[complex(v).imag for v in row] for row in x]
        m = block([[re, scale(-1, im)], [im, re]])
    else:
        m = [[float(v) for v in row] for row in x]
    g = mul(transpose(m), m)
    lam = max(_sym_eigvals(g))
    return math.sqrt(max(lam, 0.0))


def block(rows):
    """Build a matrix from a list of rows of blocks.

    A block is a matrix, or the int 0 for a zero block whose size is taken
    from the other blocks in its block row and block column.
    """
    heights = []
    for r in rows:
        h = None
        for b in r:
            if isinstance(b, list):
                h = len(b)
                break
        if h is None:
            raise ValueError("block: a block row has no matrix block")
        heights.append(h)
    ncols = len(rows[0])
    widths = []
    for j in range(ncols):
        w = None
        for r in rows:
            if isinstance(r[j], list):
                w = len(r[j][0]) if r[j] else 0
                break
        if w is None:
            raise ValueError("block: a block column has no matrix block")
        widths.append(w)
    out = []
    for r, h in zip(rows, heights):
        if len(r) != ncols:
            raise ValueError("block: block rows have different lengths")
        for i in range(h):
            line = []
            for b, w in zip(r, widths):
                if isinstance(b, list):
                    if len(b) != h or (b and len(b[0]) != w):
                        raise ValueError("block: block sizes do not match")
                    line.extend(b[i])
                elif b == 0:
                    line.extend([0] * w)
                else:
                    raise ValueError("block: a scalar block must be 0")
            out.append(line)
    return out


def kron(a, b):
    """Return the Kronecker product of a and b."""
    n, m = _shape(a)
    p, q = _shape(b)
    return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]


def vec(a):
    """Stack the columns of a into one flat list."""
    n, m = _shape(a)
    return [a[i][j] for j in range(m) for i in range(n)]


def unvec(v, n, m=None):
    """Inverse of vec: return the n by m matrix whose stacked columns are v."""
    if m is None:
        m = len(v) // n
    if n * m != len(v):
        raise ValueError("unvec: length does not match the shape")
    return [[v[j * n + i] for j in range(m)] for i in range(n)]


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a flat vector or a matrix; the result has the same form. With int
    and Fraction entries the result is exact (Fraction). Raises ValueError
    if a is singular (an exactly zero pivot).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("solve: matrix is not square")
    is_vec = not (b and isinstance(b[0], list))
    rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: right side has the wrong length")
    if _all_exact(a, rhs):
        aa = _to_fraction(a)
        rhs = _to_fraction(rhs)
    else:
        aa = [list(row) for row in a]
    k = len(rhs[0]) if rhs else 0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            raise ValueError("solve: matrix is singular")
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            rhs[c], rhs[p] = rhs[p], rhs[c]
        piv = aa[c][c]
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            row_r, row_c = aa[r], aa[c]
            for j in range(c, n):
                row_r[j] -= f * row_c[j]
            rr, rc = rhs[r], rhs[c]
            for j in range(k):
                rr[j] -= f * rc[j]
    x = [[0] * k for _ in range(n)]
    for c in range(n - 1, -1, -1):
        for j in range(k):
            s = rhs[c][j]
            for t in range(c + 1, n):
                s -= aa[c][t] * x[t][j]
            x[c][j] = s / aa[c][c]
    return [row[0] for row in x] if is_vec else x


def inv(a):
    """Return the inverse of a (exact with int and Fraction entries)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of a by elimination with partial pivoting.

    With int and Fraction entries the result is an exact Fraction.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("det: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    d = Fraction(1) if _all_exact(a) else 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            return d * 0
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            d = -d
        piv = aa[c][c]
        d *= piv
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            for j in range(c, n):
                aa[r][j] -= f * aa[c][j]
    return d


def trace(a):
    """Return the sum of the diagonal entries of a."""
    s = 0
    for i in range(len(a)):
        s += a[i][i]
    return s


def charpoly(a):
    """Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.

    Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
    a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("charpoly: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    coeffs = [1]
    mk = zeros(n)
    for k in range(1, n + 1):
        mk = mul(aa, mk)
        c = coeffs[-1]
        for i in range(n):
            mk[i][i] += c
        am = mul(aa, mk)
        coeffs.append(-trace(am) / k)
    return coeffs


def polyval(p, x):
    """Evaluate the polynomial p at x by Horner's rule."""
    s = 0
    for c in p:
        s = s * x + c
    return s


def _strip(p):
    i = 0
    while i < len(p) - 1 and p[i] == 0:
        i += 1
    return list(p[i:]) if p else [0]


def polyadd(p, q):
    """Return p + q, with exactly zero leading coefficients removed."""
    n = max(len(p), len(q))
    pp = [0] * (n - len(p)) + list(p)
    qq = [0] * (n - len(q)) + list(q)
    return _strip([x + y for x, y in zip(pp, qq)])


def polymul(p, q):
    """Return the product p q."""
    if not p or not q:
        return [0]
    out = [0] * (len(p) + len(q) - 1)
    for i, x in enumerate(p):
        for j, y in enumerate(q):
            out[i + j] += x * y
    return _strip(out)


def polyder(p):
    """Return the derivative of p."""
    n = len(p) - 1
    if n <= 0:
        return [0]
    return _strip([c * (n - i) for i, c in enumerate(p[:-1])])


def polyroots(p, tol=1e-15, maxiter=1000):
    """Return the complex roots of p, sorted by real part, then imaginary part.

    Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
    when every relative correction is below tol, then a Newton polish of
    each root. For real coefficients the roots are made exactly real or
    exact conjugate pairs. See the module notes for the accuracy.
    """
    c = [complex(v) for v in p]
    while c and c[0] == 0:
        c.pop(0)
    if not c:
        raise ValueError("polyroots: zero polynomial")
    real_coeffs = all(v.imag == 0 for v in c)
    origin = 0
    while len(c) > 1 and c[-1] == 0:
        c.pop()
        origin += 1
    n = len(c) - 1
    a = [v / c[0] for v in c]
    if n == 0:
        z = []
    elif n == 1:
        z = [-a[1]]
    else:
        r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
        if r == 0:
            r = 1.0
        z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
        for _ in range(maxiter):
            worst = 0.0
            for i in range(n):
                den = 1.0 + 0j
                for j in range(n):
                    if j != i:
                        den *= z[i] - z[j]
                if den == 0:
                    z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
                    worst = 1.0
                    continue
                d = polyval(a, z[i]) / den
                z[i] -= d
                worst = max(worst, abs(d) / (1.0 + abs(z[i])))
            if worst < tol:
                break
        dp = polyder(a)
        for i in range(n):
            zi = z[i]
            fz = abs(polyval(a, zi))
            for _ in range(5):
                der = polyval(dp, zi)
                if der == 0 or fz == 0:
                    break
                step = polyval(a, zi) / der
                if abs(step) > 1e-6 * (1.0 + abs(zi)):
                    break
                znew = zi - step
                fnew = abs(polyval(a, znew))
                if fnew >= fz:
                    break
                zi, fz = znew, fnew
            z[i] = zi
    z = z + [0j] * origin
    if real_coeffs:
        thr = 1e-9
        upper = [v for v in z if v.imag > thr * (1 + abs(v))]
        lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
        reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
        # A cluster of close roots can leave more roots above the real axis
        # than below it (or the other way). The extra roots nearest to the
        # axis are then taken as real, so the output is closed under
        # conjugation.
        if len(upper) < len(lower):
            upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
        upper.sort(key=lambda v: v.imag)
        extra = len(upper) - len(lower)
        reals += [complex(v.real, 0.0) for v in upper[:extra]]
        upper = upper[extra:]
        out = list(reals)
        rest = list(lower)
        for u in upper:
            w = min(rest, key=lambda v: abs(v - u.conjugate()))
            rest.remove(w)
            re = (u.real + w.real) / 2
            im = (u.imag - w.imag) / 2
            out.append(complex(re, im))
            out.append(complex(re, -im))
        z = out
    return sorted(z, key=lambda v: (v.real, v.imag))


def _norm_inf(a):
    return max((sum(abs(v) for v in row) for row in a), default=0.0)


def expm(a):
    """Return e^A in floating point by scaling and squaring with a Taylor series.

    A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
    series of the scaled matrix is summed until a term is below 2^-60 of the
    sum, and the result is squared s times. Entries of the result are float
    (complex if A has complex entries).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("expm: matrix is not square")
    cplx = any(isinstance(v, complex) for row in a for v in row)
    conv = complex if cplx else float
    x = [[conv(v) for v in row] for row in a]
    nrm = _norm_inf(x)
    s = 0
    while nrm > 0.5:
        nrm /= 2.0
        s += 1
    x = scale(conv(2.0 ** -s), x)
    e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
    term = [row[:] for row in e]
    for k in range(1, 60):
        term = scale(1.0 / k, mul(term, x))
        e = add(e, term)
        tn = _norm_inf(term)
        if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
            break
    for _ in range(s):
        e = mul(e, e)
    return e


def mat_power(a, k):
    """Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
    n, m = _shape(a)
    if n != m:
        raise ValueError("mat_power: matrix is not square")
    if k < 0:
        a = inv(a)
        k = -k
    result = eye(n)
    base = [list(row) for row in a]
    while k:
        if k & 1:
            result = mul(result, base)
        k >>= 1
        if k:
            base = mul(base, base)
    return result


def is_symmetric(a, tol=0):
    """Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
    n, m = _shape(a)
    if n != m:
        return False
    return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))


def is_pos_def(a, margin=0):
    """Return True if a is symmetric and a - margin I is positive definite.

    With int and Fraction entries (and an exact margin) the test is exact:
    every leading principal minor of a - margin I must be positive
    (Sylvester's criterion), computed in Fraction. With float entries the
    matrix must be symmetric within 1e-12 times its largest entry, and the
    Cholesky factorization of a - margin I must have positive pivots.
    Complex entries are not accepted.
    """
    n, m = _shape(a)
    if n != m:
        return False
    if any(isinstance(v, complex) for row in a for v in row):
        raise ValueError("is_pos_def: complex entries are not accepted")
    if _all_exact(a) and _is_exact(margin):
        b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
        if not is_symmetric(b):
            return False
        return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
    b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
    big = max((abs(float(v)) for row in a for v in row), default=0.0)
    if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
        return False
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
        if not d > 0.0:
            return False
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return True


def _self_test():
    a = [[0, 1], [-2, -3]]
    assert charpoly(a) == [1, 3, 2]
    assert det(a) == 2
    assert mul(inv(a), a) == eye(2)
    assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
    r = polyroots([1, 3, 2])
    assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
    t = 0.7
    e = expm([[0.0, t], [-t, 0.0]])
    want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
    assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
    assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
    assert not is_pos_def([[1, 2], [2, 1]])
    assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
    return True


if __name__ == "__main__":
    _self_test()
ctlsim.py 120 lines
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Fixed step simulation for the control pages.

Conventions:
- A continuous-time system is a function f(t, x, u) that returns x' as a
  flat list. x is a flat list. u is whatever the control returns (a flat
  list, a scalar, or None when there is no control).
- A discrete-time system is a function F(k, x, u) that returns x_(k+1).
- The integrator is the classical 4th order Runge-Kutta method with a fixed
  step dt. The input is held constant over each step.
- Time t_k = t0 + k dt is computed by multiplication, not by summation.
- The number of steps round((t1 - t0) / dt) and the hold ratio
  round(hold / dt) must match the real ratios within 1e-9 (relative), or
  ValueError is raised.

This file holds no controller or observer of a control page.
"""

__all__ = ["rk4_step", "simulate", "simulate_discrete", "lti"]


def _axpy(a, x, y):
    return [yi + a * xi for xi, yi in zip(x, y)]


def rk4_step(f, t, x, u, dt):
    """Return x(t + dt) after one RK4 step of x' = f(t, x, u), u held constant."""
    k1 = f(t, x, u)
    k2 = f(t + dt / 2, _axpy(dt / 2, k1, x), u)
    k3 = f(t + dt / 2, _axpy(dt / 2, k2, x), u)
    k4 = f(t + dt, _axpy(dt, k3, x), u)
    return [xi + dt / 6 * (a + 2 * b + 2 * c + d) for xi, a, b, c, d in zip(x, k1, k2, k3, k4)]


def _ratio(num, den, what):
    r = round(num / den)
    if abs(r * den - num) > 1e-9 * max(abs(num), abs(den)):
        raise ValueError(what + " is not an integer multiple of dt")
    return r


def simulate(f, x0, t0, t1, dt, control=None, hold=None):
    """Simulate x' = f(t, x, u) from x(t0) = x0 to t1 with RK4 and step dt.

    control(t, x) gives the input. It is called at each sampling instant
    t0 + j hold, and its value is held (zero-order hold) until the next
    instant. hold must be an integer multiple of dt; hold = None means
    hold = dt. With control = None the input is None.

    Returns (ts, xs, us): ts has N + 1 times, xs the N + 1 states, and us the
    N inputs, where us[k] acts on [ts[k], ts[k + 1]].
    """
    if dt <= 0:
        raise ValueError("dt must be positive")
    n_steps = _ratio(t1 - t0, dt, "t1 - t0")
    if n_steps < 0:
        raise ValueError("t1 is before t0")
    r = 1 if hold is None else _ratio(hold, dt, "hold")
    if r < 1:
        raise ValueError("hold must be at least dt")
    x = list(x0)
    ts = [t0]
    xs = [list(x)]
    us = []
    u = None
    for k in range(n_steps):
        t = t0 + k * dt
        if control is not None and k % r == 0:
            u = control(t, list(x))
        x = rk4_step(f, t, x, u, dt)
        ts.append(t0 + (k + 1) * dt)
        xs.append(x)
        us.append(u)
    return ts, xs, us


def simulate_discrete(F, x0, N, control=None):
    """Run x_(k+1) = F(k, x_k, u_k) for k = 0, ..., N - 1.

    u_k = control(k, x_k), or None if control is None. Returns (xs, us) with
    N + 1 states and N inputs. Exact if F and control are exact.
    """
    x = list(x0)
    xs = [list(x)]
    us = []
    for k in range(N):
        u = control(k, list(x)) if control is not None else None
        x = list(F(k, x, u))
        xs.append(x)
        us.append(u)
    return xs, us


def lti(A, B=None):
    """Return f(t, x, u) = A x + B u for the system x' = A x + B u.

    u may be a flat list, a scalar (one input) or None (zero input). B may
    be None for a system with no input.
    """
    def f(t, x, u):
        dx = [sum(a * xi for a, xi in zip(row, x)) for row in A]
        if B is None or u is None:
            return dx
        uu = u if isinstance(u, (list, tuple)) else [u]
        return [d + sum(b * ui for b, ui in zip(row, uu)) for d, row in zip(dx, B)]
    return f


def _self_test():
    import math
    f = lti([[-1.0]])
    _, xs, _ = simulate(f, [1.0], 0.0, 1.0, 0.01)
    assert abs(xs[-1][0] - math.exp(-1.0)) < 1e-9
    return True


if __name__ == "__main__":
    _self_test()
event_triggered_control.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/event-triggered-control/. The authors are listed in prov/66J2N7.jsonl.

"""Event-triggered state feedback for x' = A x + B u with a relative threshold.

The controller holds u = -K x(t_k) until the next event. With the error
e(t) = x(t_k) - x(t), the next event is the first time t > t_k with
||e(t)|| >= sigma ||x(t)|| (Euclidean norm), as in Tabuada (2007).

lyapunov(A_cl, Q) solves A_cl' P + P A_cl = -Q. For a Hurwitz A_cl = A - B K,
and with V = x' P x, the trigger gives
dV/dt <= -(lambda_min(Q) - 2 sigma ||P B K||) ||x||^2, so every
sigma < lambda_min(Q) / (2 ||P B K||) gives exponential stability
(sigma_max below). min_inter_event_time gives a lower bound tau* > 0 on the
time between two events (the derivation is on the page).

The simulation uses RK4 from ctlsim with a fixed step dt and tests the
trigger at the end of each step, so an event can be up to dt late.
"""

import math

from ctlmat import charpoly, kron, eye, mul, norm2, polyroots, solve, sub, transpose, unvec, vec
from ctlsim import lti, rk4_step

__all__ = ["lyapunov", "sigma_max", "min_inter_event_time", "simulate_etc"]


def lyapunov(acl, q):
    """Solve A' P + P A = -Q by the Kronecker form (I kron A' + A' kron I) vec(P) = -vec(Q)."""
    n = len(acl)
    at = transpose(acl)
    big = [[x + y for x, y in zip(r1, r2)] for r1, r2 in zip(kron(eye(n), at), kron(at, eye(n)))]
    return unvec(solve(big, [-v for v in vec(q)]), n)


def sigma_max(a, b, k, q):
    """Return (sigma_bar, P): sigma_bar = lambda_min(Q) / (2 ||P B K||_2)."""
    bk = mul(b, k)
    acl = sub(a, bk)
    p = lyapunov(acl, q)
    lam_min = min(z.real for z in polyroots(charpoly(q)))
    return lam_min / (2 * norm2([[float(v) for v in row] for row in mul(p, bk)])), p


def min_inter_event_time(a, b, k, sigma):
    """Lower bound tau* on the inter-event times for the trigger ||e|| >= sigma ||x||.

    With alpha = ||A - B K||_2 and beta = ||B K||_2, y = ||e|| / ||x|| obeys
    y' <= (alpha + beta y)(1 + y) and y(t_k) = 0, so y needs at least
    tau* = ln(alpha (1 + sigma) / (alpha + beta sigma)) / (alpha - beta) to reach sigma
    (sigma / (alpha (1 + sigma)) when alpha = beta).
    """
    bk = mul(b, k)
    al = norm2([[float(v) for v in row] for row in sub(a, bk)])
    be = norm2([[float(v) for v in row] for row in bk])
    if abs(al - be) <= 1e-12 * max(al, be):
        return sigma / (al * (1 + sigma))
    return math.log(al * (1 + sigma) / (al + be * sigma)) / (al - be)


def simulate_etc(a, b, k, x0, sigma, t_end, dt):
    """Simulate the event-triggered loop. Returns (event_times, ts, xs).

    The first event is at t = 0. After each RK4 step the trigger is tested;
    on an event the held state x_hat becomes x(t).
    """
    f = lti(a, b)
    x = [float(v) for v in x0]
    xhat = list(x)  # @line L1
    u = [-sum(kij * xj for kij, xj in zip(row, xhat)) for row in k]  # @line L2
    events, ts, xs = [0.0], [0.0], [list(x)]
    steps = round(t_end / dt)
    for i in range(steps):
        x = rk4_step(f, i * dt, x, u, dt)  # @line L3
        t = (i + 1) * dt
        e = math.sqrt(sum((p - q) ** 2 for p, q in zip(xhat, x)))  # @line L4
        if e >= sigma * math.sqrt(sum(v * v for v in x)):  # @line L5
            xhat = list(x)  # @line L6
            u = [-sum(kij * xj for kij, xj in zip(row, xhat)) for row in k]  # @line L7
            events.append(t)
        ts.append(t)
        xs.append(x)
    return events, ts, xs
test_event_triggered_control.py 87 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/event-triggered-control/. The authors are listed in prov/66J2N7.jsonl.

import math
import random
from fractions import Fraction

from ctlmat import add, mul, sub, transpose
from event_triggered_control import lyapunov, min_inter_event_time, sigma_max, simulate_etc

# The example of the page: an unstable plant and u = x_1 - 4 x_2.
A = [[0, 1], [-2, 3]]
B = [[0], [1]]
K = [[-1, 4]]
Q = [[1, 0], [0, 1]]


def test_lyapunov_solution_is_exact():
    p = lyapunov(sub(A, mul(B, K)), Q)
    assert p == [[Fraction(3, 2), Fraction(1, 2)], [Fraction(1, 2), Fraction(1)]]
    acl = sub(A, mul(B, K))
    assert add(mul(transpose(acl), p), mul(p, acl)) == [[-1, 0], [0, -1]]
    # The check value of the area: A = [[0, 1], [-2, -3]] gives P = [[5/4, 1/4], [1/4, 1/4]].
    assert lyapunov([[0, 1], [-2, -3]], Q) == [[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]]


def test_threshold_and_bound_of_the_example():
    sb, _ = sigma_max(A, B, K, Q)
    assert abs(sb - 1 / (2 * math.sqrt(21.25))) < 1e-12
    tau = min_inter_event_time(A, B, K, 0.05)
    al, be = (1 + math.sqrt(5)) / 2, math.sqrt(17)
    assert abs(tau - math.log(al * 1.05 / (al + 0.05 * be)) / (al - be)) < 1e-12
    assert abs(tau - 0.028396) < 1e-6


def test_equal_norms_branch():
    # A - B K = -I and B K = I: alpha = beta = 1, so tau* = sigma / (1 + sigma).
    a = [[0.0, 0.0], [0.0, 0.0]]
    b = [[1.0, 0.0], [0.0, 1.0]]
    k = [[1.0, 0.0], [0.0, 1.0]]
    assert abs(min_inter_event_time(a, b, k, 0.2) - 0.2 / 1.2) < 1e-12


def test_events_respect_the_bound_and_state_converges():
    tau = min_inter_event_time(A, B, K, 0.05)
    events, ts, xs = simulate_etc(A, B, K, [1.0, 0.0], 0.05, 10.0, 0.001)
    gaps = [b - a for a, b in zip(events, events[1:])]
    assert len(events) == 218
    assert min(gaps) >= tau - 0.001
    assert math.hypot(*xs[-1]) < 0.004
    # Fewer updates than periodic sampling with the period tau*.
    assert len(events) < 10.0 / tau


def test_bound_on_random_stable_loops():
    rng = random.Random(5)
    for _ in range(6):
        # A - B K = [[a11, 1], [-c1, -c2]] with a11 <= 0.2 and c1, c2 in [1, 3]:
        # its trace is negative and its determinant c1 - a11 c2 >= 0.4, so it is Hurwitz.
        a = [[rng.uniform(-1, 0.2), 1.0], [rng.uniform(-2, 2), rng.uniform(-1, 1)]]
        k = [[a[1][0] + rng.uniform(1, 3), a[1][1] + rng.uniform(1, 3)]]
        acl = sub(a, mul(B, k))
        assert acl[0][0] + acl[1][1] < 0 and acl[0][0] * acl[1][1] - acl[0][1] * acl[1][0] > 0
        sb, p = sigma_max(a, B, k, Q)
        assert p[0][0] > 0 and p[0][0] * p[1][1] - p[0][1] * p[1][0] > 0
        sigma = 0.8 * sb
        tau = min_inter_event_time(a, B, k, sigma)
        x0 = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
        events, _, xs = simulate_etc(a, B, k, x0, sigma, 5.0, 0.001)
        gaps = [q - p for p, q in zip(events, events[1:])]
        assert min(gaps) >= tau - 0.001
        assert math.hypot(*xs[-1]) < math.hypot(*x0)


def test_error_stays_below_threshold_between_events():
    """Between events ||x_hat - x|| < sigma ||x|| at every step, up to the step delay."""
    sigma = 0.05
    events, ts, xs = simulate_etc(A, B, K, [1.0, 0.0], sigma, 3.0, 0.001)
    held = None
    j = 0
    for t, x in zip(ts, xs):
        if j < len(events) and abs(t - events[j]) < 1e-9:
            held = x
            j += 1
            continue
        e = math.hypot(held[0] - x[0], held[1] - x[1])
        assert e < sigma * math.hypot(*x)

Exercises

  1. For the example, compute σˉ\bar\sigma with Q=2IQ = 2I and with Q=diag(1,4)Q = \mathrm{diag}(1, 4). How does the choice of QQ change the allowed threshold?
  2. Take the scalar plant x′=ux' = u with u=−kxu = -kx and k>0k > 0. Show that every gap between two events is exactly σ/(k(1+σ))\sigma / (k(1 + \sigma)), so the bound τ∗\tau^* is reached here. (Hint: between events, x(t)=x^(1−k(t−tk))x(t) = \hat x (1 - k(t - t_k)).)
  3. Derive τ∗\tau^* for the case α=β\alpha = \beta by solving z′=α(1+z)2z' = \alpha(1 + z)^2.
  4. Replace the trigger by ∥e∥≥δ\|e\| \ge \delta with a fixed δ>0\delta > 0. Show that the state enters a ball whose radius is proportional to δ\delta, and give a lower bound on the time between events.
  5. Explain why a periodic loop with the period τ∗\tau^* is stable, using the fact that ∥e∥≤σ∥x∥\|e\| \le \sigma\|x\| holds on every interval of length at most τ∗\tau^* after an update.
Proof: The relative trigger makes the linear loop exponentially stable and keeps the inter-event times above tau*full

Setting. The plant is x′=Ax+Bux' = Ax + Bu with x∈Rnx \in \mathbb{R}^n, and the controller applies u(t)=−Kx(tk)u(t) = -K x(t_k) for t∈[tk,tk+1)t \in [t_k, t_{k+1}). The closed-loop matrix Acl=A−BKA_{cl} = A - BK is Hurwitz. The error is e(t)=x(tk)−x(t)e(t) = x(t_k) - x(t), and the next event is

tk+1=inf⁡{t>tk:∥e(t)∥≥σ∥x(t)∥},t_{k+1} = \inf\{t > t_k : \|e(t)\| \ge \sigma \|x(t)\|\},

with ∥⋅∥\|\cdot\| the Euclidean norm and the induced matrix 2-norm. Q≻0Q \succ 0, and P≻0P \succ 0 solves AclTP+PAcl=−QA_{cl}^T P + P A_{cl} = -Q. Let α=∥Acl∥\alpha = \|A_{cl}\| and β=∥BK∥\beta = \|BK\|. The template lines L1 to L7 implement this trigger. If x(tk)=0x(t_k) = 0, then u=0u = 0 and xx stays at 00, so no more events are needed; the statements below concern x(tk)≠0x(t_k) \ne 0.

Lemma 1 (the closed loop with the error). On [tk,tk+1)[t_k, t_{k+1}), x′=Aclx−BKex' = A_{cl} x - BK e and e′=−x′e' = -x'.

Proof. x′=Ax−BKx(tk)=Ax−BK(x+e)x' = Ax - BK x(t_k) = Ax - BK(x + e), and x(tk)x(t_k) is constant on the interval. ■\blacksquare

Lemma 2 (Lyapunov equation). For a Hurwitz AclA_{cl} and Q≻0Q \succ 0, the equation AclTP+PAcl=−QA_{cl}^T P + P A_{cl} = -Q has one solution, and it is positive definite. The function lyapunov solves its Kronecker form (I⊗AclT+AclT⊗I)vec⁡(P)=−vec⁡(Q)(I \otimes A_{cl}^T + A_{cl}^T \otimes I)\operatorname{vec}(P) = -\operatorname{vec}(Q).

Proof. The eigenvalues of the Kronecker matrix are λi+λj\lambda_i + \lambda_j for eigenvalues λi,λj\lambda_i, \lambda_j of AclA_{cl}; their real parts are negative, so the matrix is invertible and the solution is unique. The integral P=∫0∞eAclTtQeAclt dtP = \int_0^\infty e^{A_{cl}^T t} Q e^{A_{cl} t}\, dt converges, solves the equation, and has xTPx>0x^T P x > 0 for x≠0x \ne 0. The Kronecker form follows from vec⁡(MXN)=(NT⊗M)vec⁡(X)\operatorname{vec}(MXN) = (N^T \otimes M)\operatorname{vec}(X). ■\blacksquare

Theorem 1 (exponential stability). If σ<σˉ=λmin⁡(Q)/(2∥PBK∥)\sigma < \bar\sigma = \lambda_{\min}(Q) / (2\|PBK\|), then with c=λmin⁡(Q)−2σ∥PBK∥>0c = \lambda_{\min}(Q) - 2\sigma\|PBK\| > 0,

∥x(t)∥≤λmax⁡(P)/λmin⁡(P)  e−ct/(2λmax⁡(P))∥x(0)∥for all t≥0,\|x(t)\| \le \sqrt{\lambda_{\max}(P) / \lambda_{\min}(P)}\; e^{-c t / (2\lambda_{\max}(P))} \|x(0)\| \quad \text{for all } t \ge 0,

so the origin is globally exponentially stable.

Proof. By the definition of tk+1t_{k+1}, ∥e(t)∥≤σ∥x(t)∥\|e(t)\| \le \sigma \|x(t)\| on [tk,tk+1][t_k, t_{k+1}]. With V=xTPxV = x^T P x and Lemma 1,

V′=xT(AclTP+PAcl)x−2xTPBKe≤−λmin⁡(Q)∥x∥2+2∥PBK∥ ∥x∥ ∥e∥≤−c∥x∥2≤−cλmax⁡(P)V.V' = x^T (A_{cl}^T P + P A_{cl}) x - 2 x^T P B K e \le -\lambda_{\min}(Q)\|x\|^2 + 2\|PBK\|\,\|x\|\,\|e\| \le -c\|x\|^2 \le -\frac{c}{\lambda_{\max}(P)} V.

VV is continuous across events, because xx is. So V(t)≤e−ct/λmax⁡(P)V(0)V(t) \le e^{-ct/\lambda_{\max}(P)} V(0) on every interval that the event times cover, and λmin⁡(P)∥x∥2≤V≤λmax⁡(P)∥x∥2\lambda_{\min}(P)\|x\|^2 \le V \le \lambda_{\max}(P)\|x\|^2 gives the bound. Theorem 2 shows that the event times do not accumulate, so they cover [0,∞)[0, \infty). ■\blacksquare

Theorem 2 (inter-event times). For every kk, tk+1−tk≥τ∗t_{k+1} - t_k \ge \tau^*, where

τ∗=1α−βln⁡α(1+σ)α+βσ(α≠β),τ∗=σα(1+σ)(α=β).\tau^* = \frac{1}{\alpha - \beta} \ln\frac{\alpha(1 + \sigma)}{\alpha + \beta\sigma} \quad (\alpha \ne \beta), \qquad \tau^* = \frac{\sigma}{\alpha(1 + \sigma)} \quad (\alpha = \beta).

Proof. Let y=∥e∥/∥x∥y = \|e\| / \|x\| on [tk,tk+1)[t_k, t_{k+1}). Here x≠0x \ne 0: yy is continuous where x≠0x \ne 0, y(tk)=0y(t_k) = 0, and yy would tend to infinity as x→0x \to 0, so the event comes first. Wherever e≠0e \ne 0, ∥e∥′≤∥e′∥=∥x′∥\|e\|' \le \|e'\| = \|x'\| and ∥x∥′≥−∥x′∥\|x\|' \ge -\|x'\|, so

y′≤∥x′∥∥x∥(1+y)≤α∥x∥+β∥e∥∥x∥(1+y)=(α+βy)(1+y),y' \le \frac{\|x'\|}{\|x\|}(1 + y) \le \frac{\alpha\|x\| + \beta\|e\|}{\|x\|}(1 + y) = (\alpha + \beta y)(1 + y),

and the same bound holds for the upper right Dini derivative where e=0e = 0. Let zz solve z′=(α+βz)(1+z)z' = (\alpha + \beta z)(1 + z), z(0)=0z(0) = 0. By the comparison lemma, y(tk+s)≤z(s)y(t_k + s) \le z(s). Separating the variables, with 1(α+βz)(1+z)=1α−β(11+z−βα+βz)\frac{1}{(\alpha + \beta z)(1 + z)} = \frac{1}{\alpha - \beta}\left(\frac{1}{1 + z} - \frac{\beta}{\alpha + \beta z}\right), gives the time for zz to go from 00 to σ\sigma:

s(σ)=1α−β[ln⁡(1+z)−ln⁡(α+βz)]0σ=1α−βln⁡α(1+σ)α+βσ.s(\sigma) = \frac{1}{\alpha - \beta}\Big[\ln(1 + z) - \ln(\alpha + \beta z)\Big]_0^\sigma = \frac{1}{\alpha - \beta}\ln\frac{\alpha(1 + \sigma)}{\alpha + \beta\sigma}.

For α=β\alpha = \beta, z′=α(1+z)2z' = \alpha(1 + z)^2 gives s=1α(1−11+σ)=σα(1+σ)s = \frac{1}{\alpha}\left(1 - \frac{1}{1 + \sigma}\right) = \frac{\sigma}{\alpha(1 + \sigma)}. The event needs y=σy = \sigma, so it cannot come before zz reaches σ\sigma, that is before tk+τ∗t_k + \tau^*. ■\blacksquare

Termination. By Theorem 2, a time interval of length TT has at most ⌈T/τ∗⌉+1\lceil T / \tau^* \rceil + 1 events, so there is no Zeno behavior and the loop runs for all time. The simulation of lines L3 to L7 takes T/ΔtT / \Delta t steps of the Runge-Kutta method.

What the simulation checks. The simulation tests the trigger only at the end of each step of length Δt\Delta t, so an event can be up to Δt\Delta t late, and the error can exceed σ∥x∥\sigma\|x\| by a term of order Δt\Delta t just before an event. The theorems are about the exact trigger. The tests check that the simulated gaps are at least τ∗−Δt\tau^* - \Delta t, that the error stays below σ∥x∥\sigma\|x\| at the steps between events, and that the state goes to zero on random stable loops with σ=0.8σˉ\sigma = 0.8\bar\sigma.

References

  1. P. Tabuada, Event-triggered real-time scheduling of stabilizing control tasks, IEEE Transactions on Automatic Control 52(9), 2007, pages 1680 to 1685, the relative trigger from an ISS Lyapunov function, asymptotic stability, and the positive lower bound on the inter-event times
  2. K. J. Åström and B. M. Bernhardsson, Comparison of Riemann and Lebesgue sampling for first order stochastic systems, IEEE Conference on Decision and Control, 2002, pages 2011 to 2016, event-based (Lebesgue) sampling against periodic (Riemann) sampling for a first order system
  3. W. P. M. H. Heemels, K. H. Johansson and P. Tabuada, An introduction to event-triggered and self-triggered control, IEEE Conference on Decision and Control, 2012, pages 3270 to 3285, the tutorial overview of triggers, inter-event times, periodic event-triggered and self-triggered control
  4. A. Girard, Dynamic triggering mechanisms for event-triggered control, IEEE Transactions on Automatic Control 60(7), 2015, pages 1992 to 1997, the dynamic trigger with an internal variable and its larger inter-event times
  5. D. P. Borgers and W. P. M. H. Heemels, Event-separation properties of event-triggered control systems, IEEE Transactions on Automatic Control 59(10), 2014, pages 2644 to 2656, which triggers keep a positive minimum time between events when disturbances act

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 proofH2 full proof
  • correctness: no review record reviews/66J2N7/proof-correctness.yaml
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
  • three classic examples