Algorithmadvanced
Ho-Kalman algorithm
Also called Ho-Kalman realization algorithm.
Builds a minimal state-space realization from exact Markov parameters by a rank factorization of their block Hankel matrix.
- Solves
- Realization problem
- Time
- O(N^2 m n p + n^3) worst
- Space
- O(N^2 m p) extra
- Where
- N = the number of block rows and block columns of the Hankel matrix; m = the number of inputs; n = the minimal order; p = the number of outputs
- Model
- Real RAM
- Properties
- deterministicexactoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- B. L. Ho, Rudolf E. Kalman, 1966
The Ho-Kalman algorithm takes the first Markov parameters of a discrete-time linear system and returns matrices of the smallest possible order that reproduce them. It puts the parameters in a block Hankel matrix, finds its rank by exact elimination, and reads the realization off an invertible submatrix. The realization problem is the task, the minimal realization theorem says that the answer is unique up to a change of coordinates, and Ho-Kalman is the exact construction for data without noise. For measured, noisy data use the eigensystem realization algorithm, which replaces the exact rank by a truncated singular value decomposition.
In plain words
Hit a system with a single short pulse and record the response at every sample. These numbers fix the input-output behaviour of the system, but they do not show its internal state. Write the numbers in a table where each row is the row above it moved one step to the left. A system with a small state can only make a few independent patterns, so the table has a low rank, and the rank is the number of state variables that you need. Pick that many independent rows and columns. A small square block of the table then gives the input map and the output map, and the same block taken from the table moved one step gives the state transition.
The problem
Input. Matrices of size , and the integer .
Precondition. Some state-space system of order at most has and for every . The system is , with , and .
Output. of the smallest order with and for every .
There is no page for the Hankel matrix, so here is the definition. The block Hankel matrix with block rows and block columns is
with block equal to . The shifted matrix has block equal to , so it uses .
The algorithm
HO-KALMAN(h, N)- 1
H ← the block Hankel matrix of h_1, ..., h_(2N-1) - 2
Hs ← the shifted block Hankel matrix of h_2, ..., h_(2N) - 3
J ← indices of a maximal set of independent columns of H; n ← |J| - 4
I ← indices of n independent rows of H[:, J] - 5
M ← H[I, J] - 6
A ← M⁻¹ Hs[I, J] - 7
B ← M⁻¹ H[I, 1:m] - 8
C ← H[1:p, J] - 9
D ← h_0 - 10
return (A, B, C, D)
L3 runs Gaussian elimination on and keeps a column when it is not a combination of the columns kept before it. The number of kept columns is the rank of , and Lemma 2 of the proof shows that this rank is the minimal order. L4 does the same on the rows of the matrix , so the matrix of L5 is invertible. L6 and L7 solve linear systems with ; they never form . L7 uses the first block column of , which holds , and L8 uses the first block row. With integer or rational data every step is exact in rational arithmetic.
Example
Take one input and one output () and the data
with . L1 and L2 give
has rank 2, so L3 and L4 keep both columns and both rows, and . Then
Check: , , and . The characteristic polynomial of is , so the poles are , and the realization predicts , which is the next value of the sequence . The test file checks the predicted values up to exactly in Fraction.
Correctness
Claim. Under the precondition, HO-KALMAN returns a realization of order , the minimal order, with for every , also for the that were not in the data.
Key invariant. For a minimal realization of order , and , where stacks and lines up for . Both factors have rank because a minimal realization is controllable and observable.
With and the selected block is , so both factors are invertible. The output is then , and , a change of coordinates of the minimal realization. The full proof is below.
Proof: The Ho-Kalman algorithm returns a minimal realization of the Markov parametersfull
We work in exact arithmetic, as in the real RAM (the implementation uses Fraction). The data are , matrices of size . The precondition is that some system of order has for every . Let be the minimal order of a realization of the sequence .
For a system of order write the -step observability and controllability matrices
is the block Hankel matrix of L1, with block equal to for . is the shifted matrix of L2, with block equal to . Both use only .
Lemma 1 (factorization). For every realization of the sequence, and .
Proof. Block of is . Block of is .
Lemma 2 (the rank is the minimal order). .
Proof. The precondition gives a realization of order at most , so . Take a minimal realization of order . A minimal realization is controllable and observable (the minimal realization theorem; otherwise the Kalman decomposition gives a realization of smaller order with the same Markov parameters). By the Kalman rank condition, the matrices with block rows and block columns already have rank , and , so has full column rank and has full row rank . For such a product, : the map is onto and is one to one. With Lemma 1, .
From now on fix this minimal realization, so is and is .
Lemma 3 (the selected blocks are invertible). L3 returns a set of column indices with of rank , and L4 returns a set of row indices with nonsingular. Let and , both . Then , and and are nonsingular.
Proof. The routine of L3 is Gaussian elimination: it keeps column exactly when column is not a linear combination of the columns kept before it. The kept columns are linearly independent, and every other column is a combination of them, so they span the column space and there are of them (Lemma 2). L4 applies the same routine to the rows of the matrix , which has rank , so it returns rows that form a nonsingular matrix . By Lemma 1, and . Since is nonsingular, .
Lemma 4 (the result is similar to the minimal realization). The matrices of L6 to L8 are , and .
Proof. By Lemma 1, . So L6 gives . The first columns of are , because the first block column of is . So L7 gives . The first rows of are , because the first block row of is . So L8 gives .
Theorem. Under the precondition, the Ho-Kalman algorithm returns of order , the minimal order, with for every (also for ) and .
Proof. By Lemma 4, for every . L9 sets . The order is by Lemma 3, and no realization has a smaller order by the definition of .
Remark (uniqueness). Any two minimal realizations are similar (the minimal realization theorem), so the result differs from every other minimal realization by a change of state coordinates. The choice of and only selects the coordinates: the state of the result is times the state of .
Remark (the precondition). Without a realization of order at most , the rank of can be smaller than the minimal order of the whole sequence, and Lemma 2 fails. Example: , , has , , . With the algorithm returns the order 1 system , , . It matches and , but it gives for . The test test_too_few_block_rows_fails checks this case.
Complexity
In the real RAM, with exact arithmetic. L1 and L2 copy numbers. L3 eliminates on the matrix ; each of the pivots updates entries, and the search for pivots in the other columns costs in total, so L3 costs . L4 eliminates on an matrix in . L6 and L7 factor once in and solve for right-hand sides in . The total is , which is because . The extra space is for and .
With rational data the numbers in the elimination can grow; the operation count above does not include the bit length. In floating point, the rank decision of L3 needs a tolerance and becomes the weak point (see Pitfalls).
Properties
- Minimal (theorem). The order of the result is the rank of , and under the precondition this is the minimal order (Ho and Kalman 1966).
- Exact extrapolation (theorem). The result reproduces every Markov parameter, not only the that were used.
- Unique up to coordinates (theorem). Any other choice of and gives a similar realization, because all minimal realizations are similar.
- Enough data (theorem). If the order is at most , then is enough, so Markov parameters fix the whole sequence.
- Not robust to noise. The rank of a matrix is not a continuous function of its entries. Any noise makes generically of full rank.
Variants and improvements
- Eigensystem realization algorithm. Replace L3 to L5 by a singular value decomposition of and keep the largest singular values. This gives a balanced realization on exact data and a good approximation on noisy data.
- Kung's method. The same SVD idea, published for signal processing in 1978, with the shift structure of the observability factor used to find .
- Rectangular Hankel matrices. Use block rows and block columns with . The proof does not change.
- Partial realization. When the sequence is only known up to and no order is given, the minimal partial realization problem asks for the smallest system that matches the given terms. The Berlekamp-Massey algorithm solves the scalar case.
- From input-output data. Estimate the Markov parameters first, for example by an FIR fit, or skip them and use subspace identification.
When to use it
Use it when the Markov parameters are exact: symbolic models, rational data, the conversion of a transfer function or an FIR model to state-space form, and teaching. It also checks other methods: on exact data, ERA and subspace methods must give a system similar to the Ho-Kalman result. For measured impulse responses, use ERA.
Pitfalls
- Too few block rows. If is smaller than the order, the rank of can be smaller than the order and the result is wrong after the data. For with the algorithm returns , , , which matches and but predicts instead of .
- Floating-point rank decisions. In floating point, a pivot of can be noise or a real small mode. The result depends on a threshold that the algorithm does not give. Use the SVD of ERA, which shows the gap in the singular values.
- Forgetting . is not in the Hankel matrix. A strictly proper model has ; a model with a direct feedthrough needs L9.
- Index shift. Block of is , starting at . If starts at , then enters the factorization and the rank is wrong.
- Continuous time. For the same construction works with the coefficients of the expansion at infinity. These are the derivatives of the impulse response at . They are not the samples of the impulse response, which are the Markov parameters of the discretized system.
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.
# 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()
ho_kalman_algorithm.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ho-kalman-algorithm/. The authors are listed in prov/A1602S.jsonl.
"""The Ho-Kalman algorithm: a minimal realization from Markov parameters.
Input: the Markov parameters h_0 = D and h_k = C A^(k-1) B for k = 1, ..., 2N
of a discrete-time system x_(k+1) = A x_k + B u_k, y_k = C x_k + D u_k, as a
list h of 2N + 1 matrices of size p by m (lists of rows), and the number N of
block rows and block columns of the Hankel matrix.
Precondition: the sequence has a realization of order at most N. Then the
rank n of the Hankel matrix is the minimal order, and the result (A, B, C, D)
is a minimal realization: C A^(k-1) B = h_k for every k >= 1, also beyond 2N.
The rank factorization picks n linearly independent columns J of the Hankel
matrix H and n linearly independent rows I of H[:, J]; then
A = M^-1 Hs[I, J], B = M^-1 H[I, 0:m], C = H[0:p, J], D = h_0,
with M = H[I, J] and Hs the shifted Hankel matrix. With int or Fraction data
every step is exact (Fraction).
Cost: O(N^2 p m n) operations for the rank decisions and O(n^3 + n^2 m) for
the solves, in the real RAM.
"""
from fractions import Fraction
from ctlmat import mat_power, mul, solve
__all__ = ["hankel", "independent_columns", "ho_kalman", "markov_parameters"]
def hankel(h, rows, cols, shift=0):
"""Return the block Hankel matrix whose block (i, j) is h[i + j + 1 + shift]."""
p, m = len(h[0]), len(h[0][0])
out = []
for i in range(rows):
for a in range(p):
line = []
for j in range(cols):
line.extend(h[i + j + 1 + shift][a])
out.append(line)
return out
def independent_columns(a):
"""Return the indices of the first linearly independent columns of a.
Exact Gaussian elimination in Fraction. Column j is taken when it is not a
linear combination of the columns taken before it. The number of indices
is the rank of a.
"""
rows = [[Fraction(v) for v in row] for row in a]
nr = len(rows)
nc = len(rows[0]) if rows else 0
picked = []
r = 0
for j in range(nc):
piv = next((i for i in range(r, nr) if rows[i][j] != 0), None)
if piv is None:
continue
rows[r], rows[piv] = rows[piv], rows[r]
for i in range(r + 1, nr):
f = rows[i][j] / rows[r][j]
if f:
for t in range(j, nc):
rows[i][t] -= f * rows[r][t]
picked.append(j)
r += 1
if r == nr:
break
return picked
def ho_kalman(h, N):
"""Return (A, B, C, D) of a minimal realization of h_0, ..., h_(2N)."""
if len(h) < 2 * N + 1:
raise ValueError("ho_kalman: need h_0, ..., h_(2N)")
p, m = len(h[0]), len(h[0][0])
H = hankel(h, N, N) # @line L1
Hs = hankel(h, N, N, shift=1) # @line L2
J = independent_columns(H) # @line L3
n = len(J)
HJ = [[row[j] for j in J] for row in H]
I = independent_columns([list(col) for col in zip(*HJ)]) # @line L4
M = [[H[i][j] for j in J] for i in I] # @line L5
A = solve(M, [[Hs[i][j] for j in J] for i in I]) # @line L6
B = solve(M, [[H[i][c] for c in range(m)] for i in I]) # @line L7
C = [[Fraction(H[a][j]) for j in J] for a in range(p)] # @line L8
D = [[Fraction(v) for v in row] for row in h[0]] # @line L9
assert len(A) == n
return A, B, C, D # @line L10
def markov_parameters(A, B, C, D, K):
"""Return [D, C B, C A B, ..., C A^(K-1) B]."""
out = [[list(row) for row in D]]
p, m = len(D), len(D[0])
for k in range(1, K + 1):
if not A: # order 0: every Markov parameter is zero
out.append([[0] * m for _ in range(p)])
else:
out.append(mul(mul(C, mat_power(A, k - 1)), B))
return out
test_ho_kalman_algorithm.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ho-kalman-algorithm/. The authors are listed in prov/A1602S.jsonl.
import random
from fractions import Fraction
from ctlmat import charpoly, mat_power, mul
from ho_kalman_algorithm import hankel, ho_kalman, independent_columns, markov_parameters
def _rank(a):
return len(independent_columns(a))
def _ctrb(A, B):
n = len(A)
blocks = [mul(mat_power(A, k), B) for k in range(n)]
return [sum((blk[i] for blk in blocks), []) for i in range(n)]
def _obsv(A, C):
n = len(A)
out = []
for k in range(n):
out.extend(mul(C, mat_power(A, k)))
return out
def test_worked_example():
q = Fraction
h = [[[1]], [[2]], [[0]], [[q(1, 2)]], [[0]], [[q(1, 8)]]]
assert hankel(h, 2, 2) == [[2, 0], [0, q(1, 2)]]
A, B, C, D = ho_kalman(h, 2)
assert A == [[0, q(1, 4)], [1, 0]]
assert B == [[1], [0]]
assert C == [[2, 0]]
assert D == [[1]]
assert charpoly(A) == [1, 0, q(-1, 4)]
# h_k = (1/2)^(k-1) + (-1/2)^(k-1) holds beyond the data
hk = markov_parameters(A, B, C, D, 10)
for k in range(1, 11):
assert hk[k] == [[q(1, 2) ** (k - 1) + q(-1, 2) ** (k - 1)]]
def _random_system(rng, n, m, p):
A = [[Fraction(rng.randint(-4, 4), 4) for _ in range(n)] for _ in range(n)]
B = [[rng.randint(-2, 2) for _ in range(m)] for _ in range(n)]
C = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(p)]
D = [[rng.randint(-1, 1) for _ in range(m)] for _ in range(p)]
return A, B, C, D
def test_random_mimo_exact():
rng = random.Random(4)
done = 0
for _ in range(40):
n, m, p = rng.randint(1, 4), rng.randint(1, 2), rng.randint(1, 2)
A0, B0, C0, D0 = _random_system(rng, n, m, p)
N = n
h = markov_parameters(A0, B0, C0, D0, 2 * N)
A, B, C, D = ho_kalman(h, N)
# the order is the rank of the Hankel matrix, at most n
n_min = _rank(hankel(h, N, N))
assert len(A) == n_min <= n
# all Markov parameters agree, also far beyond the 2N that were used
assert markov_parameters(A, B, C, D, 3 * N + 4) == markov_parameters(A0, B0, C0, D0, 3 * N + 4)
# a controllable and observable system gives the same order and the same poles
if _rank(_ctrb(A0, B0)) == n and _rank(_obsv(A0, C0)) == n:
assert len(A) == n
assert charpoly(A) == charpoly(A0)
done += 1
assert done >= 10
def test_non_minimal_system_is_reduced():
# the second state is not controllable, the third is not observable
A = [[Fraction(1, 2), 0, 0], [0, Fraction(1, 3), 0], [0, 0, Fraction(-1, 5)]]
B = [[1], [0], [1]]
C = [[1, 1, 0]]
D = [[0]]
h = markov_parameters(A, B, C, D, 6)
Ar, Br, Cr, Dr = ho_kalman(h, 3)
assert Ar == [[Fraction(1, 2)]]
assert markov_parameters(Ar, Br, Cr, Dr, 12) == markov_parameters(A, B, C, D, 12)
def test_too_few_block_rows_fails():
# order 2, but N = 1: the result reproduces h_1 and h_2 only
q = Fraction
A0 = [[q(1, 2), 0], [0, q(-1, 2)]]
B0 = [[1], [1]]
C0 = [[1, 1]]
D0 = [[0]]
h = markov_parameters(A0, B0, C0, D0, 2)
A, B, C, D = ho_kalman(h, 1)
assert len(A) == 1
assert A == [[0]]
assert markov_parameters(A, B, C, D, 2) == h
assert markov_parameters(A, B, C, D, 3)[3] == [[0]]
assert markov_parameters(A0, B0, C0, D0, 3)[3] == [[Fraction(1, 2)]]
def test_independent_columns_against_brute_force():
rng = random.Random(9)
from itertools import combinations
from ctlmat import det
for _ in range(30):
r, c = rng.randint(1, 4), rng.randint(1, 4)
a = [[rng.randint(-1, 1) for _ in range(c)] for _ in range(r)]
rank = 0
for k in range(1, min(r, c) + 1):
if any(det([[a[i][j] for j in cs] for i in rs]) != 0
for rs in combinations(range(r), k) for cs in combinations(range(c), k)):
rank = k
assert len(independent_columns(a)) == rank
History
Ho and Kalman published the construction in 1966 in Regelungstechnik, in a paper on the effective construction of linear state-variable models from input-output functions. They showed that the rank of the block Hankel matrix of the Markov parameters is the dimension of a minimal realization, and they built the realization from a factorization of that matrix. The idea that a rational transfer function gives a Hankel matrix of finite rank is older, and goes back to Kronecker's work on rational functions in the nineteenth century. In the 1970s Kung, Zeiger and McEwen, and later Juang and Pappa in 1985, replaced the exact rank by a singular value decomposition, so that the method could use measured data.
References
- B. L. Ho and Rudolf E. Kalman, Effective construction of linear state-variable models from input/output functions, Regelungstechnik 14(1-12), 545-548, 1966, the rank of the block Hankel matrix as the minimal order, and the construction of the realization from it
- Chi-Tsong Chen, Linear System Theory and Design, third edition, Oxford University Press, 1999, Chapter 7 (minimal realizations), the section on realization from Markov parameters
- Jer-Nan Juang, Applied System Identification, Prentice Hall, 1994, the chapter on system realization (the Ho-Kalman construction as the noise-free case of ERA)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag A1602S Edit this page History Report an error Markdown