Algorithm Search⌘K

Algorithmcore

Deadbeat control

Also called deadbeat controller.

A discrete-time state feedback that places all closed-loop poles at the origin, so the state reaches zero in at most n steps.

Time
O(N n^2 (n + m)) worst
Space
O(n (n + m)) extra
Where
N = the number of steps to reach zero; m = the number of inputs; n = the number of states
Properties
deterministicexactofflineiterative
Origin
John O'Reilly, 1981

Deadbeat control is a state feedback uk=−Kxku_k = -K x_k for a discrete-time system xk+1=Axk+Bukx_{k+1} = A x_k + B u_k that makes A−BKA - BK nilpotent: (A−BK)N=0(A - BK)^N = 0 for some N≤nN \le n. All closed-loop eigenvalues are then at z=0z = 0, and every initial state reaches the origin exactly after NN steps and stays there. The algorithm on this page finds a gain with the least possible NN, for any number of inputs. With one input, it is Ackermann's formula with the polynomial znz^n. Deadbeat control has no continuous-time counterpart: no finite gain brings a continuous linear system to rest in finite time. The price is large inputs, especially for short sampling periods.

In plain words

A computer controls a machine at fixed clock ticks. A deadbeat controller is a rule that brings the machine exactly to rest after a fixed number of ticks, from any starting point. It is not a slow approach that gets closer and closer: after the last tick, the error is zero. The method builds the rule backwards. First it finds the states that can be stopped in one tick, then those that can be moved into that set in one tick, and so on, until every state is covered. Then it picks, for each kind of state, the push that moves it one set closer to rest. The pushes can be very large, and the motion between ticks is not controlled.

The problem

Input: A∈Rn×nA \in \mathbb{R}^{n \times n} and B∈Rn×mB \in \mathbb{R}^{n \times m} for the system xk+1=Axk+Bukx_{k+1} = A x_k + B u_k. Output: K∈Rm×nK \in \mathbb{R}^{m \times n} and the least NN with (A−BK)N=0(A - BK)^N = 0.

A deadbeat gain exists if and only if every uncontrollable eigenvalue of AA is 00; this holds in particular when (A,B)(A, B) is controllable. By the pole placement theorem, the eigenvalues of the uncontrollable part do not move under feedback, so they must already be 0. With one input and (A,b)(A, b) controllable, N=nN = n and KK is unique. With several inputs, KK is not unique and NN can be smaller than nn.

The least NN is the same for feedback and for open-loop input sequences: it is the least jj such that every state can be brought to 0 in jj steps by some inputs, that is, the least jj with range⁡Aj⊆range⁡[B,AB,…,Aj−1B]\operatorname{range} A^j \subseteq \operatorname{range} [B, AB, \dots, A^{j-1} B]. If AA is invertible, this is the controllability index, the least jj with rank⁡[B,AB,…,Aj−1B]=n\operatorname{rank} [B, AB, \dots, A^{j-1} B] = n.

The algorithm

  1. DEADBEAT(A, B)
  2. 1V ← [] (basis of S_0 = {0}); C ← []; N ← 0; while |V| < n: N ← N + 1
  3. 2S_N ← {x : A x = V a + B c for some a, c} ▷ null space of [A, -V, -B]
  4. 3for each vector x of S_N that is independent of V: append x to V, its c to C
  5. 4if no vector was appended: fail ▷ an uncontrollable eigenvalue is not 0
  6. 5return K = C V^(-1), N ▷ K v_i = c_i for every basis vector

The subspace SjS_j is the set of states that some input sequence brings to 0 in jj steps: x∈Sjx \in S_j exactly when one input u=−cu = -c moves xx to Ax−Bc∈Sj−1Ax - Bc \in S_{j-1}. Line L2 computes SjS_j as the projection of a null space, and the null vector also gives the input cc. Line L3 extends the basis, so the basis vectors are ordered by the first SjS_j that contains them. Line L5 defines KK by its values on this basis: for a basis vector vv of SjS_j, (A−BK)v=Av−Bc(A - BK) v = Av - Bc lies in Sj−1S_{j-1}. So A−BKA - BK maps SjS_j into Sj−1S_{j-1}, and NN steps map SN=RnS_N = \mathbb{R}^n to S0={0}S_0 = \{0\}.

Example

Double integrator, sampled. The zero-order hold model of a unit mass with period hh is A=[1h01]A = \begin{bmatrix} 1 & h \\ 0 & 1 \end{bmatrix}, B=[h2/2h]B = \begin{bmatrix} h^2/2 \\ h \end{bmatrix}. The algorithm gives N=2N = 2 and

K=[1/h23/(2h)],A−BK=[1/2h/4−1/h−1/2],(A−BK)2=0.K = \begin{bmatrix} 1/h^2 & 3/(2h) \end{bmatrix}, \qquad A - BK = \begin{bmatrix} 1/2 & h/4 \\ -1/h & -1/2 \end{bmatrix}, \qquad (A - BK)^2 = 0.

From x0=(1,0)x_0 = (1, 0), the inputs are u0=−1/h2u_0 = -1/h^2 and u1=1/h2u_1 = 1/h^2, and x1=(1/2,−1/h)x_1 = (1/2, -1/h), x2=0x_2 = 0. With h=0.1h = 0.1 the inputs are ∓100\mp 100 and the peak velocity is 10, for a move of length 1. Halving hh makes the inputs four times larger. This is the price of deadbeat control.

Two inputs, fewer steps. For

A=[110011001],B=[001001],A = \begin{bmatrix} 1 & 1 & 0 \\ 0 & 1 & 1 \\ 0 & 0 & 1 \end{bmatrix}, \qquad B = \begin{bmatrix} 0 & 0 \\ 1 & 0 \\ 0 & 1 \end{bmatrix},

rank⁡[B,AB]=3\operatorname{rank}[B, AB] = 3, so the controllability index is 2. The algorithm returns N=2N = 2 and K=[121001]K = \begin{bmatrix} 1 & 2 & 1 \\ 0 & 0 & 1 \end{bmatrix}, with A−BK=[110−1−10000]A - BK = \begin{bmatrix} 1 & 1 & 0 \\ -1 & -1 & 0 \\ 0 & 0 & 0 \end{bmatrix}, whose square is 0. Any single input of this system needs three steps.

Singular AA. For A=[010000000]A = \begin{bmatrix} 0 & 1 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix} and B=e2B = e_2, the third state is not controllable, but its eigenvalue is 0, and AA maps it to 0 in one step. The algorithm returns K=0K = 0 and N=2N = 2: the open loop is already deadbeat.

Correctness

The full proof is in proofs/correctness.md. Its steps:

  • The subspaces grow. S0⊆S1⊆⋯S_0 \subseteq S_1 \subseteq \cdots, by induction on jj. If Sj=Sj−1S_j = S_{j-1} for some jj, then Si=SjS_i = S_j for all i≥ji \ge j, so the loop ends after at most nn rounds, by success or by line L4.
  • Meaning of SjS_j. SjS_j is exactly the set of states that some input sequence brings to 0 in jj steps.
  • Nilpotency. For the gain of line L5, (A−BK)Sj⊆Sj−1(A - BK) S_j \subseteq S_{j-1}, so (A−BK)N=0(A - BK)^N = 0.
  • Minimality. If (A−BK′)N′=0(A - BK')^{N'} = 0 for some gain K′K', then the feedback inputs bring every state to 0 in N′N' steps, so SN′=RnS_{N'} = \mathbb{R}^n and N′≥NN' \ge N.
  • Failure. If the loop stops with Sj=Sj−1≠RnS_j = S_{j-1} \ne \mathbb{R}^n, no input sequence brings every state to 0, so no gain is deadbeat. This happens exactly when an uncontrollable eigenvalue is not 0.
Proof: The subspace recursion gives a deadbeat gain with the least number of steps, or proves that none existsfull

Let A∈Rn×nA \in \mathbb{R}^{n \times n} and B∈Rn×mB \in \mathbb{R}^{n \times m}, and write B=range⁡B\mathcal{B} = \operatorname{range} B. Define S0={0}S_0 = \{0\} and

Sj={x∈Rn:Ax∈Sj−1+B},j≥1.S_j = \{x \in \mathbb{R}^n : Ax \in S_{j-1} + \mathcal{B}\}, \qquad j \ge 1.

Each SjS_j is a subspace, because it is the preimage under AA of the subspace Sj−1+BS_{j-1} + \mathcal{B}. Line L2 computes SjS_j: a null vector (x,a,c)(x, a, c) of [A,−V,−B][A, -V, -B] satisfies Ax=Va+BcAx = Va + Bc, where the columns of VV span Sj−1S_{j-1}, and the xx-parts of the null vectors span SjS_j, because the projection of the null space onto the first nn coordinates is linear and onto SjS_j.

Lemma 1: the subspaces grow, and stop growing for good

Sj−1⊆SjS_{j-1} \subseteq S_j for all j≥1j \ge 1. If Sj=Sj−1S_j = S_{j-1} for some jj, then Si=Sj−1S_i = S_{j-1} for all i≥j−1i \ge j - 1.

Proof. S0={0}⊆S1S_0 = \{0\} \subseteq S_1. If Sj−2⊆Sj−1S_{j-2} \subseteq S_{j-1}, then for x∈Sj−1x \in S_{j-1} we have Ax∈Sj−2+B⊆Sj−1+BAx \in S_{j-2} + \mathcal{B} \subseteq S_{j-1} + \mathcal{B}, so x∈Sjx \in S_j. For the second claim, Sj+1S_{j+1} is defined from SjS_j by the same rule as SjS_j from Sj−1S_{j-1}, so Sj=Sj−1S_j = S_{j-1} gives Sj+1=SjS_{j+1} = S_j, and so on. □\square

So the dimensions increase strictly until they stop, and the loop of line L1 runs at most nn rounds.

Lemma 2: meaning of the subspaces

x∈Sjx \in S_j if and only if there are inputs u0,…,uj−1u_0, \dots, u_{j-1} that bring x0=xx_0 = x to xj=0x_j = 0.

Proof. By induction on jj. For j=0j = 0 both sides say x=0x = 0. For j≥1j \ge 1: if x∈Sjx \in S_j, write Ax=s+BcAx = s + Bc with s∈Sj−1s \in S_{j-1}, and take u0=−cu_0 = -c; then x1=Ax−Bc=sx_1 = Ax - Bc = s, which the induction hypothesis brings to 0 in j−1j - 1 more steps. Conversely, if inputs bring xx to 0 in jj steps, then x1=Ax+Bu0x_1 = Ax + Bu_0 is brought to 0 in j−1j - 1 steps, so x1∈Sj−1x_1 \in S_{j-1} and Ax=x1−Bu0∈Sj−1+BAx = x_1 - Bu_0 \in S_{j-1} + \mathcal{B}. □\square

Lemma 3: the gain is deadbeat

Suppose the loop ends with SN=RnS_N = \mathbb{R}^n. Then the gain KK of line L5 satisfies (A−BK)Sj⊆Sj−1(A - BK) S_j \subseteq S_{j-1} for j=1,…,Nj = 1, \dots, N, and (A−BK)N=0(A - BK)^N = 0.

Proof. Line L3 adds each new basis vector vv in the first round jj with v∈Sjv \in S_j, together with the cc of its null vector, so Av=s+BcAv = s + Bc with s∈Sj−1s \in S_{j-1}. Because the vectors added before round jj span Sj−1S_{j-1} (Lemma 1 and the fact that line L3 adds a maximal independent set of new vectors), the vectors added up to round jj span SjS_j. They are independent by construction, and after round NN they form a basis v1,…,vnv_1, \dots, v_n of Rn\mathbb{R}^n, so VV is invertible and K=CV−1K = C V^{-1} is the unique matrix with Kvi=ciK v_i = c_i. For viv_i added in round jj, (A−BK)vi=Avi−Bci=si∈Sj−1(A - BK) v_i = Av_i - Bc_i = s_i \in S_{j-1}. Every vector of SjS_j is a combination of basis vectors added in rounds up to jj, each of which is mapped into Sj′−1⊆Sj−1S_{j'-1} \subseteq S_{j-1} for its round j′≤jj' \le j. So (A−BK)Sj⊆Sj−1(A - BK) S_j \subseteq S_{j-1}. Applying this NN times gives (A−BK)NRn=(A−BK)NSN⊆S0={0}(A - BK)^N \mathbb{R}^n = (A - BK)^N S_N \subseteq S_0 = \{0\}. □\square

Lemma 4: no gain needs fewer steps

If (A−BK′)N′=0(A - BK')^{N'} = 0 for some K′K', then N′≥NN' \ge N.

Proof. The feedback inputs uk=−K′xku_k = -K' x_k bring every state to xN′=(A−BK′)N′x0=0x_{N'} = (A - BK')^{N'} x_0 = 0. By Lemma 2, every state lies in SN′S_{N'}, so SN′=RnS_{N'} = \mathbb{R}^n. Since NN is the first index with SN=RnS_N = \mathbb{R}^n and the subspaces grow, N≤N′N \le N'. □\square

The same argument with open-loop inputs shows that no input sequence brings every state to 0 in fewer than NN steps.

Lemma 5: when the loop fails

If line L4 fails, no deadbeat gain exists, and this happens if and only if AA has an uncontrollable eigenvalue other than 0.

Proof. Line L4 fails when round jj adds no vector, that is, Sj=Sj−1≠RnS_j = S_{j-1} \ne \mathbb{R}^n. By Lemma 1, Si≠RnS_i \ne \mathbb{R}^n for all ii, so by Lemma 2 some state cannot be brought to 0 in any number of steps, and by the proof of Lemma 4 no gain is deadbeat.

For the second statement, use the Kalman decomposition: in suitable coordinates A=[A11A120A22]A = \begin{bmatrix} A_{11} & A_{12} \\ 0 & A_{22} \end{bmatrix} and B=[B10]B = \begin{bmatrix} B_1 \\ 0 \end{bmatrix} with (A11,B1)(A_{11}, B_1) controllable, and the uncontrollable eigenvalues are the eigenvalues of A22A_{22}. For every K=[K1,K2]K = [K_1, K_2], A−BKA - BK is block upper triangular with the diagonal blocks A11−B1K1A_{11} - B_1 K_1 and A22A_{22}. If a deadbeat gain exists, A−BKA - BK is nilpotent, so all its eigenvalues are 0, and so are those of A22A_{22}. Conversely, if all eigenvalues of A22A_{22} are 0, then A22A_{22} is nilpotent. By the pole placement theorem there is a K1K_1 that makes all eigenvalues of A11−B1K1A_{11} - B_1 K_1 equal to 0, so this block is nilpotent too. With K2=0K_2 = 0, a block upper triangular matrix with nilpotent diagonal blocks is nilpotent, because its kk-th power has the kk-th powers of the diagonal blocks on its diagonal and is again block upper triangular. Then a deadbeat gain exists, and the loop does not fail. □\square

Theorem

For every AA and BB, the algorithm either returns KK and NN with (A−BK)N=0(A - BK)^N = 0 and NN the least such number over all gains and all input sequences, or it raises an error, and it raises an error exactly when no deadbeat gain exists.

Proof. Lemmas 1, 3, 4 and 5. □\square

Remarks

  • One input. If m=1m = 1 and (A,b)(A, b) is controllable, a matrix is nilpotent exactly when its characteristic polynomial is znz^n, and the Ackermann formula page proves that exactly one gain gives this polynomial. So the algorithm returns the Ackermann gain for p(z)=znp(z) = z^n. In the coordinates of the controllable canonical form, A−bKA - bK is the companion matrix of znz^n, a single nilpotent Jordan block of size nn, so N=nN = n. The tests check that the two gains agree.
  • Invertible AA. By Lemma 2 and induction, Sj=A−jrange⁡[B,AB,…,Aj−1B]S_j = A^{-j} \operatorname{range}[B, AB, \dots, A^{j-1} B] when AA is invertible, so dim⁡Sj=rank⁡[B,…,Aj−1B]\dim S_j = \operatorname{rank}[B, \dots, A^{j-1} B], and NN is the controllability index.
  • Exactness. With integer or rational data the implementation uses exact fractions, so the rank decisions are exact and (A−BK)N=0(A - BK)^N = 0 holds exactly, as the tests check.

Complexity

In the real RAM, with exact arithmetic: each round of the loop computes the null space of a matrix with nn rows and at most 2n+m2n + m columns, by elimination in O(n2(n+m))O(n^2 (n + m)) operations, and tests at most 2n+m2n + m vectors for independence. With the independence tests done incrementally against an echelon form of VV, each costs O(n2)O(n^2), so a round costs O(n2(n+m))O(n^2 (n + m)), and there are N≤nN \le n rounds. Line L5 is one solve with mm right sides, O(n3+n2m)O(n^3 + n^2 m). The total is O(Nn2(n+m))O(N n^2 (n + m)) and the extra space is O(n(n+m))O(n (n + m)). The code on this page recomputes each rank from scratch, which is simpler and slower by a factor of nn. With rational data the entries can grow; the implementation uses exact fractions, and the bit cost is polynomial but larger.

In floating point, the rank decisions in lines L2 to L4 need a tolerance, and a system close to an uncontrollable one gives a gain that is very large or wrong. For one input, the Ackermann formula with p(z)=znp(z) = z^n has the same numerical weakness.

Properties

  • Exact zero, not decay. After NN steps the state is 0, not small. In the zz-domain, all closed-loop poles are at z=0z = 0, and the closed-loop response to any initial state is a polynomial in z−1z^{-1} of degree below NN, a finite impulse response.
  • Minimum time. No feedback and no open-loop input sequence reaches the origin from every state in fewer than NN steps.
  • Size of the inputs. The gain grows as hh shrinks. In the double integrator, ∥K∥\|K\| grows like 1/h21/h^2. With bounded inputs, the deadbeat law works only for small enough states; a time-optimal controller with bounds needs more steps.
  • Not unique with several inputs. For m>1m > 1 the algorithm returns one of many deadbeat gains. The choice of basis in line L3 decides which one. The Jordan structure of A−BKA - BK can also differ between gains with the same NN.
  • Observers. Applied to (AT,CT)(A^T, C^T), the algorithm gives a deadbeat observer gain L=KTL = K^T: the estimation error of a Luenberger observer is then exactly 0 after NN steps.

Variants and improvements

  • Single input. Use Ackermann's formula with p(z)=znp(z) = z^n: K=enTW−1AnK = e_n^T W^{-1} A^n.
  • Deadbeat tracking. Add a feedforward term so that the output follows a step reference after a finite number of steps; with integral action as in state feedback with integral action, the augmented system is made deadbeat.
  • Bounded inputs. If the inputs must stay within bounds, the minimum time problem becomes a linear program for each initial state, or a model predictive control problem. The deadbeat gain is its unbounded limit.
  • Ripple-free deadbeat. A deadbeat design on the sampled model can leave oscillations between samples, for example when it cancels a sampling zero near −1-1. Ripple-free designs constrain the controller so that the continuous output also settles; see sampled-data system.
  • Robust alternatives. Placing all poles at a small positive radius rr instead of 0 gives a smooth decay like rkr^k, much smaller inputs, and less sensitivity. The design is then ordinary pole placement.

When to use it

Use deadbeat control when the samples must settle in the least number of steps and the inputs can be large: for slow sampling relative to the plant, in digital servo loops with a strong actuator, or as the observer in a system where the state must be known exactly after nn samples. It is also a clean test case for discrete-time designs, because the result can be checked exactly. Avoid it when the sampling is fast relative to the plant dynamics, when the actuator saturates, or when the model is uncertain: the gain is large and the poles at 0 are very sensitive.

Pitfalls

  • Large gains for short periods. The inputs grow like 1/h21/h^2 for the double integrator, and faster for higher order systems. Check the input sequence for the largest expected initial state.
  • Sensitive poles. A nilpotent matrix with one Jordan block of size nn has eigenvalues that move like ε1/n\varepsilon^{1/n} under a change ε\varepsilon of its entries. A small model error therefore moves the poles far from 0, and the finite settling is lost.
  • Intersample ripple. The design controls only the samples. Simulate the continuous plant with the held input, as the zero-order hold page shows.
  • Not continuous-time. For x˙=Ax+Bu\dot x = Ax + Bu with u=−Kxu = -Kx, the state is e(A−BK)tx0e^{(A - BK)t} x_0, which is never 0 for x0≠0x_0 \ne 0. Finite time settling in continuous time needs nonlinear or time-varying control.
  • Uncontrollable modes. The algorithm fails when an uncontrollable eigenvalue is not 0. A stable uncontrollable mode still decays, but not in finite time; then use ordinary pole placement for the controllable part.

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.

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()
deadbeat_control.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deadbeat-control/. The authors are listed in prov/HZQ8MT.jsonl.

"""Deadbeat state feedback for x_(k+1) = A x_k + B u_k, with u_k = -K x_k.

The gain makes A - B K nilpotent, (A - B K)^N = 0, with the least possible N,
so every initial state reaches 0 in at most N steps. It works with any
number of inputs.

Method: the subspaces S_0 = {0} and S_j = {x : A x in S_(j-1) + range B}
are the states that some input sequence brings to 0 in j steps. They grow
until S_N = R^n. Choose a basis of R^n that runs through S_1, S_2, ...,
and for each basis vector v of S_j solve A v = s + B c with s in S_(j-1).
Setting K v = c gives (A - B K) v = s, so A - B K maps S_j into S_(j-1).

All arithmetic is exact (Fraction) for int and Fraction data. With float
data the rank decisions use a tolerance and the result is approximate.
"""

from fractions import Fraction

from ctlmat import mul, solve, transpose

__all__ = ["rref", "nullspace", "deadbeat_gain", "steps_to_zero"]


def _exact(M):
    return all(isinstance(v, (int, Fraction)) for row in M for v in row)


def rref(M, tol=1e-10):
    """Return (R, pivots): the reduced row echelon form of M and its pivot columns."""
    exact = _exact(M)
    R = [[Fraction(v) for v in row] for row in M] if exact else [[float(v) for v in row] for row in M]
    rows = len(R)
    cols = len(R[0]) if R else 0
    scale = 1.0 if exact else max([abs(v) for row in R for v in row] + [1.0])
    pivots = []
    r = 0
    for c in range(cols):
        if r == rows:
            break
        p = max(range(r, rows), key=lambda i: abs(R[i][c]))
        if (R[p][c] == 0) if exact else (abs(R[p][c]) <= tol * scale):
            continue
        R[r], R[p] = R[p], R[r]
        piv = R[r][c]
        R[r] = [v / piv for v in R[r]]
        for i in range(rows):
            if i != r and R[i][c] != 0:
                f = R[i][c]
                R[i] = [a - f * b for a, b in zip(R[i], R[r])]
        pivots.append(c)
        r += 1
    return R, pivots


def nullspace(M, tol=1e-10):
    """Return a basis (list of flat vectors) of the null space of M."""
    cols = len(M[0])
    R, pivots = rref(M, tol)
    free = [c for c in range(cols) if c not in pivots]
    basis = []
    one = Fraction(1) if _exact(M) else 1.0
    for f in free:
        v = [0 * one] * cols
        v[f] = one
        for i, p in enumerate(pivots):
            v[p] = -R[i][f]
        basis.append(v)
    return basis


def _rank(vectors, tol=1e-10):
    """Return the rank of a list of flat vectors."""
    if not vectors:
        return 0
    return len(rref(vectors, tol)[1])


def deadbeat_gain(A, B, tol=1e-10):
    """Return (K, N): a gain with (A - B K)^N = 0 and the least such N.

    A is n by n, B is n by m (lists of rows). Raises ValueError if no
    feedback makes A - B K nilpotent, that is, if some state cannot be
    brought to 0 in finite time (an uncontrollable eigenvalue is not 0).
    """
    n = len(A)
    m = len(B[0])
    V = []  # basis of S_(j-1), flat vectors
    C = []  # C[i] = c with A V[i] - B c in the previous subspace
    N = 0
    while len(V) < n:  # @line L1
        N += 1
        # Rows of [A, -V, -B]; a null vector (x, a, c) gives A x = V a + B c.
        big = [list(A[i]) + [-v[i] for v in V] + [-B[i][j] for j in range(m)] for i in range(n)]
        found = False
        offset = n + len(V)
        for z in nullspace(big, tol):  # @line L2
            x = z[:n]
            c = z[offset:]
            if _rank(V + [x], tol) > len(V):  # @line L3
                V.append(x)
                C.append(c)
                found = True
        if not found:  # @line L4
            raise ValueError("A - B K cannot be made nilpotent: an uncontrollable eigenvalue is not 0")
    # K V = C, so K = C V^(-1); solve V^T K^T = C^T.
    Vm = transpose(V)
    Cm = transpose(C)
    K = transpose(solve(transpose(Vm), transpose(Cm)))  # @line L5
    return K, N


def steps_to_zero(A, B):
    """Return the least j with range A^j inside range [B, A B, ..., A^(j-1) B].

    This is the least number of steps in which every state can be brought
    to 0 by some input sequence. Brute force, exact for exact data. Raises
    ValueError if there is no such j at most n.
    """
    n = len(A)
    R = []  # the columns of [B, A B, ..., A^(j-1) B]
    P = [[1 if i == j else 0 for j in range(n)] for i in range(n)]  # A^j
    for j in range(0, n + 1):
        if _rank(R + transpose(P)) == _rank(R):
            return j
        R = R + transpose(mul(P, B))
        P = mul(A, P)
    raise ValueError("some state cannot be brought to 0 in n steps")
test_deadbeat_control.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deadbeat-control/. The authors are listed in prov/HZQ8MT.jsonl.

import random
from fractions import Fraction

import pytest

import ctlmat as cm
from deadbeat_control import deadbeat_gain, nullspace, rref, steps_to_zero


def closed_loop(A, B, K):
    return cm.sub(A, cm.mul(B, K))


def nil_index(M):
    """Return the least N with M^N = 0 (exact), or None if M is not nilpotent."""
    n = len(M)
    P = cm.eye(n)
    for N in range(0, n + 1):
        if P == cm.zeros(n):
            return N
        P = cm.mul(M, P)
    return None


def ackermann_deadbeat(A, b):
    """Single-input deadbeat gain by Ackermann's formula with p(z) = z^n."""
    n = len(A)
    cols = [list(b)]
    for _ in range(n - 1):
        cols.append(cm.matvec(A, cols[-1]))
    q = cm.solve(cm.transpose(cm.transpose(cols)), [0] * (n - 1) + [1])
    return cm.mul([q], cm.mat_power(A, n))[0]


def run(A, B, K, x0, steps):
    x = list(x0)
    xs, us = [x], []
    for _ in range(steps):
        u = [-v for v in cm.matvec(K, x)]
        x = [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, u))]
        xs.append(x)
        us.append(u)
    return xs, us


def test_zoh_double_integrator():
    for h in (Fraction(1, 10), Fraction(1, 4), Fraction(2)):
        A = [[1, h], [0, 1]]
        B = [[h * h / 2], [h]]
        K, N = deadbeat_gain(A, B)
        assert N == 2
        assert K == [[1 / h ** 2, Fraction(3, 2) / h]]
        xs, us = run(A, B, K, [1, 0], 2)
        assert xs[2] == [0, 0]
        assert us == [[-1 / h ** 2], [1 / h ** 2]]


def test_single_input_matches_ackermann():
    rng = random.Random(3)
    done = 0
    while done < 12:
        n = rng.randint(1, 5)
        A = [[rng.randint(-3, 3) for _ in range(n)] for _ in range(n)]
        b = [rng.randint(-2, 2) for _ in range(n)]
        W = cm.transpose([cm.matvec(cm.mat_power(A, k), b) for k in range(n)])
        if cm.det(W) == 0:
            continue
        K, N = deadbeat_gain(A, [[v] for v in b])
        assert N == n
        assert K[0] == ackermann_deadbeat(A, b)
        done += 1


def test_multi_input_minimum_time():
    rng = random.Random(4)
    for trial in range(25):
        n = rng.randint(2, 6)
        m = rng.randint(1, 3)
        A = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(n)]
        B = [[rng.randint(-1, 1) for _ in range(m)] for _ in range(n)]
        try:
            want = steps_to_zero(A, B)
        except ValueError:
            with pytest.raises(ValueError):
                deadbeat_gain(A, B)
            continue
        K, N = deadbeat_gain(A, B)
        assert N == want
        assert nil_index(closed_loop(A, B, K)) == N
        x0 = [rng.randint(-5, 5) for _ in range(n)]
        xs, _ = run(A, B, K, x0, N)
        assert xs[N] == [0] * n


def test_stated_three_state_example():
    A = [[1, 1, 0], [0, 1, 1], [0, 0, 1]]
    B = [[0, 0], [1, 0], [0, 1]]
    K, N = deadbeat_gain(A, B)
    assert N == 2
    Acl = closed_loop(A, B, K)
    assert cm.mat_power(Acl, 2) == cm.zeros(3)
    assert Acl != cm.zeros(3)


def test_singular_A_uncontrollable_zero_mode_is_fine():
    # The third state is not reachable but decays to 0 in one step by itself.
    A = [[0, 1, 0], [0, 0, 0], [0, 0, 0]]
    B = [[0], [1], [0]]
    K, N = deadbeat_gain(A, B)
    assert N == 2
    assert nil_index(closed_loop(A, B, K)) == 2


def test_unstable_uncontrollable_mode_rejected():
    A = [[1, 0], [0, 2]]
    B = [[1], [0]]
    with pytest.raises(ValueError):
        deadbeat_gain(A, B)
    with pytest.raises(ValueError):
        steps_to_zero(A, B)


def test_rref_and_nullspace():
    M = [[1, 2, 3], [2, 4, 6], [1, 0, 1]]
    R, piv = rref(M)
    assert piv == [0, 1]
    for v in nullspace(M):
        assert cm.matvec(M, v) == [0, 0, 0]
    assert len(nullspace(M)) == 1


def test_float_data():
    h = 0.1
    A = [[1.0, h], [0.0, 1.0]]
    B = [[h * h / 2], [h]]
    K, N = deadbeat_gain(A, B)
    assert N == 2
    assert abs(K[0][0] - 100.0) < 1e-9 and abs(K[0][1] - 15.0) < 1e-9

History

Designs with a finite settling time for sampled systems appeared in the early transfer-function theory of sampled-data control, under the name deadbeat response. The state-space form, with the minimum number of steps given by the controllability structure of (A,B)(A, B), came with the state-space theory of the 1960s. O'Reilly (1981) surveyed the discrete time-optimal control problem and its deadbeat solutions. For one input, Ackermann's formula of 1972 gives the deadbeat gain directly.

References

  1. John O'Reilly, The discrete linear time invariant time-optimal control problem, an overview, Automatica 17(2), 363-370, 1981, the survey of the minimum-time problem for discrete linear systems and its deadbeat solutions
  2. Karl J. Åström and Björn Wittenmark, Computer-Controlled Systems, Theory and Design, third edition, Prentice Hall, 1997 (Dover reprint, 2011), Chapter 4, on pole placement by state feedback in discrete time and on the deadbeat case
  3. Jürgen Ackermann, Der Entwurf linearer Regelungssysteme im Zustandsraum, Regelungstechnik 20(7), 297-300, 1972, the single-input gain formula, which gives the deadbeat gain for p(z) = z^n
  4. Chi-Tsong Chen, Linear System Theory and Design, third edition, Oxford University Press, 1999, Section 8.2, State Feedback, and Section 8.6, State Feedback, Multivariable Case

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