Algorithm Search⌘K

Algorithmcore

Ackermann's formula

Also called Ackermann pole placement formula.

Gives the single-input pole placement gain as K = [0 ... 0 1] W^(-1) p(A), from the controllability matrix W and the desired polynomial p.

Time
O(n^3) worst
Space
O(n^2) extra
Where
n = the number of states
Properties
deterministicexactofflineiterative
Origin
Jürgen Ackermann, 1972

Ackermann's formula computes the state feedback gain KK that gives a single-input system x˙=Ax+bu\dot x = A x + b u the closed-loop characteristic polynomial p(s)p(s), with u=−Kxu = -Kx:

K=[0⋯01]W−1p(A),W=[bAb⋯An−1b].K = \begin{bmatrix} 0 & \cdots & 0 & 1 \end{bmatrix} W^{-1} p(A), \qquad W = \begin{bmatrix} b & Ab & \cdots & A^{n-1} b \end{bmatrix}.

The formula needs no change of coordinates, and it is the same in discrete time. It is one method for the pole placement problem. The pole placement theorem says when a solution exists, and the formula is the constructive part of its single-input proof. With one input, KK is unique, so all exact methods give the same KK; they differ only in rounding error. With more than one input, KK is not unique, and robust pole placement uses the extra freedom to make the closed loop well conditioned. The formula is exact in exact arithmetic, but it is numerically unstable for larger nn.

In plain words

A machine has one control knob. Its state is a list of numbers, and the knob is set to a weighted sum of these numbers. The choice of weights decides how the machine settles: fast or slow, with or without oscillation. The designer writes down the wanted settling behaviour as a polynomial. Ackermann's formula turns that polynomial into the weights in one step. It uses only the model of the machine and a table of how the knob moves the state over successive steps. If some part of the state cannot be moved by the knob, the table is singular and no set of weights exists. The formula is short and easy to check by hand. On a computer it loses accuracy fast when the state has many numbers.

The problem

Input: A∈Rn×nA \in \mathbb{R}^{n \times n}, b∈Rnb \in \mathbb{R}^n and a monic polynomial p(s)=sn+p1sn−1+⋯+pnp(s) = s^n + p_1 s^{n-1} + \cdots + p_n with real coefficients. Output: the row vector K∈R1×nK \in \mathbb{R}^{1 \times n} with det⁡(sI−(A−bK))=p(s)\det(sI - (A - bK)) = p(s). A solution exists for every pp if and only if (A,b)(A, b) is controllable, that is, WW is invertible (the Kalman rank condition). The solution is then unique. If the wanted poles are λ1,…,λn\lambda_1, \dots, \lambda_n, then p(s)=∏i(s−λi)p(s) = \prod_i (s - \lambda_i), and the complex poles must come in conjugate pairs for pp to be real.

The same formula serves the discrete system xk+1=Axk+bukx_{k+1} = A x_k + b u_k and the observer gain: for x^˙=Ax^+Bu+L(y−Cx^)\dot{\hat x} = A \hat x + B u + L(y - C\hat x) with one output, apply it to (AT,CT)(A^T, C^T) and set L=KTL = K^T; see Luenberger observer.

The algorithm

  1. ACKERMANN(A, b, p) ▷ p = [1, p_1, ..., p_n]
  2. 1W ← [b, A b, ..., A^(n-1) b] ▷ n matrix-vector products
  3. 2solve W^T q = e_n; if W is singular, fail ▷ q^T = last row of W^(-1)
  4. 3K ← 0 (a row vector); for each coefficient c of p, highest power first:
  5. 4K ← K A + c q^T ▷ Horner's rule on row vectors
  6. 5return K ▷ K = q^T p(A)

Line L1 builds the controllability matrix one column at a time. Line L2 gets the last row of W−1W^{-1} by one linear solve; a singular WW means that (A,b)(A, b) is not controllable. Lines L3 and L4 compute qTp(A)=∑ipi qTAn−iq^T p(A) = \sum_i p_i\, q^T A^{n-i} by Horner's rule, so the code multiplies row vectors by AA and never forms p(A)p(A).

Example

Double integrator. Take A=[0100]A = \begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix}, b=[01]b = \begin{bmatrix} 0 \\ 1 \end{bmatrix} and the poles −1±i-1 \pm i, so p(s)=s2+2s+2p(s) = s^2 + 2s + 2. Line L1 gives W=[0110]W = \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}, and line L2 gives qT=[10]q^T = \begin{bmatrix} 1 & 0 \end{bmatrix}. Then

p(A)=A2+2A+2I=[2202],K=qTp(A)=[22].p(A) = A^2 + 2A + 2I = \begin{bmatrix} 2 & 2 \\ 0 & 2 \end{bmatrix}, \qquad K = q^T p(A) = \begin{bmatrix} 2 & 2 \end{bmatrix}.

Check: A−bK=[01−2−2]A - bK = \begin{bmatrix} 0 & 1 \\ -2 & -2 \end{bmatrix} has the characteristic polynomial s2+2s+2s^2 + 2s + 2.

A companion matrix. For A=[01−2−3]A = \begin{bmatrix} 0 & 1 \\ -2 & -3 \end{bmatrix}, b=[01]b = \begin{bmatrix} 0 \\ 1 \end{bmatrix} and the poles −4,−5-4, -5, the formula gives K=[186]K = \begin{bmatrix} 18 & 6 \end{bmatrix}. Here AA is already in controllable canonical form, and KK is the difference of the coefficient vectors: p(s)=s2+9s+20p(s) = s^2 + 9s + 20 and det⁡(sI−A)=s2+3s+2\det(sI - A) = s^2 + 3s + 2, so K=[20−29−3]K = \begin{bmatrix} 20 - 2 & 9 - 3 \end{bmatrix}.

Deadbeat in discrete time. The zero-order hold model of the double integrator 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}. With p(z)=z2p(z) = z^2, line L2 gives qT=[1/h2−1/(2h)]q^T = \begin{bmatrix} 1/h^2 & -1/(2h) \end{bmatrix}, and K=qTA2=[1/h23/(2h)]K = q^T A^2 = \begin{bmatrix} 1/h^2 & 3/(2h) \end{bmatrix}. Then (A−bK)2=0(A - bK)^2 = 0, so every initial state reaches 0 in two samples. See deadbeat control.

Loss of accuracy. Take A=diag⁡(−1,−2,…,−n)A = \operatorname{diag}(-1, -2, \dots, -n), bb the vector of ones, and the poles −(n+1),…,−2n-(n+1), \dots, -2n, all well separated. The code was run in double precision, and the characteristic polynomial of the computed A−bKA - bK was then evaluated exactly. The largest relative error of its coefficients, and the 2-norm condition number of WW, were:

nn κ2(W)\kappa_2(W) relative coefficient error
4 1.2×1031.2 \times 10^{3} 2×10−152 \times 10^{-15}
6 7.3×1057.3 \times 10^{5} 3×10−123 \times 10^{-12}
8 9.5×1089.5 \times 10^{8} 3×10−93 \times 10^{-9}
10 2.1×10122.1 \times 10^{12} 9×10−69 \times 10^{-6}
12 7.1×10157.1 \times 10^{15} 9×10−29 \times 10^{-2}

The error grows roughly like κ2(W)\kappa_2(W) times the unit roundoff. At n=12n = 12 the placed polynomial is wrong in the second digit.

Correctness

The full proof is in proofs/correctness.md. In short: write Ac=A−bKA_c = A - bK. Expanding AckA_c^k gives Ack=Ak−∑j=0k−1Ajb (KAck−1−j)A_c^k = A^k - \sum_{j=0}^{k-1} A^j b\, (K A_c^{k-1-j}). Summing with the coefficients of pp gives p(Ac)=p(A)−WMp(A_c) = p(A) - W M, where MM is an n×nn \times n matrix whose last row is KK. If pp is the characteristic polynomial of AcA_c, the Cayley-Hamilton theorem gives p(Ac)=0p(A_c) = 0, so WM=p(A)W M = p(A), and the last row of M=W−1p(A)M = W^{-1} p(A) is KK. This proves uniqueness. Existence follows from the controllable canonical form, where the gain that gives pp is obvious; by uniqueness it equals the formula.

Proof: Ackermann's formula gives the only single-input gain with the wanted characteristic polynomialfull

Let A∈Rn×nA \in \mathbb{R}^{n \times n}, b∈Rnb \in \mathbb{R}^n, and p(s)=∑i=0npisn−ip(s) = \sum_{i=0}^{n} p_i s^{n-i} with p0=1p_0 = 1. Write W=[b,Ab,…,An−1b]W = [b, Ab, \dots, A^{n-1} b], Ac=A−bKA_c = A - bK for a row vector KK, and ene_n for the last unit vector. The claim is: if WW is invertible, then K=enTW−1p(A)K = e_n^T W^{-1} p(A) is the only row vector with det⁡(sI−Ac)=p(s)\det(sI - A_c) = p(s), and lines L1 to L5 compute it.

Lemma 1: expansion of the powers

For every row vector KK and every k≥0k \ge 0,

Ack=Ak−∑j=0k−1Ajb KAck−1−j.A_c^k = A^k - \sum_{j=0}^{k-1} A^j b\, K A_c^{k-1-j}.

Proof. For k=0k = 0 the sum is empty and both sides are II. If the identity holds for kk, then

Ack+1=AAck−bKAck=Ak+1−∑j=0k−1Aj+1b KAck−1−j−bKAck.A_c^{k+1} = A A_c^k - bK A_c^k = A^{k+1} - \sum_{j=0}^{k-1} A^{j+1} b\, K A_c^{k-1-j} - b K A_c^k.

Shift the index j+1→jj + 1 \to j in the sum. The last term is the term j=0j = 0 of the new sum, so Ack+1=Ak+1−∑j=0kAjb KAck−jA_c^{k+1} = A^{k+1} - \sum_{j=0}^{k} A^j b\, K A_c^{k-j}. □\square

Lemma 2: the polynomial of the closed loop

p(Ac)=p(A)−WMp(A_c) = p(A) - W M, where MM is the n×nn \times n matrix with rows

rj=K∑k=j+1npn−kAck−1−j,j=0,…,n−1,r_j = K \sum_{k=j+1}^{n} p_{n-k} A_c^{k-1-j}, \qquad j = 0, \dots, n-1,

and the last row is rn−1=Kr_{n-1} = K.

Proof. By Lemma 1, p(Ac)=∑k=0npn−kAck=p(A)−∑k=1npn−k∑j=0k−1Ajb KAck−1−jp(A_c) = \sum_{k=0}^{n} p_{n-k} A_c^k = p(A) - \sum_{k=1}^{n} p_{n-k} \sum_{j=0}^{k-1} A^j b\, K A_c^{k-1-j}. Exchange the two sums: jj runs from 0 to n−1n-1, and for fixed jj, kk runs from j+1j + 1 to nn. This gives p(A)−∑j=0n−1Ajb rj=p(A)−WMp(A) - \sum_{j=0}^{n-1} A^j b\, r_j = p(A) - W M, because AjbA^j b is column j+1j + 1 of WW and rjr_j is row j+1j + 1 of MM. For j=n−1j = n - 1 only k=nk = n occurs, with p0=1p_0 = 1 and Ac0=IA_c^0 = I, so rn−1=Kr_{n-1} = K. □\square

Lemma 3: uniqueness

If WW is invertible and det⁡(sI−Ac)=p(s)\det(sI - A_c) = p(s), then K=enTW−1p(A)K = e_n^T W^{-1} p(A).

Proof. By the Cayley-Hamilton theorem, a matrix satisfies its characteristic polynomial, so p(Ac)=0p(A_c) = 0. Lemma 2 gives WM=p(A)W M = p(A), so M=W−1p(A)M = W^{-1} p(A). The last row of MM is KK (Lemma 2), and the last row of W−1p(A)W^{-1} p(A) is enTW−1p(A)e_n^T W^{-1} p(A). □\square

Lemma 4: existence

If WW is invertible, some row vector KK gives det⁡(sI−Ac)=p(s)\det(sI - A_c) = p(s).

Proof. Let qT=enTW−1q^T = e_n^T W^{-1}, so qTW=enTq^T W = e_n^T, that is, qTAjb=0q^T A^j b = 0 for j<n−1j < n - 1 and qTAn−1b=1q^T A^{n-1} b = 1. Let TT be the matrix with rows qT,qTA,…,qTAn−1q^T, q^T A, \dots, q^T A^{n-1}.

TT is invertible. The entry (i,j)(i, j) of TWTW is qTAi+j−2bq^T A^{i+j-2} b. It is 0 if i+j<n+1i + j < n + 1 and 1 if i+j=n+1i + j = n + 1. So TWTW has ones on the antidiagonal and zeros above it, its determinant is ±1\pm 1, and TT is invertible.

The new coordinates. Entry ii of TbTb is qTAi−1bq^T A^{i-1} b, which is 1 for i=ni = n and 0 otherwise, so Tb=enTb = e_n. Row ii of TATA is qTAiq^T A^i, which is row i+1i + 1 of TT for i<ni < n. Let det⁡(sI−A)=sn+a1sn−1+⋯+an\det(sI - A) = s^n + a_1 s^{n-1} + \cdots + a_n. By the Cayley-Hamilton theorem, qTAn=−∑k=1nak qTAn−kq^T A^n = -\sum_{k=1}^{n} a_k\, q^T A^{n-k}. So TA=AˉTTA = \bar A T, where Aˉ\bar A has rows e2T,…,enTe_2^T, \dots, e_n^T and the last row [−an,…,−a1][-a_n, \dots, -a_1].

The gain. Let Kˉ=[pn−an,…,p1−a1]\bar K = [p_n - a_n, \dots, p_1 - a_1]. Then Aˉ−enKˉ\bar A - e_n \bar K has rows e2T,…,enTe_2^T, \dots, e_n^T and the last row [−pn,…,−p1][-p_n, \dots, -p_1]. Call this companion matrix CpC_p. Expand det⁡(sI−Cp)\det(sI - C_p) along the first column. The entry ss in position (1,1)(1, 1) has the minor det⁡(sI−Cp′)\det(sI - C_{p'}) with p′(s)=sn−1+p1sn−2+⋯+pn−1p'(s) = s^{n-1} + p_1 s^{n-2} + \cdots + p_{n-1}. The entry pnp_n in position (n,1)(n, 1) has a minor that is lower triangular with −1-1 on the diagonal, so its cofactor is (−1)n+1(−1)n−1pn=pn(-1)^{n+1} (-1)^{n-1} p_n = p_n. So det⁡(sI−Cp)=s p′(s)+pn=p(s)\det(sI - C_p) = s\, p'(s) + p_n = p(s) by induction on nn, with the base case det⁡(s−(−p1))=s+p1\det(s - (-p_1)) = s + p_1. Finally set K=KˉTK = \bar K T. Then T(A−bK)T−1=Aˉ−enKˉ=CpT(A - bK)T^{-1} = \bar A - e_n \bar K = C_p, and similar matrices have the same characteristic polynomial. □\square

Theorem

If WW is invertible, the output of lines L1 to L5 is the only row vector KK with det⁡(sI−(A−bK))=p(s)\det(sI - (A - bK)) = p(s).

Proof. By Lemma 4 a solution exists, and by Lemma 3 every solution equals enTW−1p(A)e_n^T W^{-1} p(A), so this vector is the unique solution. It remains to see that the lines compute it.

Line L1 builds WW column by column, since column j+1j + 1 is AA times column jj. Line L2 solves WTq=enW^T q = e_n, so qTW=enTq^T W = e_n^T and qT=enTW−1q^T = e_n^T W^{-1}. In lines L3 and L4, the loop invariant is: after the coefficients p0,…,pip_0, \dots, p_i have been used, K=qT∑l=0iplAi−lK = q^T \sum_{l=0}^{i} p_l A^{i-l}. This holds after the first step, where K=0⋅A+p0qTK = 0 \cdot A + p_0 q^T. If it holds after step ii, the update K←KA+pi+1qTK \leftarrow KA + p_{i+1} q^T gives qT∑l=0i+1plAi+1−lq^T \sum_{l=0}^{i+1} p_l A^{i+1-l}. After step nn, K=qTp(A)K = q^T p(A), which line L5 returns. The code forms KAKA as the vector ATKTA^T K^T, which is the same numbers. □\square

When WW is singular

If WW is singular, (A,b)(A, b) is not controllable by the Kalman rank condition. By the pole placement theorem, the eigenvalues of the uncontrollable part are then eigenvalues of A−bKA - bK for every KK, so some polynomials pp cannot be reached. The solve in line L2 meets a zero pivot, and the code raises an error for every pp, also for the polynomials that could be reached. With exact data this test is exact. With floating point data, a nearly singular WW usually gives a nonzero pivot, and the code returns a very large gain; the page discusses this.

Complexity

Line L1 costs n−1n - 1 matrix-vector products, O(n3)O(n^3) in total. Line L2 is one LULU solve, O(n3)O(n^3). Lines L3 and L4 cost n+1n + 1 vector-matrix products, O(n3)O(n^3). The time is O(n3)O(n^3) and the extra space is O(n2)O(n^2) for WW. Forming p(A)p(A) by matrix products, as the textbook formula reads, costs O(n4)O(n^4) and is not needed.

In the floating-point model the cost is the same, but the accuracy is poor. The controllability matrix of a well behaved system is often very ill conditioned, because its columns AkbA^k b turn towards the dominant eigenvector of AA as kk grows. The solve in line L2 then has a relative error of about κ(W)\kappa(W) times the unit roundoff, and the table above shows this growth. Mehrmann and Xu (1996) show that the single-input problem itself is often ill conditioned, so no method can be accurate for every input. Methods that use orthogonal transformations do not form WW and do better than the formula in practice.

Properties

  • Exact in rational arithmetic. With integer or rational data, every step is a rational operation, and the result is exact. This makes the formula a good reference for tests.
  • Linear in pp. The gain is affine in the coefficients of pp: K=qTAn+∑i=1npi qTAn−iK = q^T A^n + \sum_{i=1}^{n} p_i\, q^T A^{n-i}. If pp is the open-loop polynomial, K=0K = 0, by the Cayley-Hamilton theorem.
  • Same in continuous and discrete time. The formula is pure algebra on AA, bb and pp. Only the choice of pp depends on the time domain: Hurwitz roots in continuous time, roots inside the unit circle in discrete time.
  • Invariance. If A~=TAT−1\tilde A = T A T^{-1} and b~=Tb\tilde b = T b, then W~=TW\tilde W = T W, and the gain in the new coordinates is K~=KT−1\tilde K = K T^{-1}, as it should be.

Variants and improvements

  • Bass-Gura formula. Transform to controllable canonical form by a matrix TT built from WW and the open-loop coefficients. In the new coordinates the gain is the difference of the wanted and the open-loop coefficient vectors, as in the companion example above; multiply by TT to return. It has the same unique result and the same numerical weakness.
  • Observer form. For one output, L=(enT(WoT)−1p(AT))T=p(A)Wo−1enL = \left(e_n^T (W_o^T)^{-1} p(A^T)\right)^T = p(A) W_o^{-1} e_n, with WoW_o the observability matrix.
  • Multi-input systems. Choose a vector vv so that (A−BK0,Bv)(A - BK_0, Bv) is controllable for some K0K_0 (Heymann's lemma), and apply the formula to that pair. The result is one of many valid gains, often a poor one. Robust pole placement chooses among them.
  • Orthogonal methods. Reduce (A,b)(A, b) by an orthogonal similarity to Hessenberg form with bb a multiple of e1e_1, then compute KK by a recursion on the Hessenberg matrix. No controllability matrix is formed. MATLAB's acker is the formula of this page. MATLAB's place uses the Kautsky-Nichols-Van Dooren method, and SciPy's place_poles uses the Tits-Yang refinement of it by default.

When to use it

Use the formula for hand computation, for teaching, for exact computation with rational data, and for systems of small order, say n≤6n \le 6 with well spread poles. It is also the standard proof of the single-input case of the pole placement theorem. For larger nn, for poles close together, or for any use in floating point where accuracy matters, use an orthogonal method. Even then, check the closed-loop eigenvalues of A−bKA - bK after the design.

Pitfalls

  • Instability for larger nn. As in the table above, the formula can give a gain that places the poles in the wrong place, with no warning. Compute the eigenvalues of A−bKA - bK and compare.
  • Near loss of controllability. If (A,b)(A, b) is close to an uncontrollable pair, WW is close to singular. The gain is then very large, and the closed loop is very sensitive, with any method. This is a property of the plant, not of the formula.
  • Sign convention. The formula is for u=−Kxu = -Kx and the closed loop A−bKA - bK. With u=Kxu = Kx the sign of KK changes.
  • Conjugate pairs. If one pole of a complex pair is missing, pp has complex coefficients and KK is complex. The code rejects such pole lists.
  • Poles are not the whole design. The formula places poles only. The zeros, the input size and the robustness margins follow from the choice of poles and are not under separate control; see state feedback.

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.

ackermann_formula.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ackermann-formula/. The authors are listed in prov/DZTY4S.jsonl.

"""Ackermann's formula for single-input pole placement.

For x' = A x + b u (or x_(k+1) = A x_k + b u_k) with one input and the
control u = -K x, the closed-loop matrix is A - b K. If (A, b) is
controllable, the only row vector K with det(s I - (A - b K)) = p(s) for a
given monic p of degree n is

    K = [0 ... 0 1] W^(-1) p(A),    W = [b, A b, ..., A^(n-1) b].

The code computes q^T = e_n^T W^(-1) by one linear solve W^T q = e_n, so W
is never inverted, and then K = q^T p(A) by Horner's rule on row vectors,
K <- K A + p_i q^T, so p(A) is never formed. The cost is O(n^3).
With int and Fraction data the result is exact. With
float data the formula is numerically unstable for larger n, because W is
then badly conditioned (see the page).
"""

from fractions import Fraction

from ctlmat import matvec, mul, polymul, solve, transpose, zeros

__all__ = ["controllability_matrix", "poly_of_matrix", "poly_from_roots", "ackermann", "ackermann_poles"]


def controllability_matrix(A, b):
    """Return W = [b, A b, ..., A^(n-1) b] for a flat vector b."""
    n = len(A)
    if len(b) != n or any(len(row) != n for row in A):
        raise ValueError("A must be n by n and b must have n entries")
    cols = [list(b)]
    for _ in range(n - 1):
        cols.append(matvec(A, cols[-1]))
    return transpose(cols)


def poly_of_matrix(p, A):
    """Return p(A) = p_0 A^n + p_1 A^(n-1) + ... + p_n I by Horner's rule."""
    n = len(A)
    P = zeros(n)
    for c in p:
        P = mul(A, P)
        for i in range(n):
            P[i][i] += c
    return P


def poly_from_roots(roots):
    """Return the monic polynomial with the given roots, highest power first.

    Exact roots (int, Fraction) give exact coefficients. If the roots are
    closed under complex conjugation, the tiny imaginary parts of the
    coefficients are removed and the coefficients are real floats.
    """
    p = [1]
    for r in roots:
        p = polymul(p, [1, -r])
    if any(isinstance(c, complex) for c in p):
        big = max(abs(c) for c in p)
        if all(abs(complex(c).imag) <= 1e-12 * big for c in p):
            p = [complex(c).real for c in p]
    return p


def ackermann(A, b, p):
    """Return the row vector K (a flat list) with charpoly(A - b K) = p.

    p is monic of degree n, highest power first. Raises ValueError if p has
    the wrong form or if (A, b) is not controllable (W is singular).
    """
    n = len(A)
    if len(p) != n + 1 or p[0] != 1:
        raise ValueError("p must be monic of degree n")
    W = controllability_matrix(A, b)  # @line L1
    e_n = [0] * (n - 1) + [1]
    try:
        q = solve(transpose(W), e_n)  # @line L2
    except ValueError:
        raise ValueError("(A, b) is not controllable") from None
    At = transpose(A)
    K = [0] * n
    for c in p:  # @line L3
        K = [x + c * y for x, y in zip(matvec(At, K), q)]  # @line L4
    return K  # @line L5


def ackermann_poles(A, b, poles):
    """Return K that places the eigenvalues of A - b K at the given poles.

    Complex poles must come in conjugate pairs, so that K is real.
    """
    if len(poles) != len(A):
        raise ValueError("give exactly n poles")
    p = poly_from_roots(poles)
    if any(isinstance(c, complex) for c in p):
        raise ValueError("complex poles must come in conjugate pairs")
    return ackermann(A, b, p)


if __name__ == "__main__":
    h = Fraction(1, 10)
    print(ackermann([[0, 1], [0, 0]], [0, 1], [1, 2, 2]))
    print(ackermann([[1, h], [0, 1]], [h * h / 2, h], [1, 0, 0]))
ctlmat.py 630 lines
# 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()
test_ackermann_formula.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ackermann-formula/. The authors are listed in prov/DZTY4S.jsonl.

import random
from fractions import Fraction

import pytest

import ctlmat as cm
from ackermann_formula import (
    ackermann,
    ackermann_poles,
    controllability_matrix,
    poly_from_roots,
    poly_of_matrix,
)


def closed_loop(A, b, K):
    return [[A[i][j] - b[i] * K[j] for j in range(len(A))] for i in range(len(A))]


def rand_pair(rng, n, lo=-3, hi=3):
    while True:
        A = [[rng.randint(lo, hi) for _ in range(n)] for _ in range(n)]
        b = [rng.randint(lo, hi) for _ in range(n)]
        if cm.det(controllability_matrix(A, b)) != 0:
            return A, b


def brute_force_gain(A, b, p):
    """Solve the affine map from K to the closed-loop coefficients directly.

    The coefficients of charpoly(A - b K) are affine in K, because
    A - b K is a rank-one change of A. Evaluate the map at K = 0 and at the
    n unit vectors, then solve the n by n linear system.
    """
    n = len(A)
    c0 = cm.charpoly(A)[1:]
    cols = []
    for j in range(n):
        e = [0] * n
        e[j] = 1
        cj = cm.charpoly(closed_loop(A, b, e))[1:]
        cols.append([x - y for x, y in zip(cj, c0)])
    M = cm.transpose(cols)
    rhs = [Fraction(x) - y for x, y in zip(p[1:], c0)]
    return cm.solve(M, rhs)


def test_double_integrator():
    A = [[0, 1], [0, 0]]
    b = [0, 1]
    K = ackermann(A, b, [1, 2, 2])
    assert K == [2, 2]
    assert cm.charpoly(closed_loop(A, b, K)) == [1, 2, 2]


def test_companion_example():
    A = [[0, 1], [-2, -3]]
    b = [0, 1]
    K = ackermann_poles(A, b, [-4, -5])
    assert K == [18, 6]


def test_zoh_double_integrator_deadbeat():
    for h in (Fraction(1, 10), Fraction(1, 2), Fraction(3)):
        A = [[1, h], [0, 1]]
        b = [h * h / 2, h]
        K = ackermann(A, b, [1, 0, 0])
        assert K == [1 / h ** 2, Fraction(3, 2) / h]
        Acl = closed_loop(A, b, K)
        assert cm.mat_power(Acl, 2) == cm.zeros(2)


def test_random_exact():
    rng = random.Random(1)
    for n in range(1, 7):
        for _ in range(6):
            A, b = rand_pair(rng, n)
            p = [1] + [Fraction(rng.randint(-20, 20), rng.randint(1, 4)) for _ in range(n)]
            K = ackermann(A, b, p)
            assert cm.charpoly(closed_loop(A, b, K)) == p
            assert K == brute_force_gain(A, b, p)


def test_poly_of_matrix_matches_powers():
    rng = random.Random(2)
    A = [[rng.randint(-4, 4) for _ in range(4)] for _ in range(4)]
    p = [1, 3, -2, 5, 7]
    want = cm.zeros(4)
    for i, c in enumerate(p):
        want = cm.add(want, cm.scale(c, cm.mat_power(A, len(p) - 1 - i)))
    assert poly_of_matrix(p, A) == want


def test_matches_textbook_form():
    # K = e_n^T W^(-1) p(A), with the inverse and p(A) formed explicitly.
    rng = random.Random(4)
    for n in range(1, 6):
        A, b = rand_pair(rng, n)
        p = [1] + [rng.randint(-9, 9) for _ in range(n)]
        Winv = cm.inv(controllability_matrix(A, b))
        want = cm.mul([Winv[-1]], poly_of_matrix(p, A))[0]
        assert ackermann(A, b, p) == want


def test_cayley_hamilton_gives_zero_gain():
    rng = random.Random(3)
    A, b = rand_pair(rng, 4)
    assert ackermann(A, b, cm.charpoly(A)) == [0, 0, 0, 0]


def test_complex_poles_float():
    A = [[0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, -2.0, 0.5]]
    b = [0.0, 0.0, 1.0]
    poles = [-2.0, complex(-1.0, 2.0), complex(-1.0, -2.0)]
    K = ackermann_poles(A, b, poles)
    assert all(isinstance(k, float) for k in K)
    roots = cm.polyroots(cm.charpoly(closed_loop(A, b, K)))
    for r, w in zip(roots, sorted(poles, key=lambda v: (complex(v).real, complex(v).imag))):
        assert abs(r - w) < 1e-9


def test_unpaired_complex_pole_rejected():
    with pytest.raises(ValueError):
        ackermann_poles([[0, 1], [0, 0]], [0, 1], [complex(-1, 1), -2])


def test_uncontrollable_rejected():
    A = [[1, 0], [0, 2]]
    b = [1, 0]
    with pytest.raises(ValueError):
        ackermann(A, b, [1, 3, 2])


def test_wrong_polynomial_rejected():
    with pytest.raises(ValueError):
        ackermann([[0, 1], [0, 0]], [0, 1], [2, 2, 2])
    with pytest.raises(ValueError):
        ackermann([[0, 1], [0, 0]], [0, 1], [1, 2])


def test_poly_from_roots_exact():
    assert poly_from_roots([-1, -2]) == [1, 3, 2]
    assert poly_from_roots([Fraction(1, 2)]) == [1, Fraction(-1, 2)]
    p = poly_from_roots([complex(-1, 1), complex(-1, -1)])
    assert p == [1.0, 2.0, 2.0]


def test_float_error_grows_with_n():
    # A = diag(-1, ..., -n), b = ones, poles at -(n + 1), ..., -2n. The
    # coefficient error of the placed polynomial, relative to its size,
    # grows quickly with n. This shows the instability; the bound is loose.
    def rel_error(n):
        A = [[float(-(i + 1)) if i == j else 0.0 for j in range(n)] for i in range(n)]
        b = [1.0] * n
        p = poly_from_roots([float(-(n + 1 + i)) for i in range(n)])
        K = ackermann(A, b, p)
        Acl = [[Fraction(v) for v in row] for row in closed_loop(A, b, K)]
        got = cm.charpoly(Acl)
        return max(abs(float(g) - c) / abs(c) for g, c in zip(got, p))

    assert rel_error(4) < 1e-10
    assert rel_error(12) > 100 * rel_error(4)

History

Ackermann (1972) published the formula in the German journal Regelungstechnik as a direct design rule for single-input systems in state space. Before it, the usual route was a change of coordinates to a canonical form and a comparison of coefficients, as in the Bass-Gura formula. The formula became a standard textbook result and appears in Chen (1999) and in Åström and Wittenmark (1997). Its numerical weakness was well known by the 1980s; Kautsky, Nichols and Van Dooren (1985) cite the poor conditioning of canonical form methods as the reason for their algorithm, and Mehrmann and Xu (1996) analysed the conditioning of the single-input problem.

References

  1. Jürgen Ackermann, Der Entwurf linearer Regelungssysteme im Zustandsraum, Regelungstechnik 20(7), 297-300, 1972, the formula for the feedback vector of a single-input system from the controllability matrix and the desired characteristic polynomial
  2. Chi-Tsong Chen, Linear System Theory and Design, third edition, Oxford University Press, 1999, Section 8.2, State Feedback
  3. Karl J. Åström and Björn Wittenmark, Computer-Controlled Systems, Theory and Design, third edition, Prentice Hall, 1997 (Dover reprint, 2011), Section 4.3, Regulation by State Feedback
  4. Volker Mehrmann and Hongguo Xu, An analysis of the pole placement problem I. The single-input case, Electronic Transactions on Numerical Analysis 4, 89-105, 1996, the conditioning of the single-input pole placement problem and of the closed-loop eigenvalues
  5. Jaroslav Kautsky, Nancy K. Nichols and Paul Van Dooren, Robust pole assignment in linear state feedback, International Journal of Control 41(5), 1129-1155, 1985, the introduction, on the numerical problems of methods that use canonical forms

Where this leads

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