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.
- Solves
- Channel equalization
- Time
- O(N log N) worst
- Space
- O(N) extra
- Where
- L = the number of channel taps; N = the number of subcarriers
- Model
- Real RAM
- Properties
- deterministicexact without noiseone tap per subcarrier
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Stephen B. Weinstein, Paul M. Ebert, 1971
Orthogonal frequency-division multiplexing (OFDM) sends data symbols at the same time on subcarriers, one symbol per subcarrier. The transmitter computes the samples with an inverse FFT and puts a copy of the last 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 of that subcarrier. If the channel has taps and , this one-tap division is exact apart from the noise: the frequency-selective channel, which causes intersymbol interference for a single carrier, becomes flat channels . 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 , with , and is the imaginary unit. The algebra pages on the discrete Fourier transform write 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 complex data symbols , for example points of QPSK with energy . The channel is a linear time-invariant filter with taps (the tapped delay line model at one tap per sample) followed by white noise . The SNR is . The receiver knows . 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 for each symbol. The frequency response of the channel is , the unnormalized DFT of the taps padded to length .
The algorithm
OFDM(X, h, N_cp)- 1
x ← Fᴴ X ▷ transmitter: unitary inverse FFT of the N symbols - 2
s ← (x[N-N_cp], .., x[N-1], x[0], .., x[N-1]) ▷ put the cyclic prefix in front, send s - 3
y ← (r[N_cp], .., r[N_cp+N-1]) ▷ receiver: r is s through the channel; drop the prefix - 4
Y ← F y ▷ unitary FFT - 5
H[k] ← Σ_l h[l] e^(-j2πkl/N) for k = 0, .., N-1 ▷ channel gains, unnormalized DFT of the taps - 6
return X̂ with X̂[k] = Y[k] / H[k] ▷ one tap per subcarrier
Line L1 builds the time samples. Sample is a sum of complex exponentials, one per subcarrier, with frequency for the sample rate ; index stands for the negative frequency . Line L2 copies the last samples to the front, so the symbol on the air has samples. Line L3 waits until the echoes of the previous symbol have died out and keeps the last samples. Inside this window, every sample of the current symbol that the channel mixes in is either a sample of or a copy of one from the prefix, so the window is the circular convolution of and . Line L4 turns the circular convolution into a product on each subcarrier, line L5 computes the gains, and line L6 undoes them. In practice 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 , , the channel with , so , no noise, and the BPSK block .
| Step | Line | Values |
|---|---|---|
| inverse FFT | L1 | |
| add the prefix | L2 | |
| channel output | ||
| drop the prefix | L3 | |
| FFT | L4 | |
| gains | L5 | |
| one tap | L6 |
For example , and , so . The last output sample 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 (), the window misses the echo in , and line L6 returns : every subcarrier is disturbed, not only one.
A larger case, as a measurement: , , , QPSK, dB. Subcarrier sees the SNR , which goes from at to at . The QPSK symbol error rate , averaged over the 64 values of , is , and 200 simulated symbols (12800 decisions) agree with it inside a Wilson interval. A flat channel at the same SNR gives ; the weak subcarriers dominate the average, which is why OFDM needs coding or bit loading across subcarriers.
Correctness
Claim. If , lines L1 to L4 give for every , where are independent . So line L6 returns , which is exactly without noise when . 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, plus noise, a circular convolution: every input sample that reaches the window is a sample of 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 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: for , and . The matrix is unitary, , because is for and otherwise (a geometric sum of -th roots of unity). The channel has the taps and the frequency response , the unnormalized DFT of the taps padded to length . Indices of are taken modulo .
Line L1 gives . Line L2 sends the samples for . The channel output is
where for is a sample of the previous symbol, and are independent samples. Line L3 keeps for , and line L4 computes .
Lemma 1 (the prefix makes the convolution circular). If , then for
Proof. In (1) with , the index is at least , so every sample that reaches belongs to the current symbol, and none belongs to the previous one. By the definition of line L2, for every with . Here , so .
Lemma 2 (the DFT turns circular convolution into products). Let with . Then for every .
Proof.
Write and exchange the sums. For a fixed , the map is a bijection of , and depends only on . So the inner sum over is , and the outer sum gives .
Lemma 3 (white noise stays white). If has independent entries, then has independent entries.
Proof. is a linear map of a circularly symmetric Gaussian vector, so it is circularly symmetric Gaussian with zero mean and covariance . Uncorrelated jointly Gaussian entries are independent.
Theorem. If , lines L1 to L4 give, for every subcarrier ,
with independent and . Line L6 returns for each with . Without noise, exactly.
Proof. By Lemma 1, with the circular convolution of and and . By linearity and Lemma 2, , and . The samples are independent , so Lemma 3 applies to . Line L5 computes by the same sum, so line L6 divides by the exact gain.
Remarks.
- Energy. Because is unitary, (Parseval for this pair). With for every , each time sample has mean energy , and subcarrier sees the SNR . With the unnormalized pair, would have variance and the transmit samples energy ; 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 , Lemma 1 fails: for contains samples of the previous symbol, and is no longer a circular convolution, so the subcarriers interfere. The tests show an error above for and with five taps.
- The rate cost of the prefix is the factor , because samples carry symbols.
Complexity
Lines L1 and L4 are FFTs of size , time each in the real RAM. Lines L2 and L3 copy samples, line L6 is divisions, and line L5 is one more FFT, done once for as long as the channel stays fixed. So a symbol costs time, or per data symbol, whatever the length of the channel, against per block for a time-domain equalizer with taps. The extra space is . The implementation has its own radix-2 FFT for a power of two and checks it against the direct DFT of the shared helper.
Properties
- Orthogonality. The subcarriers , , 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 .
- Cost of the prefix. The data rate drops by the factor , and the energy in the prefix is lost too. With IEEE 802.11a numbers, , and MHz, the spacing is kHz, the symbol lasts s and the factor is .
- Energy. With the unitary pair, (Parseval's theorem), so the energy per subcarrier equals the energy per time sample and has the same variance as .
- 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 independent terms and are close to Gaussian for large , 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 and often 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 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 in line L2, the window of line L3 picks up samples of the previous symbol and is no longer a circular convolution; every subcarrier gets interference, not only the edge ones. Line L2 must use , where is the delay of the last significant tap in samples.
- The wrong window. Line L3 must start at sample of the symbol. A window that starts inside the prefix but late enough still works, with a phase ramp 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 and line L4 the unitary , the result is . Use one pair, and use the unnormalized DFT for in line L5 with either pair.
- Division by a deep fade. Line L6 divides by , so a subcarrier with near zero has a huge noise . A decoder should weight each subcarrier by , or the transmitter should not use that subcarrier.
- The prefix in the SNR. The prefix carries energy but no new data. Count per data symbol as times the energy per sample when you compare OFDM with a single carrier at the same .
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)
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
- 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)
- 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)
- 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)
- 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)
- 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)
- 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
- Affine frequency-division multiplexing
- Comb-type pilot channel estimation
- Common phase error correction
- DFT-based channel estimation
- Discrete multitone
- Effective SNR mapping
- Filter bank multicarrier
- Generalized frequency-division multiplexing
- Integrated sensing and communication
- Inter-carrier interference
- IQ imbalance compensation
- Iterative clipping and filtering
- Moose frequency offset estimator
- Orthogonal frequency-division multiple access
- Orthogonal time frequency space modulation
- Partial transmit sequence
- Peak-to-average power ratio
- Schmidl-Cox synchronization
- Selected mapping
- Tone reservation
- Two-dimensional Wiener pilot interpolation
- Universal filtered multicarrier
- Van de Beek estimator
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 2QCF2N Edit this page History Report an error Markdown