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.
- Solves
- Channel estimation
- Time
- O(K L^2) worst
- Space
- O(L^2) extra
- Where
- K = the number of symbols; L = the number of channel taps
- Model
- Real RAM
- Properties
- deterministicexact for gauss markov modelneeds dopplerneeds noise levelonline
- Evidence
- Proof sketchCode in 1 languages
- 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, , 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 and symbol time , the lag-1 fit is . 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 per symbol for 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 taps at symbol time . The receiver sees
with the row of symbols and . The receiver knows the symbols, either as pilots or as decisions, and symbols before time 0 are 0. The state model is
with . This keeps every tap stationary with , the power of tap in the tapped delay line model. The output is, for each , the estimate of from and its error covariance .
Choosing a. The taps of a Clarke channel have the autocorrelation . The Yule-Walker equation of order 1 matches lag 1 of this: . The model is a fit, not the Clarke process. It keeps the correlation at lag 1 and replaces the rest by .
The algorithm
KALMAN-CHANNEL-TRACK(y, x, a, P, N0)- 1
ĥ ← 0; Σ ← diag(P) ▷ the prior of the taps - 2
for k ← 0 to K - 1 do - 3
ĥ ← a ĥ; Σ ← a² Σ + Q ▷ predict, Q = (1 - a²) diag(P) - 4
c ← (x[k], x[k-1], ..., x[k-L+1]) ▷ known or decided symbols - 5
s ← c Σ cᴴ + N0 ▷ the variance of the innovation - 6
g ← Σ cᴴ / s ▷ the Kalman gain, a column - 7
ĥ ← ĥ + g (y[k] - c ĥ) ▷ update with the innovation - 8
Σ ← Σ - g c Σ - 9
output ĥ, Σ
Line L1 starts from the stationary law of the taps. Line L3 is the prediction. It moves the estimate toward 0 by the factor and adds the variance of the new random part. At it gives back , because . 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 , 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 , and line L8 removes the part of the uncertainty that explains. The filter needs , and . It does not need a step size.
Example
Take one tap, , with , pilots of modulus 1, (an SNR of 10 dB) and . Then and . The variances do not depend on the received samples:
| 0 | 1 | 2 | 3 | 9 | 49 and later | |
|---|---|---|---|---|---|---|
| predicted (line L3) | 1 | 0.092702 | 0.049984 | 0.035233 | 0.017330 | 0.014960 |
| gain (line L6) | 0.909091 | 0.481065 | 0.333262 | 0.260535 | 0.147702 | 0.130133 |
| error (line L8) | 0.090909 | 0.048106 | 0.033326 | 0.026054 | 0.014770 | 0.013013 |
The first pilot gives the error . After about 50 pilots, the filter is in steady state. The steady predicted variance solves , which is , and the error is . This is 7.7 times smaller than the error of one pilot alone. The gain 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, and a faster channel, (seed 4, 600 symbols). The average of over the symbols 300 to 599 is 0.0233 with . A filter that assumes a static channel (, so ) 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 and the noise are independent and circular Gaussian, and the symbols in are known and independent of them, then after line L8 at step , and is the conditional error covariance. So minimizes the mean squared error over all estimators. Without the Gaussian assumption, is still the best linear estimator. This is a theorem.
Key step. By induction, given the past samples is Gaussian with mean and covariance . Then given the same samples has mean and covariance , because is independent of the past (line L3). The pair is then jointly Gaussian, with and . The formula for a Gaussian conditional mean gives lines L6 to L8. The full proof, with the proper complex Gaussian case and the fit , is in the proofs folder. The tests check the filter against the batch LMMSE estimate from the joint covariance within .
The claim does not cover two common uses. In decision-directed mode, a wrong decision puts a wrong row 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 . The model is for , with , and . The sample is , where is a known row vector. The random vectors , and are all independent, and . Write .
A random vector is proper complex Gaussian, , if its real and imaginary parts are jointly Gaussian and . Linear maps and sums of independent proper Gaussian vectors are proper Gaussian.
Lemma 1 (Gaussian conditioning). Let be jointly proper complex Gaussian, with means , , covariances , (invertible) and . Then given is .
Proof. Let and . Then . Also , because the pair is proper. The real and imaginary parts of and are jointly Gaussian and uncorrelated, so is independent of . Hence given has the mean and the covariance .
Lemma 2 (stationarity). for every .
Proof. True for . If , then , because is independent of .
Theorem 1. For every , the values and after line L8 at step satisfy and , and given is proper Gaussian.
Proof. Use induction on , with the statement for read as: line L1 gives the mean and the covariance of given no samples. This is true by the model.
Assume that given is , with the values before step . The increment is independent of , since depends only on and . So given is . These are the values of line L3; call them and .
Given , the pair is proper Gaussian, because and is independent of everything else. Its moments are , , and , which is line L5 and is at least . Lemma 1 with and gives the conditional mean and the covariance , using . With (line L6), these are lines L7 and L8. Conditioning on and then on is conditioning on , so the statement holds for .
Corollary 1 (optimality). minimizes over all measurable functions , and the minimum is 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 makes the error uncorrelated with , which is the orthogonality condition of the linear minimum mean squared error estimator.
Corollary 2 (bounded uncertainty). for every and .
Proof. The conditional variance of a Gaussian variable never exceeds its unconditional variance, which is by Lemma 2.
Lemma 3 (the lag-1 fit). Let be a stationary process with autocorrelation , the Clarke model sampled at the symbol time . The coefficient that minimizes over real or complex is , and the minimum is , which is the variance of in the model.
Proof. . Its minimum over is at , which is the Yule-Walker equation of order 1. The minimum value is .
The AR(1) model with this has the same lag-0 and lag-1 correlations as the Clarke process, but its lag- correlation is , not . So Theorem 1 states optimality for the model, not for the Clarke process.
Remarks on the conditions.
- The proof uses that is known and independent of and . 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.
- The gain needs , which holds because . With and , line L6 divides by 0.
- The tests check Theorem 1 numerically: for the filter equals the batch Bayesian estimate , and for it equals Lemma 1 applied to the stacked taps with , within . A simulation checks Corollary 1: the measured mean of divided by the mean of is within 5 percent of 1.
Complexity
Line L3 costs for the covariance, and lines L5, L6 and L8 cost each, because is a full matrix after the first update. Lines L4 and L7 cost . So symbols cost time in the real RAM, with extra space for . There is no matrix inverse: the innovation is a scalar. With pilots of known values, the sequence of and 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 , , and the regressors. With constant-modulus pilots on one tap, converges to the steady value of the example.
- Bounded uncertainty. The error variance of each tap stays at most , its prior variance.
- Two limits. With and , the filter gives the Bayesian LMMSE estimate of a fixed channel, and its memory grows without limit. With , 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() model fitted by the Yule-Walker equations matches lags of the Clarke correlation. The state then holds past values of each tap, so the cost grows to . 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 . 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 in line L3, is 0, the gain decays, and the filter stops following the channel. The example shows an error 28 times larger. Set from the Doppler spread, and keep .
- The conjugate in the gain. The observation is without a conjugate on , so line L6 uses . With in place of , 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 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, and 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.
# 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag JMK6AT Edit this page History Report an error Markdown