Algorithm Search⌘K

Algorithmadvanced

Kautsky-Nichols-Van Dooren pole placement

Also called KNV algorithm, robust eigenstructure assignment.

Places the eigenvalues of A - BK and uses the freedom of a multi-input gain to make the eigenvector matrix well conditioned, so the poles are less sensitive.

Time
O(n^4 (s + 1)) worst
Space
O(n^2 m) extra
Where
m = the number of inputs; n = the number of states; s = the number of sweeps
Properties
deterministicnot exactofflineiterative
Origin
Jaroslav Kautsky, Nancy K. Nichols, Paul Van Dooren, 1985

Kautsky-Nichols-Van Dooren (KNV) pole placement computes a state feedback gain KK for x˙=Ax+Bu\dot x = Ax + Bu, u=−Kxu = -Kx, such that A−BKA - BK has given eigenvalues λ1,…,λn\lambda_1, \dots, \lambda_n and a matrix XX of unit eigenvectors that is as well conditioned as the method can find. With m>1m > 1 inputs the pole placement problem has many solutions, because each eigenvector can be chosen in an mm-dimensional subspace. KNV uses this freedom to make the placed eigenvalues insensitive to errors in AA, BB and KK. It differs from Ackermann's formula, which has no freedom to use because it handles one input, and from the pole placement theorem, which only says that a solution exists. This page describes method 0 of the 1985 paper, the simplest of its methods.

In plain words

A machine with several control knobs can be made to settle in the same way by many different settings of the knob weights. Some settings are fragile: a tiny error in the model or in the weights moves the settling behaviour a lot. Others are robust. The method looks at the modes of the closed loop, the directions in which the state settles. Fragile settings have modes that point in almost the same direction. The method changes one mode direction at a time and turns it as far as it can from the others, within the directions the knobs allow. When no mode can be turned further, it computes the knob weights for these directions. The settling rates stay exactly as the designer asked.

The problem

Input: A∈Rn×nA \in \mathbb{R}^{n \times n}, B∈Rn×mB \in \mathbb{R}^{n \times m} of rank mm with (A,B)(A, B) controllable, and nn numbers λ1,…,λn\lambda_1, \dots, \lambda_n, closed under complex conjugation. Output: a real K∈Rm×nK \in \mathbb{R}^{m \times n} and an invertible XX with unit columns such that (A−BK)X=XΛ(A - BK) X = X \Lambda, Λ=diag⁡(λj)\Lambda = \operatorname{diag}(\lambda_j), and with a small 2-norm condition number κ2(X)=∥X∥2∥X−1∥2\kappa_2(X) = \|X\|_2 \|X^{-1}\|_2.

The measure comes from the Bauer-Fike theorem: if A−BKA - BK changes by Δ\Delta, every eigenvalue of the changed matrix lies within κ2(X)∥Δ∥2\kappa_2(X) \|\Delta\|_2 of some λj\lambda_j. The eigenvalue condition numbers of the single λj\lambda_j are also bounded by κ2(X)\kappa_2(X). A small κ2(X)\kappa_2(X) also tends to give a smaller ∥K∥\|K\|, because K=Z−1U0T(A−XΛX−1)K = Z^{-1} U_0^T (A - X \Lambda X^{-1}) and ∥XΛX−1∥2≤κ2(X)max⁡j∣λj∣\|X \Lambda X^{-1}\|_2 \le \kappa_2(X) \max_j |\lambda_j|.

The algorithm

  1. KNV0(A, B, λ_1..λ_n)
  2. 1B = [U_0, U_1] [Z; 0] ▷ QR of B; Z is m by m, invertible
  3. 2for each j: S_j ← orthonormal basis of null(U_1^T (A - λ_j I)) ▷ n by m
  4. 3for each j: x_j ← unit vector in range S_j (from a fixed random start)
  5. 4repeat sweeps until κ_2(X) stops falling:
  6. 5for each j: y_j ← unit vector orthogonal to all x_i with i ≠ j
  7. 6x_j ← S_j S_j^H y_j, normalized
  8. 7M ← X Λ X^(-1)
  9. 8return K = Z^(-1) U_0^T (A - M)

Line L1 splits the state space into the range of BB, spanned by U0U_0, and its orthogonal complement, spanned by U1U_1. Line L2 finds, for each wanted eigenvalue, all vectors that can be eigenvectors for it: xx is one exactly when (A−λjI)x(A - \lambda_j I) x lies in the range of BB, that is, when U1T(A−λjI)x=0U_1^T (A - \lambda_j I) x = 0. Lines L5 and L6 replace one eigenvector by the unit vector of SjS_j that is closest to the normal yjy_j of the other columns. For a complex pair, the code updates the member with positive imaginary part and sets its partner to the complex conjugate, so that KK is real. Lines L7 and L8 solve BK=A−XΛX−1BK = A - X \Lambda X^{-1} for KK.

Example

Take

A=[010000100001−120−1],B=[00100001],A = \begin{bmatrix} 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \\ -1 & 2 & 0 & -1 \end{bmatrix}, \qquad B = \begin{bmatrix} 0 & 0 \\ 1 & 0 \\ 0 & 0 \\ 0 & 1 \end{bmatrix},

and the poles −1,−2,−3,−4-1, -2, -3, -4. The code returns

K=[7.94525.97810.4796−0.2082−1.52041.79183.05483.0219],K = \begin{bmatrix} 7.9452 & 5.9781 & 0.4796 & -0.2082 \\ -1.5204 & 1.7918 & 3.0548 & 3.0219 \end{bmatrix},

with κ2(X)=9.11\kappa_2(X) = 9.11 and ∥K∥2=9.96\|K\|_2 = 9.96. The eigenvalues of A−BKA - BK agree with the wanted ones to about 10−1410^{-14}.

A rank-one design uses one direction of the inputs: set u=−v k xu = -v\, k\, x, with kk from Ackermann's formula for the single-input pair (A,Bv)(A, Bv). For the same poles:

design κ2(X)\kappa_2(X) ∥K∥2\|K\|_2
KNV method 0 9.11 9.96
rank one, v=(1,1)v = (1, 1) 224 43.1
rank one, v=(0,1)v = (0, 1) 595 67.4
rank one, v=(1,0)v = (1, 0) 860 81.6

All four gains place the same eigenvalues. The KNV gain is the smallest, and its eigenvalues are about 25 to 95 times less sensitive by the Bauer-Fike bound.

Correctness

The full proof is in proofs/correctness.md. It has three parts.

  • The gain. For an invertible XX with unit columns, there is a KK with (A−BK)X=XΛ(A - BK)X = X\Lambda if and only if every column xjx_j lies in range SjS_j, and then KK is the matrix of line L8. Multiply BK=A−XΛX−1BK = A - X\Lambda X^{-1} on the left by [U0,U1]T[U_0, U_1]^T: the top block gives ZK=U0T(A−XΛX−1)ZK = U_0^T(A - X\Lambda X^{-1}), and the bottom block is the condition U1T(A−λjI)xj=0U_1^T(A - \lambda_j I)x_j = 0.
  • The subspaces. If (A,B)(A, B) is controllable, each SjS_j has dimension exactly mm. This follows from the Popov-Belevitch-Hautus test: rank⁡[A−λI,B]=m+rank⁡U1T(A−λI)\operatorname{rank}[A - \lambda I, B] = m + \operatorname{rank} U_1^T (A - \lambda I).
  • The sweep. If every other column is fixed, ∣det⁡X∣=∣yjHxj∣⋅∣det⁡[…,yj,… ]∣|\det X| = |y_j^H x_j| \cdot |\det [\dots, y_j, \dots]|, and line L6 maximizes ∣yjHxj∣|y_j^H x_j| over unit vectors of range SjS_j by the Cauchy-Schwarz inequality. So for real eigenvalues no step decreases ∣det⁡X∣|\det X|. By Hadamard's inequality ∣det⁡X∣≤1|\det X| \le 1, with equality only for orthonormal columns, so the sweep pushes XX towards orthogonality.

If the poles are closed under conjugation and the conjugate columns are conjugate, XΛX−1X \Lambda X^{-1} is real, so KK is real.

Proof: Every eigenvector matrix built from the subspaces S_j gives a real gain with the wanted poles, and method 0 does not decrease the determinantfull

Let A∈Rn×nA \in \mathbb{R}^{n \times n} and B∈Rn×mB \in \mathbb{R}^{n \times m} with rank mm. Line L1 gives an orthogonal matrix [U0,U1][U_0, U_1] and an invertible Z∈Rm×mZ \in \mathbb{R}^{m \times m} with B=U0ZB = U_0 Z; the columns of U0U_0 span the range of BB, and U1U_1 has n−mn - m columns. For a number λ\lambda, let S(λ)={x∈Cn:U1T(A−λI)x=0}\mathcal{S}(\lambda) = \{x \in \mathbb{C}^n : U_1^T (A - \lambda I) x = 0\}. Line L2 computes an orthonormal basis SjS_j of S(λj)\mathcal{S}(\lambda_j). Write X=[x1,…,xn]X = [x_1, \dots, x_n] and Λ=diag⁡(λ1,…,λn)\Lambda = \operatorname{diag}(\lambda_1, \dots, \lambda_n).

Lemma 1: which eigenvector matrices are possible

Let XX be invertible. There is a K∈Cm×nK \in \mathbb{C}^{m \times n} with (A−BK)X=XΛ(A - BK) X = X \Lambda if and only if xj∈S(λj)x_j \in \mathcal{S}(\lambda_j) for every jj. In that case KK is unique and equals Z−1U0T(A−XΛX−1)Z^{-1} U_0^T (A - X \Lambda X^{-1}).

Proof. Let M=XΛX−1M = X \Lambda X^{-1}. The equation (A−BK)X=XΛ(A - BK)X = X\Lambda is the same as BK=A−MBK = A - M, because XX is invertible. Since [U0,U1][U_0, U_1] is orthogonal, this equation holds if and only if it holds after multiplication on the left by [U0,U1]T[U_0, U_1]^T. With U0TB=ZU_0^T B = Z and U1TB=0U_1^T B = 0, it splits into

ZK=U0T(A−M),0=U1T(A−M).Z K = U_0^T (A - M), \qquad 0 = U_1^T (A - M).

The first equation has the unique solution K=Z−1U0T(A−M)K = Z^{-1} U_0^T (A - M). The second equation holds if and only if U1T(A−M)X=0U_1^T (A - M) X = 0, because XX is invertible. Its column jj is U1T(Axj−λjxj)=0U_1^T (A x_j - \lambda_j x_j) = 0, that is, xj∈S(λj)x_j \in \mathcal{S}(\lambda_j). □\square

Lemma 2: the dimension of the subspaces

rank⁡[A−λI,B]=m+rank⁡U1T(A−λI)\operatorname{rank} [A - \lambda I, B] = m + \operatorname{rank} U_1^T (A - \lambda I) for every λ∈C\lambda \in \mathbb{C}. So if (A,B)(A, B) is controllable, every S(λ)\mathcal{S}(\lambda) has dimension mm.

Proof. Multiplication on the left by the invertible matrix [U0,U1]T[U_0, U_1]^T does not change the rank, and gives

[U0T(A−λI)ZU1T(A−λI)0].\begin{bmatrix} U_0^T (A - \lambda I) & Z \\ U_1^T (A - \lambda I) & 0 \end{bmatrix}.

Because ZZ is invertible, column operations with the last mm columns remove the block U0T(A−λI)U_0^T (A - \lambda I) without changing the rank. The result is block diagonal up to the order of the blocks, with rank m+rank⁡U1T(A−λI)m + \operatorname{rank} U_1^T(A - \lambda I). By the Popov-Belevitch-Hautus test, (A,B)(A, B) is controllable if and only if the left side is nn for every λ\lambda. Then U1T(A−λI)U_1^T(A - \lambda I), an (n−m)×n(n - m) \times n matrix, has rank n−mn - m, and its null space S(λ)\mathcal{S}(\lambda) has dimension mm. □\square

Lemma 3: the update does not decrease the determinant

Fix all columns of XX except column jj. Let XjX_j be the matrix of the other n−1n - 1 columns, assume they are independent, and let yjy_j be a unit vector with yjHxi=0y_j^H x_i = 0 for all i≠ji \ne j (line L5). Among the unit vectors x∈S(λj)x \in \mathcal{S}(\lambda_j), the vector x∗=Pyj/∥Pyj∥x^\ast = P y_j / \|P y_j\|, where P=SjSjHP = S_j S_j^H is the orthogonal projector onto S(λj)\mathcal{S}(\lambda_j), maximizes ∣det⁡X∣|\det X|, if Pyj≠0P y_j \ne 0.

Proof. Write any xx as x=(yjHx)yj+wx = (y_j^H x) y_j + w, with ww in the span of the other columns, since yjy_j and these columns together span Cn\mathbb{C}^n and yjy_j is orthogonal to them. The determinant is linear in column jj and vanishes when column jj is a combination of the other columns, so det⁡X=(yjHx)det⁡X(y)\det X = (y_j^H x) \det X^{(y)}, where X(y)X^{(y)} is XX with column jj replaced by yjy_j. The factor det⁡X(y)\det X^{(y)} does not depend on xx. For a unit vector x∈S(λj)x \in \mathcal{S}(\lambda_j), x=Pxx = Px, so yjHx=yjHPx=(Pyj)Hxy_j^H x = y_j^H P x = (P y_j)^H x, and by the Cauchy-Schwarz inequality ∣yjHx∣≤∥Pyj∥|y_j^H x| \le \|P y_j\|, with equality at x=x∗x = x^\ast. □\square

The old column xjx_j is one of the admissible vectors, so the update of line L6 never decreases ∣det⁡X∣|\det X| when only one column changes. This is the case for every real λj\lambda_j. For a complex pair the code changes two columns, xjx_j and its conjugate, and this argument does not apply. Hadamard's inequality gives ∣det⁡X∣≤∏i∥xi∥=1|\det X| \le \prod_i \|x_i\| = 1, with equality if and only if the columns are orthonormal, so for real poles the values of ∣det⁡X∣|\det X| form a bounded nondecreasing sequence and converge. This proves nothing about the limit of XX itself; the code only uses it as a heuristic and keeps the matrix with the smallest κ2(X)\kappa_2(X) that it has seen.

Lemma 4: the gain is real

Assume that the poles are closed under conjugation, that U0,U1,ZU_0, U_1, Z are real, and that for every complex pair λk=λˉj\lambda_k = \bar\lambda_j the code sets xk=xˉjx_k = \bar x_j. Then XΛX−1X \Lambda X^{-1} and KK are real.

Proof. Let Π\Pi be the permutation matrix that swaps the columns of each complex pair and fixes the others. Then Xˉ=XΠ\bar X = X \Pi and Λˉ=ΠΛΠ\bar\Lambda = \Pi \Lambda \Pi, with Π−1=Π\Pi^{-1} = \Pi. So

XΛX−1‾=XΠ ΠΛΠ Π−1X−1=XΛX−1.\overline{X \Lambda X^{-1}} = X \Pi\, \Pi \Lambda \Pi\, \Pi^{-1} X^{-1} = X \Lambda X^{-1}.

Then K=Z−1U0T(A−XΛX−1)K = Z^{-1} U_0^T (A - X\Lambda X^{-1}) is a product of real matrices. Also xˉj∈S(λˉj)\bar x_j \in \mathcal{S}(\bar\lambda_j) whenever xj∈S(λj)x_j \in \mathcal{S}(\lambda_j), because U1U_1 and AA are real; so the conjugate columns satisfy the condition of Lemma 1. □\square

Theorem

If (A,B)(A, B) is controllable, the poles are distinct and closed under conjugation, and the final XX is invertible, then the gain KK of line L8 is real and (A−BK)X=XΛ(A - BK) X = X\Lambda. So the eigenvalues of A−BKA - BK are exactly λ1,…,λn\lambda_1, \dots, \lambda_n, with the columns of XX as eigenvectors.

Proof. Every column that the code ever stores is a vector of the form SjcS_j c, from line L3 or line L6, or the conjugate of one; so xj∈S(λj)x_j \in \mathcal{S}(\lambda_j) for all jj. Lemma 1 gives (A−BK)X=XΛ(A - BK)X = X\Lambda for the gain of line L8, and Lemma 4 shows that it is real. An n×nn \times n matrix with nn independent eigenvectors for the eigenvalues λj\lambda_j has exactly these eigenvalues. □\square

The code raises an error if the final κ2(X)\kappa_2(X) exceeds 101210^{12}, so it never returns a gain from a numerically singular XX. If (A,B)(A, B) is not controllable and an uncontrollable eigenvalue of AA is not among the λj\lambda_j, no invertible XX with xj∈S(λj)x_j \in \mathcal{S}(\lambda_j) exists: by Lemma 1 it would give a gain that moves an uncontrollable eigenvalue, which the pole placement theorem excludes. Every XX the code builds is then singular, and the test reports it, up to rounding error. In floating point all equalities above hold up to rounding error; the tests check the residual ∥(A−BK)X−XΛ∥\|(A - BK) X - X \Lambda\| and the characteristic polynomial of A−BKA - BK.

Complexity

In the floating-point model: line L1 costs O(n2m)O(n^2 m). Line L2 costs O(n3)O(n^3) for each jj, O(n4)O(n^4) in total, and stores nn bases of size n×mn \times m, which is the O(n2m)O(n^2 m) extra space. In this implementation each step of line L5 orthogonalizes n−1n - 1 columns, O(n3)O(n^3), so a sweep costs O(n4)O(n^4); with updates of a QR factorization of XX a sweep costs O(n3)O(n^3). Lines L7 and L8 cost O(n3)O(n^3). The code stops when a sweep does not lower κ2(X)\kappa_2(X), or after a fixed number of sweeps; no general bound on the number of sweeps is known.

Rounding errors in lines L7 and L8 act like a small change Δ\Delta of the closed-loop matrix. By the Bauer-Fike theorem the placed eigenvalues then move by at most κ2(X)∥Δ∥2\kappa_2(X) \|\Delta\|_2. So a small κ2(X)\kappa_2(X) is both the robustness of the design and the accuracy of the computation.

Properties

  • Exact placement, approximate optimum. The eigenvalues are placed exactly in exact arithmetic for any choice of the xjx_j in range SjS_j. Only the conditioning is optimized, and only locally.
  • Monotone sweeps for real poles. Each step does not decrease ∣det⁡X∣|\det X|, so the values converge. Nothing guarantees that XX converges to a global maximum, or that κ2(X)\kappa_2(X) is minimal.
  • Single input. With m=1m = 1, each SjS_j is one line, XX is fixed by the poles, and the method returns the unique single-input gain, the same as Ackermann's formula in exact arithmetic.
  • Full input. With m=nm = n, Sj=RnS_j = \mathbb{R}^n, and for real poles one sweep gives an orthonormal XX with κ2(X)=1\kappa_2(X) = 1: each new column is orthogonal to all columns at the time of its update, and the later updates keep this.
  • Repeated poles. A pole can be repeated at most mm times with a diagonalizable closed loop, since its eigenvectors must be independent vectors of one mm-dimensional SjS_j. The full method allows this; the code on this page needs distinct poles.

Variants and improvements

  • Other KNV methods. The 1985 paper gives further methods with other update rules and other measures of conditioning.
  • Tits and Yang (1996). Maximize ∣det⁡X∣|\det X| directly, update two columns at a time, also for complex pairs, and prove that the iteration converges from any start. SciPy's place_poles uses this method by default and KNV method 0 as an option. MATLAB's place uses a KNV method.
  • Eigenstructure assignment. Choose the eigenvectors for other goals, such as decoupling of modes or the shape of the response, instead of conditioning.
  • Observer design. Apply the method to (AT,CT)(A^T, C^T) and set L=KTL = K^T to get a well conditioned Luenberger observer.
  • Optimal control instead. The infinite-horizon LQR chooses KK by a cost and gives guaranteed margins for state feedback. Pole placement with KNV gives the exact poles, LQR gives the margins.

When to use it

Use KNV, or the Tits-Yang method, whenever a multi-input system needs a pole placement gain computed in floating point. It is the default in the main control libraries. It is also the right choice when the rank-one approach gives a large gain or poles that move under small model errors. Do not expect it to make an ill posed design good: if the wanted poles are far from the open-loop ones, or if (A,B)(A, B) is close to an uncontrollable pair, every gain is large, and KNV only finds a less bad one.

Pitfalls

  • Robust poles are not a robust loop. A small κ2(X)\kappa_2(X) means that the eigenvalues move little under small changes of A−BKA - BK. It gives no gain margin or phase margin at the plant input, and it says nothing about unmodelled dynamics; see model uncertainty.
  • Repeated poles. Do not ask for a pole more than mm times; the closed loop then has a Jordan block, and its eigenvalue is very sensitive. Spread close poles a little instead.
  • Local optimum. The result depends on the starting XX. Try a few starts, or use the Tits-Yang method, when the conditioning matters.
  • Rank of BB. Remove dependent columns of BB first; the method needs ZZ invertible. A redundant input adds nothing to the freedom of XX.
  • Complex pairs. Give both members of a pair. The code checks this and rejects an unpaired complex pole.

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()
robust_pole_placement.py 251 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/robust-pole-placement/. The authors are listed in prov/PCC8GC.jsonl.

"""Robust pole placement by the Kautsky-Nichols-Van Dooren method 0.

Given x' = A x + B u with m inputs (rank B = m) and n wanted closed-loop
eigenvalues, find K with u = -K x so that A - B K has these eigenvalues and
a well conditioned matrix X of eigenvectors.

Steps:
- QR of B: B = U0 Z with [U0, U1] orthogonal and Z invertible.
- For each eigenvalue lambda_j, S_j is an orthonormal basis of the null
  space of U1^T (A - lambda_j I). Every eigenvector of A - B K for lambda_j
  lies in range S_j, and every vector of range S_j is such an eigenvector
  for a suitable K.
- Method 0: sweep over j. Replace x_j by the normalized projection onto
  range S_j of a unit vector y_j orthogonal to all other columns of X. For
  real eigenvalues each such step does not decrease |det X| when the
  columns have unit length.
- K = Z^(-1) U0^T (A - X Lambda X^(-1)).

This implementation needs distinct eigenvalues, closed under complex
conjugation. For a complex pair it updates the member with positive
imaginary part and sets the other column to its conjugate, so K is real.
It is a plain version of method 0 for teaching; it is not the full KNV
algorithm with repeated eigenvalues and the real treatment of complex
pairs. Computation is in floating point (complex where needed).
"""

import random

from ctlmat import inv, mul, norm2, solve, transpose

__all__ = ["input_qr", "eigvec_subspace", "knv0", "eigvec_condition", "eigenvectors"]


def _cdot(x, y):
    """Return x^H y."""
    return sum(complex(a).conjugate() * b for a, b in zip(x, y))


def _cnorm(x):
    return sum(abs(v) ** 2 for v in x) ** 0.5


def _orthonormal_extend(vectors, n, total):
    """Gram-Schmidt the given vectors, then add unit vectors up to `total`.

    Returns (Q, R): Q is the orthonormal basis of the span of `vectors`
    (vectors with a tiny residual are dropped), R are the added vectors
    (orthonormal and orthogonal to Q). Two passes of orthogonalization keep
    the result orthonormal to rounding error.
    """
    basis = []

    def residual(v):
        r = [complex(a) for a in v]
        for _ in range(2):
            for q in basis:
                c = _cdot(q, r)
                r = [a - c * b for a, b in zip(r, q)]
        return r

    scale = max([_cnorm(v) for v in vectors] + [1.0])
    for v in vectors:
        r = residual(v)
        nr = _cnorm(r)
        if nr > 1e-10 * scale:
            basis.append([a / nr for a in r])
    q_count = len(basis)
    while len(basis) < total:
        best, best_norm = None, -1.0
        for i in range(n):
            e = [0.0] * n
            e[i] = 1.0
            r = residual(e)
            nr = _cnorm(r)
            if nr > best_norm:
                best, best_norm = r, nr
        basis.append([a / best_norm for a in best])
    return basis[:q_count], basis[q_count:]


def _real_if_close(vectors):
    out = []
    for v in vectors:
        if all(abs(complex(a).imag) <= 1e-14 for a in v):
            out.append([complex(a).real for a in v])
        else:
            out.append(v)
    return out


def input_qr(B):
    """Return (U0, U1, Z) with B = U0 Z, [U0, U1] orthogonal, Z m by m.

    U0 and U1 are lists of columns (each a flat list). Raises ValueError if
    B does not have full column rank.
    """
    n = len(B)
    m = len(B[0])
    cols = [[float(B[i][j]) for i in range(n)] for j in range(m)]
    q, rest = _orthonormal_extend(cols, n, n)
    if len(q) != m:
        raise ValueError("B must have full column rank")
    U0 = _real_if_close(q)
    U1 = _real_if_close(rest)
    Z = [[sum(U0[i][k] * cols[j][k] for k in range(n)) for j in range(m)] for i in range(m)]
    return U0, U1, Z


def eigvec_subspace(A, U1, lam):
    """Return an orthonormal basis (list of columns) of null(U1^T (A - lam I))."""
    n = len(A)
    rows = []
    for u in U1:
        row = [sum(u[k] * (A[k][j] - (lam if k == j else 0)) for k in range(n)) for j in range(n)]
        rows.append(row)
    conj_rows = [[complex(v).conjugate() for v in r] for r in rows]
    q, null = _orthonormal_extend(conj_rows, n, n)
    return null


def _orth_to_others(X, j, n):
    others = [X[i] for i in range(len(X)) if i != j]
    _, rest = _orthonormal_extend(others, n, len(others) + 1)
    return rest[0]


def _project(S, y):
    coeffs = [_cdot(s, y) for s in S]
    x = [sum(c * s[i] for c, s in zip(coeffs, S)) for i in range(len(y))]
    return x


def eigvec_condition(X):
    """Return the 2-norm condition number of the matrix with columns X."""
    M = transpose(X)
    return norm2(M) * norm2(inv(M))


def _pairs(poles):
    """Return the indices of the poles to update and the partner index of each."""
    n = len(poles)
    used = [False] * n
    leaders = []
    partner = [None] * n
    for i, p in enumerate(poles):
        if used[i]:
            continue
        p = complex(p)
        if abs(p.imag) <= 1e-14 * (1 + abs(p)):
            used[i] = True
            leaders.append(i)
            continue
        best = None
        for j in range(n):
            if not used[j] and j != i and abs(complex(poles[j]) - p.conjugate()) <= 1e-12 * (1 + abs(p)):
                best = j
                break
        if best is None:
            raise ValueError("complex poles must come in conjugate pairs")
        used[i] = used[best] = True
        lead, other = (i, best) if p.imag > 0 else (best, i)
        leaders.append(lead)
        partner[lead] = other
    return leaders, partner


def knv0(A, B, poles, sweeps=50, seed=0):
    """Return (K, X, cond): the gain, the eigenvector columns and cond_2(X).

    A is n by n, B is n by m with rank m, and poles is a list of n distinct
    numbers closed under conjugation. Raises ValueError if the poles are
    not distinct, if a complex pole has no partner, or if no independent
    eigenvectors are found (then (A, B) is not controllable at some pole).
    """
    n = len(A)
    if len(poles) != n:
        raise ValueError("give exactly n poles")
    for i in range(n):
        for j in range(i + 1, n):
            if abs(complex(poles[i]) - complex(poles[j])) <= 1e-12 * (1 + abs(complex(poles[i]))):
                raise ValueError("this implementation needs distinct poles")
    leaders, partner = _pairs(poles)
    lam = [complex(p) if abs(complex(p).imag) > 0 else float(complex(p).real) for p in poles]
    U0, U1, Z = input_qr(B)  # @line L1
    S = [eigvec_subspace(A, U1, l) for l in lam]  # @line L2
    rng = random.Random(seed)
    X = [None] * n
    for j in leaders:  # @line L3
        y = [rng.uniform(-1, 1) for _ in range(n)]
        x = _project(S[j], y)
        nx = _cnorm(x)
        X[j] = [v / nx for v in x]
        if partner[j] is not None:
            X[partner[j]] = [complex(v).conjugate() for v in X[j]]
    best, best_X = eigvec_condition(X), [list(c) for c in X]
    for _ in range(sweeps):  # @line L4
        for j in leaders:
            y = _orth_to_others(X, j, n)  # @line L5
            x = _project(S[j], y)  # @line L6
            nx = _cnorm(x)
            if nx < 1e-12:
                continue
            X[j] = [v / nx for v in x]
            if partner[j] is not None:
                X[partner[j]] = [complex(v).conjugate() for v in X[j]]
        c = eigvec_condition(X)
        if c >= best * (1 - 1e-9):
            if c < best:
                best, best_X = c, [list(col) for col in X]
            break
        best, best_X = c, [list(col) for col in X]
    X, cond = best_X, best
    if cond > 1e12:
        raise ValueError("no independent eigenvectors found; (A, B) may be uncontrollable")
    Xm = transpose(X)
    XL = [[Xm[i][j] * lam[j] for j in range(n)] for i in range(n)]
    # M = X Lambda X^(-1), computed as the solution of X^T M^T = (X Lambda)^T.
    M = transpose(solve(transpose(Xm), transpose(XL)))  # @line L7
    D = [[A[i][j] - M[i][j] for j in range(n)] for i in range(n)]
    # U0, a list of columns, read as a list of rows is the matrix U0^T.
    Kc = solve(Z, mul(U0, D))  # @line L8
    big = max(1.0, max(abs(v) for row in Kc for v in row))
    if any(abs(complex(v).imag) > 1e-8 * big for row in Kc for v in row):
        raise ValueError("the gain is not real; check the conjugate pairs")
    K = [[complex(v).real for v in row] for row in Kc]
    return K, X, cond


def eigenvectors(Acl, poles, iters=3):
    """Return unit eigenvectors (columns) of Acl for the given simple poles.

    Uses inverse iteration with a small shift. For use on a closed loop from
    any method, so that conditions can be compared.
    """
    n = len(Acl)
    rng = random.Random(1)
    cols = []
    for lam in poles:
        lam = complex(lam)
        shift = lam + 1e-9 * (1 + abs(lam))
        M = [[complex(Acl[i][j]) - (shift if i == j else 0) for j in range(n)] for i in range(n)]
        x = [complex(rng.uniform(-1, 1)) for _ in range(n)]
        for _ in range(iters):
            x = solve(M, x)
            nx = _cnorm(x)
            x = [v / nx for v in x]
        cols.append(x)
    return cols
test_robust_pole_placement.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/robust-pole-placement/. The authors are listed in prov/PCC8GC.jsonl.

import random

import pytest

import ctlmat as cm
from robust_pole_placement import eigenvectors, eigvec_condition, eigvec_subspace, input_qr, knv0

A4 = [[0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], [-1.0, 2.0, 0.0, -1.0]]
B4 = [[0.0, 0.0], [1.0, 0.0], [0.0, 0.0], [0.0, 1.0]]
POLES4 = [-1.0, -2.0, -3.0, -4.0]


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


def residual(Acl, X, poles):
    """Return max over j of |Acl x_j - lambda_j x_j|."""
    worst = 0.0
    for x, lam in zip(X, poles):
        ax = cm.matvec(Acl, x)
        worst = max(worst, max(abs(a - lam * v) for a, v in zip(ax, x)))
    return worst


def ackermann_single(A, b, p):
    """Ackermann's formula, written out here as the reference gain."""
    n = len(A)
    cols = [list(b)]
    for _ in range(n - 1):
        cols.append(cm.matvec(A, cols[-1]))
    W = cm.transpose(cols)
    q = cm.solve(cm.transpose(W), [0.0] * (n - 1) + [1.0])
    K = [0.0] * n
    At = cm.transpose(A)
    for c in p:
        K = [x + c * y for x, y in zip(cm.matvec(At, K), q)]
    return K


def poly_from_roots(roots):
    p = [1.0]
    for r in roots:
        p = cm.polymul(p, [1.0, -r])
    return [complex(c).real for c in p]


def check_placement(A, B, poles, K, X, tol=1e-8):
    Acl = closed_loop(A, B, K)
    assert residual(Acl, X, poles) < tol * (1 + max(abs(v) for r in Acl for v in r))
    got = cm.charpoly(Acl)
    want = poly_from_roots(poles)
    for g, w in zip(got, want):
        assert abs(g - w) < 1e-7 * (1 + abs(w))


def test_stated_example_beats_rank_one_ackermann():
    K, X, cond = knv0(A4, B4, POLES4)
    check_placement(A4, B4, POLES4, K, X)
    roots = cm.polyroots(cm.charpoly(closed_loop(A4, B4, K)))
    for r, w in zip(roots, sorted(POLES4)):
        assert abs(r - w) < 1e-8
    # Rank-one design: u = -v k x with b = B v and k from Ackermann.
    for v in ([1.0, 1.0], [1.0, 0.0], [0.0, 1.0]):
        b = cm.matvec(B4, v)
        k = ackermann_single(A4, b, poly_from_roots(POLES4))
        Kr = [[vi * kj for kj in k] for vi in v]
        Acl = closed_loop(A4, B4, Kr)
        Xr = eigenvectors(Acl, POLES4)
        assert residual(Acl, Xr, POLES4) < 1e-6
        assert cond <= eigvec_condition(Xr)
        assert cm.norm2(K) <= cm.norm2(Kr)
    assert cond < 10.0


def test_identity_input_gives_orthonormal_eigenvectors():
    rng = random.Random(5)
    n = 4
    A = [[rng.uniform(-2, 2) for _ in range(n)] for _ in range(n)]
    B = cm.eye(n)
    poles = [-1.0, -2.0, -3.0, -5.0]
    K, X, cond = knv0(A, [[float(v) for v in r] for r in B], poles)
    check_placement(A, B, poles, K, X)
    assert cond < 1 + 1e-6


def test_random_systems_real_and_complex():
    rng = random.Random(7)
    for trial in range(8):
        n = rng.randint(3, 6)
        m = rng.randint(2, min(3, n))
        A = [[rng.uniform(-2, 2) for _ in range(n)] for _ in range(n)]
        B = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(n)]
        poles = [-(1.0 + i) for i in range(n)]
        if trial % 2 == 1:
            poles[0] = complex(-1.0, 1.5)
            poles[1] = complex(-1.0, -1.5)
        K, X, cond = knv0(A, B, poles, seed=trial)
        assert all(isinstance(v, float) for row in K for v in row)
        check_placement(A, B, poles, K, X, tol=1e-7)


def test_sweeps_do_not_increase_condition():
    rng = random.Random(11)
    A = [[rng.uniform(-2, 2) for _ in range(5)] for _ in range(5)]
    B = [[rng.uniform(-1, 1) for _ in range(2)] for _ in range(5)]
    poles = [-1.0, -2.0, -3.0, -4.0, -5.0]
    _, _, c0 = knv0(A, B, poles, sweeps=0)
    _, _, c1 = knv0(A, B, poles, sweeps=1)
    _, _, c9 = knv0(A, B, poles, sweeps=20)
    assert c9 <= c1 <= c0


def test_subspace_dimension_and_property():
    U0, U1, Z = input_qr(B4)
    assert len(U0) == 2 and len(U1) == 2
    Bq = cm.mul(cm.transpose(U0), Z)
    assert max(abs(x - y) for r, s in zip(Bq, B4) for x, y in zip(r, s)) < 1e-14
    for lam in (-1.0, complex(-2.0, 1.0)):
        S = eigvec_subspace(A4, U1, lam)
        assert len(S) == 2
        for s in S:
            v = [sum(A4[i][j] * s[j] for j in range(4)) - lam * s[i] for i in range(4)]
            for u in U1:
                assert abs(sum(a * b for a, b in zip(u, v))) < 1e-12


def test_rejections():
    with pytest.raises(ValueError):
        knv0(A4, B4, [-1.0, -1.0, -2.0, -3.0])
    with pytest.raises(ValueError):
        knv0(A4, B4, [complex(-1.0, 1.0), -2.0, -3.0, -4.0])
    with pytest.raises(ValueError):
        knv0(A4, [[1.0, 2.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], POLES4)
    # Uncontrollable: the last state is decoupled from both inputs.
    A = [[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 2.0]]
    B = [[1.0, 0.0], [0.0, 1.0], [0.0, 0.0]]
    with pytest.raises(ValueError):
        knv0(A, B, [-1.0, -2.0, -3.0])

History

Kautsky, Nichols and Van Dooren (1985) showed that the choice of the eigenvectors decides the sensitivity of the placed poles, gave the parametrization of the possible eigenvectors by the subspaces SjS_j, and proposed iterative methods, method 0 among them, that make XX well conditioned. Their paper also showed the numerical problems of methods that go through canonical forms. Tits and Yang (1996) reformulated the problem as the maximization of ∣det⁡X∣|\det X|, extended the updates to complex pairs, and gave globally convergent algorithms. Mehrmann and Xu (1996, 1997) analysed the conditioning of the single-input and multi-input problems.

References

  1. 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 parametrization of the eigenvectors by the subspaces S_j, the formula for K, and method 0 with its column updates
  2. André L. Tits and Yaguang Yang, Globally convergent algorithms for robust pole assignment by state feedback, IEEE Transactions on Automatic Control 41(10), 1432-1452, 1996, the maximization of the absolute value of det X, its relation to method 0, and the treatment of complex conjugate pairs
  3. Volker Mehrmann and Hongguo Xu, An analysis of the pole placement problem II. The multi-input case, Electronic Transactions on Numerical Analysis 5, 77-97, 1997, the conditioning of the multi-input pole placement problem
  4. Chi-Tsong Chen, Linear System Theory and Design, third edition, Oxford University Press, 1999, 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