Algorithm Search⌘K

Algorithmadvanced

IQ imbalance compensation

Also called IQ mismatch compensation.

Estimates from two training symbols how IQ imbalance couples each OFDM subcarrier with its mirror, and removes the mirror image by a 2x2 solve per pair of subcarriers.

Time
O(N) worst
Space
O(N) extra
Where
N = the number of subcarriers
Properties
data aideddeterministicexact without noisejoint with channel
Origin
Alireza Tarighat, Rahim Bagheri, Ali H. Sayed, 2005

IQ imbalance compensation removes a distortion of the analog receiver that an OFDM system feels strongly. A direct-conversion receiver mixes the signal down on two branches, in phase and in quadrature, and their gains and phases never match exactly. With a gain gg and a phase error ϕ\phi on the quadrature branch, the complex baseband signal yy becomes r=μy+νy∗r = \mu y + \nu y^*, with μ=(1+ge−jϕ)/2\mu = (1 + g e^{-j\phi})/2 and ν=(1−gejϕ)/2\nu = (1 - g e^{j\phi})/2. Conjugation in time mirrors the spectrum, so after the DFT, subcarrier kk receives an image of its mirror subcarrier −k-k: R[k]=A[k]X[k]+B[k]X[−k]∗R[k] = A[k] X[k] + B[k] X[-k]^*, with A[k]=μH[k]A[k] = \mu H[k] and B[k]=νH[−k]∗B[k] = \nu H[-k]^*. The receiver estimates AA and BB from two training symbols by a 2x2 solve per subcarrier, and then recovers the data of each mirror pair by another 2x2 solve. This handles the channel and the imbalance together and is exact without noise. The page uses jj for the imaginary unit and the unitary DFT pair of the OFDM page, with indices modulo NN, so −k-k is N−kN - k.

In plain words

A radio receiver splits the signal into two parts, which should be exactly equal in strength and exactly a quarter turn apart. Cheap hardware gets this slightly wrong. The result is a faint mirror image: every subcarrier gets a little copy of the subcarrier on the opposite side of the center. If the opposite subcarrier is strong and this one is weak, the copy can spoil it. The receiver learns how strong the copy is from two known symbols, designed so that the true signal and the copy can be told apart. Then, for each pair of mirror subcarriers, it solves two equations in two unknowns to get both data values back without the copy.

The problem

The input is the received OFDM symbols after the DFT: two training symbols R1R_1, R2R_2 with the known values T1T_1, T2T_2, and a data symbol RR. The model is R[k]=A[k]X[k]+B[k]X[−k]∗+V[k]R[k] = A[k] X[k] + B[k] X[-k]^* + V[k] with unknown A[k]A[k] and B[k]B[k] that stay the same during the burst, and noise VV. Subcarriers 00 and N/2N/2 are their own mirrors and carry no data. Output estimates of X[k]X[k] for every other subcarrier.

The algorithm

  1. IQ-COMPENSATE(R1, R2, T1, T2, R)
  2. 1for k ≠ 0, N/2: M ← [[T1[k], conj(T1[-k])], [T2[k], conj(T2[-k])]]
  3. 2(A[k], B[k]) ← the solution of M (A, B) = (R1[k], R2[k])
  4. 3for k ≠ 0, N/2: Q ← [[A[k], B[k]], [conj(B[-k]), conj(A[-k])]]
  5. 4(X̂[k], ·) ← the solution of Q (u, v) = (R[k], conj(R[-k]))
  6. 5return X̂

Lines L1 and L2 write the training symbols in the model, two equations per subcarrier with the unknowns A[k]A[k] and B[k]B[k], and solve them. The training must make the matrix nonsingular: here T2T_2 equals T1T_1 on the lower half of the band and −T1-T_1 on the upper half, so exactly one of kk and −k-k changes sign. Line L3 forms the equations of the data symbol at kk and at its mirror, conjugated, which have the two unknowns X[k]X[k] and X[−k]∗X[-k]^*. Line L4 solves them and keeps X[k]X[k]; the mirror value is found again when the loop reaches −k-k. The estimates of line L2 contain the channel, so no separate channel estimate is needed.

Example

Take N=8N = 8, the channel taps (0.9,0.3j,−0.2)(0.9, 0.3j, -0.2), g=1.1g = 1.1, ϕ=5\phi = 5 degrees, random 4-QAM training and data (seed 2), zero on subcarriers 0 and 4, and no noise. Then μ=1.048−0.048j\mu = 1.048 - 0.048j and ν=−0.048−0.048j\nu = -0.048 - 0.048j, and the image rejection ratio ∣μ∣2/∣ν∣2|\mu|^2 / |\nu|^2 is 23.7923.79 dB.

kk H[k]H[k] A[k]A[k] (line L2) B[k]B[k] (line L2) sent X[k]X[k] R[k]/A[k]R[k] / A[k] (one tap) error X^[k]\hat X[k] (line L4)
1 1.112+0.412j1.112 + 0.412j 1.185+0.379j1.185 + 0.379j −0.034−0.032j-0.034 - 0.032j −0.707−0.707j-0.707 - 0.707j −0.719−0.743j-0.719 - 0.743j 0.038 −0.707−0.707j-0.707 - 0.707j
2 1.4001.400 1.467−0.067j1.467 - 0.067j −0.038−0.038j-0.038 - 0.038j −0.707−0.707j-0.707 - 0.707j −0.709−0.670j-0.709 - 0.670j 0.037 −0.707−0.707j-0.707 - 0.707j
3 1.112−0.412j1.112 - 0.412j 1.146−0.485j1.146 - 0.485j −0.032−0.034j-0.032 - 0.034j 0.707+0.707j0.707 + 0.707j 0.673+0.692j0.673 + 0.692j 0.038 0.707+0.707j0.707 + 0.707j
5 0.688−0.012j0.688 - 0.012j 0.720−0.046j0.720 - 0.046j −0.034−0.073j-0.034 - 0.073j 0.707+0.707j0.707 + 0.707j 0.605+0.662j0.605 + 0.662j 0.111 0.707+0.707j0.707 + 0.707j
6 0.8000.800 0.838−0.038j0.838 - 0.038j −0.067−0.067j-0.067 - 0.067j −0.707+0.707j-0.707 + 0.707j −0.594+0.712j-0.594 + 0.712j 0.113 −0.707+0.707j-0.707 + 0.707j
7 0.688+0.012j0.688 + 0.012j 0.721−0.020j0.721 - 0.020j −0.073−0.034j-0.073 - 0.034j 0.707−0.707j0.707 - 0.707j 0.813−0.743j0.813 - 0.743j 0.111 0.707−0.707j0.707 - 0.707j

The plain one-tap equalizer leaves the image: an error of about 0.040.04 on the strong subcarriers 1 to 3 and about 0.110.11 on the weak subcarriers 5 to 7, whose mirrors are stronger. Lines L3 and L4 return the sent values exactly. The ratios B[k]/A[−k]∗B[k] / A[-k]^* all equal ν/μ∗=−0.0477−0.0436j\nu / \mu^* = -0.0477 - 0.0436j, the coefficient of the time-domain fix below.

With 64 subcarriers, the same channel and imbalance, and N0=0.001N_0 = 0.001 (30 dB), the tests measure over 25 symbols a mean squared error per subcarrier of 8.5×10−38.5 \times 10^{-3} for the one-tap equalizer and 2.8×10−32.8 \times 10^{-3} with compensation; the rest is noise, including the noise of the estimates from line L2.

Correctness

Claim. (a) The receiver output is μy+νy∗\mu y + \nu y^*, so after the DFT, R[k]=A[k]X[k]+B[k]X[−k]∗R[k] = A[k] X[k] + B[k] X[-k]^* with A[k]=μH[k]A[k] = \mu H[k] and B[k]=νH[−k]∗B[k] = \nu H[-k]^*. (b) With the training of lines L1 and L2, the 2x2 systems are nonsingular and return AA and BB exactly without noise. (c) The pair system of lines L3 and L4 has the determinant gcos⁡ϕ H[k]H[−k]∗g \cos\phi\, H[k] H[-k]^*, so it returns X[k]X[k] exactly without noise when ∣ϕ∣<π/2|\phi| < \pi/2 and both subcarriers of the pair have a nonzero channel. All are theorems in the model above.

Key invariant. Conjugation in time is conjugation and mirroring in frequency: the DFT of y∗y^* at kk is Y[−k]∗Y[-k]^*. So the imbalance couples only the pairs (k,−k)(k, -k), and each pair is a separate system of two equations.

The determinant follows from ∣μ∣2−∣ν∣2=gcos⁡ϕ|\mu|^2 - |\nu|^2 = g \cos\phi. The full proof is below.

Proof: IQ imbalance couples each subcarrier with its mirror, two training symbols identify the coupling, and a 2x2 solve per pair removes it exactly without noisefull

Notation. NN subcarriers, jj the imaginary unit, the unitary DFT pair Y=FyY = F y with F[k,n]=e−j2πkn/N/NF[k, n] = e^{-j 2\pi k n / N} / \sqrt N, and indices modulo NN, so −k-k means N−kN - k. The ideal baseband signal in the DFT window is yy, with Y[k]=H[k]X[k]Y[k] = H[k] X[k] after a cyclic prefix that covers the channel. The in-phase branch is ideal; the quadrature branch has the gain g>0g > 0 and the phase error ϕ\phi with ∣ϕ∣<π/2|\phi| < \pi/2. Let

μ=1+ge−jϕ2,ν=1−gejϕ2.\mu = \frac{1 + g e^{-j\phi}}{2}, \qquad \nu = \frac{1 - g e^{j\phi}}{2}.

The used subcarriers are k≠0,N/2k \ne 0, N/2; these two are their own mirrors and carry no data.

Lemma 1 (the two-branch model). The receiver output r=Re⁡(y)+jg(Im⁡(y)cos⁡ϕ−Re⁡(y)sin⁡ϕ)r = \operatorname{Re}(y) + j g \left( \operatorname{Im}(y) \cos\phi - \operatorname{Re}(y) \sin\phi \right) equals μy+νy∗\mu y + \nu y^*.

Proof. Write y=a+jby = a + jb with real aa and bb. Then

μy+νy∗=(a+jb)+(a−jb)2+g2(e−jϕ(a+jb)−ejϕ(a−jb))=a+g2(−2jasin⁡ϕ+2jbcos⁡ϕ),\mu y + \nu y^* = \frac{(a + jb) + (a - jb)}{2} + \frac g2 \left( e^{-j\phi} (a + jb) - e^{j\phi} (a - jb) \right) = a + \frac g2 \left( -2j a \sin\phi + 2j b \cos\phi \right),

which is a+jg(bcos⁡ϕ−asin⁡ϕ)a + j g (b \cos\phi - a \sin\phi). □\square

Lemma 2 (the mirror). The DFT of y∗y^* at kk is Y[−k]∗Y[-k]^*. Hence

R[k]=A[k]X[k]+B[k]X[−k]∗,A[k]=μH[k],B[k]=νH[−k]∗.R[k] = A[k] X[k] + B[k] X[-k]^*, \qquad A[k] = \mu H[k], \quad B[k] = \nu H[-k]^*.

Proof. 1N∑ny[n]∗e−j2πkn/N=(1N∑ny[n]e−j2π(−k)n/N)∗=Y[−k]∗\frac{1}{\sqrt N} \sum_n y[n]^* e^{-j 2\pi k n / N} = \left( \frac{1}{\sqrt N} \sum_n y[n] e^{-j 2\pi (-k) n / N} \right)^* = Y[-k]^*. The DFT is linear, so by Lemma 1, R[k]=μY[k]+νY[−k]∗=μH[k]X[k]+νH[−k]∗X[−k]∗R[k] = \mu Y[k] + \nu Y[-k]^* = \mu H[k] X[k] + \nu H[-k]^* X[-k]^*. □\square

Theorem 1 (training identifies A and B). Let the training symbols satisfy T2[k]=T1[k]T_2[k] = T_1[k] for k<N/2k < N/2 and T2[k]=−T1[k]T_2[k] = -T_1[k] for k≥N/2k \ge N/2, with T1[k]≠0T_1[k] \ne 0 for all kk. Without noise, lines L1 and L2 return A[k]A[k] and B[k]B[k] exactly for every used kk.

Proof. By Lemma 2, the received training symbols give the two linear equations Ri[k]=A[k]Ti[k]+B[k]Ti[−k]∗R_i[k] = A[k] T_i[k] + B[k] T_i[-k]^* for i=1,2i = 1, 2, which is the system of lines L1 and L2. Its determinant is T1[k]T2[−k]∗−T2[k]T1[−k]∗T_1[k] T_2[-k]^* - T_2[k] T_1[-k]^*. For a used kk, exactly one of kk and −k-k is below N/2N/2, so exactly one of the two training values changes sign, and the determinant is ±2 T1[k]T1[−k]∗≠0\pm 2\, T_1[k] T_1[-k]^* \ne 0. A nonsingular system has the unique solution A[k]A[k], B[k]B[k]. □\square

Theorem 2 (the pair solve recovers the data). For a used kk with m=−km = -k, the values satisfy

(A[k]B[k]B[m]∗A[m]∗)(X[k]X[m]∗)=(R[k]R[m]∗),\begin{pmatrix} A[k] & B[k] \\ B[m]^* & A[m]^* \end{pmatrix} \begin{pmatrix} X[k] \\ X[m]^* \end{pmatrix} = \begin{pmatrix} R[k] \\ R[m]^* \end{pmatrix},

and the determinant is gcos⁡ϕ H[k]H[m]∗g \cos\phi\, H[k] H[m]^*. So if H[k]≠0H[k] \ne 0 and H[m]≠0H[m] \ne 0, lines L3 and L4 return X[k]X[k] exactly without noise.

Proof. The first row is Lemma 2 at kk. Lemma 2 at mm gives R[m]=A[m]X[m]+B[m]X[k]∗R[m] = A[m] X[m] + B[m] X[k]^*, because −m=k-m = k; conjugating gives the second row. The determinant is A[k]A[m]∗−B[k]B[m]∗=∣μ∣2H[k]H[m]∗−∣ν∣2H[m]∗H[k]A[k] A[m]^* - B[k] B[m]^* = |\mu|^2 H[k] H[m]^* - |\nu|^2 H[m]^* H[k], using B[m]=νH[k]∗B[m] = \nu H[k]^*. Finally ∣μ∣2−∣ν∣2=(1+2gcos⁡ϕ+g2)−(1−2gcos⁡ϕ+g2)4=gcos⁡ϕ>0|\mu|^2 - |\nu|^2 = \frac{(1 + 2g\cos\phi + g^2) - (1 - 2g\cos\phi + g^2)}{4} = g\cos\phi > 0. □\square

Corollary (the error of a one-tap equalizer). A receiver that ignores the imbalance and divides by A[k]A[k] gets X[k]+B[k]A[k]X[−k]∗X[k] + \frac{B[k]}{A[k]} X[-k]^*. For unit-modulus data the image has the power ∣ν∣2∣H[−k]∣2∣μ∣2∣H[k]∣2\frac{|\nu|^2 |H[-k]|^2}{|\mu|^2 |H[k]|^2}. On a flat channel this is the inverse of the image rejection ratio ∣μ∣2/∣ν∣2|\mu|^2 / |\nu|^2, which is 23.7923.79 dB for g=1.1g = 1.1 and ϕ=5\phi = 5 degrees. On a subcarrier whose mirror is stronger, the image is stronger by the ratio of the channel powers.

The time-domain fix (a theorem). Let c=ν/μ∗c = \nu / \mu^*. Then z=r−c r∗=(μ−∣ν∣2/μ∗)yz = r - c\, r^* = \left( \mu - |\nu|^2 / \mu^* \right) y, with no term in y∗y^*.

Proof. r∗=μ∗y∗+ν∗yr^* = \mu^* y^* + \nu^* y, so c r∗=νy∗+∣ν∣2μ∗yc\, r^* = \nu y^* + \frac{|\nu|^2}{\mu^*} y, and subtracting from r=μy+νy∗r = \mu y + \nu y^* removes νy∗\nu y^*. □\square

From the estimates, B[k]/A[−k]∗=νH[−k]∗/(μ∗H[−k]∗)=ν/μ∗B[k] / A[-k]^* = \nu H[-k]^* / (\mu^* H[-k]^*) = \nu / \mu^* for every kk, so the implementation estimates cc as the mean of these ratios.

Complexity

Each used subcarrier needs one 2x2 solve in line L2 and one in line L4, O(1)O(1) each, so the time is O(N)O(N) per symbol after the DFT, and the extra space is O(N)O(N) for AA, BB and the output in the real RAM.

Properties

  • Joint with the channel. A[k]A[k] already contains H[k]H[k], so the method replaces the channel estimate; it needs two training symbols where an ideal receiver needs one.
  • Image rejection. Without compensation, the image on a flat channel is ∣ν∣2/∣μ∣2|\nu|^2 / |\mu|^2 of the signal power, 23.7923.79 dB below it for g=1.1g = 1.1 and 5 degrees. This limits the SNR of dense constellations such as 64-QAM and 256-QAM.
  • Worse on weak subcarriers. The image on kk scales with ∣H[−k]∣2/∣H[k]∣2|H[-k]|^2 / |H[k]|^2, so a subcarrier in a fade whose mirror is strong is hurt most, as in the example.
  • Frequency-flat imbalance. The model assumes that gg and ϕ\phi do not depend on frequency. Mismatched filters in the two branches make them frequency dependent; the pair solve still works, because A[k]A[k] and B[k]B[k] are estimated per subcarrier.
  • DC and the middle. Subcarriers 0 and N/2N/2 are their own mirrors, so their equations cannot separate XX from X∗X^*; OFDM systems usually leave the DC subcarrier empty anyway.

Variants and improvements

  • Time-domain fix. With c=ν/μ∗c = \nu / \mu^*, the correction z=r−c r∗z = r - c\, r^* before the DFT gives (μ−∣ν∣2/μ∗) y(\mu - |\nu|^2 / \mu^*)\, y, with no image. The coefficient is the mean of B[k]/A[−k]∗B[k] / A[-k]^*, and the ordinary channel estimate then absorbs the scale. This is cheaper per symbol than the pair solve.
  • Blind estimation. For a proper complex signal, E[y2]=0E[y^2] = 0, while the imbalance makes E[r2]=2μνE∣y∣2≠0E[r^2] = 2\mu\nu E|y|^2 \ne 0. Statistics of r2r^2 over many samples give ν/μ∗\nu / \mu^* without training, at the cost of a long average.
  • Transmitter imbalance. A transmitter with IQ imbalance sends μtx+νtx∗\mu_t x + \nu_t x^*, which gives the same mirror model; the pair solve handles both together if both are present.
  • With a frequency offset. A carrier offset makes the image of kk fall at −k-k shifted by twice the offset, so the pair model breaks; joint estimators of the offset and the imbalance exist for this case.
  • Adaptive. Least mean squares updates of cc track slow drift of the analog branches.

When to use it

Use IQ imbalance compensation in OFDM receivers with direct-conversion front ends, which is most low-cost Wi-Fi and cellular hardware, especially for dense constellations where an image 2424 dB down already costs throughput. Use the pair solve when training for both AA and BB is available and the imbalance may depend on frequency, and the time-domain fix when the imbalance is flat and the per-symbol cost must be minimal.

Pitfalls

  • Training that cannot separate the image. Line L1 needs two training symbols that are not proportional on every pair. If T2=T1T_2 = T_1 everywhere, the matrix of line L1 is singular for every kk. Changing the sign on half the band, as here, fixes it.
  • The wrong mirror. Lines L1 and L3 must use −k-k, that is N−kN - k modulo NN, not N−1−kN - 1 - k. With the off-by-one mirror, the equations pair the wrong subcarriers and the image stays.
  • Forgetting the conjugates. The second row in line L3 is the equation at −k-k conjugated, [B[−k]∗,A[−k]∗][B[-k]^*, A[-k]^*] against R[−k]∗R[-k]^*. Without the conjugates, the unknowns do not match the first row.
  • Using the DC or middle subcarrier. Lines L1 and L3 must skip k=0k = 0 and k=N/2k = N/2; there the mirror is the subcarrier itself, and the 2x2 system is singular in general.
  • Estimating the channel separately first. Dividing by a channel estimate before line L2 mixes the image into the channel estimate; estimate AA and BB together from the raw values.

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)
iq_imbalance_compensation.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iq-imbalance-compensation/. The authors are listed in prov/GSXKAS.jsonl.

"""Compensation of receiver IQ imbalance in OFDM, per mirror pair of subcarriers.

The receiver mixes the signal down on two branches. If the I branch is ideal
and the Q branch has gain g and phase error phi, the complex baseband signal
y becomes

    r = Re(y) + j g (Im(y) cos(phi) - Re(y) sin(phi)) = mu y + nu conj(y)
    mu = (1 + g e^(-j phi)) / 2,   nu = (1 - g e^(j phi)) / 2

The DFT of conj(y) at k is conj(Y[-k]), so after the DFT (unitary pair) and
a channel H, subcarrier k sees its mirror -k:

    R[k] = A[k] X[k] + B[k] conj(X[-k]),   A[k] = mu H[k],   B[k] = nu conj(H[-k])

Two training symbols T1 and T2 give two equations per k, which a 2x2 solve
turns into A[k] and B[k]. Data on the pair (k, -k) then follows from

    [ A[k]        B[k]       ] [ X[k]        ]   [ R[k]        ]
    [ conj(B[-k]) conj(A[-k])] [ conj(X[-k]) ] = [ conj(R[-k]) ]

Subcarrier 0 (DC) and N/2 are their own mirrors and carry no data here.
Indices are taken modulo N, so -k is N - k.
"""

import cmath

import cbb


def mu_nu(g: float, phi: float) -> tuple[complex, complex]:
    """mu and nu for Q-branch gain g and phase error phi (radians)."""
    return (1 + g * cmath.exp(-1j * phi)) / 2, (1 - g * cmath.exp(1j * phi)) / 2


def impair(y: list[complex], g: float, phi: float) -> list[complex]:
    """Apply the imbalance to time samples: r = mu y + nu conj(y)."""
    mu, nu = mu_nu(g, phi)
    return [mu * v + nu * v.conjugate() for v in y]


def estimate(r1: list[complex], r2: list[complex], t1: list[complex], t2: list[complex]) -> tuple[list[complex], list[complex]]:
    """A[k] and B[k] for k != 0, N/2 from two received training symbols (after the DFT)."""
    n = len(r1)
    a = [0j] * n
    b = [0j] * n
    for k in range(1, n):
        if 2 * k == n:
            continue
        m = (n - k) % n
        mat = [[t1[k], t1[m].conjugate()], [t2[k], t2[m].conjugate()]]  # @line L1
        a[k], b[k] = cbb.solve(mat, [r1[k], r2[k]])  # @line L2
    return a, b


def compensate(r: list[complex], a: list[complex], b: list[complex]) -> list[complex]:
    """The data estimates X[k] for k != 0, N/2 (zero there), solving each mirror pair."""
    n = len(r)
    x = [0j] * n
    for k in range(1, n):
        if 2 * k == n:
            continue
        m = n - k
        mat = [[a[k], b[k]], [b[m].conjugate(), a[m].conjugate()]]  # @line L3
        x[k], _ = cbb.solve(mat, [r[k], r[m].conjugate()])  # @line L4
    return x  # @line L5


def image_coefficient(a: list[complex], b: list[complex]) -> complex:
    """c = nu / conj(mu), from the mean of B[k] / conj(A[-k]) over the used k.

    In the time domain z = r - c conj(r) equals (mu - |nu|^2 / conj(mu)) y, with no image.
    """
    n = len(a)
    ks = [k for k in range(1, n) if 2 * k != n]
    return sum(b[k] / a[n - k].conjugate() for k in ks) / len(ks)
test_iq_imbalance_compensation.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iq-imbalance-compensation/. The authors are listed in prov/GSXKAS.jsonl.

import math
import random

import cbb
from iq_imbalance_compensation import compensate, estimate, image_coefficient, impair, mu_nu

S = 1 / math.sqrt(2)
N = 64
TAPS = [0.9, 0.3j, -0.2]
G, PHI = 1.1, math.radians(5.0)
USED = [k for k in range(1, N) if 2 * k != N]


def qpsk(rng: random.Random, n: int) -> list[complex]:
    return [complex(rng.choice((S, -S)), rng.choice((S, -S))) for _ in range(n)]


def received(rng: random.Random, x: list[complex], n0: float, g: float = G, phi: float = PHI) -> list[complex]:
    """Subcarrier values after the channel (prefix long enough), AWGN, IQ imbalance and the unitary DFT."""
    y = cbb.cconv(cbb.uidft(x), TAPS, N)
    if n0 > 0:
        y = cbb.awgn(rng, y, n0)
    return cbb.udft(impair(y, g, phi))


def training(rng: random.Random) -> tuple[list[complex], list[complex]]:
    """T2 equals T1 on k < N/2 and -T1 on k >= N/2, so each 2x2 training matrix is invertible."""
    t1 = qpsk(rng, N)
    return t1, [t1[k] if k < N // 2 else -t1[k] for k in range(N)]


def test_impairment_matches_the_two_branch_model() -> None:
    rng = random.Random(1)
    for _ in range(20):
        y = cbb.cn(rng, 1.0)
        r = impair([y], G, PHI)[0]
        want = complex(y.real, G * (y.imag * math.cos(PHI) - y.real * math.sin(PHI)))
        assert abs(r - want) < 1e-12


def test_subcarrier_k_sees_its_mirror() -> None:
    rng = random.Random(2)
    mu, nu = mu_nu(G, PHI)
    h = cbb.dft(TAPS + [0j] * (N - len(TAPS)))
    x = qpsk(rng, N)
    r = received(rng, x, 0.0)
    for k in range(N):
        m = (N - k) % N
        assert abs(r[k] - (mu * h[k] * x[k] + nu * h[m].conjugate() * x[m].conjugate())) < 1e-9


def test_exact_without_noise() -> None:
    rng = random.Random(3)
    mu, nu = mu_nu(G, PHI)
    h = cbb.dft(TAPS + [0j] * (N - len(TAPS)))
    t1, t2 = training(rng)
    a, b = estimate(received(rng, t1, 0.0), received(rng, t2, 0.0), t1, t2)
    for k in USED:
        assert abs(a[k] - mu * h[k]) < 1e-9
        assert abs(b[k] - nu * h[N - k].conjugate()) < 1e-9
    assert abs(image_coefficient(a, b) - nu / mu.conjugate()) < 1e-9
    for _ in range(3):
        x = qpsk(rng, N)
        xh = compensate(received(rng, x, 0.0), a, b)
        assert max(abs(xh[k] - x[k]) for k in USED) < 1e-9


def test_without_imbalance_the_image_term_is_zero() -> None:
    rng = random.Random(4)
    t1, t2 = training(rng)
    a, b = estimate(received(rng, t1, 0.0, 1.0, 0.0), received(rng, t2, 0.0, 1.0, 0.0), t1, t2)
    assert max(abs(b[k]) for k in USED) < 1e-12


def test_time_domain_fix_removes_the_image() -> None:
    rng = random.Random(5)
    mu, nu = mu_nu(G, PHI)
    c = nu / mu.conjugate()
    y = [cbb.cn(rng, 1.0) for _ in range(32)]
    z = [v - c * v.conjugate() for v in impair(y, G, PHI)]
    scale = mu - abs(nu) ** 2 / mu.conjugate()
    assert max(abs(a - scale * b) for a, b in zip(z, y)) < 1e-12


def test_error_power_with_and_without_compensation() -> None:
    # Closed form without noise: a one-tap equalizer R[k] / A[k] leaves the image B[k] conj(X[-k]) / A[k],
    # of power |B[k]|^2 / |A[k]|^2 with |X| = 1. Image rejection |mu|^2 / |nu|^2 = 23.79 dB for g = 1.1, 5 degrees.
    # With N0 = 0.001 (30 dB), 25 symbols, seed 6, compensation brings the error down to the noise level.
    rng = random.Random(6)
    mu, nu = mu_nu(G, PHI)
    assert abs(cbb.db(abs(mu) ** 2 / abs(nu) ** 2) - 23.7946) < 1e-4
    t1, t2 = training(rng)
    a, b = estimate(received(rng, t1, 0.0), received(rng, t2, 0.0), t1, t2)
    x = qpsk(rng, N)
    r = received(rng, x, 0.0)
    plain = sum(abs(r[k] / a[k] - x[k]) ** 2 for k in USED)
    assert abs(plain - sum(abs(b[k] / a[k]) ** 2 for k in USED)) < 1e-9
    n0 = 0.001
    e_plain = e_comp = 0.0
    for _ in range(25):
        t1, t2 = training(rng)
        a, b = estimate(received(rng, t1, n0), received(rng, t2, n0), t1, t2)
        x = qpsk(rng, N)
        r = received(rng, x, n0)
        xh = compensate(r, a, b)
        e_plain += sum(abs(r[k] / a[k] - x[k]) ** 2 for k in USED)
        e_comp += sum(abs(xh[k] - x[k]) ** 2 for k in USED)
    assert e_comp < e_plain / 2

History

IQ imbalance is a classic problem of direct-conversion receivers, which became common in the 1990s because they need no intermediate frequency stage. OFDM made it more visible, because the image falls on another data subcarrier instead of outside the band. Alireza Tarighat, Rahim Bagheri and Ali H. Sayed published compensation schemes for OFDM receivers in 2005, with the model of mirror subcarriers, methods before and after the DFT, and an analysis of their performance. Many later papers treat joint estimation with a frequency offset and frequency-dependent imbalance.

References

  1. A. Tarighat, R. Bagheri and A. H. Sayed, Compensation schemes and performance analysis of IQ imbalances in OFDM receivers, IEEE Transactions on Signal Processing 53(8), 2005, pages 3257 to 3268 (the model in which each subcarrier interferes with its mirror, and compensation schemes in the time and the frequency domain)

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
  • at least three sources
  • a scene preset for the example