Algorithm Search⌘K

Algorithmadvanced

Common phase error correction

Also called CPE correction.

Estimates from pilot subcarriers the rotation that phase noise gives to all subcarriers of an OFDM symbol, and removes it before the one-tap equalizer.

Time
O(N + P) worst
Space
O(N) extra
Where
N = the number of subcarriers; P = the number of pilot subcarriers
Properties
data aideddeterministicexact for constant phasenot removes ici
Origin
Patrick Robertson, Stefan Kaiser, 1995

Common phase error correction removes the part of oscillator phase noise that an OFDM receiver can remove cheaply. Phase noise φ[n]\varphi[n] multiplies time sample nn by ejφ[n]e^{j\varphi[n]}. After the DFT, every subcarrier is scaled by the same complex factor I0I_0, the mean of ejφ[n]e^{j\varphi[n]} over the symbol, and receives some inter-carrier interference from the others. The angle of I0I_0 is the common phase error (CPE). It changes from symbol to symbol, so the channel estimate of an earlier symbol does not include it. The receiver knows the pilot values XpX_p and the channel H[p]H[p], so it adds up Y[p](H[p]Xp)∗Y[p] (H[p] X_p)^* over the pilots, takes the angle of the sum, and rotates every subcarrier back by it before the one-tap equalizer. A constant phase is removed exactly; for slowly varying phase noise most of the error is removed, and the interference part, of power 1−∣I0∣21 - |I_0|^2, stays. The page uses jj for the imaginary unit and the unitary DFT pair of the OFDM page.

In plain words

The local oscillator of a receiver does not hold a perfectly steady phase; it wanders a little all the time. Over one OFDM symbol, most of that wander acts as one twist of the whole symbol: every subcarrier is turned by the same angle. The rest smears a little energy between subcarriers. The twist alone would make many decisions wrong, but it is easy to fix. A few subcarriers carry known pilots, so the receiver checks how far they have turned, averages that over the pilots, and turns the whole symbol back. The smear cannot be fixed this way, but it is small when the oscillator is good.

The problem

The input is one received OFDM symbol after the DFT, Y[0],…,Y[N−1]Y[0], \ldots, Y[N-1], the channel H[k]H[k] on every subcarrier (known from an earlier estimate), and the pilot subcarriers p∈Pp \in \mathcal P with their known values XpX_p. The model is Y[k]=I0H[k]X[k]+∑m≠kIk−mH[m]X[m]+W[k]Y[k] = I_0 H[k] X[k] + \sum_{m \ne k} I_{k - m} H[m] X[m] + W[k] with Iq=1N∑nejφ[n]e−j2πqn/NI_q = \frac1N \sum_n e^{j\varphi[n]} e^{-j 2\pi q n / N}, an unknown phase noise φ[n]\varphi[n] and white noise W[k]∼CN(0,N0)W[k] \sim \mathcal{CN}(0, N_0). Output the equalized values Z[k]=Y[k]e−jφ^/H[k]Z[k] = Y[k] e^{-j\hat\varphi} / H[k], with φ^\hat\varphi an estimate of ∠I0\angle I_0.

The algorithm

  1. CPE-CORRECT(Y, H, pilots, X_p)
  2. 1C ← Σ_{p in pilots} Y[p] conj(H[p] X_p)
  3. 2φ̂ ← angle(C)
  4. 3Z[k] ← Y[k] e^(-j φ̂) / H[k] for k = 0, .., N-1
  5. 4return Z

Line L1 correlates the received pilots with what they would be without phase noise. Each term is I0∣H[p]Xp∣2I_0 |H[p] X_p|^2 plus interference and noise, so all terms point in the direction of I0I_0, weighted by the pilot power. Line L2 takes the angle. Line L3 rotates every subcarrier back and divides by the channel. The pilots in line L1 are the same kind as those used for comb pilot channel estimation; 802.11a, for example, sends four pilot subcarriers in every symbol for this kind of phase tracking.

Example

Take N=16N = 16, pilots on subcarriers 2, 6, 10, 14, the channel taps (0.9,0.3j,−0.2)(0.9, 0.3j, -0.2), random 4-QAM values (seed 4), no noise, and Wiener phase noise that starts at 0.60.6 rad with steps of variance 0.0040.004 per sample. Over the symbol, φ[n]\varphi[n] moves between 0.600.60 and 0.810.81 rad, and I0=0.776+0.628jI_0 = 0.776 + 0.628j, with ∣I0∣=0.998|I_0| = 0.998 and the angle 0.6800.680 rad.

pilot pp ∣H[p]Xp∣2\lvert H[p] X_p\rvert^2 Y[p] (H[p]Xp)∗Y[p]\, (H[p] X_p)^* angle (rad)
2 1.407 1.021+0.921j1.021 + 0.921j 0.734
6 1.407 1.079+0.919j1.079 + 0.919j 0.706
10 0.473 0.362+0.260j0.362 + 0.260j 0.622
14 0.473 0.352+0.325j0.352 + 0.325j 0.745

Line L1 gives C=2.814+2.424jC = 2.814 + 2.424j, and line L2 gives φ^=0.711\hat\varphi = 0.711 rad, 0.0310.031 rad from the angle of I0I_0; the difference is the interference on the pilots. Before the correction, the equalized data values are 0.650.65 to 0.810.81 away from the sent points, which is close to the decision boundary for 4-QAM at a rotation of about 3939 degrees: subcarrier 0, sent as −0.707−0.707j-0.707 - 0.707j, gives −0.020−1.021j-0.020 - 1.021j. After line L3 the errors are 0.0140.014 to 0.1160.116, and subcarrier 0 gives −0.681−0.760j-0.681 - 0.760j.

At N=64N = 64 with 8 pilots, a step variance of 0.0020.002, a random start phase and N0=0.02N_0 = 0.02, the tests count the wrong 4-QAM decisions on 5600 data subcarriers (100 symbols, seed 3): 4091 without correction, 1 with CPE correction, and 0 with the true angle of I0I_0.

Correctness

Claim. (a) Each subcarrier after the DFT is I0H[k]X[k]I_0 H[k] X[k] plus inter-carrier interference and noise, with I0I_0 the same for all kk. (b) For a constant phase θ\theta and no noise, line L2 returns θ\theta and line L3 returns the sent values exactly. (c) For a fixed phase noise and independent zero-mean unit-modulus subcarrier values, E[C]=I0∑p∣H[p]∣2E[C] = I_0 \sum_p |H[p]|^2, so the estimate points at the angle of I0I_0 on average. (d) For Wiener phase noise with step variance σ2\sigma^2, E∣I0∣2=1N2∑n,me−σ2∣n−m∣/2≈1−σ2N/6E|I_0|^2 = \frac{1}{N^2} \sum_{n,m} e^{-\sigma^2 |n - m| / 2} \approx 1 - \sigma^2 N / 6, and the interference power that the correction cannot remove is 1−∣I0∣21 - |I_0|^2 for a channel with ∣H∣=1|H| = 1. Parts (a) to (d) are theorems; the size of the spread of φ^\hat\varphi around the angle of I0I_0 is measured, not proved.

Key invariant. The factor I0I_0 multiplies every subcarrier, so after line L3 every subcarrier carries the same residual factor I0e−jφ^I_0 e^{-j\hat\varphi}, which is real and positive when φ^=∠I0\hat\varphi = \angle I_0.

Part (a) follows by putting the expansion of the channel output in subcarriers into the DFT. Part (d) uses that φ[n]−φ[m]\varphi[n] - \varphi[m] is Gaussian with variance σ2∣n−m∣\sigma^2 |n - m|, and Parseval, ∑q∣Iq∣2=1\sum_q |I_q|^2 = 1. The full proof is below.

Proof: Phase noise scales every subcarrier by the same factor I_0, the pilot correlation points in its direction on average, and a constant phase is removed exactlyfull

Notation. NN subcarriers, jj the imaginary unit, the unitary DFT pair x=FHXx = F^H X with F[k,n]=e−j2πkn/N/NF[k, n] = e^{-j 2\pi k n / N} / \sqrt N, and H[k]=∑lhle−j2πlk/NH[k] = \sum_l h_l e^{-j 2\pi l k / N}. The cyclic prefix covers the channel, so inside the DFT window the channel output is the circular convolution cc of the taps with the symbol xx. The oscillator adds the phase φ[n]\varphi[n] to sample nn, and the noise w[n]w[n] is white CN(0,N0)\mathcal{CN}(0, N_0), so the window holds ejφ[n]c[n]+w[n]e^{j\varphi[n]} c[n] + w[n]. Let

Iq=1N∑n=0N−1ejφ[n]e−j2πqn/N.I_q = \frac1N \sum_{n=0}^{N-1} e^{j\varphi[n]} e^{-j 2\pi q n / N}.

The pilots are the subcarriers p∈Pp \in \mathcal P with known values XpX_p, and the receiver knows HH. Lines L1 and L2 compute C=∑p∈PY[p](H[p]Xp)∗C = \sum_{p \in \mathcal P} Y[p] \left( H[p] X_p \right)^* and φ^=∠C\hat\varphi = \angle C.

Lemma 1 (the received subcarriers). Y[k]=I0H[k]X[k]+∑m≠kIk−mH[m]X[m]+W[k]Y[k] = I_0 H[k] X[k] + \sum_{m \ne k} I_{k - m} H[m] X[m] + W[k], with indices modulo NN and W=FwW = F w white CN(0,N0)\mathcal{CN}(0, N_0).

Proof. By the convolution theorem for the unitary pair, c[n]=1N∑mH[m]X[m]ej2πmn/Nc[n] = \frac{1}{\sqrt N} \sum_m H[m] X[m] e^{j 2\pi m n / N}. Then

Y[k]=1N∑nejφ[n]c[n]e−j2πkn/N+W[k]=∑mH[m]X[m]⋅1N∑nejφ[n]e−j2π(k−m)n/N+W[k],Y[k] = \frac{1}{\sqrt N} \sum_n e^{j\varphi[n]} c[n] e^{-j 2\pi k n / N} + W[k] = \sum_m H[m] X[m] \cdot \frac1N \sum_n e^{j\varphi[n]} e^{-j 2\pi (k - m) n / N} + W[k],

and the inner sum is Ik−mI_{k - m}. A unitary map keeps white Gaussian noise white with the same variance. □\square

The factor I0I_0 is the same for every subcarrier. Its angle is the common phase error, and its size is at most 1 by the triangle inequality. The sum over m≠km \ne k is inter-carrier interference.

Lemma 2 (Parseval for the factors). ∑q=0N−1∣Iq∣2=1\sum_{q=0}^{N-1} |I_q|^2 = 1.

Proof. (I0,…,IN−1)(I_0, \ldots, I_{N-1}) is 1NF\frac{1}{\sqrt N} F applied to the vector ejφ[n]e^{j\varphi[n]}, whose squared norm is NN. A unitary map keeps the norm, so the squared norm of II is N/N=1N / N = 1. □\square

So with ∣H[m]∣=1|H[m]| = 1 and independent unit-energy data, the interference on a subcarrier has the power ∑q≠0∣Iq∣2=1−∣I0∣2\sum_{q \ne 0} |I_q|^2 = 1 - |I_0|^2, which a common rotation cannot remove.

Theorem 1 (a constant phase is removed exactly). If φ[n]=θ\varphi[n] = \theta for all nn, θ∈(−π,π]\theta \in (-\pi, \pi], there is no noise, and H[p]Xp≠0H[p] X_p \ne 0 for some pilot, then φ^=θ\hat\varphi = \theta, and line L3 returns X[k]X[k] on every subcarrier with H[k]≠0H[k] \ne 0.

Proof. I0=ejθI_0 = e^{j\theta} and Iq=ejθN∑ne−j2πqn/N=0I_q = \frac{e^{j\theta}}{N} \sum_n e^{-j 2\pi q n / N} = 0 for q≠0q \ne 0. By Lemma 1, Y[k]=ejθH[k]X[k]Y[k] = e^{j\theta} H[k] X[k], so C=ejθ∑p∣H[p]Xp∣2C = e^{j\theta} \sum_p |H[p] X_p|^2 with a positive sum, and ∠C=θ\angle C = \theta. Line L3 computes Y[k]e−jθ/H[k]=X[k]Y[k] e^{-j\theta} / H[k] = X[k]. □\square

Theorem 2 (the pilot sum points at I_0 on average). Fix φ\varphi. Let all subcarrier values, the pilot values included, be independent with zero mean, and let ∣X[k]∣=1|X[k]| = 1. Then

E[C]=I0∑p∈P∣H[p]∣2,E[C] = I_0 \sum_{p \in \mathcal P} |H[p]|^2,

so ∠E[C]=∠I0\angle E[C] = \angle I_0.

Proof. By Lemma 1, C=∑p(I0∣H[p]∣2∣Xp∣2+∑m≠pIp−mH[m]H[p]∗X[m]Xp∗+W[p]H[p]∗Xp∗)C = \sum_p \left( I_0 |H[p]|^2 |X_p|^2 + \sum_{m \ne p} I_{p - m} H[m] H[p]^* X[m] X_p^* + W[p] H[p]^* X_p^* \right). The first term is I0∣H[p]∣2I_0 |H[p]|^2. In the second, E[X[m]Xp∗]=E[X[m]] E[Xp]∗=0E[X[m] X_p^*] = E[X[m]]\, E[X_p]^* = 0 for m≠pm \ne p by independence and zero mean. In the third, WW has zero mean and is independent of the data. □\square

Theorem 2 says that the estimate is aimed at the right angle; the spread around it comes from the interference and the noise on the pilots, and it shrinks as the number of pilots grows, because CC adds the pilots coherently and the disturbances incoherently. This is a heuristic statement about the spread; the tests measure its effect on symbol errors.

Theorem 3 (the power left in I_0 for Wiener phase noise). Let φ[n+1]−φ[n]\varphi[n + 1] - \varphi[n] be independent N(0,σ2)\mathcal N(0, \sigma^2), the Wiener model of an oscillator. Then

E∣I0∣2=1N2∑n=0N−1∑m=0N−1e−σ2∣n−m∣/2=1−σ2(N2−1)6N+O((σ2N)2).E|I_0|^2 = \frac{1}{N^2} \sum_{n=0}^{N-1} \sum_{m=0}^{N-1} e^{-\sigma^2 |n - m| / 2} = 1 - \frac{\sigma^2 (N^2 - 1)}{6N} + O\left( (\sigma^2 N)^2 \right).

Proof. ∣I0∣2=1N2∑n,mej(φ[n]−φ[m])|I_0|^2 = \frac{1}{N^2} \sum_{n, m} e^{j(\varphi[n] - \varphi[m])}, and φ[n]−φ[m]\varphi[n] - \varphi[m] is a sum of ∣n−m∣|n - m| independent steps, so it is N(0,σ2∣n−m∣)\mathcal N(0, \sigma^2 |n - m|), whose characteristic function at 1 is e−σ2∣n−m∣/2e^{-\sigma^2 |n - m| / 2}. For the expansion, e−x=1−x+O(x2)e^{-x} = 1 - x + O(x^2) and ∑n,m∣n−m∣=(N3−N)/3\sum_{n, m} |n - m| = (N^3 - N)/3, so the sum is 1−σ22N2⋅N3−N3+O((σ2N)2)1 - \frac{\sigma^2}{2N^2} \cdot \frac{N^3 - N}{3} + O((\sigma^2 N)^2). □\square

For N=64N = 64 and σ2=0.002\sigma^2 = 0.002, the closed form is close to 1−σ2N/6=0.9791 - \sigma^2 N / 6 = 0.979, so about 2 percent of the power becomes interference that line L3 cannot remove, and the rest is the common rotation that it does remove.

Complexity

Line L1 costs O(P)O(P) for PP pilots, line L2 is O(1)O(1), and line L3 costs O(N)O(N), so the time is O(N+P)O(N + P) per symbol after the DFT, with O(N)O(N) extra space for the output in the real RAM. This is negligible next to the FFT.

Properties

  • Exact for a constant phase. A phase offset that is the same over the symbol, such as a residual carrier phase, is removed exactly without noise.
  • Removes the common part only. The interference power 1−∣I0∣21 - |I_0|^2 stays. For N=64N = 64 and a step variance of 0.0020.002, it is about 22 percent of the power, a signal to interference ratio of about 17 dB.
  • Weighted average. Line L1 weights each pilot by ∣H[p]Xp∣2|H[p] X_p|^2, so pilots in deep fades count little, as they should.
  • Residual frequency offset. A small residual frequency offset gives a phase that grows from symbol to symbol; CPE correction removes it symbol by symbol, apart from its small interference part.
  • Needs the channel. Line L1 uses H[p]H[p]; if the channel estimate itself was made from pilots in the same symbol, the CPE is already inside it, and the correction does nothing more.

Variants and improvements

  • Tracking across symbols. The CPE of successive symbols is correlated, so a phase-locked loop or a Kalman filter over the estimates of line L2 reduces their noise.
  • Decision-directed. After a first decision, all data subcarriers can join the sum of line L1 as if they were pilots, which reduces the noise of the estimate at a high SNR.
  • ICI suppression. Estimating a few of the factors IqI_q near q=0q = 0 and equalizing with a short filter across subcarriers removes part of the interference, at a higher cost.
  • Pilot design. 5G NR adds phase tracking reference signals for high carrier frequencies, where phase noise is stronger.
  • Joint with the channel. When the channel is estimated in the same symbol, the CPE is part of the estimate, and only the symbols between pilot symbols need the correction.

When to use it

Use CPE correction in every OFDM receiver whose channel estimate comes from earlier symbols, such as a preamble, and whose oscillator has noticeable phase noise, as in Wi-Fi, DVB-T and millimeter wave systems. It costs a few pilots and a few operations per symbol. When the phase noise bandwidth is a large fraction of the subcarrier spacing, CPE correction is not enough and interference suppression, or a larger subcarrier spacing, is needed.

Pitfalls

  • Conjugating the received value. Line L1 must use Y[p]conj⁡(H[p]Xp)Y[p] \operatorname{conj}(H[p] X_p). With conj⁡(Y[p])H[p]Xp\operatorname{conj}(Y[p]) H[p] X_p the angle has the wrong sign, and line L3 doubles the error instead of removing it.
  • Averaging the angles. Line L2 must take the angle of the complex sum from line L1. Taking the angle of each pilot term and averaging gives weak pilots too much weight and fails near ±π\pm\pi.
  • Rotating the wrong way. Line L3 must multiply by e−jφ^e^{-j\hat\varphi}, not e+jφ^e^{+j\hat\varphi}.
  • Ignoring the interference. CPE correction cannot remove the interference part, so a design must not expect error-free symbols from a poor oscillator; the remaining 1−∣I0∣21 - |I_0|^2 sets a floor on the SINR.
  • Few pilots in deep fades. If all pilots of a symbol fall in fades, the sum of line L1 is small and its angle is noisy. Spreading the pilots across the band avoids this.

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)
common_phase_error_correction.py 37 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/common-phase-error-correction/. The authors are listed in prov/3R84JE.jsonl.

"""Common phase error (CPE) correction in OFDM with pilot subcarriers.

Phase noise phi[n] multiplies time sample n by e^(j phi[n]). After the DFT,
with the unitary pair of the OFDM page,

    Y[k] = I_0 H[k] X[k] + (sum over m != k of I_(k - m) H[m] X[m]) + W[k]
    I_q  = (1/N) sum over n of e^(j phi[n]) e^(-j 2 pi q n / N)

I_0 is the same for every subcarrier: the common phase error. The other
terms are inter-carrier interference. The receiver knows H and the pilot
values X_p, and estimates the angle of I_0 from the pilots:

    C = sum over pilots p of Y[p] conj(H[p] X_p),  phi_hat = angle(C)

then rotates every subcarrier back by phi_hat before the one-tap equalizer.
"""

import cmath


def estimate_phase(y: list[complex], h: list[complex], pilots: list[int], pilot_values: list[complex]) -> float:
    """phi_hat = angle of sum over pilots of Y[p] conj(H[p] X_p)."""
    if len(pilots) != len(pilot_values) or not pilots:
        raise ValueError("need one value per pilot and at least one pilot")
    c = sum(y[p] * (h[p] * x).conjugate() for p, x in zip(pilots, pilot_values))  # @line L1
    return cmath.phase(c)  # @line L2


def correct(y: list[complex], h: list[complex], pilots: list[int], pilot_values: list[complex]) -> list[complex]:
    """The equalized subcarrier values Y[k] e^(-j phi_hat) / H[k] for all k."""
    phi = estimate_phase(y, h, pilots, pilot_values)
    rot = cmath.exp(-1j * phi)
    z = [v * rot / hk for v, hk in zip(y, h)]  # @line L3
    return z  # @line L4
test_common_phase_error_correction.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/common-phase-error-correction/. The authors are listed in prov/3R84JE.jsonl.

import cmath
import math
import random

import cbb
from common_phase_error_correction import correct, estimate_phase

S = 1 / math.sqrt(2)
N = 64
TAPS = [0.9, 0.3j, -0.2]
PILOTS = list(range(4, N, 8))


def qpsk(rng: random.Random, n: int) -> list[complex]:
    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 wiener_phase(rng: random.Random, n: int, var: float, start: float) -> list[float]:
    """phi[0] = start, then independent steps of variance var (var = 2 pi beta T_s for linewidth beta)."""
    out = [start]
    for _ in range(n - 1):
        out.append(out[-1] + rng.gauss(0.0, math.sqrt(var)))
    return out


def receive(rng: random.Random, x: list[complex], phi: list[float], n0: float) -> list[complex]:
    """Subcarrier values through the channel (prefix assumed long enough), phase noise and AWGN."""
    t = cbb.cconv(cbb.uidft(x), TAPS, len(x))
    r = [v * cmath.exp(1j * p) for v, p in zip(t, phi)]
    return cbb.udft(cbb.awgn(rng, r, n0) if n0 > 0 else r)


def test_a_constant_phase_is_removed_exactly() -> None:
    rng = random.Random(1)
    h = cbb.dft(TAPS + [0j] * (N - len(TAPS)))
    for theta in (0.3, -2.0, 3.1):
        x = qpsk(rng, N)
        y = receive(rng, x, [theta] * N, 0.0)
        assert abs(estimate_phase(y, h, PILOTS, [x[p] for p in PILOTS]) - theta) < 1e-9
        z = correct(y, h, PILOTS, [x[p] for p in PILOTS])
        assert max(abs(a - b) for a, b in zip(z, x)) < 1e-9


def test_the_pilot_sum_is_unbiased_for_i0() -> None:
    # Fixed phase noise, random data: E[C] = I_0 sum |H[p] X_p|^2, because the ICI terms have zero mean.
    rng = random.Random(2)
    h = cbb.dft(TAPS + [0j] * (N - len(TAPS)))
    phi = wiener_phase(rng, N, 0.01, 0.7)
    i0 = sum(cmath.exp(1j * p) for p in phi) / N
    acc = 0j
    trials = 200
    for _ in range(trials):
        x = qpsk(rng, N)
        y = receive(rng, x, phi, 0.0)
        c = sum(y[p] * (h[p] * x[p]).conjugate() for p in PILOTS)
        acc += c / sum(abs(h[p] * x[p]) ** 2 for p in PILOTS)
    assert abs(acc / trials - i0) < 0.01


def test_symbol_errors_with_and_without_correction() -> None:
    # Measurement: N = 64, 8 pilots, per-sample phase step variance 0.002, a random start phase,
    # N0 = 0.02, 100 symbols, seed 3. Without correction about 3 in 4 data symbols are wrong;
    # with CPE correction about as few errors as with the true angle of I_0.
    rng = random.Random(3)
    h = cbb.dft(TAPS + [0j] * (N - len(TAPS)))
    data = [k for k in range(N) if k not in PILOTS]
    e_none = e_cpe = e_true = 0
    trials = 100
    for _ in range(trials):
        phi = wiener_phase(rng, N, 0.002, rng.uniform(-math.pi, math.pi))
        x = qpsk(rng, N)
        y = receive(rng, x, phi, 0.02)
        i0 = sum(cmath.exp(1j * p) for p in phi) / N
        z = correct(y, h, PILOTS, [x[p] for p in PILOTS])
        rot = cmath.exp(-1j * cmath.phase(i0))
        e_cpe += sum(slice_qpsk(z[k]) != x[k] for k in data)
        e_true += sum(slice_qpsk(y[k] * rot / h[k]) != x[k] for k in data)
        e_none += sum(slice_qpsk(y[k] / h[k]) != x[k] for k in data)
    total = trials * len(data)
    assert e_none > 0.5 * total
    assert e_cpe < 0.01 * total
    assert e_cpe <= e_true + 10


def test_power_left_in_i0() -> None:
    # Closed form for Wiener phase noise: E|I_0|^2 = (1/N^2) sum over n, m of e^(-var |n - m| / 2),
    # about 1 - var N / 6 for small var N. The rest, 1 - |I_0|^2, is ICI that CPE correction cannot remove.
    rng = random.Random(4)
    var = 0.002
    exact = sum(math.exp(-var * abs(a - b) / 2) for a in range(N) for b in range(N)) / N ** 2
    assert abs(exact - (1 - var * N / 6)) < 2e-3
    acc = 0.0
    trials = 1000
    for _ in range(trials):
        phi = wiener_phase(rng, N, var, 0.0)
        acc += abs(sum(cmath.exp(1j * p) for p in phi) / N) ** 2
    assert abs(acc / trials - exact) < 2e-3

History

Patrick Robertson and Stefan Kaiser at the German Aerospace Center analyzed phase noise in OFDM in 1995 and showed that it splits into a common phase error, shared by all subcarriers, and inter-carrier interference. The same year, Pollet, Van Bladel and Moeneclaey gave the SNR degradation caused by Wiener phase noise. Ana Garcia Armada explained both effects for broadcasting in 2001. Pilot-based phase tracking is part of IEEE 802.11a and its successors, and phase tracking reference signals were added to 5G NR for millimeter wave bands.

References

  1. P. Robertson and S. Kaiser, Analysis of the effects of phase-noise in orthogonal frequency division multiplex (OFDM) systems, IEEE International Conference on Communications (ICC), 1995, pages 1652 to 1657 (the split of phase noise into a common phase error and inter-carrier interference)
  2. A. Garcia Armada, Understanding the effects of phase noise in orthogonal frequency division multiplexing (OFDM), IEEE Transactions on Broadcasting 47(2), 2001, pages 153 to 159 (the common phase error and the inter-carrier interference from phase noise)
  3. T. Pollet, M. Van Bladel and M. Moeneclaey, BER sensitivity of OFDM systems to carrier frequency offset and Wiener phase noise, IEEE Transactions on Communications 43(2/3/4), 1995, pages 191 to 193 (the SNR degradation caused by Wiener phase noise)

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