Algorithmcore
Zero-order hold discretization
Also called ZOH discretization, step-invariant discretization.
Turns a continuous LTI system into the exact discrete one for inputs held constant between samples, with A_d = e^(Ah).
- Time
- O((n + m)^3 (s + 1)) worst
- Space
- O((n + m)^2) extra
- Where
- m = the number of inputs; n = the number of states; s = the number of squarings in the matrix exponential
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Charles F. Van Loan, 1978
Zero-order hold (ZOH) discretization turns the continuous linear time-invariant model , into the discrete model , , with and , for the sampling period . The discrete model is exact, not an approximation: if the input is held constant between samples, equals the continuous state for every . One matrix exponential of the block matrix gives both matrices (Van Loan 1978). It differs from controller discretization by Tustin or matched poles, which approximate a continuous controller, and from the bilinear transform, which is an approximate map of to .
In plain words
A computer controls a physical system. At each tick of its clock it reads the sensors, computes a new command, and sends it to a device that keeps that command fixed until the next tick. Between two ticks the system therefore moves under a constant push. For a linear system, the move over one tick depends only on where the system started and on the size of the push, and both effects are linear. This method computes the two matrices that describe that one-tick move. With these matrices, the computer sees the system as a simple step-by-step rule that gives the correct state at every tick. The model says nothing about the motion between ticks; for that you need the continuous model.
The problem
Input: , and a sampling period . Output: and such that every solution of with a zero-order hold input, for , satisfies for all , all initial states and all input sequences.
The output matrices and do not change, because when the output is read at the sampling instant. Both matrices are unique: the solution over one period is linear in , and its matrix is fixed by the plant (see variation of constants formula). Notation follows the state-space representation page.
The algorithm
ZOH(A, B, h)- 1
M ← [[A·h, B·h], [0, 0]] ▷ (n + m) by (n + m), last m rows zero - 2
E ← exp(M) ▷ any accurate matrix exponential - 3
A_d ← E[1..n, 1..n] - 4
B_d ← E[1..n, n+1..n+m]; return (A_d, B_d)
Line L1 builds the block matrix of Van Loan (1978), already multiplied by . Line L2 takes its exponential. The implementation uses scaling and squaring with a Taylor series; libraries use scaling and squaring with a Padé approximant (Higham 2005). Lines L3 and L4 read the two top blocks. The bottom right block of is the identity , and the bottom left block is zero; the code does not use them.
The reason is the identity
which is proved in proofs/correctness.md. It avoids the formula , which fails when is singular, for example for an integrator, and loses accuracy when is close to singular.
Example
Double integrator. Take , , a mass pushed by a force, and . Line L1 gives
So the series stops, and line L2 gives . Lines L3 and L4 read and . For a general these are and : in one period a unit force moves the mass by and changes the velocity by . Here is singular, so cannot be used.
Oscillator. For , and , the code returns , which is the rotation , and .
Poles and zeros. For with , , and , the pulse transfer function is
The poles are and . The continuous system has no finite zero, but has a zero at . With the zero moves to , close to . For the triple integrator the result is
with zeros , that is and , for every . One zero is outside the unit circle. The tests compute these numerators as .
Correctness
The full proof is in proofs/correctness.md. In short: on one period the input is a constant , and the solution of from is by the variation of constants formula. At this is . The block identity follows because satisfies and , which defines . The tests check the result against the double integrator values, against for invertible , against the identity , , and against an RK4 simulation with step and the input held over each period, which agrees to .
Proof: The zero-order hold model is exact at the sampling instants, and one block exponential gives both of its matricesfull
Let , and . The plant is . The input is a zero-order hold signal: for , with any vectors . Write and
The matrix exponential is . The series converges absolutely for every square , it can be differentiated term by term, and .
Lemma 1: existence and uniqueness
For every and every zero-order hold input, the plant has exactly one continuous solution on with , and on each interval it is the solution of that starts at .
Proof. On one interval the right side is affine in , so it is globally Lipschitz with constant . The Picard-Lindelöf theorem gives one solution on the closed interval. The solutions on consecutive intervals join at , so the joined function is continuous and solves the equation at every that is not a sampling instant. Uniqueness on each interval gives uniqueness of the joined function, by induction on .
Lemma 2: the solution on one interval
For , .
Proof. Let be the right side. Then , because and . By the fundamental theorem of calculus, , so
Also , because is the derivative of . So
So solves with the right initial value, and by Lemma 1 it is the solution. This is the variation of constants formula for a constant input.
Theorem 1: exactness at the samples
For every , .
Proof. Put in Lemma 2.
No approximation enters. The only assumption is on the input: it must be constant on each interval. For any other input the samples satisfy , and the model with is exact only for the held part.
Theorem 2: the block exponential (Van Loan 1978)
Let and
Then for every ,
In particular, the top blocks of are and .
Proof. Let be the matrix on the right. Both and are equal to at . The function is the unique solution of the linear matrix equation , (Lemma 1 applied to each column). So it is enough to show . Block by block:
The top right blocks agree, because (proof of Lemma 2). The other blocks agree term by term.
A second proof uses the series. Induction on gives for . So the top right block of is , and term by term integration of gives the same series for .
Theorem 3: the implementation returns
The function zoh(A, B, h) builds (line L1), takes its exponential (line L2), and returns the top left block (line L3) and the top right block (line L4).
Proof. Line L1 builds the block matrix of Theorem 2 with and in place of and , and . Lines L3 and L4 read the blocks of , which are and by Theorem 2. In exact arithmetic the result is exact. In floating point the error is that of the matrix exponential of line L2: the helper expm scales by until the infinity norm is at most , sums the Taylor series until the next term is below times the norm of the sum, and squares times. The truncation error of the series is far below the unit roundoff, and the rounding error grows with and with the norm of .
Checks used in the tests
- Double integrator, , : is nilpotent with , so , which gives and .
- Invertible : , from .
- Semigroup: two steps with period and the same held input equal one step with period : and . This follows from Theorem 1 applied to the two intervals.
- Simulation: a fine RK4 run of the plant with the input held over each sampling period agrees with to the RK4 error, which is .
Complexity
In the real RAM, with dense matrices of size :
- Line L1 costs .
- Line L2 costs per matrix product. Scaling and squaring needs squarings and a fixed number of products for the Taylor or Padé part, so the cost is flops. The number grows like .
- Lines L3 and L4 cost .
The extra space is . The computation runs once, offline, for a fixed . The discrete model then costs per step, the same as any explicit linear recursion. Exploiting the zero rows of saves a constant factor only.
Properties
- Poles map by . This is a theorem: if , then , and the eigenvalues of are the numbers with the same algebraic multiplicities. So a Hurwitz gives a Schur , because exactly when .
- Zeros do not map by . The sampled system has, in general, finite zeros whatever the continuous zeros are. If has finite zeros and relative degree , then as the zeros of tend to and the other zeros, the sampling zeros, tend to the zeros of a fixed polynomial that depends only on (Åström, Hagander and Sternby 1984). For the limit is ; for the limits include a zero outside the unit circle, for . So the sampled model of a minimum phase plant with relative degree 3 or more is not minimum phase for short sampling periods.
- Step invariance. The step response of the discrete model equals the samples of the continuous step response. This is the reason for the name "step-invariant". The static gain is kept: if is invertible and 1 is not an eigenvalue of , then , because and commutes with .
- Controllability can be lost. If two eigenvalues of differ by for a nonzero integer , the pair can lose controllability although is controllable. If no two eigenvalues differ in that way, controllability is kept (Kalman, Ho and Narendra 1963). The sampled-data system page has the example.
- Exact for any . There is no step-size limit and no stiffness problem, unlike Euler's method with , which is only first order accurate and can turn a stable plant into an unstable model when is large.
Variants and improvements
- Output and cost integrals. Van Loan's paper is about general integrals of matrix exponentials. Larger block matrices give the sampled cost matrices of a continuous quadratic cost, which finite-horizon LQR on the sampled model needs, and the covariance of sampled process noise, which a discrete Kalman filter needs.
- Time delay. An input delay of with splits the input matrix into two parts, for and for , and adds the old inputs to the state (Åström and Wittenmark, Chapter 2). See time-delay system.
- Other holds. A first-order or a triangle hold interpolates the input linearly between samples. The same block exponential method works with one more block row. These holds are less common in hardware.
- Approximate maps. Forward Euler, backward Euler and the bilinear transform give rational approximations of . They are cheaper and exact for no input class; the bilinear transform is used for controllers, not for plant models.
- The exponential itself. Moler and Van Loan (2003) compare the methods. Scaling and squaring with Padé approximants (Higham 2005) is the standard. SciPy's
cont2discretewith methodzohbuilds the same block matrix and calls itsexpm. - Exponential integrators. In numerical analysis, the same matrices give the exponential Euler method for , with frozen over a step; see exponential integrators.
When to use it
Use ZOH discretization to get the plant model for digital control design when the actuator holds the command between updates, which is what a digital-to-analog converter does. The discrete model is then exact, and pole placement, LQR, MPC and Kalman filtering in discrete time apply to it directly. It is also the right tool to simulate a linear plant with a piecewise constant input: it is exact at any step size, so a stiff plant does not force a small step.
Do not use it to discretize a continuous controller that was designed in continuous time; the input of a controller is a sampled measurement, not a held signal. Use controller discretization with Tustin or matched poles and zeros. Do not use it for a nonlinear plant without a check: for it applies only to the linearization about an equilibrium.
Pitfalls
- The model is exact only at the samples. Between samples the state is . A controller that makes the samples converge can still leave an oscillation between them, for example a deadbeat controller that cancels a sampling zero near . Check the continuous response, or compute with the same method for a few .
- The input must really be held. If the actuator has its own dynamics, add them to the plant. If the computation takes a large part of the period, the new input acts with a delay; model it as in the delay variant above.
- Sampling zeros. Do not cancel the zeros of with the controller when has a sampling zero outside the unit circle or near . The cancellation is unstable or rings between samples.
- Do not map zeros by . That is the matched pole-zero method, an approximation. The exact ZOH model has the zeros of the Example section.
- Pathological periods. For lightly damped modes, avoid near and its multiples, where is the frequency of the mode. The model then loses controllability or observability of that mode. See aliasing.
- Very short periods. As , and , and the poles all crowd near . The coefficients of then lose relative precision in floating point. Keep the state-space form, or use the scaled form .
- The choice of is a design rule, not a theorem. Rules of thumb tie to the rise time or to the closed-loop bandwidth; Åström and Wittenmark discuss them in Section 2.9. The sampling theorem is about the reconstruction of band-limited signals and gives no bound on control performance.
- by inversion. The formula is correct only for invertible and is inaccurate when has an eigenvalue near 0. The block exponential has no such condition.
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()
ctlsim.py 120 lines
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Fixed step simulation for the control pages.
Conventions:
- A continuous-time system is a function f(t, x, u) that returns x' as a
flat list. x is a flat list. u is whatever the control returns (a flat
list, a scalar, or None when there is no control).
- A discrete-time system is a function F(k, x, u) that returns x_(k+1).
- The integrator is the classical 4th order Runge-Kutta method with a fixed
step dt. The input is held constant over each step.
- Time t_k = t0 + k dt is computed by multiplication, not by summation.
- The number of steps round((t1 - t0) / dt) and the hold ratio
round(hold / dt) must match the real ratios within 1e-9 (relative), or
ValueError is raised.
This file holds no controller or observer of a control page.
"""
__all__ = ["rk4_step", "simulate", "simulate_discrete", "lti"]
def _axpy(a, x, y):
return [yi + a * xi for xi, yi in zip(x, y)]
def rk4_step(f, t, x, u, dt):
"""Return x(t + dt) after one RK4 step of x' = f(t, x, u), u held constant."""
k1 = f(t, x, u)
k2 = f(t + dt / 2, _axpy(dt / 2, k1, x), u)
k3 = f(t + dt / 2, _axpy(dt / 2, k2, x), u)
k4 = f(t + dt, _axpy(dt, k3, x), u)
return [xi + dt / 6 * (a + 2 * b + 2 * c + d) for xi, a, b, c, d in zip(x, k1, k2, k3, k4)]
def _ratio(num, den, what):
r = round(num / den)
if abs(r * den - num) > 1e-9 * max(abs(num), abs(den)):
raise ValueError(what + " is not an integer multiple of dt")
return r
def simulate(f, x0, t0, t1, dt, control=None, hold=None):
"""Simulate x' = f(t, x, u) from x(t0) = x0 to t1 with RK4 and step dt.
control(t, x) gives the input. It is called at each sampling instant
t0 + j hold, and its value is held (zero-order hold) until the next
instant. hold must be an integer multiple of dt; hold = None means
hold = dt. With control = None the input is None.
Returns (ts, xs, us): ts has N + 1 times, xs the N + 1 states, and us the
N inputs, where us[k] acts on [ts[k], ts[k + 1]].
"""
if dt <= 0:
raise ValueError("dt must be positive")
n_steps = _ratio(t1 - t0, dt, "t1 - t0")
if n_steps < 0:
raise ValueError("t1 is before t0")
r = 1 if hold is None else _ratio(hold, dt, "hold")
if r < 1:
raise ValueError("hold must be at least dt")
x = list(x0)
ts = [t0]
xs = [list(x)]
us = []
u = None
for k in range(n_steps):
t = t0 + k * dt
if control is not None and k % r == 0:
u = control(t, list(x))
x = rk4_step(f, t, x, u, dt)
ts.append(t0 + (k + 1) * dt)
xs.append(x)
us.append(u)
return ts, xs, us
def simulate_discrete(F, x0, N, control=None):
"""Run x_(k+1) = F(k, x_k, u_k) for k = 0, ..., N - 1.
u_k = control(k, x_k), or None if control is None. Returns (xs, us) with
N + 1 states and N inputs. Exact if F and control are exact.
"""
x = list(x0)
xs = [list(x)]
us = []
for k in range(N):
u = control(k, list(x)) if control is not None else None
x = list(F(k, x, u))
xs.append(x)
us.append(u)
return xs, us
def lti(A, B=None):
"""Return f(t, x, u) = A x + B u for the system x' = A x + B u.
u may be a flat list, a scalar (one input) or None (zero input). B may
be None for a system with no input.
"""
def f(t, x, u):
dx = [sum(a * xi for a, xi in zip(row, x)) for row in A]
if B is None or u is None:
return dx
uu = u if isinstance(u, (list, tuple)) else [u]
return [d + sum(b * ui for b, ui in zip(row, uu)) for d, row in zip(dx, B)]
return f
def _self_test():
import math
f = lti([[-1.0]])
_, xs, _ = simulate(f, [1.0], 0.0, 1.0, 0.01)
assert abs(xs[-1][0] - math.exp(-1.0)) < 1e-9
return True
if __name__ == "__main__":
_self_test()
zero_order_hold_discretization.py 40 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zero-order-hold-discretization/. The authors are listed in prov/TDAR9X.jsonl.
"""Zero-order hold discretization of x' = A x + B u, y = C x + D u.
With the input held constant on each interval [k h, (k + 1) h), the samples
x_k = x(k h) satisfy x_(k+1) = A_d x_k + B_d u_k exactly, where
A_d = e^(A h), B_d = (integral from 0 to h of e^(A s) ds) B.
Van Loan (1978): the exponential of the block matrix [[A, B], [0, 0]] h is
[[A_d, B_d], [0, I]], so one matrix exponential of size n + m gives both.
C and D do not change. The cost is that of one dense matrix exponential of
size n + m, O((n + m)^3) flops times the number of products in expm.
"""
from ctlmat import block, expm, scale, zeros
__all__ = ["zoh", "zoh_ss"]
def zoh(A, B, h):
"""Return (A_d, B_d) for sampling period h > 0, in floating point."""
if h <= 0:
raise ValueError("the sampling period h must be positive")
n = len(A)
m = len(B[0]) if B else 0
if any(len(row) != n for row in A) or len(B) != n:
raise ValueError("A must be n by n and B must be n by m")
big = block([[scale(h, A), scale(h, B)], [zeros(m, n), zeros(m, m)]]) # @line L1
e = expm(big) # @line L2
ad = [row[:n] for row in e[:n]] # @line L3
bd = [row[n:] for row in e[:n]] # @line L4
return ad, bd
def zoh_ss(A, B, C, D, h):
"""Return (A_d, B_d, C, D): the full discrete model of (A, B, C, D)."""
ad, bd = zoh(A, B, h)
return ad, bd, [list(r) for r in C], [list(r) for r in D]
test_zero_order_hold_discretization.py 465 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zero-order-hold-discretization/. The authors are listed in prov/TDAR9X.jsonl.
import cmath
import itertools
import math
import random
from fractions import Fraction
import pytest
import ctlmat as cm
import ctlsim as cs
from zero_order_hold_discretization import zoh, zoh_ss
def maxdiff(a, b):
return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def rand_int_matrix(rng, n, m, lo=-5, hi=5):
return [[rng.randint(lo, hi) for _ in range(m)] for _ in range(n)]
def leibniz_det(a):
n = len(a)
total = 0
for perm in itertools.permutations(range(n)):
inversions = sum(1 for i in range(n) for j in range(i + 1, n) if perm[i] > perm[j])
prod = 1
for i in range(n):
prod *= a[i][perm[i]]
total += -prod if inversions % 2 else prod
return total
# ctlmat
def test_ctlmat_self_test():
assert cm._self_test()
def test_basic_ops():
a = [[1, 2, 3], [4, 5, 6]]
assert cm.zeros(2, 3) == [[0, 0, 0], [0, 0, 0]]
assert cm.eye(2) == [[1, 0], [0, 1]]
assert cm.transpose(a) == [[1, 4], [2, 5], [3, 6]]
assert cm.add(a, a) == cm.scale(2, a)
assert cm.sub(a, a) == cm.zeros(2, 3)
assert cm.mul(a, cm.transpose(a)) == [[14, 32], [32, 77]]
assert cm.matvec(a, [1, 0, -1]) == [-2, -2]
assert cm.dot([1, 2, 3], [4, 5, 6]) == 32
assert cm.trace([[1, 2], [3, 4]]) == 5
with pytest.raises(ValueError):
cm.mul(a, a)
with pytest.raises(ValueError):
cm.add(a, cm.eye(2))
def test_mul_associative_exact():
rng = random.Random(1)
for _ in range(50):
n, m, p, q = (rng.randint(1, 4) for _ in range(4))
a = rand_int_matrix(rng, n, m)
b = [[Fraction(rng.randint(-9, 9), rng.randint(1, 5)) for _ in range(p)] for _ in range(m)]
c = rand_int_matrix(rng, p, q)
assert cm.mul(cm.mul(a, b), c) == cm.mul(a, cm.mul(b, c))
def test_block_kron_vec():
a = [[1, 2], [3, 4]]
b = [[5], [6]]
m = cm.block([[a, b], [0, [[7]]]])
assert m == [[1, 2, 5], [3, 4, 6], [0, 0, 7]]
assert cm.kron([[1, 2]], [[1], [3]]) == [[1, 2], [3, 6]]
assert cm.vec(a) == [1, 3, 2, 4]
assert cm.unvec([1, 3, 2, 4], 2) == a
rng = random.Random(2)
for _ in range(30):
n, m2, p = (rng.randint(1, 3) for _ in range(3))
aa = rand_int_matrix(rng, n, m2)
x = rand_int_matrix(rng, m2, p)
bb = rand_int_matrix(rng, p, 2)
left = cm.vec(cm.mul(cm.mul(aa, x), bb))
right = cm.matvec(cm.kron(cm.transpose(bb), aa), cm.vec(x))
assert left == right
def test_solve_inv_det_exact():
rng = random.Random(3)
for _ in range(80):
n = rng.randint(1, 5)
a = rand_int_matrix(rng, n, n)
d = cm.det(a)
assert d == leibniz_det(a)
b = [rng.randint(-9, 9) for _ in range(n)]
if d == 0:
with pytest.raises(ValueError):
cm.solve(a, b)
continue
x = cm.solve(a, b)
assert all(isinstance(v, Fraction) for v in x)
assert cm.matvec(a, x) == b
assert cm.mul(a, cm.inv(a)) == cm.eye(n)
c = rand_int_matrix(rng, n, n)
assert cm.det(cm.mul(a, c)) == d * cm.det(c)
def test_solve_float_and_complex():
rng = random.Random(4)
for _ in range(50):
n = rng.randint(1, 6)
a = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
for i in range(n):
a[i][i] += 3.0
b = [[rng.uniform(-1, 1) for _ in range(2)] for _ in range(n)]
x = cm.solve(a, b)
assert maxdiff(cm.mul(a, x), b) < 1e-12
ac = [[complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)] for _ in range(n)]
for i in range(n):
ac[i][i] += 4.0
bc = [complex(1, 1)] * n
xc = cm.solve(ac, bc)
assert max(abs(u - v) for u, v in zip(cm.matvec(ac, xc), bc)) < 1e-12
def test_charpoly_exact():
rng = random.Random(5)
for _ in range(60):
n = rng.randint(1, 6)
a = rand_int_matrix(rng, n, n)
p = cm.charpoly(a)
assert len(p) == n + 1 and p[0] == 1
for s in range(-3, 4):
si_a = [[(s if i == j else 0) - a[i][j] for j in range(n)] for i in range(n)]
assert cm.polyval(p, s) == cm.det(si_a)
acc = cm.zeros(n)
for k, c in enumerate(p):
acc = cm.add(acc, cm.scale(c, cm.mat_power(a, n - k)))
assert acc == cm.zeros(n)
def test_poly_arithmetic():
rng = random.Random(6)
for _ in range(50):
p = [rng.randint(-5, 5) for _ in range(rng.randint(1, 6))]
q = [rng.randint(-5, 5) for _ in range(rng.randint(1, 6))]
for x in (Fraction(-3, 2), Fraction(0), Fraction(2), Fraction(5, 3)):
assert cm.polyval(cm.polyadd(p, q), x) == cm.polyval(p, x) + cm.polyval(q, x)
assert cm.polyval(cm.polymul(p, q), x) == cm.polyval(p, x) * cm.polyval(q, x)
x = Fraction(1, 7)
eps = Fraction(1, 10 ** 30)
slope = (cm.polyval(p, x + eps) - cm.polyval(p, x)) / eps
assert abs(slope - cm.polyval(cm.polyder(p), x)) < Fraction(1, 10 ** 20)
assert cm.polyadd([1, 2, 3], [-1, 0, 0]) == [2, 3]
def test_polyroots_against_known_roots():
rng = random.Random(7)
for _ in range(100):
roots = []
while len(roots) < rng.randint(1, 6):
if rng.random() < 0.5:
roots.append(complex(rng.uniform(-3, 3), 0.0))
else:
z = complex(rng.uniform(-3, 3), rng.uniform(0.2, 3))
roots += [z, z.conjugate()]
roots.sort(key=lambda v: (v.real, v.imag))
if any(abs(u - v) < 0.1 for u, v in itertools.combinations(roots, 2)):
continue
p = [1.0]
for z in roots:
p = cm.polymul(p, [1.0, -z])
p = [v.real for v in p]
got = cm.polyroots(p)
assert len(got) == len(roots)
assert max(abs(u - v) for u, v in zip(got, roots)) < 1e-9
for u, v in itertools.combinations(got, 2):
assert (u.real, u.imag) <= (v.real, v.imag)
def test_polyroots_special_cases():
assert cm.polyroots([5]) == []
assert cm.polyroots([2, -4]) == [complex(2, 0)]
r = cm.polyroots([1, 0, 0])
assert r == [0j, 0j]
r = cm.polyroots([1, -1, 0.5])
assert all(abs(abs(z) - 1 / math.sqrt(2)) < 1e-12 for z in r)
assert r[0].imag < 0 < r[1].imag and r[0] == r[1].conjugate()
r = cm.polyroots([1, -2, 1])
assert all(abs(z - 1) < 1e-7 for z in r)
r = cm.polyroots([1, 4, 6, 4, 1])
assert all(abs(z + 1) < 1e-2 for z in r)
assert sorted(r, key=lambda v: (v.real, v.imag)) == r
assert sorted((z.conjugate() for z in r), key=lambda v: (v.real, v.imag)) == r
rng = random.Random(16)
for _ in range(300):
d = rng.randint(1, 10)
p = [rng.choice([-1, 1]) * rng.uniform(0.5, 5)] + [rng.uniform(-5, 5) for _ in range(d)]
for z in cm.polyroots(p):
size = sum(abs(c) * abs(z) ** (d - k) for k, c in enumerate(p))
assert abs(cm.polyval(p, z)) <= 1e-12 * size
r = cm.polyroots([1, -1j])
assert abs(r[0] - 1j) < 1e-15
r = cm.polyroots([Fraction(1), Fraction(-3), Fraction(2)])
assert abs(r[0] - 1) < 1e-12 and abs(r[1] - 2) < 1e-12
with pytest.raises(ValueError):
cm.polyroots([0, 0])
def test_expm_known_cases():
for t in (0.0, 0.3, 1.0, 5.0, 40.0):
e = cm.expm([[0, t], [-t, 0]])
want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
assert maxdiff(e, want) < 1e-12 * max(1.0, t)
e = cm.expm([[0, 1, 0], [0, 0, 1], [0, 0, 0]])
assert maxdiff(e, [[1, 1, 0.5], [0, 1, 1], [0, 0, 1]]) < 1e-15
e = cm.expm([[-30.0, 0.0], [0.0, 2.0]])
assert abs(e[0][0] - math.exp(-30)) < 1e-14 * math.exp(-30) * 100
assert abs(e[1][1] - math.exp(2)) < 1e-13 * math.exp(2)
e = cm.expm([[1j * math.pi]])
assert abs(e[0][0] + 1) < 1e-14
def test_expm_against_eigendecomposition():
rng = random.Random(8)
for _ in range(40):
n = rng.randint(1, 5)
lam = [rng.uniform(-3, 2) for _ in range(n)]
v = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
for i in range(n):
v[i][i] += 2.0
vi = cm.inv(v)
a = cm.mul(cm.mul(v, [[lam[i] if i == j else 0.0 for j in range(n)] for i in range(n)]), vi)
want = cm.mul(cm.mul(v, [[math.exp(lam[i]) if i == j else 0.0 for j in range(n)] for i in range(n)]), vi)
got = cm.expm(a)
scale_ = max(1.0, max(abs(x) for row in want for x in row))
assert maxdiff(got, want) < 1e-11 * scale_
assert maxdiff(cm.mul(got, cm.expm(cm.scale(-1, a))), cm.eye(n)) < 1e-10
def test_expm_sum_rule():
a = [[1.0, 2.0], [0.0, 3.0]]
b = cm.mul(a, a)
assert maxdiff(cm.expm(cm.add(a, b)), cm.mul(cm.expm(a), cm.expm(b))) < 1e-12 * math.exp(12)
p = [[0.0, 1.0], [0.0, 0.0]]
q = [[0.0, 0.0], [1.0, 0.0]]
assert maxdiff(cm.expm(cm.add(p, q)), cm.mul(cm.expm(p), cm.expm(q))) > 0.1
def test_mat_power():
rng = random.Random(9)
a = rand_int_matrix(rng, 3, 3)
acc = cm.eye(3)
for k in range(8):
assert cm.mat_power(a, k) == acc
acc = cm.mul(acc, a)
b = [[2, 1], [1, 1]]
assert cm.mul(cm.mat_power(b, -3), cm.mat_power(b, 3)) == cm.eye(2)
def test_pos_def_exact_and_float_agree():
rng = random.Random(10)
seen = set()
for _ in range(200):
n = rng.randint(1, 5)
r = rand_int_matrix(rng, n, n, -3, 3)
s = cm.add(cm.mul(cm.transpose(r), r), cm.scale(rng.randint(-4, 2), cm.eye(n)))
exact = cm.is_pos_def(s)
flt = cm.is_pos_def([[float(v) for v in row] for row in s])
# Skip matrices that are singular, where float rounding may decide.
if cm.det(s) == 0:
continue
assert exact == flt
seen.add(exact)
if exact:
assert cm.is_pos_def(s, Fraction(0)) and not cm.is_pos_def(s, 10 ** 6)
assert seen == {True, False}
assert not cm.is_pos_def([[1, 2], [0, 5]])
assert cm.is_symmetric([[1.0, 2.0], [2.0 + 1e-13, 1.0]], 1e-12)
assert not cm.is_symmetric([[1, 2], [3, 1]])
def test_norm2():
assert abs(cm.norm2([3, 4]) - 5.0) < 1e-15
assert abs(cm.norm2([[1j]]) - 1.0) < 1e-12
rng = random.Random(11)
for _ in range(30):
n, m = rng.randint(1, 5), rng.randint(1, 5)
u = [rng.uniform(-1, 1) for _ in range(n)]
v = [rng.uniform(-1, 1) for _ in range(m)]
a = [[ui * vj for vj in v] for ui in u]
assert abs(cm.norm2(a) - cm.norm2(u) * cm.norm2(v)) < 1e-12
b = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(n)]
nb = cm.norm2(b)
for _ in range(20):
x = [rng.gauss(0, 1) for _ in range(m)]
assert cm.norm2(cm.matvec(b, x)) <= nb * cm.norm2(x) * (1 + 1e-12)
# ctlsim
def test_ctlsim_self_test():
assert cs._self_test()
def test_rk4_exact_on_polynomials():
f = lambda t, x, u: [t ** 3]
x = cs.rk4_step(f, 0.0, [0.0], None, 0.5)
assert abs(x[0] - 0.5 ** 4 / 4) < 1e-15
_, xs, _ = cs.simulate(f, [0.0], 0.0, 2.0, 0.25)
assert abs(xs[-1][0] - 4.0) < 1e-12
def test_simulate_hold_and_steps():
calls = []
def control(t, x):
calls.append(t)
return [1.0]
f = cs.lti([[0.0, 1.0], [0.0, 0.0]], [[0.0], [1.0]])
ts, xs, us = cs.simulate(f, [0.0, 0.0], 0.0, 1.0, 0.01, control, hold=0.1)
assert len(ts) == 101 and len(xs) == 101 and len(us) == 100
assert len(calls) == 10
assert all(abs(t - 0.1 * j) < 1e-12 for j, t in enumerate(calls))
assert abs(xs[-1][0] - 0.5) < 1e-12 and abs(xs[-1][1] - 1.0) < 1e-12
with pytest.raises(ValueError):
cs.simulate(f, [0.0, 0.0], 0.0, 1.0, 0.03)
with pytest.raises(ValueError):
cs.simulate(f, [0.0, 0.0], 0.0, 1.0, 0.01, control, hold=0.015)
def test_simulate_discrete_exact():
a = [[Fraction(1, 2), 1], [0, Fraction(1, 3)]]
def F(k, x, u):
y = cm.matvec(a, x)
y[0] += u
return y
xs, us = cs.simulate_discrete(F, [1, 1], 5, lambda k, x: Fraction(k))
x = [1, 1]
for k in range(5):
x = cm.matvec(a, x)
x[0] += k
assert xs[k + 1] == x
assert us == [0, 1, 2, 3, 4]
def test_lti_scalar_and_none_input():
f = cs.lti([[-1.0]], [[2.0]])
assert f(0.0, [1.0], 3.0) == [5.0]
assert f(0.0, [1.0], None) == [-1.0]
assert cs.lti([[2.0]])(0.0, [1.0], [7.0]) == [2.0]
# zero-order hold
def test_double_integrator_check_values():
for h in (0.1, 0.5, 1.0, 2.0):
ad, bd = zoh([[0, 1], [0, 0]], [[0], [1]], h)
assert maxdiff(ad, [[1, h], [0, 1]]) < 1e-14
assert maxdiff(bd, [[h * h / 2], [h]]) < 1e-14
def test_rotation_and_scalar():
for h in (0.1, 1.0, 3.0):
ad, bd = zoh([[0, 1], [-1, 0]], [[0], [1]], h)
assert maxdiff(ad, [[math.cos(h), math.sin(h)], [-math.sin(h), math.cos(h)]]) < 1e-13
assert maxdiff(bd, [[1 - math.cos(h)], [math.sin(h)]]) < 1e-13
for a in (-2.0, -0.5, 0.7):
ad, bd = zoh([[a]], [[3.0]], 0.4)
assert abs(ad[0][0] - math.exp(a * 0.4)) < 1e-14
assert abs(bd[0][0] - 3.0 * (math.exp(a * 0.4) - 1) / a) < 1e-13
def test_against_inverse_formula():
rng = random.Random(12)
for _ in range(40):
n, m = rng.randint(1, 5), rng.randint(1, 3)
a = [[rng.uniform(-2, 2) for _ in range(n)] for _ in range(n)]
for i in range(n):
a[i][i] -= 2.5
b = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(n)]
h = rng.choice([0.05, 0.2, 1.0])
ad, bd = zoh(a, b, h)
assert maxdiff(ad, cm.expm(cm.scale(h, a))) < 1e-13
want = cm.mul(cm.solve(a, cm.sub(ad, cm.eye(n))), b)
assert maxdiff(bd, want) < 1e-11
def test_semigroup_property():
rng = random.Random(13)
for _ in range(20):
n, m = rng.randint(1, 4), rng.randint(1, 2)
a = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
b = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(n)]
ad1, bd1 = zoh(a, b, 0.3)
ad2, bd2 = zoh(a, b, 0.6)
assert maxdiff(ad2, cm.mul(ad1, ad1)) < 1e-12
assert maxdiff(bd2, cm.add(cm.mul(ad1, bd1), bd1)) < 1e-12
def test_against_rk4_with_held_input():
rng = random.Random(14)
h, dt, steps = 0.2, 0.002, 15
assert round(h / dt) == 100
for _ in range(4):
n, m = rng.randint(1, 4), rng.randint(1, 2)
a = [[rng.uniform(-1.5, 1.0) for _ in range(n)] for _ in range(n)]
b = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(n)]
inputs = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(steps)]
x0 = [rng.uniform(-1, 1) for _ in range(n)]
control = lambda t, x: inputs[round(t / h)]
ts, xs, _ = cs.simulate(cs.lti(a, b), x0, 0.0, steps * h, dt, control, hold=h)
ad, bd = zoh(a, b, h)
x = x0
for k in range(steps):
x = [p + q for p, q in zip(cm.matvec(ad, x), cm.matvec(bd, inputs[k]))]
cont = xs[(k + 1) * 100]
assert max(abs(p - q) for p, q in zip(x, cont)) < 1e-9
def test_poles_map_by_exponential():
rng = random.Random(15)
for _ in range(20):
n = rng.randint(1, 4)
lam = sorted(rng.uniform(-3, 1) for _ in range(n))
a = [[lam[i] if i == j else (rng.uniform(-1, 1) if j > i else 0.0) for j in range(n)] for i in range(n)]
t = rand_int_matrix(rng, n, n)
for i in range(n):
t[i][i] += 20
a = cm.mul(cm.mul(t, a), cm.inv([[float(v) for v in row] for row in t]))
h = 0.5
ad, _ = zoh(a, [[1.0]] * n, h)
got = cm.polyroots(cm.charpoly(ad))
want = [complex(math.exp(v * h), 0) for v in lam]
if any(abs(u - v) < 0.05 for u, v in itertools.combinations(want, 2)):
continue
assert max(abs(u - v) for u, v in zip(got, want)) < 1e-7
def test_sampling_zeros_triple_integrator():
a = [[0, 1, 0], [0, 0, 1], [0, 0, 0]]
b = [[0], [0], [1]]
c = [[1, 0, 0]]
for h in (0.1, 1.0):
ad, bd, cc, _ = zoh_ss(a, b, c, [[0]], h)
# det(zI - Ad + Bd C) - det(zI - Ad) is the numerator of C (zI - Ad)^(-1) Bd.
num = cm.polyadd(cm.charpoly(cm.sub(ad, cm.mul(bd, cc))), cm.scale(-1, [cm.charpoly(ad)])[0])
num = num[-3:]
want = [h ** 3 / 6, 4 * h ** 3 / 6, h ** 3 / 6]
assert max(abs(p - q) for p, q in zip(num, want)) < 1e-12
zs = cm.polyroots(num)
assert abs(zs[0] - (-2 - math.sqrt(3))) < 1e-9 and abs(zs[1] - (-2 + math.sqrt(3))) < 1e-9
def test_bad_input():
with pytest.raises(ValueError):
zoh([[0.0]], [[1.0]], 0.0)
with pytest.raises(ValueError):
zoh([[0.0, 1.0]], [[1.0]], 0.1)
History
The model is a direct use of the solution formula of linear differential equations. It was standard in the state-space theory of sampled systems by the early 1960s; Kalman, Ho and Narendra (1963) used it to study the loss of controllability by sampling. Van Loan (1978) showed that integrals of this kind are blocks of the exponential of a larger block triangular matrix, which reduced the computation to one call of a matrix exponential routine. Åström, Hagander and Sternby (1984) described the zeros of sampled systems and showed the unstable sampling zeros for relative degree above 2.
References
- Charles F. Van Loan, Computing integrals involving the matrix exponential, IEEE Transactions on Automatic Control 23(3), 395-404, 1978, the block triangular matrix whose exponential contains the integrals of e^(As), applied to the discretization of linear systems
- Karl J. Åström and Björn Wittenmark, Computer-Controlled Systems, Theory and Design, third edition, Prentice Hall, 1997 (Dover reprint, 2011), Section 2.3, Sampling a Continuous-Time State-Space System; Section 2.8, Poles and Zeros; Section 2.9, Selection of Sampling Rate
- Karl J. Åström, Per Hagander and Jan Sternby, Zeros of sampled systems, Automatica 20(1), 31-38, 1984, the limits of the zeros of the sampled system as h goes to 0, and the unstable sampling zeros for relative degree above 2
- Cleve Moler and Charles Van Loan, Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later, SIAM Review 45(1), 3-49, 2003, the scaling and squaring method and the methods based on block exponentials
- Nicholas J. Higham, The scaling and squaring method for the matrix exponential revisited, SIAM Journal on Matrix Analysis and Applications 26(4), 1179-1193, 2005, the choice of the scaling and of the Padé degree used by current libraries
- R. E. Kalman, Y. C. Ho and K. S. Narendra, Controllability of linear dynamical systems, Contributions to Differential Equations 1, 189-213, 1963, the section on the loss of controllability and observability due to sampling
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 TDAR9X Edit this page History Report an error Markdown