Algorithm Search⌘K

Algorithmintro

Orthogonal frequency-division multiplexing

Also called OFDM.

Builds a multicarrier symbol with an inverse FFT and a cyclic prefix, and demodulates it with an FFT and one tap per subcarrier. A prefix of at least L - 1 samples makes each subcarrier flat.

Time
O(N log N) worst
Space
O(N) extra
Where
L = the number of channel taps; N = the number of subcarriers
Properties
deterministicexact without noiseone tap per subcarrier
Origin
Stephen B. Weinstein, Paul M. Ebert, 1971

Orthogonal frequency-division multiplexing (OFDM) sends NN data symbols X[0],…,X[N−1]X[0], \ldots, X[N-1] at the same time on NN subcarriers, one symbol per subcarrier. The transmitter computes the samples with an inverse FFT and puts a copy of the last NcpN_{cp} samples in front of them, the cyclic prefix. The receiver drops the prefix, takes an FFT and divides each output by one complex number, the channel gain H[k]H[k] of that subcarrier. If the channel has LL taps and Ncp≥L−1N_{cp} \ge L - 1, this one-tap division is exact apart from the noise: the frequency-selective channel, which causes intersymbol interference for a single carrier, becomes NN flat channels Y[k]=H[k]X[k]+W[k]Y[k] = H[k] X[k] + W[k]. OFDM is the discrete form of multicarrier modulation. It differs from frequency-domain equalization of a single carrier, which uses the same prefix and FFT but puts the data symbols in time, not on the subcarriers. This page uses the unitary DFT pair x=FHXx = F^H X, Y=FyY = F y with F[k,n]=e−j2πkn/N/NF[k, n] = e^{-j 2\pi k n / N} / \sqrt N, and jj is the imaginary unit. The algebra pages on the discrete Fourier transform write ii and use the unnormalized pair.

In plain words

A channel with echoes smears each sent sample into the next ones. If you send fast, the smear spreads over many symbols and they mix. OFDM avoids this. It splits the data into many slow streams, each on its own tone, and sends all the tones together as one long block. Each tone is so narrow that the echoes only change its strength and its phase. Before each block the sender repeats the end of the block. The receiver throws this copy away, so the echoes of the previous block fall into the part that is removed. What is left looks to the receiver as if the block were repeated forever. Then a Fourier transform separates the tones exactly, and the receiver corrects each tone with one division.

The problem

The input is a block of NN complex data symbols X[0],…,X[N−1]X[0], \ldots, X[N-1], for example points of QPSK with energy Es=E∣X[k]∣2=1E_s = E|X[k]|^2 = 1. The channel is a linear time-invariant filter with taps h[0],…,h[L−1]h[0], \ldots, h[L-1] (the tapped delay line model at one tap per sample) followed by white noise w[i]∼CN(0,N0)w[i] \sim \mathcal{CN}(0, N_0). The SNR is Es/N0E_s / N_0. The receiver knows hh. The task is to send the block and recover it so that each symbol sees a scalar channel, without an equalizer whose cost grows with LL for each symbol. The frequency response of the channel is H[k]=∑l=0L−1h[l] e−j2πkl/NH[k] = \sum_{l=0}^{L-1} h[l]\, e^{-j 2\pi k l / N}, the unnormalized DFT of the taps padded to length NN.

The algorithm

  1. OFDM(X, h, N_cp)
  2. 1x ← Fᴴ X ▷ transmitter: unitary inverse FFT of the N symbols
  3. 2s ← (x[N-N_cp], .., x[N-1], x[0], .., x[N-1]) ▷ put the cyclic prefix in front, send s
  4. 3y ← (r[N_cp], .., r[N_cp+N-1]) ▷ receiver: r is s through the channel; drop the prefix
  5. 4Y ← F y ▷ unitary FFT
  6. 5H[k] ← Σ_l h[l] e^(-j2πkl/N) for k = 0, .., N-1 ▷ channel gains, unnormalized DFT of the taps
  7. 6return X̂ with X̂[k] = Y[k] / H[k] ▷ one tap per subcarrier

Line L1 builds the time samples. Sample nn is a sum of NN complex exponentials, one per subcarrier, with frequency kfs/Nk f_s / N for the sample rate fsf_s; index k≥N/2k \ge N/2 stands for the negative frequency k−Nk - N. Line L2 copies the last NcpN_{cp} samples to the front, so the symbol on the air has N+NcpN + N_{cp} samples. Line L3 waits until the echoes of the previous symbol have died out and keeps the last NN samples. Inside this window, every sample of the current symbol that the channel mixes in is either a sample of xx or a copy of one from the prefix, so the window is the circular convolution of hh and xx. Line L4 turns the circular convolution into a product on each subcarrier, line L5 computes the gains, and line L6 undoes them. In practice H[k]H[k] comes from pilots, for example by comb pilot estimation, and the receiver first finds the start of the symbol and the frequency offset with Schmidl-Cox synchronization or the van de Beek estimator.

Example

Take N=4N = 4, Ncp=1N_{cp} = 1, the channel h=(1,0.5)h = (1, 0.5) with L=2L = 2, so Ncp=L−1N_{cp} = L - 1, no noise, and the BPSK block X=(1,−1,1,1)X = (1, -1, 1, 1).

Step Line Values
inverse FFT L1 x=(1,−j,1,j)x = (1, -j, 1, j)
add the prefix L2 s=(j,1,−j,1,j)s = (j, 1, -j, 1, j)
channel output r=(j, 1+0.5j, 0.5−j, 1−0.5j, 0.5+j, 0.5j)r = (j,\ 1 + 0.5j,\ 0.5 - j,\ 1 - 0.5j,\ 0.5 + j,\ 0.5j)
drop the prefix L3 y=(1+0.5j, 0.5−j, 1−0.5j, 0.5+j)y = (1 + 0.5j,\ 0.5 - j,\ 1 - 0.5j,\ 0.5 + j)
FFT L4 Y=(1.5, −1+0.5j, 0.5, 1+0.5j)Y = (1.5,\ -1 + 0.5j,\ 0.5,\ 1 + 0.5j)
gains L5 H=(1.5, 1−0.5j, 0.5, 1+0.5j)H = (1.5,\ 1 - 0.5j,\ 0.5,\ 1 + 0.5j)
one tap L6 X^=(1,−1,1,1)\hat X = (1, -1, 1, 1)

For example x[1]=12(1−j−1−j)=−jx[1] = \frac12 (1 - j - 1 - j) = -j, and H[1]=1+0.5 e−jπ/2=1−0.5jH[1] = 1 + 0.5\, e^{-j\pi/2} = 1 - 0.5j, so Y[1]=H[1]X[1]=−1+0.5jY[1] = H[1] X[1] = -1 + 0.5j. The last output sample 0.5j0.5j is the echo of this symbol into the next one; line L3 of the next symbol drops it with that symbol's prefix. Without the prefix (Ncp=0N_{cp} = 0), the window yy misses the echo 0.5 x[3]0.5\, x[3] in y[0]y[0], and line L6 returns (1−0.167j, −0.9−0.2j, 1−0.5j, 0.9−0.2j)(1 - 0.167j,\ -0.9 - 0.2j,\ 1 - 0.5j,\ 0.9 - 0.2j): every subcarrier is disturbed, not only one.

A larger case, as a measurement: N=64N = 64, Ncp=8N_{cp} = 8, h=(1,0.5)h = (1, 0.5), QPSK, Es/N0=10E_s / N_0 = 10 dB. Subcarrier kk sees the SNR ∣H[k]∣2Es/N0|H[k]|^2 E_s / N_0, which goes from 2.52.5 at H=0.5H = 0.5 to 22.522.5 at H=1.5H = 1.5. The QPSK symbol error rate 2Q(γ)−Q(γ)22Q(\sqrt\gamma) - Q(\sqrt\gamma)^2, averaged over the 64 values of γ\gamma, is 0.0185490.018549, and 200 simulated symbols (12800 decisions) agree with it inside a Wilson interval. A flat channel at the same SNR gives 1.5648×10−31.5648 \times 10^{-3}; the weak subcarriers dominate the average, which is why OFDM needs coding or bit loading across subcarriers.

Correctness

Claim. If Ncp≥L−1N_{cp} \ge L - 1, lines L1 to L4 give Y[k]=H[k]X[k]+W[k]Y[k] = H[k] X[k] + W[k] for every kk, where W[0],…,W[N−1]W[0], \ldots, W[N-1] are independent CN(0,N0)\mathcal{CN}(0, N_0). So line L6 returns X[k]+W[k]/H[k]X[k] + W[k] / H[k], which is X[k]X[k] exactly without noise when H[k]≠0H[k] \ne 0. This is a theorem in the model of the page (linear time-invariant channel over the symbol, perfect timing, no frequency offset).

Key invariant. After line L3, y[n]=∑lh[l] x[(n−l) mod N]y[n] = \sum_l h[l]\, x[(n - l) \bmod N] plus noise, a circular convolution: every input sample that reaches the window is a sample of xx or its copy in the prefix, never a sample of the previous symbol.

The DFT of a circular convolution is the product of the DFTs, with the unnormalized DFT on the taps, and a unitary FF maps white noise to white noise of the same variance. The full proof is below.

Proof: With a prefix of at least L - 1 samples, OFDM turns an L-tap channel into N independent one-tap channelsfull

We use the unitary DFT pair of the page: F[k,n]=e−j2πkn/N/NF[k, n] = e^{-j 2\pi k n / N} / \sqrt{N} for k,n=0,…,N−1k, n = 0, \ldots, N - 1, x=FHXx = F^H X and Y=FyY = F y. The matrix FF is unitary, FFH=FHF=IF F^H = F^H F = I, because ∑nej2π(k−k′)n/N\sum_{n} e^{j 2\pi (k - k') n / N} is NN for k=k′k = k' and 00 otherwise (a geometric sum of NN-th roots of unity). The channel has the taps h[0],…,h[L−1]h[0], \ldots, h[L-1] and the frequency response H[k]=∑l=0L−1h[l] e−j2πkl/NH[k] = \sum_{l=0}^{L-1} h[l]\, e^{-j 2\pi k l / N}, the unnormalized DFT of the taps padded to length NN. Indices of xx are taken modulo NN.

Line L1 gives x=FHXx = F^H X. Line L2 sends the N+NcpN + N_{cp} samples s[i]=x[(i−Ncp) mod N]s[i] = x[(i - N_{cp}) \bmod N] for i=0,…,N+Ncp−1i = 0, \ldots, N + N_{cp} - 1. The channel output is

r[i]=∑l=0L−1h[l] s[i−l]+w[i],(1)r[i] = \sum_{l=0}^{L-1} h[l]\, s[i - l] + w[i], \tag{1}

where s[i−l]s[i - l] for i−l<0i - l < 0 is a sample of the previous symbol, and w[i]w[i] are independent CN(0,N0)\mathcal{CN}(0, N_0) samples. Line L3 keeps y[n]=r[Ncp+n]y[n] = r[N_{cp} + n] for n=0,…,N−1n = 0, \ldots, N - 1, and line L4 computes Y=FyY = F y.

Lemma 1 (the prefix makes the convolution circular). If Ncp≥L−1N_{cp} \ge L - 1, then for n=0,…,N−1n = 0, \ldots, N - 1

y[n]=∑l=0L−1h[l] x[(n−l) mod N]+w[Ncp+n].y[n] = \sum_{l=0}^{L-1} h[l]\, x[(n - l) \bmod N] + w[N_{cp} + n].

Proof. In (1) with i=Ncp+ni = N_{cp} + n, the index i−l=Ncp+n−li - l = N_{cp} + n - l is at least Ncp−(L−1)≥0N_{cp} - (L - 1) \ge 0, so every sample that reaches y[n]y[n] belongs to the current symbol, and none belongs to the previous one. By the definition of line L2, s[Ncp+m]=x[m mod N]s[N_{cp} + m] = x[m \bmod N] for every mm with −Ncp≤m≤N−1-N_{cp} \le m \le N - 1. Here m=n−l≥−(L−1)≥−Ncpm = n - l \ge -(L - 1) \ge -N_{cp}, so s[i−l]=x[(n−l) mod N]s[i - l] = x[(n - l) \bmod N]. □\square

Lemma 2 (the DFT turns circular convolution into products). Let c[n]=∑l=0L−1h[l] x[(n−l) mod N]c[n] = \sum_{l=0}^{L-1} h[l]\, x[(n - l) \bmod N] with L≤NL \le N. Then (Fc)[k]=H[k] (Fx)[k](F c)[k] = H[k]\, (F x)[k] for every kk.

Proof.

(Fc)[k]=1N∑n=0N−1∑l=0L−1h[l] x[(n−l) mod N] e−j2πkn/N.(F c)[k] = \frac{1}{\sqrt N} \sum_{n=0}^{N-1} \sum_{l=0}^{L-1} h[l]\, x[(n - l) \bmod N]\, e^{-j 2\pi k n / N}.

Write e−j2πkn/N=e−j2πkl/N e−j2πk(n−l)/Ne^{-j 2\pi k n / N} = e^{-j 2\pi k l / N}\, e^{-j 2\pi k (n - l) / N} and exchange the sums. For a fixed ll, the map n↦(n−l) mod Nn \mapsto (n - l) \bmod N is a bijection of {0,…,N−1}\{0, \ldots, N - 1\}, and e−j2πk(n−l)/Ne^{-j 2\pi k (n - l)/N} depends only on (n−l) mod N(n - l) \bmod N. So the inner sum over nn is N (Fx)[k]\sqrt N\, (F x)[k], and the outer sum gives H[k] (Fx)[k]H[k]\, (F x)[k]. □\square

Lemma 3 (white noise stays white). If vv has independent CN(0,N0)\mathcal{CN}(0, N_0) entries, then V=FvV = F v has independent CN(0,N0)\mathcal{CN}(0, N_0) entries.

Proof. VV is a linear map of a circularly symmetric Gaussian vector, so it is circularly symmetric Gaussian with zero mean and covariance F(N0I)FH=N0IF (N_0 I) F^H = N_0 I. Uncorrelated jointly Gaussian entries are independent. □\square

Theorem. If Ncp≥L−1N_{cp} \ge L - 1, lines L1 to L4 give, for every subcarrier kk,

Y[k]=H[k] X[k]+W[k],Y[k] = H[k]\, X[k] + W[k],

with W[0],…,W[N−1]W[0], \ldots, W[N-1] independent and CN(0,N0)\mathcal{CN}(0, N_0). Line L6 returns X^[k]=X[k]+W[k]/H[k]\hat X[k] = X[k] + W[k] / H[k] for each kk with H[k]≠0H[k] \ne 0. Without noise, X^=X\hat X = X exactly.

Proof. By Lemma 1, y=c+vy = c + v with cc the circular convolution of hh and xx and v[n]=w[Ncp+n]v[n] = w[N_{cp} + n]. By linearity and Lemma 2, Y[k]=H[k] (Fx)[k]+(Fv)[k]Y[k] = H[k]\, (F x)[k] + (F v)[k], and Fx=FFHX=XF x = F F^H X = X. The samples w[Ncp],…,w[Ncp+N−1]w[N_{cp}], \ldots, w[N_{cp} + N - 1] are independent CN(0,N0)\mathcal{CN}(0, N_0), so Lemma 3 applies to W=FvW = F v. Line L5 computes H[k]H[k] by the same sum, so line L6 divides by the exact gain. ■\blacksquare

Remarks.

  • Energy. Because FF is unitary, ∑n∣x[n]∣2=∑k∣X[k]∣2\sum_n |x[n]|^2 = \sum_k |X[k]|^2 (Parseval for this pair). With E∣X[k]∣2=EsE|X[k]|^2 = E_s for every kk, each time sample has mean energy EsE_s, and subcarrier kk sees the SNR ∣H[k]∣2Es/N0|H[k]|^2 E_s / N_0. With the unnormalized pair, W[k]W[k] would have variance NN0N N_0 and the transmit samples energy Es/NE_s / N; the SNR per subcarrier is the same.
  • The prefix condition is sufficient, not necessary for a given channel. If the last taps are zero, the condition only needs the index of the last nonzero tap. If Ncp<L−1N_{cp} < L - 1, Lemma 1 fails: y[n]y[n] for n<L−1−Ncpn < L - 1 - N_{cp} contains samples of the previous symbol, and yy is no longer a circular convolution, so the subcarriers interfere. The tests show an error above 10−310^{-3} for Ncp=2N_{cp} = 2 and 33 with five taps.
  • The rate cost of the prefix is the factor N/(N+Ncp)N / (N + N_{cp}), because N+NcpN + N_{cp} samples carry NN symbols.

Complexity

Lines L1 and L4 are FFTs of size NN, O(Nlog⁡N)O(N \log N) time each in the real RAM. Lines L2 and L3 copy Ncp≤NN_{cp} \le N samples, line L6 is NN divisions, and line L5 is one more FFT, done once for as long as the channel stays fixed. So a symbol costs O(Nlog⁡N)O(N \log N) time, or O(log⁡N)O(\log N) per data symbol, whatever the length LL of the channel, against O(NL)O(N L) per block for a time-domain equalizer with LL taps. The extra space is O(N)O(N). The implementation has its own radix-2 FFT for a power of two NN and checks it against the direct DFT of the shared helper.

Properties

  • Orthogonality. The subcarriers ej2πkn/Ne^{j 2\pi k n / N}, n=0,…,N−1n = 0, \ldots, N - 1, are orthogonal over one symbol. Their spectra overlap, but each one is zero at the centers of all the others, so OFDM needs no guard band between subcarriers. Their spacing is fs/Nf_s / N.
  • Cost of the prefix. The data rate drops by the factor N/(N+Ncp)N / (N + N_{cp}), and the energy in the prefix is lost too. With IEEE 802.11a numbers, N=64N = 64, Ncp=16N_{cp} = 16 and fs=20f_s = 20 MHz, the spacing is 312.5312.5 kHz, the symbol lasts 4 μ4\ \mus and the factor is 0.80.8.
  • Energy. With the unitary pair, ∑n∣x[n]∣2=∑k∣X[k]∣2\sum_n |x[n]|^2 = \sum_k |X[k]|^2 (Parseval's theorem), so the energy per subcarrier equals the energy per time sample and W[k]W[k] has the same variance N0N_0 as w[n]w[n].
  • Diversity. A coded OFDM link gets frequency diversity because a deep fade hits only a few subcarriers; an uncoded one does not, and its error rate is set by the weakest subcarriers.
  • Peaks. The time samples are sums of NN independent terms and are close to Gaussian for large NN, so the peak-to-average power ratio is high. This is the main drawback for the power amplifier.

Variants and improvements

  • Guard bands and a DC null. Real systems leave the subcarriers near ±fs/2\pm f_s/2 and often k=0k = 0 empty, to ease the filters and avoid the DC offset of the receiver.
  • Discrete multitone. On a wire the signal must be real. Discrete multitone puts X[N−k]=X[k]∗X[N-k] = X[k]^* on the input of line L1 and loads a different number of bits on each subcarrier.
  • Multiple access. OFDMA gives different subcarriers to different users. SC-FDMA spreads each user's symbols with a DFT first, to lower the peaks.
  • Other pulses. OFDM uses a rectangular pulse per subcarrier, so its spectrum falls slowly. Filter bank multicarrier, GFDM and UFMC shape the subcarriers or groups of them.
  • Doubly dispersive channels. When the channel changes inside a symbol, the subcarriers leak into each other (inter-carrier interference). OTFS and AFDM place the data in other domains for this case.

When to use it

Use OFDM when the channel delay spread is long compared with the sample period, so that a single carrier would need a long equalizer: wireless LAN, LTE and 5G NR, digital broadcasting, and wired lines in the form of discrete multitone. It also suits links where the transmitter can adapt the power and the bits per subcarrier. Prefer a single carrier with frequency-domain equalization or SC-FDMA when the power amplifier must run near saturation, and a plain single carrier when the channel is flat. OFDM is sensitive to frequency offsets, Doppler and phase noise, so it needs careful synchronization.

Pitfalls

  • A prefix shorter than the channel. With Ncp<L−1N_{cp} < L - 1 in line L2, the window of line L3 picks up samples of the previous symbol and yy is no longer a circular convolution; every subcarrier gets interference, not only the edge ones. Line L2 must use Ncp≥L−1N_{cp} \ge L - 1, where L−1L - 1 is the delay of the last significant tap in samples.
  • The wrong window. Line L3 must start at sample NcpN_{cp} of the symbol. A window that starts inside the prefix but late enough still works, with a phase ramp e−j2πkδ/Ne^{-j 2\pi k \delta / N} that the channel estimate absorbs. A window that starts after the prefix takes samples of the next symbol.
  • Mixed DFT scales. If line L1 uses the unnormalized inverse with 1/N1/N and line L4 the unitary FF, the result is H[k]X[k]/NH[k] X[k] / \sqrt N. Use one pair, and use the unnormalized DFT for H[k]H[k] in line L5 with either pair.
  • Division by a deep fade. Line L6 divides by H[k]H[k], so a subcarrier with ∣H[k]∣|H[k]| near zero has a huge noise W[k]/H[k]W[k] / H[k]. A decoder should weight each subcarrier by ∣H[k]∣2|H[k]|^2, or the transmitter should not use that subcarrier.
  • The prefix in the SNR. The prefix carries energy but no new data. Count EsE_s per data symbol as (N+Ncp)/N(N + N_{cp}) / N times the energy per sample when you compare OFDM with a single carrier at the same Eb/N0E_b / N_0.

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)
orthogonal_frequency_division_multiplexing.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/orthogonal-frequency-division-multiplexing/. The authors are listed in prov/2QCF2N.jsonl.

"""OFDM: inverse FFT and cyclic prefix at the transmitter, FFT and one tap per
subcarrier at the receiver.

The page uses the unitary DFT pair: x = F^H X and Y = F y, with
F[k, n] = e^(-j 2 pi k n / N) / sqrt(N). The channel frequency response is the
unnormalized DFT H[k] = sum over l of h[l] e^(-j 2 pi k l / N). If the prefix
length is at least L - 1 for a channel of L taps, the receiver sees
Y[k] = H[k] X[k] + W[k] on each subcarrier k.

fft is an iterative radix-2 FFT for a power of two N, and a direct sum
otherwise. It is here because OFDM costs O(N log N) per symbol only with it.
"""

import cmath
import math


def fft(x: list[complex], inverse: bool = False) -> list[complex]:
    """sum over n of x[n] e^(-+ j 2 pi k n / N), with no scale factor.

    The sign is minus for the forward transform and plus for inverse=True.
    """
    n = len(x)
    sign = 1.0 if inverse else -1.0
    if n == 0:
        return []
    if n & (n - 1):  # not a power of two: direct sum
        w = [cmath.exp(sign * 2j * math.pi * t / n) for t in range(n)]
        return [sum(x[t] * w[(k * t) % n] for t in range(n)) for k in range(n)]
    a = [complex(v) for v in x]
    j = 0
    for i in range(1, n):  # bit-reversal permutation
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            a[i], a[j] = a[j], a[i]
    size = 2
    while size <= n:
        half = size // 2
        step = cmath.exp(sign * 2j * math.pi / size)
        for start in range(0, n, size):
            w = 1 + 0j
            for k in range(start, start + half):
                t = w * a[k + half]
                a[k + half] = a[k] - t
                a[k] = a[k] + t
                w *= step
        size *= 2
    return a


def ufft(x: list[complex]) -> list[complex]:
    """The unitary DFT F x."""
    s = 1.0 / math.sqrt(len(x))
    return [v * s for v in fft(x)]


def uifft(xf: list[complex]) -> list[complex]:
    """The unitary inverse DFT F^H X."""
    s = 1.0 / math.sqrt(len(xf))
    return [v * s for v in fft(xf, inverse=True)]


def modulate(xf: list[complex], ncp: int) -> list[complex]:
    """One OFDM symbol: N + ncp time samples for the N subcarrier symbols xf."""
    n = len(xf)
    if not 0 <= ncp <= n:
        raise ValueError("need 0 <= ncp <= N")
    x = uifft(xf)  # @line L1
    return x[n - ncp:] + x  # @line L2


def transmit(blocks: list[list[complex]], ncp: int) -> list[complex]:
    """The sample stream of several OFDM symbols, one after the other."""
    out: list[complex] = []
    for xf in blocks:
        out += modulate(xf, ncp)
    return out


def demodulate(r: list[complex], n: int, ncp: int) -> list[complex]:
    """Drop the prefix of one received symbol of N + ncp samples and take the FFT."""
    if len(r) < n + ncp:
        raise ValueError("need N + ncp samples")
    y = r[ncp:ncp + n]  # @line L3
    return ufft(y)  # @line L4


def channel_response(h: list[complex], n: int) -> list[complex]:
    """H[k] = sum over l of h[l] e^(-j 2 pi k l / N), the unnormalized DFT of the taps."""
    if len(h) > n:
        raise ValueError("more taps than subcarriers")
    return fft(list(h) + [0j] * (n - len(h)))  # @line L5


def equalize(yf: list[complex], hf: list[complex]) -> list[complex]:
    """The one-tap equalizer X[k] = Y[k] / H[k]."""
    return [y / hk for y, hk in zip(yf, hf)]  # @line L6


def receive(r: list[complex], h: list[complex], n: int, ncp: int, count: int) -> list[list[complex]]:
    """Demodulate and equalize count consecutive OFDM symbols of the stream r."""
    hf = channel_response(h, n)
    out = []
    for i in range(count):
        start = i * (n + ncp)
        out.append(equalize(demodulate(r[start:start + n + ncp], n, ncp), hf))
    return out
test_orthogonal_frequency_division_multiplexing.py 143 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/orthogonal-frequency-division-multiplexing/. The authors are listed in prov/2QCF2N.jsonl.

import cmath
import math
import random

import cbb
from orthogonal_frequency_division_multiplexing import (
    channel_response,
    demodulate,
    equalize,
    fft,
    modulate,
    receive,
    transmit,
    ufft,
    uifft,
)

S = 1 / math.sqrt(2)


def qpsk(rng: random.Random, n: int) -> list[complex]:
    """n unit-energy 4-QAM symbols (+-1 +-j) / sqrt(2)."""
    return [complex(rng.choice((S, -S)), rng.choice((S, -S))) for _ in range(n)]


def slice_qpsk(z: complex) -> complex:
    return complex(S if z.real >= 0 else -S, S if z.imag >= 0 else -S)


def maxerr(a: list[complex], b: list[complex]) -> float:
    return max(abs(x - y) for x, y in zip(a, b))


def test_fft_matches_the_direct_dft() -> None:
    rng = random.Random(1)
    for n in (1, 2, 4, 8, 64, 256, 12):
        x = [cbb.cn(rng, 1.0) for _ in range(n)]
        assert maxerr(fft(x), cbb.dft(x)) < 1e-9 * max(1, n)
        assert maxerr([v / n for v in fft(x, inverse=True)], cbb.idft(x)) < 1e-9
        assert maxerr(ufft(x), cbb.udft(x)) < 1e-9
        assert maxerr(uifft(ufft(x)), x) < 1e-12 * max(1, n)


def test_parseval_with_the_unitary_pair() -> None:
    rng = random.Random(2)
    xf = qpsk(rng, 64)
    s = modulate(xf, 0)
    assert abs(cbb.norm2(s) - cbb.norm2(xf)) < 1e-9
    assert abs(cbb.norm2(xf) - 64) < 1e-9


def test_prefix_is_a_copy_of_the_tail() -> None:
    rng = random.Random(3)
    xf = qpsk(rng, 16)
    s = modulate(xf, 4)
    assert len(s) == 20
    assert s[:4] == s[16:]


def test_round_trip_without_channel() -> None:
    rng = random.Random(4)
    for n, ncp in ((8, 0), (64, 16), (256, 32)):
        xf = qpsk(rng, n)
        assert maxerr(demodulate(modulate(xf, ncp), n, ncp), xf) < 1e-12


def test_one_tap_per_subcarrier_through_a_channel() -> None:
    rng = random.Random(5)
    channels = [
        [1.0, 0.5],
        [0.407, 0.815, 0.407],  # Proakis channel B
        [cbb.cn(rng, 1 / 8) for _ in range(8)],
    ]
    n, ncp = 64, 7
    for h in channels:
        xf = qpsk(rng, n)
        r = cbb.conv(modulate(xf, ncp), h)
        yf = demodulate(r, n, ncp)
        hf = channel_response(h, n)
        assert maxerr(hf, cbb.dft(list(h) + [0] * (n - len(h)))) < 1e-9
        assert maxerr(yf, [a * b for a, b in zip(hf, xf)]) < 1e-9
        assert maxerr(equalize(yf, hf), xf) < 1e-9


def test_a_stream_of_symbols_keeps_them_apart() -> None:
    rng = random.Random(6)
    n, ncp, count = 32, 4, 6
    h = [0.8, -0.4j, 0.3, 0.2 + 0.1j, 0.1]  # 5 taps, ncp = L - 1
    blocks = [qpsk(rng, n) for _ in range(count)]
    r = cbb.conv(transmit(blocks, ncp), h)
    out = receive(r, h, n, ncp, count)
    for xf, xh in zip(blocks, out):
        assert maxerr(xh, xf) < 1e-9


def test_a_short_prefix_leaves_interference() -> None:
    rng = random.Random(7)
    n, h = 32, [0.8, -0.4j, 0.3, 0.2 + 0.1j, 0.1]
    blocks = [qpsk(rng, n) for _ in range(3)]
    for ncp in (2, 3):  # ncp < L - 1 = 4
        r = cbb.conv(transmit(blocks, ncp), h)
        out = receive(r, h, n, ncp, 3)
        assert maxerr(out[1], blocks[1]) > 1e-3


def test_symbol_error_rate_matches_the_per_subcarrier_formula() -> None:
    # Es = 1 on each subcarrier, time-domain noise CN(0, N0), Es/N0 = 10 dB, h = (1, 0.5).
    # With the unitary DFT, W[k] is CN(0, N0), so subcarrier k sees SNR |H[k]|^2 / N0
    # and the 4-QAM symbol error rate 2Q(sqrt(g)) - Q(sqrt(g))^2. The mean over k is
    # 0.018549, so 200 symbols of 64 subcarriers (12800 trials, seed 8) expect about 237 errors.
    rng = random.Random(8)
    n, ncp, n0, h, count = 64, 8, 0.1, [1.0, 0.5], 200
    hf = channel_response(h, n)
    expect = 0.0
    for hk in hf:
        q = cbb.qfunc(math.sqrt(abs(hk) ** 2 / n0))
        expect += (2 * q - q * q) / n
    assert abs(expect - 0.018549) < 1e-6
    errors = 0
    for _ in range(count):
        xf = qpsk(rng, n)
        r = cbb.awgn(rng, cbb.conv(modulate(xf, ncp), h), n0)
        xh = equalize(demodulate(r, n, ncp), hf)
        errors += sum(slice_qpsk(z) != x for z, x in zip(xh, xf))
    lo, hi = cbb.wilson(errors, count * n)
    assert lo <= expect <= hi


def test_flat_channel_check_value() -> None:
    q = cbb.qfunc(math.sqrt(10.0))
    assert abs(2 * q - q * q - 1.5648e-3) < 1e-7


def test_rate_loss_and_spacing() -> None:
    # 802.11a-like numbers: N = 64, ncp = 16, sample rate 20 MHz.
    n, ncp, fs = 64, 16, 20e6
    assert n / (n + ncp) == 0.8
    assert fs / n == 312500.0
    assert abs((n + ncp) / fs - 4e-6) < 1e-15
    assert cmath.isclose(channel_response([1.0], 4)[2], 1)

History

Chang published the conditions for band-limited orthogonal subchannels with overlapping spectra in 1966 at Bell Labs. Weinstein and Ebert showed in 1971 that the DFT performs the modulation and the demodulation of all subcarriers at once, which removed the bank of oscillators and filters. They used a guard time of silence between symbols. Peled and Ruiz replaced the silence with a cyclic extension of each block in 1980, so that the channel acts as a circular convolution. Cimini studied OFDM for the mobile radio channel in 1985. With fast FFT hardware, OFDM became the modulation of digital audio and television broadcasting, of IEEE 802.11a and its successors, and of LTE and 5G NR.

References

  1. R. W. Chang, Synthesis of band-limited orthogonal signals for multichannel data transmission, Bell System Technical Journal 45(10), 1966, pages 1775 to 1796 (band-limited subchannels whose spectra overlap and that stay orthogonal)
  2. S. B. Weinstein and P. M. Ebert, Data transmission by frequency-division multiplexing using the discrete Fourier transform, IEEE Transactions on Communication Technology 19(5), 1971, pages 628 to 634 (the DFT as the modulator and the demodulator of a frequency-division multiplexed system)
  3. A. Peled and A. Ruiz, Frequency domain data transmission using reduced computational complexity algorithms, IEEE International Conference on Acoustics, Speech, and Signal Processing (ICASSP), 1980, pages 964 to 967 (the cyclic extension of each block)
  4. L. J. Cimini, Analysis and simulation of a digital mobile channel using orthogonal frequency division multiplexing, IEEE Transactions on Communications 33(7), 1985, pages 665 to 675 (OFDM on the mobile radio channel)
  5. Andrea Goldsmith, Wireless Communications, Cambridge University Press, 2005, Chapter 12, Section 12.4.1 (the DFT implementation) and Section 12.4.2 (the cyclic prefix)
  6. David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, Section 3.4.4 (OFDM: the cyclic prefix makes the channel a circular convolution, which the DFT diagonalizes)

Where this leads

About this page

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

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