Algorithm Search⌘K

Definitioncore

Peak-to-average power ratio

Also called PAPR, crest factor.

The peak power of a signal block divided by its mean power. OFDM symbols have a high PAPR, so the power amplifier must back off. Measure it with 4 times oversampling.

The peak-to-average power ratio (PAPR) of a block of complex baseband samples x[n]x[n] is the largest instantaneous power ∣x[n]∣2|x[n]|^2 in the block divided by the mean power E∣x[n]∣2E|x[n]|^2. An OFDM symbol is a sum of NN subcarriers with independent data, so a few samples can be much larger than the rest, and its PAPR can approach NN. A power amplifier is linear only up to a saturation level, so the transmitter must set the mean power well below that level, the backoff, and this costs power efficiency. This page defines the measure and its distribution. The methods that lower it have their own pages: clipping and filtering, selected mapping, partial transmit sequences, tone reservation and active constellation extension, and the waveform SC-FDMA, which avoids most of the problem. The page uses the unitary DFT pair of the OFDM page, 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, jj is the imaginary unit, and the constellations are normalized to Es=E∣X[k]∣2=1E_s = E|X[k]|^2 = 1.

Definition

PAPR of a block. For the samples x[0],…,x[M−1]x[0], \ldots, x[M-1] of one block,

PAPR=max⁡0≤n<M∣x[n]∣2E ∣x[n]∣2,PAPRdB=10log⁡10PAPR.\mathrm{PAPR} = \frac{\max_{0 \le n < M} |x[n]|^2}{E\,|x[n]|^2}, \qquad \mathrm{PAPR}_{\mathrm{dB}} = 10 \log_{10} \mathrm{PAPR}.

The PAPR is a random variable: it changes from one OFDM symbol to the next. Many authors put the time average 1M∑n∣x[n]∣2\frac{1}{M}\sum_n |x[n]|^2 of the block in the denominator instead of the ensemble mean. For constant-modulus symbols such as QPSK the two are equal, because by Parseval's theorem the block energy is ∑k∣X[k]∣2=N\sum_k |X[k]|^2 = N for every block. For 16-QAM they differ a little from block to block.

Crest factor. The crest factor is the peak amplitude divided by the RMS amplitude, CF=PAPR\mathrm{CF} = \sqrt{\mathrm{PAPR}}. In decibels the two numbers are the same, since 20log⁡10CF=10log⁡10PAPR20 \log_{10} \mathrm{CF} = 10 \log_{10} \mathrm{PAPR}.

Continuous time and oversampling. The amplifier sees the analog signal x(t)x(t), and its peaks can fall between the samples x[n]=x(nT/N)x[n] = x(nT/N). The PAPR of x(t)x(t) over the symbol is at least the PAPR of the NN samples. To measure it, oversample by a factor LL: put (L−1)N(L - 1)N zeros in the middle of XX, between X[N/2−1]X[N/2 - 1] and X[N/2]X[N/2], so that the indices k≥N/2k \ge N/2 stay the negative frequencies, and take an inverse DFT of size LNLN. The standard choice is L=4L = 4. With the scale L\sqrt L, the oversampled block xLx_L satisfies two facts that follow from the definition of the DFT:

  1. xL[Ln]=x[n]x_L[L n] = x[n] for n=0,…,N−1n = 0, \ldots, N - 1, so the oversampled block contains the Nyquist-rate samples, and its PAPR is never smaller.
  2. 1LN∑m∣xL[m]∣2=1N∑k∣X[k]∣2\frac{1}{LN} \sum_m |x_L[m]|^2 = \frac{1}{N} \sum_k |X[k]|^2, so the mean power does not change.
  1. PAPR(X[0..N-1], L) ▷ N and L are powers of two; L = 4 is the usual choice
  2. 1Z ← (X[0], .., X[N/2-1], 0, .., 0, X[N/2], .., X[N-1]) ▷ (L-1)N zeros in the middle, length LN
  3. 2x ← √L · F_LNᴴ Z ▷ unitary inverse FFT of size LN, scaled by √L
  4. 3P ← max_m |x[m]|²
  5. 4return P / E|x[m]|² ▷ the time average of |x[m]|² for constant-modulus X

The cost is one inverse FFT of size LNLN, O(LNlog⁡(LN))O(LN \log(LN)) operations per symbol in the real-RAM model.

The upper bound NN. With the time-average denominator, PAPR≤N\mathrm{PAPR} \le N for every block and every LL, and also for the continuous signal. Each sample is x(t)=1N∑kX[k]ej2πfktx(t) = \frac{1}{\sqrt N} \sum_k X[k] e^{j 2\pi f_k t}, so by the Cauchy-Schwarz inequality ∣x(t)∣2≤1N(∑k∣X[k]∣)2≤∑k∣X[k]∣2|x(t)|^2 \le \frac{1}{N} \big(\sum_k |X[k]|\big)^2 \le \sum_k |X[k]|^2, and the mean power is 1N∑k∣X[k]∣2\frac{1}{N} \sum_k |X[k]|^2. Equality needs all ∣X[k]∣|X[k]| equal and all subcarriers in phase at one instant, for example X[k]=1X[k] = 1 for all kk.

The distribution and the rule. The CCDF Pr⁡(PAPR>γ)\Pr(\mathrm{PAPR} > \gamma) describes a waveform better than one number. If the NN samples are independent and each is CN(0,1)\mathcal{CN}(0, 1), then ∣x[n]∣2|x[n]|^2 is exponential with mean 1, Pr⁡(∣x[n]∣2≤γ)=1−e−γ\Pr(|x[n]|^2 \le \gamma) = 1 - e^{-\gamma}, and

Pr⁡(PAPR>γ)=1−(1−e−γ)N.\Pr(\mathrm{PAPR} > \gamma) = 1 - (1 - e^{-\gamma})^N.

This is exact in one case: if the X[k]X[k] are i.i.d. CN(0,1)\mathcal{CN}(0, 1) and the denominator is the ensemble mean, then x=FHXx = F^H X is again i.i.d. CN(0,1)\mathcal{CN}(0, 1), because FHF^H is unitary. For QPSK or QAM data it is a rule, not a theorem. The central limit theorem makes each sample close to Gaussian for large NN, but the rule assumes independent samples and ignores oversampling, and the oversampled samples are strongly correlated. At N=64N = 64 and γ=10\gamma = 10 dB the rule gives 1−(1−e−10)64=2.90⋅10−31 - (1 - e^{-10})^{64} = 2.90 \cdot 10^{-3}. Ochiai and Imai (2001) give a better approximation for the continuous-time signal.

Baseband and passband. The definition above uses the complex envelope. Some texts call it the peak-to-mean envelope power ratio (PMEPR). The real passband signal s(t)=Re{x(t)2 ej2πfct}s(t) = \mathrm{Re}\{x(t) \sqrt 2\, e^{j 2\pi f_c t}\} has mean power E∣x∣2E|x|^2 and, for a carrier frequency much larger than the bandwidth, peaks close to 2max⁡∣x(t)∣22 \max |x(t)|^2, so its PAPR is about 3.01 dB higher. The factor 2\sqrt 2 does not change this ratio; without it, both the peak and the mean are halved. Always say which one a number refers to.

Examples and non-examples

Four subcarriers, a hidden peak. Take N=4N = 4 and the BPSK block X=(1,1,1,−1)X = (1, 1, 1, -1). The Nyquist-rate samples are

x[n]=12∑kX[k]ej2πkn/4=(1, j, 1, −j),x[n] = \tfrac{1}{2} \textstyle\sum_k X[k] e^{j 2\pi k n / 4} = (1,\ j,\ 1,\ -j),

all of magnitude 1, so the PAPR of the 4 samples is 1, that is 0 dB. With L=4L = 4 the PAPR is 2.32 dB, and with L=64L = 64 it is 2.48 dB, close to the continuous-time value. The samples at the Nyquist rate miss the peak completely.

All subcarriers in phase. X[k]=1X[k] = 1 for all kk gives x[0]=Nx[0] = \sqrt N and x[n]=0x[n] = 0 for n=1,…,N−1n = 1, \ldots, N - 1 at the Nyquist rate. The PAPR is NN, the upper bound: 6.02 dB for N=4N = 4 and 18.06 dB for N=64N = 64. A block of training symbols with this pattern would drive the amplifier hard, which is one reason why preambles use sequences with a flat envelope, such as Zadoff-Chu sequences.

64 subcarriers with QPSK. A simulation of 4000 random QPSK symbols with N=64N = 64 (Python random.Random(1)) gives the CCDF below. The rule fits the Nyquist-rate samples well. The 4 times oversampled signal exceeds each level about twice as often as the rule says, which is the error from ignoring the peaks between samples.

γ\gamma 6 dB 7 dB 8 dB 9 dB 10 dB
rule 1−(1−e−γ)641 - (1 - e^{-\gamma})^{64} 0.701 0.348 0.110 0.0225 0.0029
simulation, L=1L = 1 0.755 0.355 0.103 0.0188 0.0025
simulation, L=4L = 4 0.954 0.636 0.236 0.0488 0.0070

In the same run the mean PAPR is 6.83 dB at L=1L = 1 and 7.48 dB at L=4L = 4, and the PAPR exceeded by 1 percent of the symbols is 9.30 dB and 9.85 dB. So, to clip at most 1 percent of the symbols, the mean power must be about 9.9 dB below the saturation power of the amplifier. In a second run of 300 symbols, the PAPR at L=16L = 16 was on average 0.07 dB above the value at L=4L = 4 (at most 0.34 dB), while the value at L=4L = 4 was on average 0.71 dB above the value at L=1L = 1 (at most 3.29 dB). So L=4L = 4 captures most of the peak, and L=1L = 1 does not.

A single carrier. The symbol-spaced samples of single-carrier QPSK all have power 1, so their PAPR is 0 dB. For 16-QAM the largest point (3+3j)/10(3 + 3j)/\sqrt{10} has power 18/1018/10, so the PAPR is 10log⁡101.8=2.5510 \log_{10} 1.8 = 2.55 dB. These are values at the symbol instants. The filtered waveform after pulse shaping has peaks between the symbols, and its PAPR depends on the roll-off. Still, it is far below the PAPR of OFDM, which is the reason for SC-FDMA in the LTE uplink.

Non-example: the mean over many symbols. The ratio of the largest peak in a long transmission to the mean power is not the PAPR of an OFDM symbol. It grows with the length of the record, because a longer record contains rarer peaks. Report the CCDF per symbol, or a quantile of it.

Non-example: a pure tone. A single subcarrier, x[n]=ej2πkn/Nx[n] = e^{j 2\pi k n / N}, has a constant envelope and a PAPR of 0 dB in baseband. Its real passband signal is a sinusoid with a PAPR of 2, 3.01 dB. Both numbers are correct; they measure different signals.

Code

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)
peak_to_average_power_ratio.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/peak-to-average-power-ratio/. The authors are listed in prov/Z633YX.jsonl.

"""The peak-to-average power ratio (PAPR) of an OFDM symbol, measured with oversampling.

The OFDM symbol is x = F^H X with the unitary DFT pair. The oversampled symbol
puts (L - 1) N zeros in the middle of X, so that the indices k >= N/2 stay the
negative frequencies, and takes an inverse FFT of size L N scaled by sqrt(L).
Then x_L[L n] equals the Nyquist-rate sample x[n], and the mean power of x_L
equals the mean of |X[k]|^2. The FFT is a radix-2 Cooley-Tukey FFT, so N and L
must be powers of two.
"""

import cmath
import math
from typing import Sequence


def fft(a: Sequence[complex], inverse: bool = False) -> list[complex]:
    """Radix-2 FFT with no scale factor: sum_n a[n] e^(-+ j 2 pi k n / n_len)."""
    n = len(a)
    if n == 0 or n & (n - 1):
        raise ValueError("the length must be a power of two")
    out = [complex(v) for v in a]
    j = 0
    for i in range(1, n):
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            out[i], out[j] = out[j], out[i]
    sign = 1 if inverse else -1
    size = 2
    while size <= n:
        half = size // 2
        tw = [cmath.exp(sign * 2j * math.pi * k / size) for k in range(half)]
        for s in range(0, n, size):
            for k in range(half):
                u = out[s + k]
                v = out[s + k + half] * tw[k]
                out[s + k] = u + v
                out[s + k + half] = u - v
        size *= 2
    return out


def ofdm_oversampled(X: Sequence[complex], L: int = 4) -> list[complex]:
    """The OFDM symbol F^H X sampled L times per Nyquist interval."""
    n = len(X)
    if n < 2 or L < 1:
        raise ValueError("need N >= 2 and L >= 1")
    z = [0j] * (L * n)  # @line L1
    for k in range(n // 2):
        z[k] = complex(X[k])
    for k in range(n // 2, n):
        z[L * n - n + k] = complex(X[k])
    s = math.sqrt(L) / math.sqrt(L * n)
    return [v * s for v in fft(z, inverse=True)]  # @line L2


def papr(x: Sequence[complex], mean_power: float | None = None) -> float:
    """max |x[n]|^2 divided by the mean power.

    The mean power is the time average of |x[n]|^2 unless mean_power gives the
    ensemble mean E|x[n]|^2. For constant-modulus subcarrier symbols the two are equal.
    """
    p = [abs(v) ** 2 for v in x]
    peak = max(p)  # @line L3
    mean = sum(p) / len(p) if mean_power is None else mean_power
    return peak / mean  # @line L4


def papr_db(x: Sequence[complex], mean_power: float | None = None) -> float:
    """The PAPR in dB."""
    return 10.0 * math.log10(papr(x, mean_power))


def ccdf_rule(gamma: float, n: int) -> float:
    """The rule P(PAPR > gamma) = 1 - (1 - e^-gamma)^N for gamma as a linear ratio."""
    return 1.0 - (1.0 - math.exp(-gamma)) ** n
test_peak_to_average_power_ratio.py 81 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/peak-to-average-power-ratio/. The authors are listed in prov/Z633YX.jsonl.

import math
import random

import cbb
from peak_to_average_power_ratio import ccdf_rule, fft, ofdm_oversampled, papr, papr_db

QPSK = [complex(a, b) / math.sqrt(2) for a in (1, -1) for b in (1, -1)]


def qpsk_block(rng, n):
    return [rng.choice(QPSK) for _ in range(n)]


def test_fft_matches_direct_dft():
    rng = random.Random(1)
    for n in (2, 8, 64):
        x = [cbb.cn(rng, 1.0) for _ in range(n)]
        assert max(abs(a - b) for a, b in zip(fft(x), cbb.dft(x))) < 1e-9
        assert max(abs(a / n - b) for a, b in zip(fft(x, inverse=True), cbb.idft(x))) < 1e-9


def test_nyquist_rate_is_the_unitary_inverse_dft():
    rng = random.Random(2)
    X = qpsk_block(rng, 16)
    assert max(abs(a - b) for a, b in zip(ofdm_oversampled(X, 1), cbb.uidft(X))) < 1e-9


def test_oversampling_keeps_the_nyquist_samples_and_the_power():
    rng = random.Random(3)
    for L in (2, 4, 8):
        X = [cbb.cn(rng, 1.0) for _ in range(32)]
        x1 = ofdm_oversampled(X, 1)
        xl = ofdm_oversampled(X, L)
        assert max(abs(xl[L * n] - x1[n]) for n in range(32)) < 1e-9
        assert abs(sum(abs(v) ** 2 for v in xl) / len(xl) - sum(abs(v) ** 2 for v in X) / 32) < 1e-9
        assert papr(xl) >= papr(x1) - 1e-12


def test_bound_n_and_its_equality_case():
    for n in (4, 16, 64):
        for L in (1, 4):
            assert abs(papr(ofdm_oversampled([1] * n, L)) - n) < 1e-9
    rng = random.Random(4)
    for _ in range(50):
        X = [cbb.cn(rng, 1.0) for _ in range(16)]
        for L in (1, 4):
            assert papr(ofdm_oversampled(X, L)) <= 16 + 1e-9


def test_small_examples_of_the_page():
    x = ofdm_oversampled([1, 1, 1, -1], 1)
    assert max(abs(a - b) for a, b in zip(x, [1, 1j, 1, -1j])) < 1e-12
    assert abs(papr(x) - 1.0) < 1e-12
    assert abs(papr_db(ofdm_oversampled([1, 1, 1, -1], 4)) - 2.323) < 1e-3
    assert abs(papr_db(ofdm_oversampled([1, 1, 1, 1], 4)) - 6.021) < 1e-3
    corner = (3 + 3j) / math.sqrt(10)
    assert abs(papr([corner], 1.0) - 1.8) < 1e-12


def test_check_value_of_the_rule():
    assert abs(ccdf_rule(10.0, 64) - 2.90e-3) < 5e-6


def test_rule_is_exact_for_gaussian_symbols_at_nyquist_rate():
    # The unitary DFT maps i.i.d. CN(0, 1) symbols to i.i.d. CN(0, 1) samples.
    rng = random.Random(7)
    trials, gamma = 1000, 10 ** 0.8
    k = sum(papr(ofdm_oversampled([cbb.cn(rng, 1.0) for _ in range(64)], 1), 1.0) > gamma for _ in range(trials))
    lo, hi = cbb.wilson(k, trials)
    assert lo <= ccdf_rule(gamma, 64) <= hi


def test_rule_underestimates_the_oversampled_qpsk_ccdf():
    rng = random.Random(1)
    trials, gamma = 1000, 10 ** 0.8
    k = sum(papr(ofdm_oversampled(qpsk_block(rng, 64), 4)) > gamma for _ in range(trials))
    lo, _ = cbb.wilson(k, trials)
    assert lo > ccdf_rule(gamma, 64)

References

  1. Seung Hee Han and Jae Hong Lee, An overview of peak-to-average power ratio reduction techniques for multicarrier transmission, IEEE Wireless Communications 12(2), 2005, pages 56 to 65, the definition of the PAPR of a multicarrier block, its CCDF under the independence approximation, the oversampled measurement and the overview of reduction methods
  2. Hideki Ochiai and Hideki Imai, On the distribution of the peak-to-average power ratio in OFDM signals, IEEE Transactions on Communications 49(2), 2001, pages 282 to 289, the distribution of the PAPR of the continuous-time OFDM signal, where the independent-sample rule does not hold
  3. Gerhard Wunder, Robert F. H. Fischer, Holger Boche, Simon Litsyn and Jong-Seon No, The PAPR problem in OFDM transmission: new directions for a long-lasting problem, IEEE Signal Processing Magazine 30(6), 2013, pages 130 to 144, the PAPR and the related metrics, and the limits of what reduction can achieve
  4. Jose Tellado, Multicarrier Modulation with Low PAR: Applications to DSL and Wireless, Kluwer Academic Publishers, 2000, chapter Peak to Average Ratio (the definition, the distribution of the peak and the effect of oversampling)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW4 complete
  • a review of the text: no review record reviews/Z633YX/text.yaml