Algorithm Search⌘K

Algorithmcore

Filtered Gaussian noise fading simulator

Also called Smith fading simulator, IFFT fading generator.

Weights N independent complex Gaussian samples by the square root of the Doppler spectrum of Clarke's model and takes one inverse DFT, which gives N samples of exactly Gaussian Rayleigh fading.

Time
O(N log N) worst
Space
O(N) extra
Where
N = the number of output samples
Properties
circularly stationarynot exact clarke autocorrelationexactly gaussianrandomized
Origin
J. I. Smith, David J. Young, Norman C. Beaulieu, 1975

The filtered Gaussian noise simulator makes NN samples of a fading gain h[n]h[n] for Clarke's model: it multiplies NN independent complex Gaussian samples by a filter F[k]F[k] whose square follows the Doppler spectrum, and takes one inverse DFT. Clarke's model is the target, the autocorrelation ΩJ0(2πfDτ)\Omega J_0(2\pi f_D\tau); the Jakes simulator and the Zheng-Xiao simulator add sinusoids, so their output is Gaussian only approximately, while the output here is exactly Gaussian. Its autocorrelation is the inverse DFT of the sampled spectrum, which is close to J0J_0 but not equal to it.

In plain words

Clarke's model says how strong each Doppler frequency is in the fading signal: a little at zero and most at the edges, near the largest Doppler shift. This simulator starts with pure random noise in the frequency domain, a separate random number for each frequency bin. It makes each number larger or smaller to match the strength that the model gives to that bin, and leaves the bins outside the Doppler band empty. One inverse Fourier transform then turns the shaped noise into a time signal. The result is random noise that changes at the speed of the Doppler, with the correct Rayleigh distribution at each time. The edge bin needs special care, because the model gives it an infinite peak.

The problem

The input is the number of samples NN, the normalized Doppler fm=fD/fsf_m = f_D/f_s (the maximum Doppler shift over the sample rate), the mean power Ω\Omega and a source of random numbers. The output is NN samples h[0],…,h[N−1]h[0], \ldots, h[N-1] spaced by 1/fs1/f_s. The goal is a circular complex Gaussian sequence with E∣h[n]∣2=ΩE|h[n]|^2 = \Omega and E[h[n+d]h[n]‾]E[h[n+d]\overline{h[n]}] close to ΩJ0(2πfmd)\Omega J_0(2\pi f_m d), so that the envelope is Rayleigh at each time and the time correlation is that of flat, time-correlated fading. The simulator gives the channel only; the receiver's CSIR or CSIT is set by the simulation that uses it.

The algorithm

  1. FILTERED-GAUSSIAN(N, f_m, Ω, rng)
  2. 1k_m ← ⌊N f_m⌋ ▷ the last bin inside the Doppler band; need 2 ≤ k_m < N/2
  3. 2F[k] ← √(1 / (2√(1 - (k / (N f_m))²))) for k = 1 .. k_m - 1
  4. 3F[k_m] ← √((k_m/2) (π/2 - arcsin((k_m - 1)/k_m))) ▷ the area of the spectrum over the edge bin
  5. 4F[N - k] ← F[k] for k = 1 .. k_m; all other F[k] ← 0
  6. 5X[k] ← F[k] G[k], with G[k] independent CN(0, 1), for k = 0 .. N-1
  7. 6y ← IDFT(X) ▷ y[n] = (1/N) Σₖ X[k] e^{j2πkn/N}
  8. 7return h[n] = N √(Ω / Σₖ F[k]²) · y[n] for n = 0 .. N-1

Lines L1 to L4 sample the Doppler spectrum S(f)∝1/1−(f/fD)2S(f) \propto 1/\sqrt{1 - (f/f_D)^2} at the bin frequencies kfs/Nk f_s/N, positive bins at kk and negative bins at N−kN - k. The spectrum is infinite at f=fDf = f_D, so line L3 replaces the edge sample by the integral of the spectrum over the last bin, ∫km−1kmdk21−(k/km)2\int_{k_m - 1}^{k_m} \frac{dk}{2\sqrt{1 - (k/k_m)^2}} with NfmN f_m replaced by kmk_m. Line L5 draws the random input; line L6 is one inverse DFT, computed by an FFT in practice. Line L7 scales the output to the mean power Ω\Omega.

Example

Take N=128N = 128 and fm=1/16f_m = 1/16, so km=8k_m = 8. The filter squares are F[1]2=0.5039F[1]^2 = 0.5039, rising to F[7]2=1/(21−49/64)=1.0328F[7]^2 = 1/(2\sqrt{1 - 49/64}) = 1.0328, and the edge bin has F[8]2=4(π/2−arcsin⁡(7/8))=2.0214F[8]^2 = 4(\pi/2 - \arcsin(7/8)) = 2.0214. Bins 9 to 119 are 0, and bins 120 to 127 mirror bins 8 to 1.

The autocorrelation of the output, r[d]=Ω∑kF[k]2cos⁡(2πkd/N)/∑kF[k]2r[d] = \Omega \sum_k F[k]^2\cos(2\pi k d/N) / \sum_k F[k]^2, is exact and can be compared with Clarke's model. For N=256N = 256 and fm=1/8f_m = 1/8, so km=32k_m = 32, with Ω=1\Omega = 1:

fDτf_D\tau 0.125 0.25 0.375 0.5 0.75 1.0 1.5 2.0
rr 0.8439 0.4464 -0.0154 -0.3459 -0.2646 0.2454 -0.2269 0.1848
J0(2πfDτ)J_0(2\pi f_D\tau) 0.8516 0.4720 0.0255 -0.3042 -0.2659 0.2203 -0.1812 0.1575

The difference is below 0.05 up to fDτ=1f_D\tau = 1. It shrinks slowly as the band gets more bins: at fDτ=0.375f_D\tau = 0.375 with fm=1/16f_m = 1/16, it is 0.105, 0.064, 0.041 and 0.027 for km=8k_m = 8, 16, 32 and 64. In a Monte Carlo run of 60 blocks of N=128N = 128 samples with fm=1/8f_m = 1/8, the sample autocorrelation agrees with r[d]r[d] within 0.1 Ω0.1\,\Omega.

Correctness

Claim. The output is a circular complex Gaussian vector. For every nn and dd, with indices modulo NN, E[h[n+d]h[n]‾]=r[d]E[h[n+d]\overline{h[n]}] = r[d] as above, E∣h[n]∣2=ΩE|h[n]|^2 = \Omega, the quadratures each have the autocorrelation r[d]/2r[d]/2, and their cross-correlation is 0. This is a theorem. That r[d]r[d] is close to ΩJ0(2πfmd)\Omega J_0(2\pi f_m d) for dd well below NN is a measurement, as in the table.

Key step. The output is a linear map of independent CN(0,1)CN(0, 1) inputs, so it is jointly circular Gaussian, and E[h[n+d]h[n]‾]=(c2/N2)∑kF[k]2ej2πkd/NE[h[n+d]\overline{h[n]}] = (c^2/N^2)\sum_k F[k]^2 e^{j2\pi kd/N} depends on dd only. Because F[N−k]=F[k]F[N - k] = F[k], this sum is real, which makes the quadratures uncorrelated. The full proof is in the proofs folder.

Proof: The filtered Gaussian noise simulator outputs a circular Gaussian vector with power Omega and a circular autocorrelation set by the filterfull

Let F[0],…,F[N−1]F[0], \ldots, F[N-1] be the filter of lines L1 to L4, with F[0]=0F[0] = 0, F[k]=F[N−k]F[k] = F[N-k] for 1≤k≤km1 \le k \le k_m, and F[k]=0F[k] = 0 for km<k<N−kmk_m < k < N - k_m. The condition km<N/2k_m < N/2 makes the bins 1,…,km1, \ldots, k_m and N−km,…,N−1N - k_m, \ldots, N - 1 disjoint, so the mirror step of line L4 is well defined, and s=∑kF[k]2>0s = \sum_k F[k]^2 > 0 because F[1]>0F[1] > 0. Let G[0],…,G[N−1]G[0], \ldots, G[N-1] be independent CN(0,1)CN(0, 1), which means EG[k]=0E G[k] = 0, E∣G[k]∣2=1E|G[k]|^2 = 1 and EG[k]2=0E G[k]^2 = 0. With c=NΩ/sc = N\sqrt{\Omega/s}, lines L5 to L7 give

h[n]=cN∑k=0N−1F[k] G[k] ej2πkn/N.h[n] = \frac{c}{N} \sum_{k=0}^{N-1} F[k]\, G[k]\, e^{j 2\pi k n/N}.

Indices of hh are taken modulo NN.

Lemma 1 (Gaussian output). The vector (h[0],…,h[N−1])(h[0], \ldots, h[N-1]) is circular complex Gaussian with mean 0.

Proof. It is a fixed linear map of the vector GG, which is circular complex Gaussian, and a linear map preserves this class. Directly, Eh[n]=0E h[n] = 0 and E[h[n]h[m]]=(c/N)2∑k,lF[k]F[l]ej2π(kn+lm)/NE[G[k]G[l]]=0E[h[n]h[m]] = (c/N)^2 \sum_{k,l} F[k]F[l] e^{j2\pi(kn + lm)/N} E[G[k]G[l]] = 0, because E[G[k]G[l]]=0E[G[k]G[l]] = 0 for k≠lk \ne l by independence and for k=lk = l by EG2=0E G^2 = 0. A zero-mean complex Gaussian vector with zero pseudo-covariance is circular. □\square

Theorem 1 (autocorrelation). For all nn and dd,

E[h[n+d] h[n]‾]=r[d]=Ωs∑k=0N−1F[k]2cos⁡(2πkdN),E\big[h[n+d]\,\overline{h[n]}\big] = r[d] = \frac{\Omega}{s} \sum_{k=0}^{N-1} F[k]^2 \cos\Big(\frac{2\pi k d}{N}\Big),

which is real, does not depend on nn, and satisfies r[0]=Ωr[0] = \Omega and r[N−d]=r[d]r[N - d] = r[d].

Proof. E[h[n+d]h[n]‾]=(c/N)2∑k,lF[k]F[l] ej2π(k(n+d)−ln)/N E[G[k]G[l]‾]E[h[n+d]\overline{h[n]}] = (c/N)^2 \sum_{k,l} F[k]F[l]\, e^{j2\pi(k(n+d) - l n)/N}\, E[G[k]\overline{G[l]}]. The expectation is 1 for k=lk = l and 0 otherwise, so the sum is (c/N)2∑kF[k]2ej2πkd/N(c/N)^2\sum_k F[k]^2 e^{j2\pi kd/N}, and nn cancels. Group the terms kk and N−kN - k: they have equal F2F^2 and conjugate exponentials, so the imaginary parts cancel and each exponential can be replaced by its cosine. The terms k=0k = 0 and, for even NN, k=N/2k = N/2 have F=0F = 0. With (c/N)2=Ω/s(c/N)^2 = \Omega/s this is r[d]r[d]. At d=0d = 0 every cosine is 1, so r[0]=Ωr[0] = \Omega. Since cos⁡(2πk(N−d)/N)=cos⁡(2πkd/N)\cos(2\pi k(N - d)/N) = \cos(2\pi k d/N), r[N−d]=r[d]r[N-d] = r[d]. □\square

Corollary (quadratures). Write h=Xc+jXsh = X_c + jX_s. Then E[Xc[n+d]Xc[n]]=E[Xs[n+d]Xs[n]]=r[d]/2E[X_c[n+d]X_c[n]] = E[X_s[n+d]X_s[n]] = r[d]/2 and E[Xc[n+d]Xs[n]]=0E[X_c[n+d]X_s[n]] = 0.

Proof. Let a=h[n+d]a = h[n+d] and b=h[n]b = h[n]. By Lemma 1, E[ab]=0E[ab] = 0; by Theorem 1, E[abˉ]=r[d]E[a\bar b] = r[d] is real. Adding and subtracting E[abˉ]=E[XcXc′]+E[XsXs′]+j(E[XsXc′]−E[XcXs′])E[a\bar b] = E[X_cX_c'] + E[X_sX_s'] + j(E[X_sX_c'] - E[X_cX_s']) and E[ab]=E[XcXc′]−E[XsXs′]+j(E[XsXc′]+E[XcXs′])E[ab] = E[X_cX_c'] - E[X_sX_s'] + j(E[X_sX_c'] + E[X_cX_s']), where the prime marks the sample at nn, gives E[XcXc′]=E[XsXs′]=r[d]/2E[X_cX_c'] = E[X_sX_s'] = r[d]/2 and E[XcXs′]=E[XsXc′]=0E[X_cX_s'] = E[X_sX_c'] = 0. □\square

So each h[n]h[n] is CN(0,Ω)CN(0, \Omega), and ∣h[n]∣|h[n]| has the Rayleigh distribution with E∣h[n]∣2=ΩE|h[n]|^2 = \Omega, for any NN and any filter.

Remark (the edge bin). For 1≤k<km1 \le k < k_m, F[k]2F[k]^2 is the sampled spectrum 1/(21−(k/(Nfm))2)1/(2\sqrt{1 - (k/(N f_m))^2}), which is finite because k<Nfmk < N f_m. At the edge, ∫km−1kmdk21−(k/km)2=km2[arcsin⁡kkm]km−1km=km2(π2−arcsin⁡km−1km)\int_{k_m-1}^{k_m} \frac{dk}{2\sqrt{1 - (k/k_m)^2}} = \frac{k_m}{2}\Big[\arcsin\frac{k}{k_m}\Big]_{k_m - 1}^{k_m} = \frac{k_m}{2}\Big(\frac\pi2 - \arcsin\frac{k_m - 1}{k_m}\Big), which is line L3; it is finite, and it is the integral of the spectrum, scaled to the band edge kmk_m, over the last bin. The sum ∑kF[k]2cos⁡(2πkd/N)\sum_k F[k]^2 \cos(2\pi k d/N) is then a Riemann sum for ∫−fDfDS(f)cos⁡(2πfτ) df\int_{-f_D}^{f_D} S(f)\cos(2\pi f \tau)\, df, which is proportional to J0(2πfDτ)J_0(2\pi f_D\tau). The theorem above does not depend on how close this sum is to the integral; that closeness is measured, not proved.

Complexity

Lines L1 to L5 take O(N)O(N) time and line L7 takes O(N)O(N). The inverse DFT of line L6 takes O(Nlog⁡N)O(N \log N) with a fast Fourier transform, so the total is O(Nlog⁡N)O(N \log N) in the real RAM, with O(N)O(N) space. The direct sum of the reference code takes O(N2)O(N^2).

Properties

  • Exactly Gaussian. Each h[n]h[n] is CN(0,Ω)CN(0, \Omega), so ∣h[n]∣|h[n]| is exactly Rayleigh, for any NN. Sum-of-sinusoids generators are Gaussian only as their number of sinusoids grows.
  • Circular, not stationary over blocks. The autocorrelation depends only on dd modulo NN: r[N−d]=r[d]r[N - d] = r[d]. Inside one block the process is periodic in its statistics, and separate blocks are independent.
  • Approximate J0J_0. r[d]r[d] is a sampled version of J0J_0, with the error set by kmk_m and by the edge bin. It is not an approximation in the number of samples alone.
  • Block generation. All NN samples come at once; the method does not run sample by sample.
  • Any spectrum. Replacing FF with the square root of another spectrum gives a Gaussian process with that spectrum, through the Wiener-Khinchin theorem.

Variants and improvements

  • Smith's form with two transforms. Smith (1975) shaped two independent noise sequences and used one inverse transform for each quadrature. Young and Beaulieu (2000) showed that one IDFT of complex noise gives the same statistics with half the work.
  • Time-domain filters. White Gaussian noise passed through an FIR filter or an IIR filter that approximates the Doppler spectrum gives samples one at a time, at the cost of a filter design error.
  • Autoregressive models. An autoregressive model fitted to J0J_0 gives fading sample by sample, with a recursion that suits Kalman channel tracking.
  • Sum of sinusoids. The Jakes simulator and the Zheng-Xiao simulator give h(t)h(t) at any time tt, but are Gaussian only approximately.

When to use it

Use it when a simulation needs long blocks of time-correlated Rayleigh fading on a fixed sample grid, with an exactly Gaussian distribution, for example for error rates, outage or level crossings at high γˉ\bar\gamma. Make NN much larger than the longest lag of interest and take kmk_m of 30 or more. Use a sum-of-sinusoids generator when the channel is needed at arbitrary times or sample by sample, and an independent draw per block when the fading is block fading.

Pitfalls

  • Wrap-around. The output is periodic in its statistics: the end of a block is correlated with its start. Do not join blocks and expect a smooth process, and do not use lags near N/2N/2.
  • Too few bins in the band. With small kmk_m the spectrum is coarse and the autocorrelation differs from J0J_0 by 0.1 or more. The test 2≤km<N/22 \le k_m < N/2 is only a minimum.
  • The edge bin. Using the spectrum value at k=kmk = k_m gives infinity when NfmN f_m is an integer. Setting it to 0 removes the strongest part of the spectrum and changes the fade rate.
  • Scaling. The inverse DFT convention changes the output power by NN or N\sqrt N. Scale by the sum of F[k]2F[k]^2, as in line L7.
  • Sample rate. fmf_m is fD/fsf_D/f_s. A sample rate far above fDf_D needs a very large NN for a few fade cycles; generate at a low rate and interpolate.

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)
filtered_gaussian_fading_simulator.py 64 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/filtered-gaussian-fading-simulator/. The authors are listed in prov/K4JBF8.jsonl.

"""Rayleigh fading by filtering complex Gaussian noise in the frequency domain.

This is the IDFT method of Young and Beaulieu 2000. Independent CN(0, 1)
samples G[k] are weighted by a filter F[k] whose square follows the Doppler
spectrum of Clarke's model, 1 / sqrt(1 - (f / f_D)^2), and one inverse DFT
gives N correlated samples h[0..N-1]. The normalized Doppler is f_m = f_D / f_s,
and k_m = floor(N f_m) is the last bin inside the spectrum. The edge bin
k_m gets the area of the spectrum over that bin, so the infinite peak at f_D
does not break the filter. The output is scaled so that E|h[n]|^2 = Omega.

The inverse DFT is the direct sum of cbb.idft. An FFT gives the same result
in O(N log N) operations.
"""

import math
import random

import cbb


def doppler_filter(n: int, fm: float) -> list[float]:
    """The real filter F[0..N-1] of Young and Beaulieu for N bins and normalized Doppler f_m."""
    km = math.floor(n * fm)  # @line L1
    if km < 2 or 2 * km >= n:
        raise ValueError("need 2 <= floor(N f_m) < N / 2")
    f = [0.0] * n
    for k in range(1, km):
        f[k] = math.sqrt(1.0 / (2.0 * math.sqrt(1.0 - (k / (n * fm)) ** 2)))  # @line L2
    f[km] = math.sqrt((km / 2.0) * (math.pi / 2.0 - math.atan((km - 1) / math.sqrt(2.0 * km - 1))))  # @line L3
    for k in range(1, km + 1):
        f[n - k] = f[k]  # @line L4
    return f


def filtered_gaussian(n: int, fm: float, rng: random.Random, omega: float = 1.0, g: list[complex] | None = None) -> list[complex]:
    """N samples of correlated Rayleigh fading with E|h|^2 = Omega.

    g, if given, replaces the N random CN(0, 1) inputs; the map from g to h is linear.
    """
    f = doppler_filter(n, fm)
    if g is None:
        g = [cbb.cn(rng, 1.0) for _ in range(n)]
    if len(g) != n:
        raise ValueError("need N inputs")
    x = [f[k] * g[k] for k in range(n)]  # @line L5
    y = cbb.idft(x)  # @line L6
    c = n * math.sqrt(omega / sum(v * v for v in f))
    return [c * v for v in y]  # @line L7


def exact_autocorrelation(n: int, fm: float, d: int, omega: float = 1.0) -> float:
    """E[h[i + d] conj(h[i])] = Omega sum_k F[k]^2 cos(2 pi k d / N) / sum_k F[k]^2, for every i (circular)."""
    f = doppler_filter(n, fm)
    s = sum(v * v for v in f)
    return omega * sum(f[k] ** 2 * math.cos(2.0 * math.pi * k * d / n) for k in range(n)) / s


def j0(x: float, points: int = 2048) -> float:
    """J0(x) = (1 / 2 pi) integral over [0, 2 pi) of cos(x sin t) dt, by the trapezoid rule."""
    h = 2.0 * math.pi / points
    return sum(math.cos(x * math.sin(k * h)) for k in range(points)) / points
test_filtered_gaussian_fading_simulator.py 80 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/filtered-gaussian-fading-simulator/. The authors are listed in prov/K4JBF8.jsonl.

import math
import random

from filtered_gaussian_fading_simulator import (
    doppler_filter,
    exact_autocorrelation,
    filtered_gaussian,
    j0,
)


def test_filter_shape() -> None:
    n, fm = 128, 1 / 16
    f = doppler_filter(n, fm)
    km = 8
    assert f[0] == 0.0
    assert all(f[k] == 0.0 for k in range(km + 1, n - km))
    assert all(f[k] == f[n - k] for k in range(1, km + 1))
    # F[k]^2 = 1 / (2 sqrt(1 - (k / 8)^2)) below the edge
    assert abs(f[1] ** 2 - 1 / (2 * math.sqrt(1 - 1 / 64))) < 1e-12
    # the edge bin holds the area of the spectrum over [k_m - 1, k_m]
    area = (km / 2) * (math.pi / 2 - math.asin((km - 1) / km))
    assert abs(f[km] ** 2 - area) < 1e-12


def test_covariance_from_unit_inputs() -> None:
    # The map from the inputs g to h is linear, so the covariance of h is the
    # sum over k of the outer products of the outputs for g = e_k.
    n, fm = 64, 1 / 8
    rng = random.Random(0)
    cols = []
    for k in range(n):
        e = [0j] * n
        e[k] = 1 + 0j
        cols.append(filtered_gaussian(n, fm, rng, g=e))
    for d in (0, 1, 2, 3, 5, 8):
        r = exact_autocorrelation(n, fm, d)
        for i in (0, 7, 33, 63):
            c = sum(col[(i + d) % n] * col[i].conjugate() for col in cols)
            assert abs(c - r) < 1e-9
    assert abs(exact_autocorrelation(n, fm, 0) - 1.0) < 1e-12


def test_sample_power_and_autocorrelation() -> None:
    n, fm = 128, 1 / 8
    rng = random.Random(8001)
    runs = 60
    lags = (0, 1, 2, 3, 4, 8)
    acc = [0j] * len(lags)
    for _ in range(runs):
        h = filtered_gaussian(n, fm, rng, omega=2.0)
        for j, d in enumerate(lags):
            acc[j] += sum(h[(i + d) % n] * h[i].conjugate() for i in range(n)) / n
    for j, d in enumerate(lags):
        assert abs(acc[j] / runs - exact_autocorrelation(n, fm, d, omega=2.0)) < 0.2


def test_close_to_clarke_and_better_with_more_bins() -> None:
    # N = 256 and f_m = 1/8 give k_m = 32: within 0.05 of J0 for f_D tau <= 1
    for d in range(0, 9):
        x = 2 * math.pi * d / 8
        assert abs(exact_autocorrelation(256, 1 / 8, d) - j0(x)) < 0.05
    # the error at f_D tau = 0.375, near the first zero of J0, shrinks as k_m grows
    errs = []
    for n in (128, 256, 512, 1024):  # k_m = 8, 16, 32, 64, and lag 6 is f_D tau = 0.375
        errs.append(abs(exact_autocorrelation(n, 1 / 16, 6) - j0(2 * math.pi * 6 / 16)))
    assert all(errs[i + 1] < errs[i] for i in range(3))
    assert abs(errs[0] - 0.10537) < 1e-4 and errs[-1] < 0.03


def test_bad_parameters() -> None:
    for n, fm in ((64, 1 / 64), (64, 0.5)):
        try:
            doppler_filter(n, fm)
        except ValueError:
            continue
        raise AssertionError("expected ValueError")

History

Smith (1975) described a computer simulation of mobile radio fading in which Gaussian noise is shaped in the frequency domain by the Doppler spectrum and transformed to the time domain, with one transform for each quadrature. The method became a standard tool, and Rappaport's textbook presents it for the Clarke and Gans fading model. Young and Beaulieu (2000) analyzed the IDFT method, showed that a single inverse transform of complex noise is enough, and gave a filter that handles the infinite spectrum at the Doppler edge by the area of the last bin.

References

  1. J. I. Smith, A computer generated multipath fading simulation for mobile radio, IEEE Transactions on Vehicular Technology 24(3), 1975, pages 39 to 40, the frequency-domain method with Gaussian noise shaped by the Doppler spectrum
  2. D. J. Young and N. C. Beaulieu, The generation of correlated Rayleigh random variates by inverse discrete Fourier transform, IEEE Transactions on Communications 48(7), 2000, pages 1114 to 1127, the IDFT method with one transform and the filter for Clarke's spectrum
  3. T. S. Rappaport, Wireless Communications: Principles and Practice, 2nd edition, Prentice Hall, 2002, Section 5.7.2, simulation of the Clarke and Gans fading model

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