Algorithm Search⌘K

Definitioncore

Differential phase-shift keying

Also called DPSK, DBPSK, DQPSK.

PSK that carries the data in the phase change between consecutive symbols, so a receiver can detect it without a carrier phase reference.

Differential phase-shift keying (DPSK) is PSK in which the data selects the change of phase from one symbol to the next, not the phase itself. The receiver compares each received symbol with the one before it, so an unknown carrier phase cancels and no phase reference is needed. The cost is a loss in noise: about 0.750.75 dB for binary DPSK at a bit error rate of 10−510^{-5}, and close to 33 dB for a large number of phases. DBPSK and DQPSK are the binary and four-phase cases.

Definition

Let MM be a power of 22 and k=log⁡2Mk = \log_2 M. The data is a sequence of steps m1,m2,…m_1, m_2, \ldots in {0,1,…,M−1}\{0, 1, \ldots, M-1\}, each from kk bits. The M-ary DPSK signal sends the symbols

s0=1,sn=sn−1 ej2πmn/M,n≥1,s_0 = 1, \qquad s_n = s_{n-1}\, e^{j 2\pi m_n / M}, \quad n \ge 1,

where jj is the imaginary unit. So sn=ejϕns_n = e^{j\phi_n} with ϕn=ϕn−1+2πmn/M\phi_n = \phi_{n-1} + 2\pi m_n/M: the phase step carries the data. The first symbol is a reference and carries no data. A Gray labeling of the steps makes neighboring steps differ in one bit. For M=2M = 2 the bit 11 gives a step of π\pi and the bit 00 no step.

The differential detector. The receiver gets rn=ejθsn+wnr_n = e^{j\theta} s_n + w_n, with an unknown phase θ\theta and noise wnw_n. It forms

zn=rn rn−1∗z_n = r_n\, r_{n-1}^{*}

and decides the step whose phase 2πm/M2\pi m/M is nearest to arg⁡zn\arg z_n. Without noise zn=ej2πmn/Mz_n = e^{j 2\pi m_n/M}: the factor ejθe^{j\theta} cancels. A phase that drifts slowly, by a small angle per symbol, only adds that angle to arg⁡zn\arg z_n.

Properties.

  • No phase reference. The receiver needs no carrier recovery, and a phase jump in the channel costs at most one or two symbols.
  • Noncoherent optimality. For DBPSK, Re(rnrn−1∗)>0\mathrm{Re}(r_n r_{n-1}^*) > 0 exactly when ∣rn+rn−1∣>∣rn−rn−1∣|r_n + r_{n-1}| > |r_n - r_{n-1}|, since ∣a+b∣2−∣a−b∣2=4 Re(ab∗)|a+b|^2 - |a-b|^2 = 4\,\mathrm{Re}(a b^*). The right side is the noncoherent maximum-likelihood rule for the two signals (1,1)(1, 1) and (1,−1)(1, -1) over two symbols with an unknown phase. So the differential detector is optimal for an observation of two symbols.
  • Bit error rate of DBPSK. In white Gaussian noise, Pb=12e−Eb/N0P_b = \tfrac12 e^{-E_b/N_0}. Coherent BPSK has Pb=Q(2Eb/N0)P_b = Q(\sqrt{2E_b/N_0}), with QQ the Gaussian Q function.
  • Loss for larger M. The noise in znz_n is the sum of two noise terms, from rnr_n and from rn−1r_{n-1}. At high SNR, MM-DPSK needs sin⁡2(π/M)/(2sin⁡2(π/(2M)))\sin^2(\pi/M) / (2\sin^2(\pi/(2M))) times the energy of coherent MM-PSK for the same symbol error rate. This factor is 00 dB for M=2M = 2, 2.322.32 dB for M=4M = 4, 2.842.84 dB for M=8M = 8, 2.972.97 dB for M=16M = 16, and it tends to 33 dB.
  • Coherent detection of the same signal. A receiver with a phase reference can detect each sns_n coherently and then take the difference of the decided phases. This removes the ambiguity of the carrier phase by multiples of 2π/M2\pi/M, which a phase-locked loop leaves. Each wrong decision then spoils two steps: for BPSK, Pb=2p(1−p)P_b = 2p(1-p) with p=Q(2Eb/N0)p = Q(\sqrt{2E_b/N_0}).

The encoder and the detector

  1. DPSK-ENCODE(b_1, ..., b_{kN}, M) ▷ k = log2 M
  2. 1s_0 ← 1 ▷ the reference symbol
  3. for n ← 1 to N
  4. 2m_n ← the step whose Gray label is the n-th group of k bits
  5. 3s_n ← s_{n-1} · e^{j2π m_n / M}
  6. 4return s_0, ..., s_N
  7. DPSK-DETECT(r_0, ..., r_N, M)
  8. for n ← 1 to N
  9. 5z_n ← r_n · conj(r_{n-1})
  10. 6m̂_n ← round(M · arg(z_n) / (2π)) mod M
  11. 7output the Gray label of m̂_n as k bits

The tests check the examples below, recover random data for M=2,4,8,16M = 2, 4, 8, 16 after an unknown phase and a drift of 1.81.8 degrees per symbol, and show that coherent detection with a fixed reference fails under the same drift. They also measure the bit error rate of DBPSK and of coherent detection with differential decoding against the formulas above.

Examples and non-examples

DBPSK by hand. The bits 1,0,1,1,01, 0, 1, 1, 0 give the symbols 1,−1,−1,1,−1,−11, -1, -1, 1, -1, -1. If the channel turns every symbol by 0.70.7 rad, the products rnrn−1∗r_n r_{n-1}^* are still −1,1,−1,−1,1-1, 1, -1, -1, 1, which give back 1,0,1,1,01, 0, 1, 1, 0. A coherent BPSK receiver with a reference that is wrong by π\pi would invert every bit; the differential detector does not care.

DQPSK by hand. With the Gray labels 00→000 \to 0, 01→π/201 \to \pi/2, 11→π11 \to \pi, 10→3π/210 \to 3\pi/2, the bits 00 01 11 1000\,01\,11\,10 give the symbols 1,1,j,−j,−11, 1, j, -j, -1.

The cost in numbers. At Eb/N0=10E_b/N_0 = 10 dB, DBPSK has Pb=12e−10=2.27×10−5P_b = \tfrac12 e^{-10} = 2.27 \times 10^{-5}. For Pb=10−5P_b = 10^{-5}, DBPSK needs Eb/N0=ln⁡(5×104)=10.82E_b/N_0 = \ln(5 \times 10^4) = 10.82, that is 10.3410.34 dB, and coherent BPSK needs 9.599.59 dB: a loss of 0.750.75 dB. At Eb/N0=4E_b/N_0 = 4 (6.026.02 dB) DBPSK has Pb=0.0092P_b = 0.0092 and coherent detection with differential decoding has Pb=0.0047P_b = 0.0047.

Where it is used. The 11 and 22 Mbit/s rates of the first IEEE 802.11 physical layer use DBPSK and DQPSK. The enhanced data rates of Bluetooth use π/4\pi/4-DQPSK and 8DPSK. In π/4\pi/4-DQPSK the steps are ±π/4\pm\pi/4 and ±3π/4\pm 3\pi/4, so the phase changes at every symbol and never by π\pi.

Non-example: fast fading. In a Rayleigh fading channel with a large Doppler spread, the channel phase changes between two symbols by a random amount. The differential detector then has an error floor: the error rate stops falling as the SNR grows. DPSK needs a channel that is close to constant over two symbols.

Non-example: plain PSK. In PSK the data is the absolute phase. A receiver must know the carrier phase, and a phase-locked loop on MM-PSK has an ambiguity of a multiple of 2π/M2\pi/M. Differential encoding is the usual way to remove this ambiguity, even in coherent receivers.

Variation: detection over more symbols. A detector that decides N−1N - 1 steps jointly from NN received symbols with an unknown common phase closes most of the gap to coherent detection as NN grows. The ordinary differential detector is the case N=2N = 2.

  • Phase-shift keying: the same constellation, detected with a phase reference.
  • Noncoherent detection: the family of detectors without a phase reference; DPSK is its member with the best error rate for two symbols.
  • Carrier recovery: what a coherent receiver needs and a DPSK receiver can skip.
  • Bit error rate: 12e−Eb/N0\tfrac12 e^{-E_b/N_0} for DBPSK, against Q(2Eb/N0)Q(\sqrt{2E_b/N_0}) for BPSK.
  • Offset QPSK: another change to QPSK, which acts on the timing of the components and not on how the data is mapped to phase.

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)
differential_phase_shift_keying.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/differential-phase-shift-keying/. The authors are listed in prov/3Q2A6K.jsonl.

"""M-ary differential PSK: the differential encoder, the differential detector, and coherent
detection followed by differential decoding, for comparison.

Each group of log2(M) bits is a Gray label u. The phase step is 2 pi m / M, where m is the
index whose Gray code is u, so that neighboring steps differ in one bit. The first transmitted
symbol is the reference 1. All symbols have unit energy.
"""

import cmath
import math


def bits_per_symbol(m: int) -> int:
    k = m.bit_length() - 1
    if m < 2 or 1 << k != m:
        raise ValueError("M must be a power of 2, at least 2")
    return k


def gray(m: int) -> int:
    return m ^ (m >> 1)


def gray_inverse(u: int) -> int:
    m = 0
    while u:
        m ^= u
        u >>= 1
    return m


def _labels(bits: list[int], k: int) -> list[int]:
    if len(bits) % k:
        raise ValueError("the number of bits must be a multiple of log2(M)")
    out = []
    for i in range(0, len(bits), k):
        u = 0
        for b in bits[i : i + k]:
            u = 2 * u + b
        out.append(u)
    return out


def _bits(u: int, k: int) -> list[int]:
    return [(u >> (k - 1 - i)) & 1 for i in range(k)]


def encode(bits: list[int], m: int) -> list[complex]:
    """The symbols s_0 = 1, s_k = s_(k-1) e^(j 2 pi m_k / M); one more symbol than labels."""
    k = bits_per_symbol(m)
    s = [1 + 0j]  # @line L1
    for u in _labels(bits, k):
        step = gray_inverse(u)  # @line L2
        s.append(s[-1] * cmath.exp(2j * math.pi * step / m))  # @line L3
    return s  # @line L4


def detect(r: list[complex], m: int) -> list[int]:
    """Differential detection: the phase of r_k conj(r_(k-1)) to the nearest step."""
    k = bits_per_symbol(m)
    bits = []
    for prev, cur in zip(r, r[1:]):
        z = cur * prev.conjugate()  # @line L5
        step = round(m * cmath.phase(z) / (2 * math.pi)) % m  # @line L6
        bits.extend(_bits(gray(step), k))  # @line L7
    return bits


def detect_coherent(r: list[complex], m: int, theta: float = 0.0) -> list[int]:
    """Coherent detection with the reference phase theta, then differential decoding."""
    k = bits_per_symbol(m)
    rot = cmath.exp(-1j * theta)
    idx = [round(m * cmath.phase(v * rot) / (2 * math.pi)) % m for v in r]
    bits = []
    for a, b in zip(idx, idx[1:]):
        bits.extend(_bits(gray((b - a) % m), k))
    return bits


def rotate(s: list[complex], theta: float, nu: float = 0.0) -> list[complex]:
    """The channel s_k e^(j (theta + 2 pi nu k)): an unknown phase and a frequency offset nu/T."""
    return [v * cmath.exp(1j * (theta + 2 * math.pi * nu * n)) for n, v in enumerate(s)]


def asymptotic_loss_db(m: int) -> float:
    """The high-SNR loss of M-DPSK against coherent M-PSK, 10 log10(sin^2(pi/M) / (2 sin^2(pi/(2M))))."""
    return 10 * math.log10(math.sin(math.pi / m) ** 2 / (2 * math.sin(math.pi / (2 * m)) ** 2))
test_differential_phase_shift_keying.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/differential-phase-shift-keying/. The authors are listed in prov/3Q2A6K.jsonl.

import math
import random

import cbb
from differential_phase_shift_keying import (
    asymptotic_loss_db,
    detect,
    detect_coherent,
    encode,
    gray,
    gray_inverse,
    rotate,
)


def close(a: list[complex], b: list[complex]) -> bool:
    return len(a) == len(b) and all(abs(x - y) < 1e-12 for x, y in zip(a, b))


def test_dbpsk_worked_example() -> None:
    bits = [1, 0, 1, 1, 0]
    s = encode(bits, 2)
    assert close(s, [1, -1, -1, 1, -1, -1])
    # An unknown phase of 0.7 rad changes every symbol and no decision.
    r = rotate(s, 0.7)
    z = [cur * prev.conjugate() for prev, cur in zip(r, r[1:])]
    assert close(z, [-1, 1, -1, -1, 1])
    assert detect(r, 2) == bits


def test_dqpsk_worked_example() -> None:
    # 00, 01, 11, 10 give the steps 0, 90, 180 and 270 degrees.
    s = encode([0, 0, 0, 1, 1, 1, 1, 0], 4)
    assert close(s, [1, 1, 1j, -1j, -1])
    assert [gray_inverse(u) for u in range(4)] == [0, 1, 3, 2]
    assert all(gray(gray_inverse(u)) == u for u in range(64))


def test_round_trip_with_unknown_phase_and_drift() -> None:
    rng = random.Random(5)
    for m in (2, 4, 8, 16):
        k = m.bit_length() - 1
        bits = [rng.randrange(2) for _ in range(600 * k)]
        s = encode(bits, m)
        assert all(abs(abs(v) - 1) < 1e-9 for v in s)
        # A frequency offset of 0.005/T turns 1.8 degrees per symbol, inside the margin 180/M.
        r = rotate(s, rng.uniform(-math.pi, math.pi), 0.005)
        assert detect(r, m) == bits


def test_coherent_detection_needs_the_phase() -> None:
    rng = random.Random(6)
    bits = [rng.randrange(2) for _ in range(800)]
    r = rotate(encode(bits, 4), 0.3, 0.005)
    # The drift reaches 45 degrees after 25 symbols, and the coherent decisions slip.
    wrong = sum(a != b for a, b in zip(detect_coherent(r, 4, 0.3), bits))
    assert wrong > 0
    assert detect(r, 4) == bits
    # With the exact phase, coherent detection and differential decoding recover the bits.
    assert detect_coherent(rotate(encode(bits, 4), 0.3), 4, 0.3) == bits


def test_differential_detector_is_the_two_symbol_noncoherent_rule() -> None:
    # For DBPSK, Re(r_k conj r_(k-1)) > 0 exactly when |r_k + r_(k-1)| > |r_k - r_(k-1)|.
    rng = random.Random(8)
    for _ in range(2000):
        a = complex(rng.gauss(0, 1), rng.gauss(0, 1))
        b = complex(rng.gauss(0, 1), rng.gauss(0, 1))
        lhs = abs(a + b) ** 2 - abs(a - b) ** 2
        assert abs(lhs - 4 * (a * b.conjugate()).real) < 1e-9


def test_dbpsk_bit_error_rate() -> None:
    # Eb/N0 = 4 (6.02 dB): Pb = exp(-4)/2 = 0.009158. n = 20000 bits, seed 21, about 183 errors.
    ebn0, n = 4.0, 20000
    rng = random.Random(21)
    bits = [rng.randrange(2) for _ in range(n)]
    s = encode(bits, 2)
    r = [v + cbb.cn(rng, 1 / ebn0) for v in rotate(s, 1.1)]
    errors = sum(a != b for a, b in zip(detect(r, 2), bits))
    want = 0.5 * math.exp(-ebn0)
    assert n * want >= 100
    lo, hi = cbb.wilson(errors, n)
    assert lo <= want <= hi, (errors, n, lo, hi, want)


def test_coherent_differentially_encoded_bpsk_doubles_the_errors() -> None:
    # Eb/N0 = 4: p = Q(sqrt(8)) = 0.002339 per decision, Pb = 2p(1 - p) = 0.004667.
    # n = 40000 bits, seed 22, about 187 errors.
    ebn0, n = 4.0, 40000
    rng = random.Random(22)
    bits = [rng.randrange(2) for _ in range(n)]
    r = [v + cbb.cn(rng, 1 / ebn0) for v in encode(bits, 2)]
    errors = sum(a != b for a, b in zip(detect_coherent(r, 2), bits))
    p = cbb.qfunc(math.sqrt(2 * ebn0))
    want = 2 * p * (1 - p)
    assert n * want >= 100
    lo, hi = cbb.wilson(errors, n)
    assert lo <= want <= hi, (errors, n, lo, hi, want)


def test_numbers_on_the_page() -> None:
    # DBPSK at 10 dB, and the Eb/N0 for 1e-5 with DBPSK and with coherent BPSK.
    assert abs(0.5 * math.exp(-10) - 2.270e-5) < 1e-8
    assert abs(10 * math.log10(math.log(5e4)) - 10.34) < 5e-3
    assert abs(10 * math.log10(cbb.qinv(1e-5) ** 2 / 2) - 9.59) < 5e-3
    # The high-SNR loss of M-DPSK against M-PSK.
    assert abs(asymptotic_loss_db(2)) < 1e-12
    assert abs(asymptotic_loss_db(4) - 2.32) < 5e-3
    assert abs(asymptotic_loss_db(8) - 2.84) < 5e-3
    assert abs(asymptotic_loss_db(16) - 2.97) < 5e-3
    assert abs(asymptotic_loss_db(1024) - 10 * math.log10(2)) < 1e-4

References

  1. John G. Proakis and Masoud Salehi, Digital Communications, fifth edition, McGraw-Hill, 2008, Chapter 4 (optimum detection in additive white Gaussian noise, including differential PSK, its detector and its error probability)
  2. Dariush Divsalar and Marvin K. Simon, Multiple-symbol differential detection of MPSK, IEEE Transactions on Communications 38(3), 1990, pp. 300 to 308 (the conventional differential detector as the two-symbol case of a maximum-likelihood detector over N symbols, and the approach to coherent detection as N grows)

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/3Q2A6K/text.yaml