Algorithm Search⌘K

Algorithmcore

Kalman channel tracking

Also called Gauss-Markov channel tracking.

Tracks the taps of a time-varying channel with a Kalman filter, using the first-order autoregressive model h_k = a h_(k-1) + v_k with a = J0(2 pi f_D T) and known or decided symbols.

Time
O(K L^2) worst
Space
O(L^2) extra
Where
K = the number of symbols; L = the number of channel taps
Properties
deterministicexact for gauss markov modelneeds dopplerneeds noise levelonline
Origin
Rudolf E. Kalman, 1960

Kalman channel tracking estimates the taps of a channel that changes from symbol to symbol, such as a mobile radio channel with a Doppler spread. It models each tap as a first-order autoregressive process, hk=a hk−1+vkh_k = a\, h_{k-1} + v_k, and runs a Kalman filter on that model. The observations are the received samples, and the regressors are known symbols: pilots, a training sequence, or decisions. For a Clarke channel with maximum Doppler shift fDf_D and symbol time TT, the lag-1 fit is a=J0(2πfDT)a = J_0(2\pi f_D T). The page differs from adaptive equalization: there, an LMS or RLS filter adapts the equalizer taps with a fixed step and no model of the channel motion. Here, the filter estimates the channel itself, and the model of the motion sets the gain at each step. The cost is O(L2)O(L^2) per symbol for LL taps.

In plain words

A mobile radio channel changes while the data passes. The receiver must follow it to undo it. Each new received sample gives a noisy look at the current channel. If the channel changes slowly, the receiver should average many looks. If it changes fast, old looks are stale and should count less. The Kalman filter makes this choice in the best way. It keeps an estimate and a measure of how wrong the estimate can be. Before each sample, it lets the estimate fade a little toward zero and adds uncertainty, as the model says. Then it moves the estimate toward the new sample by an amount set by the two uncertainties. The speed of the channel sets how much uncertainty to add each step.

The problem

The channel has LL taps hk=(hk[0],…,hk[L−1])Th_k = (h_k[0], \ldots, h_k[L-1])^T at symbol time kk. The receiver sees

y[k]=∑l=0L−1hk[l] x[k−l]+w[k]=ckhk+w[k],y[k] = \sum_{l=0}^{L-1} h_k[l]\, x[k-l] + w[k] = c_k h_k + w[k],

with the row ck=(x[k],x[k−1],…,x[k−L+1])c_k = (x[k], x[k-1], \ldots, x[k-L+1]) of symbols and w[k]∼CN(0,N0)w[k] \sim \mathcal{CN}(0, N_0). The receiver knows the symbols, either as pilots or as decisions, and symbols before time 0 are 0. The state model is

hk=a hk−1+vk,vk∼CN(0,Q),Q=(1−a2) diag(P0,…,PL−1),h_k = a\, h_{k-1} + v_k, \qquad v_k \sim \mathcal{CN}(0, Q), \qquad Q = (1 - a^2)\, \mathrm{diag}(P_0, \ldots, P_{L-1}),

with 0≤a≤10 \le a \le 1. This QQ keeps every tap stationary with E∣hk[l]∣2=PlE|h_k[l]|^2 = P_l, the power of tap ll in the tapped delay line model. The output is, for each kk, the estimate h^k\hat h_k of hkh_k from y[0],…,y[k]y[0], \ldots, y[k] and its error covariance Σk\Sigma_k.

Choosing a. The taps of a Clarke channel have the autocorrelation E[hkhˉk−m]=P J0(2πfDTm)E[h_k \bar h_{k-m}] = P\, J_0(2\pi f_D T m). The Yule-Walker equation of order 1 matches lag 1 of this: a=J0(2πfDT)a = J_0(2\pi f_D T). The model is a fit, not the Clarke process. It keeps the correlation at lag 1 and replaces the rest by ama^m.

The algorithm

  1. KALMAN-CHANNEL-TRACK(y, x, a, P, N0)
  2. 1ĥ ← 0; Σ ← diag(P) ▷ the prior of the taps
  3. 2for k ← 0 to K - 1 do
  4. 3ĥ ← a ĥ; Σ ← a² Σ + Q ▷ predict, Q = (1 - a²) diag(P)
  5. 4c ← (x[k], x[k-1], ..., x[k-L+1]) ▷ known or decided symbols
  6. 5s ← c Σ cᴴ + N0 ▷ the variance of the innovation
  7. 6g ← Σ cᴴ / s ▷ the Kalman gain, a column
  8. 7ĥ ← ĥ + g (y[k] - c ĥ) ▷ update with the innovation
  9. 8Σ ← Σ - g c Σ
  10. 9output ĥ, Σ

Line L1 starts from the stationary law of the taps. Line L3 is the prediction. It moves the estimate toward 0 by the factor aa and adds the variance QQ of the new random part. At k=0k = 0 it gives back diag(P)\mathrm{diag}(P), because a2P+(1−a2)P=Pa^2 P + (1 - a^2) P = P. Line L4 builds the regressor. In training or pilot mode it holds known symbols. In decision-directed mode it holds the decisions of an equalizer. Line L5 is the predicted variance of y[k]y[k], which is a real number. Line L6 is the gain: the covariance of the tap error with the innovation, divided by the variance of the innovation. Line L7 corrects the prediction with the innovation y[k]−c h^y[k] - c\,\hat h, and line L8 removes the part of the uncertainty that y[k]y[k] explains. The filter needs aa, PP and N0N_0. It does not need a step size.

Example

Take one tap, L=1L = 1, with P0=1P_0 = 1, pilots of modulus 1, N0=0.1N_0 = 0.1 (an SNR of 10 dB) and fDT=0.01f_D T = 0.01. Then a=J0(0.0628)=0.999013a = J_0(0.0628) = 0.999013 and Q=1−a2=0.001972Q = 1 - a^2 = 0.001972. The variances do not depend on the received samples:

kk 0 1 2 3 9 49 and later
predicted Σ\Sigma (line L3) 1 0.092702 0.049984 0.035233 0.017330 0.014960
gain gg (line L6) 0.909091 0.481065 0.333262 0.260535 0.147702 0.130133
error Σ\Sigma (line L8) 0.090909 0.048106 0.033326 0.026054 0.014770 0.013013

The first pilot gives the error N0/(1+N0)=0.0909N_0/(1 + N_0) = 0.0909. After about 50 pilots, the filter is in steady state. The steady predicted variance solves Σ−=Q(1−N0)/2+Q2(1−N0)2/4+QN0\Sigma^- = Q(1 - N_0)/2 + \sqrt{Q^2 (1 - N_0)^2/4 + Q N_0}, which is 0.0149600.014960, and the error is Σ−N0/(Σ−+N0)=0.013013\Sigma^- N_0 / (\Sigma^- + N_0) = 0.013013. This is 7.7 times smaller than the error N0=0.1N_0 = 0.1 of one pilot alone. The gain 0.1300.130 means that the filter averages about the last 8 pilots: older pilots are stale.

The tests also measure a case with two taps of powers 0.6 and 0.4, QPSK training, N0=0.05N_0 = 0.05 and a faster channel, fDT=0.02f_D T = 0.02 (seed 4, 600 symbols). The average of ∥hk−h^k∥2\|h_k - \hat h_k\|^2 over the symbols 300 to 599 is 0.0233 with a=J0(2π⋅0.02)a = J_0(2\pi \cdot 0.02). A filter that assumes a static channel (a=1a = 1, so Q=0Q = 0) has the error 0.654 on the same data. Its gain falls toward 0, and it stops following the channel.

Correctness

Claim. If the initial taps, the increments vkv_k and the noise are independent and circular Gaussian, and the symbols in ckc_k are known and independent of them, then after line L8 at step kk, h^=E[hk∣y[0],…,y[k]]\hat h = E[h_k \mid y[0], \ldots, y[k]] and Σ\Sigma is the conditional error covariance. So h^k\hat h_k minimizes the mean squared error over all estimators. Without the Gaussian assumption, h^k\hat h_k is still the best linear estimator. This is a theorem.

Key step. By induction, hk−1h_{k-1} given the past samples is Gaussian with mean h^\hat h and covariance Σ\Sigma. Then hkh_k given the same samples has mean ah^a \hat h and covariance a2Σ+Qa^2 \Sigma + Q, because vkv_k is independent of the past (line L3). The pair (hk,y[k])(h_k, y[k]) is then jointly Gaussian, with Cov(hk,y[k])=ΣcH\mathrm{Cov}(h_k, y[k]) = \Sigma c^H and Var(y[k])=cΣcH+N0\mathrm{Var}(y[k]) = c \Sigma c^H + N_0. The formula for a Gaussian conditional mean gives lines L6 to L8. The full proof, with the proper complex Gaussian case and the fit a=J0(2πfDT)a = J_0(2\pi f_D T), is in the proofs folder. The tests check the filter against the batch LMMSE estimate from the joint covariance E[hkhˉmT]=a∣k−m∣diag(P)E[h_k \bar h_m^T] = a^{|k-m|} \mathrm{diag}(P) within 10−910^{-9}.

The claim does not cover two common uses. In decision-directed mode, a wrong decision puts a wrong row ckc_k into line L4, and the filter does not know it. For a real Clarke channel, the AR(1) model is only a fit. In both cases the output is a good estimate in practice, but this is a heuristic, not a theorem.

Proof: Under the Gauss-Markov model with known symbols, the Kalman channel tracker gives the conditional mean and covariance of the taps, and a = J0(2 pi f_D T) is the lag-1 Yule-Walker fit of a Clarke channelfull

The taps are hk∈CLh_k \in \mathbb{C}^L. The model is hk=a hk−1+vkh_k = a\, h_{k-1} + v_k for k≥0k \ge 0, with 0≤a≤10 \le a \le 1, Q=(1−a2)DQ = (1 - a^2) D and D=diag(P0,…,PL−1)D = \mathrm{diag}(P_0, \ldots, P_{L-1}). The sample is y[k]=ckhk+w[k]y[k] = c_k h_k + w[k], where ckc_k is a known row vector. The random vectors h−1∼CN(0,D)h_{-1} \sim \mathcal{CN}(0, D), v0,v1,…∼CN(0,Q)v_0, v_1, \ldots \sim \mathcal{CN}(0, Q) and w[0],w[1],…∼CN(0,N0)w[0], w[1], \ldots \sim \mathcal{CN}(0, N_0) are all independent, and N0>0N_0 > 0. Write Yk=(y[0],…,y[k])Y_k = (y[0], \ldots, y[k]).

A random vector zz is proper complex Gaussian, z∼CN(m,C)z \sim \mathcal{CN}(m, C), if its real and imaginary parts are jointly Gaussian and E[(z−m)(z−m)T]=0E[(z - m)(z - m)^T] = 0. Linear maps and sums of independent proper Gaussian vectors are proper Gaussian.

Lemma 1 (Gaussian conditioning). Let (z,u)(z, u) be jointly proper complex Gaussian, with means mzm_z, mum_u, covariances CzzC_{zz}, CuuC_{uu} (invertible) and Czu=E[(z−mz)(u−mu)H]C_{zu} = E[(z - m_z)(u - m_u)^H]. Then zz given uu is CN(mz+CzuCuu−1(u−mu), Czz−CzuCuu−1CzuH)\mathcal{CN}(m_z + C_{zu} C_{uu}^{-1} (u - m_u),\ C_{zz} - C_{zu} C_{uu}^{-1} C_{zu}^H).

Proof. Let G=CzuCuu−1G = C_{zu} C_{uu}^{-1} and e=z−mz−G(u−mu)e = z - m_z - G (u - m_u). Then E[e(u−mu)H]=Czu−GCuu=0E[e (u - m_u)^H] = C_{zu} - G C_{uu} = 0. Also E[e(u−mu)T]=0E[e (u - m_u)^T] = 0, because the pair is proper. The real and imaginary parts of ee and uu are jointly Gaussian and uncorrelated, so ee is independent of uu. Hence z=mz+G(u−mu)+ez = m_z + G(u - m_u) + e given uu has the mean mz+G(u−mu)m_z + G(u - m_u) and the covariance E[eeH]=Czz−GCzuHE[e e^H] = C_{zz} - G C_{zu}^H. □\square

Lemma 2 (stationarity). Cov(hk)=D\mathrm{Cov}(h_k) = D for every k≥−1k \ge -1.

Proof. True for k=−1k = -1. If Cov(hk−1)=D\mathrm{Cov}(h_{k-1}) = D, then Cov(hk)=a2D+Q=D\mathrm{Cov}(h_k) = a^2 D + Q = D, because vkv_k is independent of hk−1h_{k-1}. □\square

Theorem 1. For every k≥0k \ge 0, the values h^\hat h and Σ\Sigma after line L8 at step kk satisfy h^=E[hk∣Yk]\hat h = E[h_k \mid Y_k] and Σ=Cov(hk∣Yk)\Sigma = \mathrm{Cov}(h_k \mid Y_k), and hkh_k given YkY_k is proper Gaussian.

Proof. Use induction on kk, with the statement for k=−1k = -1 read as: line L1 gives the mean 00 and the covariance DD of h−1h_{-1} given no samples. This is true by the model.

Assume that hk−1h_{k-1} given Yk−1Y_{k-1} is CN(h^,Σ)\mathcal{CN}(\hat h, \Sigma), with the values before step kk. The increment vkv_k is independent of (hk−1,Yk−1)(h_{k-1}, Y_{k-1}), since Yk−1Y_{k-1} depends only on h−1,v0,…,vk−1h_{-1}, v_0, \ldots, v_{k-1} and w[0],…,w[k−1]w[0], \ldots, w[k-1]. So hk=ahk−1+vkh_k = a h_{k-1} + v_k given Yk−1Y_{k-1} is CN(ah^, a2Σ+Q)\mathcal{CN}(a \hat h,\ a^2 \Sigma + Q). These are the values of line L3; call them h^−\hat h^- and Σ−\Sigma^-.

Given Yk−1Y_{k-1}, the pair (hk,y[k])(h_k, y[k]) is proper Gaussian, because y[k]=ckhk+w[k]y[k] = c_k h_k + w[k] and w[k]w[k] is independent of everything else. Its moments are E[y[k]∣Yk−1]=ckh^−E[y[k] \mid Y_{k-1}] = c_k \hat h^-, Cov(hk,y[k]∣Yk−1)=Σ−ckH\mathrm{Cov}(h_k, y[k] \mid Y_{k-1}) = \Sigma^- c_k^H, and Var(y[k]∣Yk−1)=ckΣ−ckH+N0=s\mathrm{Var}(y[k] \mid Y_{k-1}) = c_k \Sigma^- c_k^H + N_0 = s, which is line L5 and is at least N0>0N_0 > 0. Lemma 1 with z=hkz = h_k and u=y[k]u = y[k] gives the conditional mean h^−+(Σ−ckH/s)(y[k]−ckh^−)\hat h^- + (\Sigma^- c_k^H / s)(y[k] - c_k \hat h^-) and the covariance Σ−−(Σ−ckH/s) ckΣ−\Sigma^- - (\Sigma^- c_k^H / s)\, c_k \Sigma^-, using (Σ−ckH)H=ckΣ−(\Sigma^- c_k^H)^H = c_k \Sigma^-. With g=Σ−ckH/sg = \Sigma^- c_k^H / s (line L6), these are lines L7 and L8. Conditioning on Yk−1Y_{k-1} and then on y[k]y[k] is conditioning on YkY_k, so the statement holds for kk. □\square

Corollary 1 (optimality). h^k\hat h_k minimizes E∥hk−f(Yk)∥2E\|h_k - f(Y_k)\|^2 over all measurable functions ff, and the minimum is tr Σk\mathrm{tr}\, \Sigma_k in expectation over the samples. If the Gaussian assumption is dropped but the first and second moments stay the same, the same recursion gives the linear estimator with the smallest mean squared error, because lines L3 to L8 use only first and second moments and Lemma 1 holds for the best linear estimator without the Gaussian assumption.

Proof. The conditional mean minimizes the mean squared error, and its error covariance is the conditional covariance. For the linear case, the proof of Lemma 1 without the independence step shows that mz+G(u−mu)m_z + G(u - m_u) makes the error uncorrelated with uu, which is the orthogonality condition of the linear minimum mean squared error estimator. □\square

Corollary 2 (bounded uncertainty). (Σk)ll≤Pl(\Sigma_k)_{ll} \le P_l for every kk and ll.

Proof. The conditional variance of a Gaussian variable never exceeds its unconditional variance, which is PlP_l by Lemma 2. □\square

Lemma 3 (the lag-1 fit). Let (hk)(h_k) be a stationary process with autocorrelation r(m)=E[hkhˉk−m]=P J0(2πfDTm)r(m) = E[h_k \bar h_{k-m}] = P\, J_0(2\pi f_D T m), the Clarke model sampled at the symbol time TT. The coefficient aa that minimizes E∣hk−ahk−1∣2E|h_k - a h_{k-1}|^2 over real or complex aa is a=r(1)/r(0)=J0(2πfDT)a = r(1)/r(0) = J_0(2\pi f_D T), and the minimum is P(1−J0(2πfDT)2)P (1 - J_0(2\pi f_D T)^2), which is the variance of vkv_k in the model.

Proof. E∣hk−ahk−1∣2=r(0)−2 Re(aˉ r(1))+∣a∣2r(0)E|h_k - a h_{k-1}|^2 = r(0) - 2\,\mathrm{Re}(\bar a\, r(1)) + |a|^2 r(0). Its minimum over aa is at a=r(1)/r(0)a = r(1)/r(0), which is the Yule-Walker equation of order 1. The minimum value is r(0)−∣r(1)∣2/r(0)=P(1−J02)r(0) - |r(1)|^2 / r(0) = P(1 - J_0^2). □\square

The AR(1) model with this aa has the same lag-0 and lag-1 correlations as the Clarke process, but its lag-mm correlation is ama^m, not J0(2πfDTm)J_0(2\pi f_D T m). So Theorem 1 states optimality for the model, not for the Clarke process.

Remarks on the conditions.

  1. The proof uses that ckc_k is known and independent of hh and ww. Pilots and training symbols satisfy this. Decisions do not: they depend on the noise, and a wrong decision is not the transmitted symbol. In decision-directed mode, Theorem 1 holds on the event that all decisions are correct and are treated as fixed, and not in general.
  2. The gain needs s>0s > 0, which holds because N0>0N_0 > 0. With N0=0N_0 = 0 and ck=0c_k = 0, line L6 divides by 0.
  3. The tests check Theorem 1 numerically: for a=1a = 1 the filter equals the batch Bayesian estimate (D−1+CHC/N0)−1CHy/N0(D^{-1} + C^H C / N_0)^{-1} C^H y / N_0, and for a=0.9a = 0.9 it equals Lemma 1 applied to the stacked taps (h0,…,hT−1)(h_0, \ldots, h_{T-1}) with Cov(hk,hm)=a∣k−m∣D\mathrm{Cov}(h_k, h_m) = a^{|k-m|} D, within 10−910^{-9}. A simulation checks Corollary 1: the measured mean of ∥hk−h^k∥2\|h_k - \hat h_k\|^2 divided by the mean of tr Σk\mathrm{tr}\, \Sigma_k is within 5 percent of 1.

Complexity

Line L3 costs O(L2)O(L^2) for the covariance, and lines L5, L6 and L8 cost O(L2)O(L^2) each, because Σ\Sigma is a full L×LL \times L matrix after the first update. Lines L4 and L7 cost O(L)O(L). So KK symbols cost O(KL2)O(K L^2) time in the real RAM, with O(L2)O(L^2) extra space for Σ\Sigma. There is no matrix inverse: the innovation is a scalar. With pilots of known values, the sequence of Σ\Sigma and gg does not depend on the data and can be computed in advance.

Properties

  • Exact for its model. Under the Gauss-Markov model with known symbols, no estimator has a smaller mean squared error.
  • The covariance does not depend on the samples. Lines L3, L5, L6 and L8 use only aa, QQ, N0N_0 and the regressors. With constant-modulus pilots on one tap, Σ\Sigma converges to the steady value of the example.
  • Bounded uncertainty. The error variance of each tap stays at most PlP_l, its prior variance.
  • Two limits. With a=1a = 1 and Q=0Q = 0, the filter gives the Bayesian LMMSE estimate of a fixed channel, and its memory grows without limit. With a=0a = 0, each estimate uses only the current sample.
  • Smoothing is better. The filter uses only the past. A smoother, such as the Rauch-Tung-Striebel smoother, also uses later samples and has a smaller error, at the cost of delay.

Variants and improvements

  • Higher-order models. An AR(pp) model fitted by the Yule-Walker equations matches pp lags of the Clarke correlation. The state then holds pp past values of each tap, so the cost grows to O(K(pL)2)O(K (pL)^2). Baddour and Beaulieu study such fits and their numerical conditioning.
  • Decision-directed tracking. After a training block, the regressor holds the decisions of an equalizer. Per-survivor processing runs one tracker on each survivor path of a Viterbi equalizer, so that each path uses its own decisions.
  • Joint symbol and channel estimation. An extended Kalman filter puts the symbols and the taps in one state.
  • RLS and LMS. The RLS algorithm with a forgetting factor and the LMS algorithm are cheaper trackers with a fixed memory. They do not use the Doppler spread.
  • Pilot interpolation. Pilot-symbol-assisted modulation puts pilots at fixed times and interpolates between them with an LMMSE estimator. The Kalman filter is the recursive form of that estimator for the AR model.

When to use it

Use Kalman tracking when the channel changes during a block, the Doppler spread and the noise level are known or estimated, and the receiver has known symbols or reliable decisions. It suits short channels, because the cost grows as L2L^2. If the channel is static over the block, a one-shot least squares or LMMSE estimate from a preamble is simpler. If the Doppler spread is unknown, an RLS tracker with a tuned forgetting factor is more robust.

Pitfalls

  • A static model. With a=1a = 1 in line L3, QQ is 0, the gain decays, and the filter stops following the channel. The example shows an error 28 times larger. Set aa from the Doppler spread, and keep a<1a < 1.
  • The conjugate in the gain. The observation is y=c hy = c\,h without a conjugate on cc, so line L6 uses cHc^H. With cTc^T in place of cHc^H, the filter is wrong for complex symbols but still right for BPSK pilots, so the bug can hide.
  • Wrong decisions in line L4. In decision-directed mode, a decision error gives a wrong regressor, the estimate moves the wrong way, and more errors can follow. Use pilots often enough to recover.
  • Loss of symmetry in line L8. Rounding makes Σ\Sigma drift away from Hermitian and positive definite over long runs. Symmetrize it after each step, as the implementation does, or use the Joseph form of the update.
  • The wrong correlation model. The AR(1) model keeps only the lag-1 correlation. On a fast channel, J0(2πfDTm)J_0(2\pi f_D T m) and ama^m differ already at small lags, and the filter is not optimal for the true channel.

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.

cbb.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Complex baseband tools for the communications pages.

Vectors are lists of complex numbers. Matrices are lists of rows. The
functions here are plain building blocks: small linear algebra, convolution,
the DFT as a direct sum, the Gaussian Q function, dB conversion, complex
Gaussian noise and the Wilson score interval. No page algorithm (equalizer,
estimator, synchronizer, detector, precoder, demapper or power allocation)
lives in this file.

Conventions (prompts of the communications area):
- dft is X[k] = sum_n x[n] e^(-j 2 pi k n / N) with no factor; idft has 1/N.
- udft and uidft are the unitary pair, with 1/sqrt(N) on both sides.
- qfunc(x) = 0.5 erfc(x / sqrt(2)); it never computes 1 - Phi(x).
- cn(rng, var) draws CN(0, var): real and imaginary parts are independent
  with variance var / 2 each, so E|w|^2 = var.
"""

import cmath
import math
import random


# ---------------------------------------------------------------- vectors and matrices


def zeros(rows: int, cols: int | None = None) -> list:
    """A zero vector of length rows, or a rows by cols zero matrix."""
    if cols is None:
        return [0j] * rows
    return [[0j] * cols for _ in range(rows)]


def eye(n: int) -> list[list[complex]]:
    """The n by n identity matrix."""
    return [[1 + 0j if i == k else 0j for k in range(n)] for i in range(n)]


def add(a: list, b: list) -> list:
    """Elementwise a + b for two vectors or two matrices of the same shape."""
    if len(a) != len(b):
        raise ValueError("shapes differ")
    if a and isinstance(a[0], list):
        return [add(r, s) for r, s in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a: list, b: list) -> list:
    """Elementwise a - b for two vectors or two matrices of the same shape."""
    if len(a) != len(b):
        raise ValueError("shapes differ")
    if a and isinstance(a[0], list):
        return [sub(r, s) for r, s in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(c: complex, a: list) -> list:
    """The scalar c times a vector or a matrix."""
    if a and isinstance(a[0], list):
        return [scale(c, r) for r in a]
    return [c * x for x in a]


def matmul(a: list[list[complex]], b: list[list[complex]]) -> list[list[complex]]:
    """The matrix product a b."""
    if not a or not b or len(a[0]) != len(b):
        raise ValueError("inner dimensions differ")
    cols = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a]


def matvec(a: list[list[complex]], x: list[complex]) -> list[complex]:
    """The matrix times vector product a x."""
    if a and len(a[0]) != len(x):
        raise ValueError("inner dimensions differ")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def herm(a: list) -> list:
    """The conjugate transpose of a matrix. A vector gives its conjugate."""
    if a and isinstance(a[0], list):
        return [[complex(a[i][k]).conjugate() for i in range(len(a))] for k in range(len(a[0]))]
    return [complex(x).conjugate() for x in a]


def dot(x: list[complex], y: list[complex]) -> complex:
    """The inner product x^H y = sum of conj(x_i) y_i."""
    if len(x) != len(y):
        raise ValueError("lengths differ")
    return sum(complex(p).conjugate() * q for p, q in zip(x, y))


def norm2(x: list) -> float:
    """The squared Euclidean norm sum |x_i|^2 (squared Frobenius norm for a matrix)."""
    if x and isinstance(x[0], list):
        return sum(norm2(r) for r in x)
    return sum(abs(v) ** 2 for v in x)


# ---------------------------------------------------------------- linear systems


def _lu(a: list[list[complex]]) -> tuple[list[list[complex]], list[int], int]:
    """LU factorization with partial pivoting. Returns (lu, perm, sign)."""
    n = len(a)
    if any(len(r) != n for r in a):
        raise ValueError("matrix is not square")
    m = [[complex(v) for v in r] for r in a]
    perm = list(range(n))
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(m[i][k]))
        if abs(m[p][k]) == 0.0:
            raise ValueError("matrix is singular")
        if p != k:
            m[k], m[p] = m[p], m[k]
            perm[k], perm[p] = perm[p], perm[k]
            sign = -sign
        for i in range(k + 1, n):
            f = m[i][k] / m[k][k]
            m[i][k] = f
            if f != 0:
                rk, ri = m[k], m[i]
                for c in range(k + 1, n):
                    ri[c] -= f * rk[c]
    return m, perm, sign


def _lu_solve(lu: list[list[complex]], perm: list[int], b: list[complex]) -> list[complex]:
    n = len(lu)
    y = [complex(b[perm[i]]) for i in range(n)]
    for i in range(n):
        for c in range(i):
            y[i] -= lu[i][c] * y[c]
    for i in range(n - 1, -1, -1):
        for c in range(i + 1, n):
            y[i] -= lu[i][c] * y[c]
        y[i] /= lu[i][i]
    return y


def solve(a: list[list[complex]], b: list) -> list:
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector, or a matrix whose columns are right-hand sides.
    Raises ValueError if a is singular.
    """
    lu, perm, _ = _lu(a)
    if b and isinstance(b[0], list):
        cols = [list(c) for c in zip(*b)]
        xs = [_lu_solve(lu, perm, c) for c in cols]
        return [list(r) for r in zip(*xs)]
    if len(b) != len(a):
        raise ValueError("lengths differ")
    return _lu_solve(lu, perm, b)


def inv(a: list[list[complex]]) -> list[list[complex]]:
    """The inverse of a square matrix."""
    return solve(a, eye(len(a)))


def det(a: list[list[complex]]) -> complex:
    """The determinant of a square matrix (0 for a singular matrix)."""
    try:
        lu, _, sign = _lu(a)
    except ValueError as e:
        if "singular" in str(e):
            return 0j
        raise
    d = complex(sign)
    for i in range(len(lu)):
        d *= lu[i][i]
    return d


def cholesky(a: list[list[complex]]) -> list[list[complex]]:
    """The lower triangular L with a = L L^H, for a Hermitian positive definite a.

    Raises ValueError if a is not positive definite (to rounding).
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for k in range(i + 1):
            s = complex(a[i][k]) - sum(low[i][c] * low[k][c].conjugate() for c in range(k))
            if i == k:
                if s.real <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = complex(math.sqrt(s.real))
            else:
                low[i][k] = s / low[k][k].real
    return low


# ---------------------------------------------------------------- convolution and the DFT


def conv(a: list[complex], b: list[complex]) -> list[complex]:
    """Linear convolution, of length len(a) + len(b) - 1."""
    if not a or not b:
        return []
    out = [0j] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for k, y in enumerate(b):
            out[i + k] += x * y
    return out


def cconv(a: list[complex], b: list[complex], n: int | None = None) -> list[complex]:
    """Circular convolution of length n (default: the longer length).

    Both inputs are padded with zeros to length n, or must not be longer than n.
    """
    if n is None:
        n = max(len(a), len(b))
    if len(a) > n or len(b) > n:
        raise ValueError("input longer than n")
    out = [0j] * n
    for i, x in enumerate(a):
        for k, y in enumerate(b):
            out[(i + k) % n] += x * y
    return out


def _twiddles(n: int, sign: int) -> list[complex]:
    return [cmath.exp(sign * 2j * math.pi * t / n) for t in range(n)]


def dft(x: list[complex]) -> list[complex]:
    """X[k] = sum over n of x[n] e^(-j 2 pi k n / N), as a direct O(N^2) sum."""
    n = len(x)
    w = _twiddles(n, -1)
    return [sum(x[t] * w[(k * t) % n] for t in range(n)) for k in range(n)]


def idft(xf: list[complex]) -> list[complex]:
    """x[n] = (1/N) sum over k of X[k] e^(j 2 pi k n / N), the inverse of dft."""
    n = len(xf)
    w = _twiddles(n, 1)
    return [sum(xf[k] * w[(k * t) % n] for k in range(n)) / n for t in range(n)]


def udft(x: list[complex]) -> list[complex]:
    """The unitary DFT: dft(x) / sqrt(N)."""
    s = 1.0 / math.sqrt(len(x)) if x else 1.0
    return [v * s for v in dft(x)]


def uidft(xf: list[complex]) -> list[complex]:
    """The unitary inverse DFT: sqrt(N) idft(X), the inverse of udft."""
    s = math.sqrt(len(xf)) if xf else 1.0
    return [v * s for v in idft(xf)]


# ---------------------------------------------------------------- Q function and dB


def qfunc(x: float) -> float:
    """Q(x) = P(Z > x) for a standard normal Z, computed as 0.5 erfc(x / sqrt(2))."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def qinv(p: float) -> float:
    """The x with Q(x) = p, for 0 < p < 1, by bisection on Q (which decreases)."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    lo, hi = -40.0, 40.0
    for _ in range(200):
        mid = 0.5 * (lo + hi)
        if qfunc(mid) > p:
            lo = mid
        else:
            hi = mid
        if hi - lo <= 1e-15 * max(1.0, abs(mid)):
            break
    return 0.5 * (lo + hi)


def db(x: float) -> float:
    """10 log10(x), for a ratio of powers or energies."""
    return 10.0 * math.log10(x)


def undb(d: float) -> float:
    """10^(d / 10), the inverse of db."""
    return 10.0 ** (d / 10.0)


# ---------------------------------------------------------------- noise and statistics


def cn(rng: random.Random, var: float) -> complex:
    """One sample of CN(0, var): independent real and imaginary parts of variance var / 2."""
    s = math.sqrt(var / 2.0)
    return complex(rng.gauss(0.0, s), rng.gauss(0.0, s))


def awgn(rng: random.Random, x: list[complex], n0: float) -> list[complex]:
    """x plus independent CN(0, n0) noise on each sample."""
    return [v + cn(rng, n0) for v in x]


def wilson(k: int, n: int, z: float = 3.29) -> tuple[float, float]:
    """The Wilson score interval for k successes in n trials (z = 3.29 is about 0.999 two-sided)."""
    if n <= 0 or not 0 <= k <= n:
        raise ValueError("need 0 <= k <= n and n > 0")
    p = k / n
    z2 = z * z
    den = 1.0 + z2 / n
    mid = (p + z2 / (2 * n)) / den
    half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / den
    return max(0.0, mid - half), min(1.0, mid + half)
kalman_channel_tracking.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kalman-channel-tracking/. The authors are listed in prov/JMK6AT.jsonl.

"""Kalman tracking of a time-varying FIR channel with a first-order autoregressive model.

The channel has L taps h_k = (h_k[0], ..., h_k[L-1]) at symbol time k. The
state model is h_k = a h_(k-1) + v_k with v_k ~ CN(0, Q) and
Q = (1 - a^2) diag(P), where P[l] is the power of tap l. This keeps every tap
stationary with E|h_k[l]|^2 = P[l]. The observation is
y[k] = sum_l h_k[l] x[k-l] + w[k] = c_k h_k + w[k], with the row
c_k = (x[k], x[k-1], ..., x[k-L+1]) of known symbols (pilots, training or
decisions) and w[k] ~ CN(0, N0). Symbols before time 0 are taken as 0.
"""

import math
import random

import cbb


def bessel_j0(x: float) -> float:
    """J0(x) from its power series sum (-1)^m (x/2)^(2m) / (m!)^2; accurate for |x| <= 10."""
    t = 1.0
    s = 1.0
    q = (x / 2.0) ** 2
    m = 0
    while abs(t) > 1e-17 * max(1.0, abs(s)):
        m += 1
        t *= -q / (m * m)
        s += t
    return s


def ar1_coefficient(fd_t: float) -> float:
    """The lag-1 fit a = J0(2 pi f_D T) of a Clarke channel, for the normalized Doppler f_D T."""
    return bessel_j0(2.0 * math.pi * fd_t)


def regressor(x: list[complex], k: int, taps: int) -> list[complex]:
    """The row c_k = (x[k], x[k-1], ..., x[k-L+1]), with 0 before time 0."""
    return [complex(x[k - l]) if k - l >= 0 else 0j for l in range(taps)]


def kalman_track(y: list[complex], x: list[complex], a: float, p: list[float], n0: float) -> tuple[list[list[complex]], list[list[list[complex]]]]:
    """The filtered estimates E[h_k | y[0..k]] and their error covariances, for k = 0, ..., K-1."""
    taps = len(p)
    if len(x) != len(y):
        raise ValueError("x and y differ in length")
    if not 0.0 <= a <= 1.0 or n0 <= 0 or any(v < 0 for v in p):
        raise ValueError("need 0 <= a <= 1, N0 > 0 and P >= 0")
    q = [(1.0 - a * a) * v for v in p]
    h = [0j] * taps  # @line L1
    s = [[complex(p[i]) if i == j else 0j for j in range(taps)] for i in range(taps)]  # @line L1
    estimates, covariances = [], []
    for k in range(len(y)):  # @line L2
        h = [a * v for v in h]  # @line L3
        s = [[a * a * s[i][j] + (q[i] if i == j else 0.0) for j in range(taps)] for i in range(taps)]  # @line L3
        c = regressor(x, k, taps)  # @line L4
        sc = [sum(s[i][j] * c[j].conjugate() for j in range(taps)) for i in range(taps)]  # S c^H
        inn = sum(c[i] * sc[i] for i in range(taps)).real + n0  # @line L5
        g = [v / inn for v in sc]  # @line L6
        e = y[k] - sum(c[i] * h[i] for i in range(taps))
        h = [h[i] + g[i] * e for i in range(taps)]  # @line L7
        cs = [sum(c[i] * s[i][j] for i in range(taps)) for j in range(taps)]  # c S
        s = [[s[i][j] - g[i] * cs[j] for j in range(taps)] for i in range(taps)]  # @line L8
        s = [[0.5 * (s[i][j] + s[j][i].conjugate()) for j in range(taps)] for i in range(taps)]
        estimates.append(list(h))  # @line L9
        covariances.append([list(r) for r in s])
    return estimates, covariances


def ar1_channel(rng: random.Random, a: float, p: list[float], count: int) -> list[list[complex]]:
    """count channel vectors h_0, ..., h_(count-1) of the AR(1) model, started in the stationary law."""
    q = [(1.0 - a * a) * v for v in p]
    h = [cbb.cn(rng, v) for v in p]
    out = []
    for _ in range(count):
        out.append(list(h))
        h = [a * h[i] + cbb.cn(rng, q[i]) for i in range(len(p))]
    return out


def transmit(rng: random.Random, hs: list[list[complex]], x: list[complex], n0: float) -> list[complex]:
    """y[k] = c_k h_k + w[k] with w[k] ~ CN(0, N0)."""
    taps = len(hs[0])
    return [sum(c * v for c, v in zip(regressor(x, k, taps), hs[k])) + cbb.cn(rng, n0) for k in range(len(x))]
test_kalman_channel_tracking.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kalman-channel-tracking/. The authors are listed in prov/JMK6AT.jsonl.

import math
import random

import pytest

import cbb
from kalman_channel_tracking import (
    ar1_channel,
    ar1_coefficient,
    bessel_j0,
    kalman_track,
    regressor,
    transmit,
)


def qpsk(rng):
    return complex(rng.choice((-1, 1)), rng.choice((-1, 1))) / math.sqrt(2)


def test_bessel_j0() -> None:
    assert bessel_j0(0.0) == 1.0
    assert abs(bessel_j0(2.404825557695773)) < 1e-13  # the first zero
    assert abs(bessel_j0(1.0) - 0.7651976865579666) < 1e-14
    assert abs(ar1_coefficient(0.01) - 0.99901328) < 1e-8


def test_static_channel_gives_the_batch_estimate() -> None:
    # a = 1 makes Q = 0: the filter is the batch Bayesian LMMSE estimate of one fixed h
    rng = random.Random(1)
    p, n0, k = [1.0, 0.5, 0.25], 0.2, 20
    x = [qpsk(rng) for _ in range(k)]
    h = [cbb.cn(rng, v) for v in p]
    y = transmit(rng, [h] * k, x, n0)
    est, cov = kalman_track(y, x, 1.0, p, n0)
    c = [regressor(x, t, 3) for t in range(k)]
    a = cbb.add(cbb.scale(1 / n0, cbb.matmul(cbb.herm(c), c)), [[1 / p[i] if i == j else 0 for j in range(3)] for i in range(3)])
    want = cbb.solve(a, cbb.scale(1 / n0, cbb.matvec(cbb.herm(c), y)))
    assert max(abs(u - v) for u, v in zip(est[-1], want)) < 1e-9
    want_cov = cbb.inv(a)
    assert max(abs(cov[-1][i][j] - want_cov[i][j]) for i in range(3) for j in range(3)) < 1e-9


def test_filter_equals_the_joint_lmmse_estimate() -> None:
    # the stacked taps (h_0, ..., h_(T-1)) are Gaussian with Cov(h_k[l], h_m[l]) = a^|k-m| P[l]
    rng = random.Random(2)
    a, p, n0, t = 0.9, [1.0, 0.4], 0.3, 6
    x = [qpsk(rng) for _ in range(t)]
    hs = ar1_channel(rng, a, p, t)
    y = transmit(rng, hs, x, n0)
    est, cov = kalman_track(y, x, a, p, n0)
    n = 2 * t
    sig = [[a ** abs(i // 2 - j // 2) * p[i % 2] if i % 2 == j % 2 else 0 for j in range(n)] for i in range(n)]
    obs = [[0j] * n for _ in range(t)]
    for k in range(t):
        obs[k][2 * k:2 * k + 2] = regressor(x, k, 2)
    for last in range(1, t + 1):
        # the estimate of h_(last-1) from y[0], ..., y[last-1]
        o = [row for row in obs[:last]]
        s_oh = cbb.matmul(o, sig)
        cyy = cbb.add(cbb.matmul(s_oh, cbb.herm(o)), cbb.scale(n0, cbb.eye(last)))
        gain_t = cbb.solve(cyy, s_oh)  # Cyy^-1 O Sigma
        rows = [2 * (last - 1), 2 * (last - 1) + 1]
        want = [sum(gain_t[r][i].conjugate() * y[r] for r in range(last)) for i in rows]
        assert max(abs(u - v) for u, v in zip(est[last - 1], want)) < 1e-9
        want_cov = [[sig[i][j] - sum(s_oh[r][i].conjugate() * gain_t[r][j] for r in range(last)) for j in rows] for i in rows]
        assert max(abs(cov[last - 1][u][v] - want_cov[u][v]) for u in range(2) for v in range(2)) < 1e-9


def test_error_power_matches_the_trace_of_the_covariance() -> None:
    # E ||h_k - h^_k||^2 = trace of the error covariance, checked by simulation (seed 3)
    rng = random.Random(3)
    # 100 runs of 100 symbols; the measured ratio is 1.0005
    a, p, n0 = ar1_coefficient(0.05), [0.6, 0.4], 0.1
    err = tr = 0.0
    for _ in range(100):
        x = [qpsk(rng) for _ in range(100)]
        hs = ar1_channel(rng, a, p, 100)
        y = transmit(rng, hs, x, n0)
        est, cov = kalman_track(y, x, a, p, n0)
        for k in range(100):
            err += cbb.norm2(cbb.sub(hs[k], est[k]))
            tr += cov[k][0][0].real + cov[k][1][1].real
    assert abs(err / tr - 1.0) < 0.05


def test_tracking_beats_a_static_model() -> None:
    # on a fading channel, the filter with the right a has a smaller error than the filter with a = 1
    rng = random.Random(4)
    a, p, n0, k = ar1_coefficient(0.02), [0.6, 0.4], 0.05, 600
    x = [qpsk(rng) for _ in range(k)]
    hs = ar1_channel(rng, a, p, k)
    y = transmit(rng, hs, x, n0)
    good, _ = kalman_track(y, x, a, p, n0)
    stale, _ = kalman_track(y, x, 1.0, p, n0)
    e_good = sum(cbb.norm2(cbb.sub(hs[t], good[t])) for t in range(300, k))
    e_stale = sum(cbb.norm2(cbb.sub(hs[t], stale[t])) for t in range(300, k))
    assert e_good < 0.2 * e_stale


def test_covariance_stays_hermitian_and_bounded() -> None:
    rng = random.Random(5)
    a, p, n0 = 0.95, [1.0, 0.5, 0.2], 0.5
    x = [qpsk(rng) for _ in range(200)]
    y = transmit(rng, ar1_channel(rng, a, p, 200), x, n0)
    _, cov = kalman_track(y, x, a, p, n0)
    for s in cov:
        for i in range(3):
            assert 0 < s[i][i].real <= p[i] + 1e-12
            for j in range(3):
                assert abs(s[i][j] - s[j][i].conjugate()) < 1e-12


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        kalman_track([1j], [1, 1], 0.9, [1.0], 0.1)
    with pytest.raises(ValueError):
        kalman_track([1j], [1], 1.5, [1.0], 0.1)
    with pytest.raises(ValueError):
        kalman_track([1j], [1], 0.9, [1.0], 0.0)

History

Kalman published the recursive filter for linear state-space models in 1960. Fading channels came into this frame through Gauss-Markov models of the taps: a first-order autoregressive model has one parameter, which can be set from the Doppler spread. Baddour and Beaulieu (2005) studied autoregressive models fitted to the Clarke autocorrelation, for simulation and for tracking. Komninakis, Fragouli, Sayed and Wesel (2002) used a Kalman filter on such a model to track a MIMO fading channel from decisions, for equalization.

References

  1. R. E. Kalman, A new approach to linear filtering and prediction problems, Transactions of the ASME, Journal of Basic Engineering 82(1), 1960, pages 35 to 45, the recursive filter for a linear state-space model
  2. Kareem E. Baddour and Norman C. Beaulieu, Autoregressive modeling for fading channel simulation, IEEE Transactions on Wireless Communications 4(4), 2005, pages 1650 to 1662, autoregressive models of a Rayleigh fading process fitted to the Clarke autocorrelation by the Yule-Walker equations
  3. Christos Komninakis, Christina Fragouli, Ali H. Sayed and Richard D. Wesel, Multi-input multi-output fading channel tracking and equalization using Kalman estimation, IEEE Transactions on Signal Processing 50(5), 2002, pages 1065 to 1076, a Kalman tracker of a MIMO fading channel with an autoregressive model, driven by decisions
  4. Steven M. Kay, Fundamentals of Statistical Signal Processing, Volume I: Estimation Theory, Prentice Hall, 1993, Chapter 13 (Kalman filters)

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