Algorithm Search⌘K

Algorithmadvanced

Kalman-Bucy filter

Also called continuous-time Kalman filter.

The continuous-time optimal linear filter, whose gain comes from a Riccati differential equation dual to that of LQR.

Time
O(n^3 + n p^2 + p^3 + n m) worst
Space
O(n^2 + n p) extra
Where
h = the time step; m = the number of inputs; n = the number of states; p = the number of outputs
Properties
deterministicnot exactonlinerecursive
Origin
Rudolf E. Kalman, Richard S. Bucy, 1961

The Kalman-Bucy filter is the Kalman filter for a plant in continuous time. It is a state observer whose gain Lo(t)=S(t)CTV−1L_o(t) = S(t) C^T V^{-1} comes from the Riccati differential equation S˙=AS+SAT+W−SCTV−1CS\dot S = A S + S A^T + W - S C^T V^{-1} C S, where S(t)S(t) is the covariance of the estimation error. No other gain gives a smaller error covariance, and for Gaussian noise the estimate is the conditional mean of the state. As tt grows, S(t)S(t) settles at the stabilizing solution of the filter algebraic Riccati equation, and the filter becomes a time-invariant observer. This page covers the continuous-time filter; the discrete-time recursion with its predict and update steps is on the Kalman filter page.

In plain words

A machine moves in continuous time, pushed by random forces, and a sensor reports its position with random errors. The filter keeps a running guess of the full state. It moves the guess forward with the model, and at every instant it nudges the guess toward what the sensor says. The size of the nudge depends on how sure the filter is: when its own guess is poor, it trusts the sensor more, and when the sensor is noisy, it trusts it less. A second equation tracks how unsure the filter is, and it does not depend on the data at all, so it can be solved ahead of time. After a while the uncertainty stops changing and the nudge becomes a fixed amount.

The problem

Input: matrices A∈Rn×nA \in \mathbb{R}^{n \times n}, B∈Rn×mB \in \mathbb{R}^{n \times m}, C∈Rp×nC \in \mathbb{R}^{p \times n} of the plant

dx=(Ax+Bu) dt+dw,dz=Cx dt+dv,dx = (A x + B u)\, dt + dw, \qquad dz = C x\, dt + dv,

the noise intensities W=WT≥0W = W^T \ge 0 and V=VT>0V = V^T > 0 of the independent Wiener processes ww and vv, the mean x^0\hat x_0 and covariance S0≥0S_0 \ge 0 of x(0)x(0), the known input u(t)u(t), and the measurement z(t)z(t). In the white noise notation y=z˙=Cx+v˙y = \dot z = C x + \dot v is the measured output.

Output: for each tt, the estimate x^(t)\hat x(t) that depends only on z(s)z(s) and u(s)u(s) for s≤ts \le t and minimizes the error covariance E (x−x^)(x−x^)T\mathbb{E}\,(x - \hat x)(x - \hat x)^T in the sense of positive semidefinite matrices, together with that covariance S(t)S(t).

The filter.

dx^=(Ax^+Bu) dt+Lo(t)(dz−Cx^ dt),Lo=SCTV−1,d\hat x = (A \hat x + B u)\, dt + L_o(t) \left(dz - C \hat x\, dt\right), \qquad L_o = S C^T V^{-1},
S˙=AS+SAT+W−SCTV−1CS,x^(0)=x^0,S(0)=S0.\dot S = A S + S A^T + W - S C^T V^{-1} C S, \qquad \hat x(0) = \hat x_0, \quad S(0) = S_0.

The term dz−Cx^ dtdz - C \hat x\, dt is the innovation. Its increments are white with intensity VV when the filter is optimal.

Duality. Replace (A,B,Q,R)(A, B, Q, R) of the regulator by (AT,CT,W,V)(A^T, C^T, W, V) and run time backward: the regulator Riccati equation becomes the filter equation. So the steady state filter needs the stabilizing solution of the CARE for the dual data, and every Riccati solver serves both problems.

The algorithm

The filter is advanced in steps of length hh. In practice the measurement arrives as samples; Δzk\Delta z_k is the integral of yy over the step.

  1. KALMAN-BUCY(A, B, C, W, V, x̂₀, S₀, h)
  2. 1x̂ ← x̂₀; S ← S₀
  3. 2for each step k, with input u_k and measurement increment Δz_k do
  4. 3L_o ← S Cᵀ V⁻¹ ▷ gain from the current covariance
  5. 4x̂ ← x̂ + (A x̂ + B u_k) h + L_o (Δz_k - C x̂ h) ▷ Euler-Maruyama step of the filter
  6. 5S ← RK4 step of S' = A S + S Aᵀ + W - S Cᵀ V⁻¹ C S ▷ needs no data
  7. 6output (x̂, S)
  8. STEADY-STATE(A, C, W, V, S₀, h, tol)
  9. 7S ← S₀
  10. 8repeat S ← RK4 step of the Riccati equation until ‖S'‖ ≤ tol
  11. 9return S and L_o = S Cᵀ V⁻¹

Lines L3 and L5 do not use the measurements, so the gain sequence can be computed before the run and stored. Line L4 is the only line that touches the data. If the filter is run long enough, SS reaches its steady state, and lines L3 and L5 can be dropped: the filter is then the time-invariant observer x^˙=Ax^+Bu+Lo(y−Cx^)\dot{\hat x} = A \hat x + B u + L_o (y - C \hat x), which is the form used in LQG control. Lines L7 to L9 compute that steady state by integrating the Riccati equation until it stops changing. A direct CARE solver such as the Schur method, applied to the dual data, is faster when only the steady state is needed.

Example

Scalar, a=0a = 0. With x˙=w\dot x = w, y=x+v˙y = x + \dot v, W=V=1W = V = 1 and S0=0S_0 = 0, the Riccati equation is S˙=1−S2\dot S = 1 - S^2, so S(t)=tanh⁡tS(t) = \tanh t, and the gain Lo=SL_o = S grows from 0 to 1. At t=0.5,1,2t = 0.5, 1, 2 the variance is 0.4621,0.7616,0.96400.4621, 0.7616, 0.9640.

Scalar, a=1a = 1. With x˙=x+w\dot x = x + w and the same data, S˙=2S+1−S2\dot S = 2 S + 1 - S^2. Put S=1+σS = 1 + \sigma: σ˙=2−σ2\dot \sigma = 2 - \sigma^2, so

S(t)=1+2tanh⁡(2 t−ln⁡(1+2)),S(t) = 1 + \sqrt2 \tanh\left(\sqrt2\, t - \ln(1 + \sqrt2)\right),

which takes the values 0.3159,0.7560,1.6895,2.3578,2.41080.3159, 0.7560, 1.6895, 2.3578, 2.4108 at t=0.25,0.5,1,2,3t = 0.25, 0.5, 1, 2, 3 and tends to 1+2≈2.41421 + \sqrt2 \approx 2.4142. The steady state error dynamics are e˙=(1−Lo)e+⋯=−2 e+…\dot e = (1 - L_o) e + \dots = -\sqrt2\, e + \dots, so the filter is Hurwitz although the plant is not. With a=−1a = -1 the limit is 2−1≈0.4142\sqrt2 - 1 \approx 0.4142.

Double integrator. With A=[0100]A = \begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix}, C=[10]C = \begin{bmatrix} 1 & 0 \end{bmatrix}, W=IW = I and V=1V = 1, the steady state is

S∞=[3113],Lo=[31],S_\infty = \begin{bmatrix} \sqrt3 & 1 \\ 1 & \sqrt3 \end{bmatrix}, \qquad L_o = \begin{bmatrix} \sqrt3 \\ 1 \end{bmatrix},

and A−LoCA - L_o C has the characteristic polynomial s2+3 s+1s^2 + \sqrt3\, s + 1. This is the dual of the LQR problem with Q=IQ = I and R=1R = 1 for the dual plant (AT,CT)(A^T, C^T), whose gain is K=[31]=LoTK = \begin{bmatrix} \sqrt3 & 1 \end{bmatrix} = L_o^T.

Against a fixed gain. For any constant gain GG, the error covariance obeys P˙=(A−GC)P+P(A−GC)T+W+GVGT\dot P = (A - G C) P + P (A - G C)^T + W + G V G^T. Started from the same S0S_0, P(t)−S(t)P(t) - S(t) stays positive semidefinite for every tt.

Sample paths. Take the scalar plant a=−1a = -1 with W=V=1W = V = 1, x(0)∼N(0,1)x(0) \sim N(0, 1), x^0=0\hat x_0 = 0 and S0=1S_0 = 1, and simulate 400 paths with the Euler-Maruyama scheme and h=0.04h = 0.04 (seed 2024). At t=2t = 2 the Riccati equation gives S(2)=0.4159S(2) = 0.4159. The mean squared error over the paths is 0.4500.450, and the error lies within S(2)\sqrt{S(2)} in 255 of the 400 paths (63.8 percent), against 68.3 percent for a Gaussian error with variance S(2)S(2). With 400 paths, Hoeffding's inequality allows a deviation of 0.135 at confidence 1−10−61 - 10^{-6}, so the run agrees with the theory.

Correctness

The proof is in proofs/correctness.md. For a gain G(t)G(t) the error e=x−x^e = x - \hat x obeys de=(A−GC)e dt+dw−G dvde = (A - G C) e\, dt + dw - G\, dv, and the Itô rule gives the covariance equation P˙G=(A−GC)PG+PG(A−GC)T+W+GVGT\dot P_G = (A - GC) P_G + P_G (A - GC)^T + W + G V G^T. With G=SCTV−1G = S C^T V^{-1} this is the Riccati equation, so SS is the error covariance. For any other gain, D=PG−SD = P_G - S satisfies

D˙=(A−GC)D+D(A−GC)T+(G−Lo)V(G−Lo)T,D(0)=0,\dot D = (A - G C) D + D (A - G C)^T + (G - L_o) V (G - L_o)^T, \qquad D(0) = 0,

so D(t)≥0D(t) \ge 0 for all tt. By duality with the finite horizon LQR, S(t)S(t) tends to the stabilizing algebraic solution when (C,A)(C, A) is detectable and (A,W1/2)(A, W^{1/2}) is stabilizable, from every S0≥0S_0 \ge 0.

Proof: The Riccati differential equation is the error covariance of the filter, no other gain gives a smaller covariance, and the solution settles at the stabilizing algebraic solutionfull

The plant is dx=(Ax+Bu) dt+dwdx = (A x + B u)\, dt + dw, dz=Cx dt+dvdz = C x\, dt + dv, where ww and vv are independent Wiener processes with intensities W≥0W \ge 0 and V>0V > 0 (so E dw dwT=Wdt\mathbb{E}\, dw\, dw^T = W dt), x(0)x(0) has mean x^0\hat x_0 and covariance S0S_0, and x(0)x(0), ww, vv are independent. The input uu is known. A linear filter with a gain function G(t)G(t) is

dx^=(Ax^+Bu) dt+G(t)(dz−Cx^ dt),x^(0)=x^0.d\hat x = (A \hat x + B u)\, dt + G(t) (dz - C \hat x\, dt), \qquad \hat x(0) = \hat x_0.

The Kalman-Bucy filter is the choice G=Lo(t)=S(t)CTV−1G = L_o(t) = S(t) C^T V^{-1}, where SS solves S˙=AS+SAT+W−SCTV−1CS\dot S = A S + S A^T + W - S C^T V^{-1} C S with S(0)=S0S(0) = S_0. The proof has four parts: the error covariance of any gain (Part 1), the optimality of LoL_o (Part 2), the limit of S(t)S(t) (Part 3), and what the discrete steps of the code compute (Part 4).

Part 1: the error covariance of a gain

Lemma 1. Let e=x−x^e = x - \hat x and PG(t)=E eeTP_G(t) = \mathbb{E}\, e e^T. Then E e(t)=0\mathbb{E}\, e(t) = 0 and

P˙G=(A−GC)PG+PG(A−GC)T+W+GVGT,PG(0)=S0.\dot P_G = (A - G C) P_G + P_G (A - G C)^T + W + G V G^T, \qquad P_G(0) = S_0.

Proof. Subtract the filter from the plant. The input terms cancel, so de=(A−GC)e dt+dw−G dvde = (A - G C) e\, dt + dw - G\, dv. The mean obeys ddtE e=(A−GC) E e\frac{d}{dt}\mathbb{E}\,e = (A - GC)\,\mathbb{E}\,e with E e(0)=0\mathbb{E}\,e(0) = 0. The Itô product rule gives d(eeT)=de eT+e deT+de deTd(e e^T) = de\, e^T + e\, de^T + de\, de^T, and E de deT=(W+GVGT)dt\mathbb{E}\, de\, de^T = (W + G V G^T) dt because ww and vv are independent. Take expectations; the Itô integrals have mean 0. □\square

Lemma 2. With G=Lo=SCTV−1G = L_o = S C^T V^{-1}, the covariance PLoP_{L_o} equals SS.

Proof. LoVLoT=SCTV−1CSL_o V L_o^T = S C^T V^{-1} C S and LoCS=SCTV−1CSL_o C S = S C^T V^{-1} C S. Put them into Lemma 1:

(A−LoC)S+S(A−LoC)T+W+LoVLoT=AS+SAT+W−SCTV−1CS.(A - L_o C) S + S (A - L_o C)^T + W + L_o V L_o^T = A S + S A^T + W - S C^T V^{-1} C S.

So SS solves the equation of Lemma 1 with the same initial value, and the solution is unique (the right side is locally Lipschitz, and SS exists for all t≥0t \ge 0 by Part 3). □\square

Part 2: no gain does better

Lemma 3. For every bounded measurable gain G(t)G(t) and every t≥0t \ge 0, PG(t)−S(t)≥0P_G(t) - S(t) \ge 0. Equality on an interval holds only when G=LoG = L_o there, up to the null space of VV, which is {0}\{0\}.

Proof. Let D=PG−SD = P_G - S and F=A−GCF = A - G C. Subtract the two equations, write FPG=FD+FSF P_G = F D + F S, and use CS=VLoTC S = V L_o^T (from LoV=SCTL_o V = S C^T):

D˙=FD+DFT+(−GCS−SCTGT+GVGT+LoVLoT)=FD+DFT+(G−Lo)V(G−Lo)T.\dot D = F D + D F^T + \left(- G C S - S C^T G^T + G V G^T + L_o V L_o^T\right) = F D + D F^T + (G - L_o) V (G - L_o)^T.

Since D(0)=0D(0) = 0, the solution is D(t)=∫0tΦ(t,s)(G−Lo)V(G−Lo)TΦ(t,s)TdsD(t) = \int_0^t \Phi(t, s) (G - L_o) V (G - L_o)^T \Phi(t, s)^T ds, where Φ\Phi is the transition matrix of FF. The integrand is positive semidefinite, so D(t)≥0D(t) \ge 0. □\square

So the Kalman-Bucy gain minimizes E aTe(t)e(t)Ta\mathbb{E}\, a^T e(t) e(t)^T a for every direction aa and every tt, among all filters of the given form. Kalman and Bucy (1961) show more: when x(0)x(0), ww and vv are Gaussian, x^(t)\hat x(t) is the conditional mean E[x(t)∣z(s),s≤t]\mathbb{E}[x(t) \mid z(s), s \le t], so no estimator, linear or not, has a smaller error covariance. Without the Gaussian assumption, x^\hat x is the best linear estimate.

Part 3: the limit of the Riccati solution

Lemma 4. If (C,A)(C, A) is detectable and (A,W1/2)(A, W^{1/2}) is stabilizable, then for every S0≥0S_0 \ge 0 the solution S(t)S(t) exists for all t≥0t \ge 0 and tends to the unique stabilizing solution S∞≥0S_\infty \ge 0 of AS+SAT−SCTV−1CS+W=0A S + S A^T - S C^T V^{-1} C S + W = 0; A−S∞CTV−1CA - S_\infty C^T V^{-1} C is Hurwitz.

Proof. Set A~=AT\tilde A = A^T, B~=CT\tilde B = C^T, Q~=W\tilde Q = W, R~=V\tilde R = V. Then S(t)=Π(T−t)S(t) = \Pi(T - t), where Π\Pi solves the backward Riccati equation of the finite horizon LQR problem for (A~,B~,Q~,R~)(\tilde A, \tilde B, \tilde Q, \tilde R) on [0,T][0, T] with terminal weight S0S_0: the two equations are the same after the time reversal τ=T−t\tau = T - t. The LQR value ξTΠξ\xi^T \Pi \xi is the minimum of a cost that is nonnegative, so Π≥0\Pi \ge 0, and it is at most the cost of any fixed stabilizing feedback, so Π\Pi is bounded uniformly in the horizon; hence no finite escape. The hypotheses translate into (A~,B~)(\tilde A, \tilde B) stabilizable and (Q~1/2,A~)(\tilde Q^{1/2}, \tilde A) detectable, and under them the finite horizon solution converges, as the horizon grows, to the stabilizing solution of the CARE for any terminal weight S0≥0S_0 \ge 0 (Anderson and Moore 1990, the chapter on the infinite-time regulator). The transpose of that CARE is the filter equation, and A~−B~R~−1B~TS∞\tilde A - \tilde B \tilde R^{-1} \tilde B^T S_\infty Hurwitz means A−S∞CTV−1CA - S_\infty C^T V^{-1} C Hurwitz. □\square

Part 4: what the code computes

  • Lines L1 and L2. The state (x^,S)(\hat x, S) starts at (x^0,S0)(\hat x_0, S_0) and the loop takes one step per input and measurement increment.
  • Line L3 forms Lo=SCTV−1L_o = S C^T V^{-1} from the current SS, as in the definition.
  • Line L4 is one Euler-Maruyama step of the filter equation, with dzdz replaced by the measured increment Δzk=z(tk+1)−z(tk)\Delta z_k = z(t_{k+1}) - z(t_k). The noise enters additively in the filter equation (the gain does not depend on x^\hat x), so the scheme converges in mean square with order 1 in the step hh as h→0h \to 0. For a plant that is itself simulated by the same scheme, the discrete error obeys ek+1=(I+h(A−LoC))ek+Δwk−LoΔvke_{k+1} = (I + h (A - L_o C)) e_k + \Delta w_k - L_o \Delta v_k exactly, which is what the tests use.
  • Line L5 is one RK4 step of the Riccati equation, with a local error O(h5)O(h^5) on any bounded interval where SS is smooth. The symmetrization after the step only removes rounding.
  • Lines L7 to L9. A fixed point of the RK4 map with S˙=0\dot S = 0 is a solution of the algebraic equation. The loop stops when the residual ∥S˙∥\|\dot S\| is at most the tolerance, so the returned SS solves the algebraic equation with that residual. By Lemma 4 the exact flow reaches every neighborhood of S∞S_\infty; RK4 with a small enough step keeps the stable fixed point stable, so the loop ends. The linearized flow at S∞S_\infty is Δ˙=FΔ+ΔFT\dot \Delta = F \Delta + \Delta F^T with F=A−LoCF = A - L_o C, whose eigenvalues are the sums λi+λj\lambda_i + \lambda_j of eigenvalues of FF; the step hh must be small compared with the inverse of their largest modulus.

Complexity

One step costs O(n3)O(n^3) for the products in the Riccati right-hand side (four evaluations per RK4 step), O(np2+p3)O(n p^2 + p^3) for the gain with VV factored once, and O(n2+nm+np)O(n^2 + n m + n p) for the estimate. Memory is O(n2+np)O(n^2 + n p). With a precomputed gain sequence the online cost per step drops to O(n2+nm+np)O(n^2 + n m + n p). Integrating to the steady state takes a number of steps that grows with the ratio of the slowest to the fastest time constant of the Riccati flow.

Properties

  • Optimal among linear filters, for every tt and in the matrix sense, with no Gaussian assumption. With Gaussian x(0)x(0), ww and vv, the estimate is the conditional mean, and so it is optimal among all estimators.
  • The covariance does not depend on the data. S(t)S(t) is known before any measurement arrives. This also means that the filter cannot detect a wrong noise model from SS; only the innovations can show it.
  • The innovation is white with intensity VV for the optimal filter. Testing this property on data checks the model.
  • Steady state. Under detectability and stabilizability, S(t)→S∞S(t) \to S_\infty and A−LoCA - L_o C is Hurwitz. When AA is Hurwitz and the signals are stationary, the steady state filter is the causal Wiener filter for the same problem, written in state-space form.
  • Duality. S(t)S(t) for the plant equals the regulator Riccati solution for the dual plant with time reversed. Every property of the LQR Riccati equation has a filter version.

Variants and improvements

  • Correlated noises. If ww and vv have cross intensity MM, the gain becomes Lo=(SCT+M)V−1L_o = (S C^T + M) V^{-1}, and the Riccati equation uses A−MV−1CA - M V^{-1} C and W−MV−1MTW - M V^{-1} M^T.
  • Time-varying plants. The same equations hold with A(t)A(t), C(t)C(t), W(t)W(t) and V(t)V(t); there is then no steady state in general.
  • Square root forms propagate a factor of SS so that it stays positive semidefinite in floating point.
  • Continuous-discrete filter. The state moves in continuous time and the measurements arrive at sampling instants. Propagate x^\hat x and SS between samples with the plant equation and the Lyapunov equation S˙=AS+SAT+W\dot S = A S + S A^T + W, and update at each sample with the discrete Kalman filter step.
  • Nonlinear plants. Linearize along the estimate: the continuous-time extended Kalman filter. It loses the optimality and the data independence of SS.

When to use it

Use the Kalman-Bucy filter when the plant model is in continuous time and the measurements are dense compared with the plant dynamics, or as the estimator of an analog or high rate controller. Use the steady state form inside LQG control and wherever a fixed observer gain is wanted with a noise based tuning. When the measurements come at a slow, fixed rate, use the discrete-time Kalman filter on the sampled model, or the continuous-discrete form. A pole placement Luenberger observer is the alternative when no noise model exists.

Pitfalls

  • Discretizing with a large step. The Euler step of line L4 is accurate only for hh small compared with the time constants of A−LoCA - L_o C. For slow sampling, discretize the plant exactly and use the discrete filter.
  • White noise is an idealization. A measurement with a bandwidth that is not much wider than the filter bandwidth is not white; model its color with a shaping filter as extra states.
  • Losing positive semidefiniteness. Rounding can make SS slightly indefinite; symmetrize after each step, or use a square root form.
  • Wrong intensities. SS reports the covariance under the assumed WW and VV, not the true error. A filter with too small WW trusts the model too much and can diverge from the true state while SS stays small.
  • Undetectable modes. If (C,A)(C, A) is not detectable, the error in the unobservable unstable modes grows without bound, and S(t)S(t) grows with it.

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()
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()
kalman_bucy_filter.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kalman-bucy-filter/. The authors are listed in prov/HYX6WP.jsonl.

"""The Kalman-Bucy filter: the continuous-time Kalman filter.

Plant: dx = (A x + B u) dt + dw, dz = C x dt + dv, where z is the integrated
measurement (y = dz/dt in the white noise notation) and w, v are independent
Wiener processes with intensities W >= 0 and V > 0.

The filter is

    dxhat = (A xhat + B u) dt + L_o (dz - C xhat dt),  L_o = S C^T V^-1,
    S' = A S + S A^T + W - S C^T V^-1 C S,             S(0) = S_0.

The class KalmanBucy advances the filter over steps of length h: xhat by one
Euler-Maruyama step driven by the measurement increment dz of the step, S by
one RK4 step of the Riccati differential equation (ctlsim.rk4_step).
steady_state integrates the Riccati equation until it stops changing, which
gives the stabilizing solution of the filter algebraic Riccati equation when
(C, A) is detectable and (A, W^(1/2)) is stabilizable.
"""

from ctlmat import add, inv, matvec, mul, sub, transpose
from ctlsim import rk4_step

__all__ = ["riccati_rhs", "gain", "KalmanBucy", "steady_state"]


def _flat(S):
    return [v for row in S for v in row]


def _mat(s, n):
    return [[s[i * n + j] for j in range(n)] for i in range(n)]


def _sym(S):
    n = len(S)
    return [[(S[i][j] + S[j][i]) / 2 for j in range(n)] for i in range(n)]


def riccati_rhs(A, C, W, V):
    """Return f(t, s, u) for the flattened Riccati equation S' = A S + S A^T + W - S C^T V^-1 C S."""
    n = len(A)
    M = mul(mul(transpose(C), inv(V)), C)
    At = transpose(A)

    def f(t, s, u):
        S = _mat(s, n)
        dS = add(add(mul(A, S), mul(S, At)), sub(W, mul(mul(S, M), S)))
        return _flat(dS)
    return f


def gain(S, C, V):
    """Return the filter gain L_o = S C^T V^-1."""
    return mul(mul(S, transpose(C)), inv(V))


class KalmanBucy:
    """Kalman-Bucy filter advanced in steps of length h."""

    def __init__(self, A, B, C, W, V, xhat0, S0):
        self.A, self.B, self.C, self.V = A, B, C, V
        self.n = len(A)
        self.f = riccati_rhs(A, C, W, V)
        self.xhat = list(xhat0)  # @line L1
        self.S = _sym(S0)
        self.t = 0.0

    def step(self, u, dz, h):
        """Advance by h with input u (flat list) and measurement increment dz = integral of y over the step."""
        A, B, C = self.A, self.B, self.C
        Lo = gain(self.S, C, self.V)  # @line L3
        x = self.xhat
        drift = matvec(A, x)
        if B is not None and u is not None:
            drift = [d + b for d, b in zip(drift, matvec(B, u))]
        innov = [dzi - h * cx for dzi, cx in zip(dz, matvec(C, x))]
        corr = matvec(Lo, innov)
        self.xhat = [xi + h * di + ci for xi, di, ci in zip(x, drift, corr)]  # @line L4
        s = rk4_step(self.f, self.t, _flat(self.S), None, h)  # @line L5
        self.S = _sym(_mat(s, self.n))
        self.t += h
        return self.xhat, self.S  # @line L6

    def run(self, inputs, increments, h):
        """Run over the lists of inputs and measurement increments; return the list of (xhat, S)."""
        out = []
        for u, dz in zip(inputs, increments):  # @line L2
            xh, S = self.step(u, dz, h)
            out.append((list(xh), [row[:] for row in S]))
        return out


def riccati_solution(A, C, W, V, S0, t1, h):
    """Return S(t1) of the Riccati differential equation from S(0) = S0, RK4 with step h."""
    f = riccati_rhs(A, C, W, V)
    n = len(A)
    steps = round(t1 / h)
    if abs(steps * h - t1) > 1e-9 * max(t1, h):
        raise ValueError("t1 is not an integer multiple of h")
    s = _flat(S0)
    for k in range(steps):
        s = rk4_step(f, k * h, s, None, h)
    return _sym(_mat(s, n))


def steady_state(A, C, W, V, S0=None, h=0.01, tol=1e-12, max_steps=1000000):
    """Integrate the Riccati equation until |S'| <= tol; return (S, L_o)."""
    n = len(A)
    f = riccati_rhs(A, C, W, V)
    s = _flat(S0 if S0 is not None else [[0.0] * n for _ in range(n)])  # @line L7
    for k in range(max_steps):  # @line L8
        if max(abs(v) for v in f(0.0, s, None)) <= tol:
            S = _sym(_mat(s, n))
            return S, gain(S, C, V)  # @line L9
        s = rk4_step(f, k * h, s, None, h)
    raise ArithmeticError("the Riccati equation did not settle; check detectability and stabilizability")
test_kalman_bucy_filter.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kalman-bucy-filter/. The authors are listed in prov/HYX6WP.jsonl.

import math
import random

import ctlmat as cm
from ctlsim import rk4_step
from kalman_bucy_filter import KalmanBucy, gain, riccati_rhs, riccati_solution, steady_state

R2 = math.sqrt(2.0)
R3 = math.sqrt(3.0)

# Double integrator, position measured, W = I, V = 1.
A = [[0.0, 1.0], [0.0, 0.0]]
B = [[0.0], [1.0]]
C = [[1.0, 0.0]]
W = [[1.0, 0.0], [0.0, 1.0]]
V = [[1.0]]


def test_scalar_riccati_closed_forms():
    # a = 0, c = w = v = 1, S(0) = 0: S(t) = tanh(t).  RK4 with h = 0.01, error below 1e-8.
    for t in [0.5, 1.0, 2.0]:
        S = riccati_solution([[0.0]], [[1.0]], [[1.0]], [[1.0]], [[0.0]], t, 0.01)
        assert abs(S[0][0] - math.tanh(t)) < 1e-8
    # a = 1: S(t) = 1 + sqrt2 tanh(sqrt2 t + atanh(-1/sqrt2)).
    c0 = math.atanh(-1.0 / R2)
    for t in [0.5, 1.0, 3.0]:
        S = riccati_solution([[1.0]], [[1.0]], [[1.0]], [[1.0]], [[0.0]], t, 0.01)
        assert abs(S[0][0] - (1.0 + R2 * math.tanh(R2 * t + c0))) < 1e-8


def test_steady_state_values():
    S, L = steady_state([[1.0]], [[1.0]], [[1.0]], [[1.0]])
    assert abs(S[0][0] - (1.0 + R2)) < 1e-9
    S, L = steady_state([[-1.0]], [[1.0]], [[1.0]], [[1.0]])
    assert abs(S[0][0] - (R2 - 1.0)) < 1e-9
    S, L = steady_state(A, C, W, V)
    want = [[R3, 1.0], [1.0, R3]]
    assert all(abs(S[i][j] - want[i][j]) < 1e-9 for i in range(2) for j in range(2))
    assert abs(L[0][0] - R3) < 1e-9 and abs(L[1][0] - 1.0) < 1e-9
    # Error polynomial s^2 + sqrt3 s + 1.
    p = cm.charpoly(cm.sub(A, cm.mul(L, C)))
    assert abs(p[1] - R3) < 1e-9 and abs(p[2] - 1.0) < 1e-9


def test_steady_state_solves_the_filter_are_on_random_plants():
    rng = random.Random(7)
    for _ in range(5):
        n = rng.choice([2, 3])
        A_ = [[rng.uniform(-1.0, 1.0) - (1.5 if i == j else 0.0) for j in range(n)] for i in range(n)]
        C_ = [[rng.uniform(-1, 1) for _ in range(n)]]
        W_ = cm.eye(n)
        S, L = steady_state(A_, C_, W_, [[0.5]], h=0.02)
        res = riccati_rhs(A_, C_, W_, [[0.5]])(0.0, [v for row in S for v in row], None)
        assert max(abs(v) for v in res) < 1e-9
        assert cm.is_pos_def(S)
        assert max(z.real for z in cm.polyroots(cm.charpoly(cm.sub(A_, cm.mul(L, C_))))) < 0


def test_riccati_solution_beats_every_constant_gain():
    # For a fixed gain G the error covariance obeys P' = (A - G C) P + P (A - G C)^T + W + G V G^T.
    # P(t) - S(t) stays positive semidefinite for every G when both start at S0.
    rng = random.Random(1)
    S0 = [[2.0, 0.0], [0.0, 2.0]]
    h = 0.02
    f = riccati_rhs(A, C, W, V)
    for _ in range(4):
        G = [[rng.uniform(0.5, 3.0)], [rng.uniform(0.3, 2.0)]]
        F = cm.sub(A, cm.mul(G, C))
        Ft = cm.transpose(F)
        N = cm.add(W, cm.mul(cm.mul(G, V), cm.transpose(G)))

        def g(t, s, u, F=F, Ft=Ft, N=N):
            P = [s[0:2], s[2:4]]
            dP = cm.add(cm.add(cm.mul(F, P), cm.mul(P, Ft)), N)
            return [v for row in dP for v in row]
        s = [v for row in S0 for v in row]
        p = list(s)
        for k in range(150):
            s = rk4_step(f, k * h, s, None, h)
            p = rk4_step(g, k * h, p, None, h)
            if k % 10 == 9:
                D = [[p[0] - s[0], p[1] - s[1]], [p[2] - s[2], p[3] - s[3]]]
                ev = [(D[0][0] + D[1][1]) / 2 + sg * math.sqrt(((D[0][0] - D[1][1]) / 2) ** 2 + D[0][1] * D[1][0]) for sg in (-1, 1)]
                assert min(ev) >= -1e-9


def test_noise_free_error_decays():
    S, L = steady_state(A, C, W, V)
    h = 0.01
    kb = KalmanBucy(A, B, C, W, V, [0.0, 0.0], S)
    x = [1.0, -1.0]
    e0 = math.hypot(x[0], x[1])
    rate = R3 / 2 - 0.05
    for k in range(1, 801):
        u = [math.sin(0.3 * k * h)]
        dz = [h * cm.dot(C[0], x)]
        kb.step(u, dz, h)
        x = [x[0] + h * x[1], x[1] + h * u[0]]  # Euler step of the plant, the same scheme as the filter
        e = math.hypot(x[0] - kb.xhat[0], x[1] - kb.xhat[1])
        assert e <= 4.0 * math.exp(-rate * k * h) * e0  # max over t of |e^((A - L C) t)| e^(rate t) is about 3.2
    assert e < 1e-2


def test_monte_carlo_error_matches_the_riccati_variance():
    # Scalar plant a = -1, c = 1, W = V = 1, x0 ~ N(0, 1), xhat0 = 0, S0 = 1, Euler-Maruyama with h = 0.04 to T = 2.
    # The event |e(T)| <= sqrt(S(T)) has probability erf(1/sqrt2) = 0.6827 for e ~ N(0, S(T)).
    # Hoeffding with M = 400 paths and delta = 1e-6 gives the tolerance sqrt(ln(2/delta) / (2 M)) = 0.135;
    # 0.02 more covers the O(h) bias of the Euler-Maruyama scheme.
    rng = random.Random(2024)
    h, steps, M = 0.04, 50, 400
    a = -1.0
    S_T = riccati_solution([[a]], [[1.0]], [[1.0]], [[1.0]], [[1.0]], h * steps, h)[0][0]
    hit = 0
    below = 0
    sq = math.sqrt(h)
    for _ in range(M):
        x = rng.gauss(0.0, 1.0)
        kb = KalmanBucy([[a]], None, [[1.0]], [[1.0]], [[1.0]], [0.0], [[1.0]])
        for _ in range(steps):
            dz = [x * h + sq * rng.gauss(0.0, 1.0)]
            kb.step(None, dz, h)
            x = x + a * x * h + sq * rng.gauss(0.0, 1.0)
        e = x - kb.xhat[0]
        hit += abs(e) <= math.sqrt(S_T)
        below += e <= 0.0
    tol = math.sqrt(math.log(2 / 1e-6) / (2 * M)) + 0.02
    assert abs(hit / M - math.erf(1 / R2)) <= tol
    assert abs(below / M - 0.5) <= tol


def test_gain_formula():
    S = [[2.0, 0.5], [0.5, 1.0]]
    assert gain(S, C, [[4.0]]) == [[0.5], [0.125]]

History

Kalman (1960) published the discrete-time filter. Kalman and Bucy (1961) treated the continuous-time case: they derived the filter, the variance equation that is now called the Riccati differential equation, and the duality with the regulator problem that Kalman had solved. The steady state filter became the estimator of the LQG controller, which Athans (1971) presented as a design method.

References

  1. R. E. Kalman and R. S. Bucy, New results in linear filtering and prediction theory, Journal of Basic Engineering 83(1), 95-108, 1961, the filter equations, the variance equation (the Riccati differential equation) and the duality with the regulator problem
  2. Brian D. O. Anderson and John B. Moore, Optimal Control, Linear Quadratic Methods, Prentice Hall, 1990 (Dover reprint, 2007), the chapters on the infinite-time regulator and on state estimator design, with the Kalman-Bucy filter as the dual of the regulator
  3. Michael Athans, The role and use of the stochastic linear-quadratic-Gaussian problem in control system design, IEEE Transactions on Automatic Control 16(6), 529-552, 1971, the steady state Kalman-Bucy filter as the estimator of the LQG controller

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example