Algorithm Search⌘K

Algorithmcore

Constant modulus algorithm

Also called Godard algorithm.

A blind equalizer that adapts its taps by stochastic gradient on E(|z|^2 - R2)^2, so that the output modulus is as constant as possible. It ignores the carrier phase and can lock to a local minimum.

Time
O(K N) worst
Space
O(N) extra
Where
K = the number of samples; N = the number of equalizer taps
Properties
blinddeterministicnot global convergenceonlinephase independent
Origin
Dominique N. Godard, John R. Treichler, Brian G. Agee, 1980

The constant modulus algorithm (CMA) is the most used blind equalizer. It adapts the NN taps of a linear equalizer without a training sequence. It does this by a stochastic gradient step on the cost J=E(∣z∣2−R2)2J = E(|z|^2 - R_2)^2, where zz is the equalizer output and R2=E∣a∣4/E∣a∣2R_2 = E|a|^4 / E|a|^2 is a constant of the symbol alphabet. The cost does not change if zz is rotated, so CMA works before the carrier phase is known, and it leaves the phase to a later carrier recovery stage. It costs O(N)O(N) per sample. Among the methods for blind equalization, it differs from the Sato algorithm, which pushes the output toward a scaled sign and so depends on the phase, and from Tong-Xu-Kailath identification and subspace identification, which estimate the channel in one batch from second-order statistics of an oversampled signal. CMA uses fourth-order statistics, so it can equalize a nonminimum-phase channel at one sample per symbol. Its weak points are that a finite equalizer can lock to a local minimum and that the output has an unknown phase.

In plain words

A blind equalizer must fix a distorted signal without being told what was sent. CMA uses one fact about the symbols: for PSK all of them have the same size, and for QAM their sizes vary in a known way. Echoes from the channel make the received samples grow and shrink in size. So the equalizer changes its weights a little after each sample, in the direction that makes the size of its output steadier. When the size is as steady as it can be, the echoes are gone. The method never looks at the angle of the output. So it works before the receiver has found the carrier phase, but at the end the output can still be turned by an unknown angle, and a later stage must remove it.

The problem

The input is the received sequence y[k]=∑lhl a[k−l]+w[k]y[k] = \sum_l h_l\, a[k-l] + w[k] at one sample per symbol (or several, for a fractionally spaced equalizer), the number of taps NN and a step size μ>0\mu > 0. The channel hh is unknown. The symbols a[k]a[k] are independent and identically distributed, with mean zero, Ea2=0E a^2 = 0 (a circular alphabet such as QPSK or square QAM) and a known distribution. The equalizer output is z[k]=∑i=0N−1ci y[k−i]z[k] = \sum_{i=0}^{N-1} c_i\, y[k-i]. The goal is taps cc with z[k]≈ejθa[k−d]z[k] \approx e^{j\theta} a[k - d] for some delay dd and phase θ\theta. Blind methods can find dd and θ\theta only up to these ambiguities.

The cost is the Godard criterion with p=2p = 2:

J(c)=E(∣z[k]∣2−R2)2,R2=E∣a∣4E∣a∣2.J(c) = E\left(|z[k]|^2 - R_2\right)^2, \qquad R_2 = \frac{E|a|^4}{E|a|^2}.

For unit-energy QPSK and every PSK, R2=1R_2 = 1. For unit-energy 16-QAM, the raw points ±1,±3\pm 1, \pm 3 on each axis give E∣a∣2=10E|a|^2 = 10 and E∣a∣4=132E|a|^4 = 132, so R2=132/100=1.32R_2 = 132/100 = 1.32.

The algorithm

  1. CMA(y, N, μ, R2)
  2. 1c ← (0, ..., 0); c[⌊N/2⌋] ← 1 ▷ the center spike
  3. 2for k ← N - 1 to K - 1 do
  4. 3u ← (y[k], y[k-1], ..., y[k-N+1])
  5. 4z[k] ← Σ_i c[i] u[i] ▷ the equalizer output
  6. 5e ← z[k] (|z[k]|² - R2) ▷ the CMA error
  7. 6c[i] ← c[i] - μ e conj(u[i]) for all i ▷ the stochastic gradient step
  8. 7return c, z

Line L1 starts the taps at a single 1 in the middle. This lets the equalizer reach a delay near N/2N/2, which it needs for a nonminimum-phase channel, whose inverse looks into the future. Line L4 is the filter. Line L5 is the error term. It is zero when ∣z∣=R2|z| = \sqrt{R_2}, and it has the direction of zz. Line L6 is the update. The derivative of (∣z∣2−R2)2(|z|^2 - R_2)^2 with respect to cˉi\bar c_i is 2(∣z∣2−R2) z uˉi2(|z|^2 - R_2)\, z\, \bar u_i, so line L6 is one step of stochastic gradient descent on JJ, with the factor 2 in μ\mu. The update has the form of the LMS algorithm, with $z - $ (desired value) replaced by the CMA error. No line uses a decision or a known symbol. After the taps converge, a decision device and a phase tracker take over, often with a switch to the decision-directed LMS update of adaptive equalization.

Example

The check value. For unit-energy 16-QAM, R2=1.32R_2 = 1.32, as computed above. The tests check it with exact fractions.

QPSK through a nonminimum-phase channel. Take h=(0.5,1)h = (0.5, 1). Its zero is at −2-2, outside the unit circle, so it is nonminimum phase. Use N=11N = 11 taps, μ=0.01\mu = 0.01, R2=1R_2 = 1 and N0=0.001N_0 = 0.001 (seed 5). The combined response g=c∗hg = c * h should become one large tap. Its residual ISI, (∑∣gk∣2−max⁡∣gk∣2)/max⁡∣gk∣2(\sum |g_k|^2 - \max |g_k|^2) / \max |g_k|^2, falls as follows:

samples 500 1000 2000 6000
residual ISI 0.00672 0.00065 0.00033 0.00042
largest tap ∣g6∣\lvert g_6 \rvert 0.966 0.999 0.994 0.992

The delay is d=6d = 6: the center spike at tap 5 plus the main tap of hh at index 1. The taps approximate the anticausal inverse z−5/(1+0.5z)z^{-5} / (1 + 0.5 z). The last 2000 decisions have no errors. The residual ISI stops falling near 4×10−44 \times 10^{-4}, because the noise and the step size keep the taps moving.

The phase is not found. If the channel is ejπ/6(0.5,1)e^{j\pi/6} (0.5, 1) instead, CMA gives the same taps exactly, and the output is turned by 30 degrees. The tests check this: a rotated input gives the same taps within 10−910^{-9}.

A local minimum. Take h=(1,0.5)h = (1, 0.5), QPSK, no noise and only N=2N = 2 taps. The mean update, which is gradient descent on JJ, ends in one of two points. From c=(1,0)c = (1, 0) it reaches c=(0.934,−0.376)c = (0.934, -0.376) with J=0.0838J = 0.0838 and delay 0. From c=(0,1)c = (0, 1) it reaches c=(0.069,0.751)c = (0.069, 0.751) with J=0.2375J = 0.2375, delay 1 and the residual ISI 0.236. Small random moves of the taps return to the same point, so this is a local minimum, not a saddle. Started there, CMA stays in the worse equalizer.

Correctness

Claim 1 (the cost of a combined response). Let the symbols be independent, circular (Ea2=0E a^2 = 0), with E∣a∣2=1E|a|^2 = 1 and κ=E∣a∣4\kappa = E|a|^4, and let the noise be zero. Then z=∑kgk a[n−k]z = \sum_k g_k\, a[n-k] and

J=2s2+(κ−2)∑k∣gk∣4−2κs+κ2,s=∑k∣gk∣2.J = 2 s^2 + (\kappa - 2) \sum_k |g_k|^4 - 2\kappa s + \kappa^2, \qquad s = \sum_k |g_k|^2 .

This is a closed form, and the tests check it against an exact sum over all symbol patterns.

Claim 2 (the global minima). If κ<2\kappa < 2, which holds for every PSK and QAM alphabet (κ=1\kappa = 1 for PSK, 1.321.32 for 16-QAM), then the minimum of JJ over all combined responses is κ(κ−1)\kappa(\kappa - 1), and the minimizers are exactly g=ejθedg = e^{j\theta} e_d: one tap of modulus 1, at any delay dd and any phase θ\theta. This is a theorem. So if the equalizer can produce g=edg = e_d, the global minima of CMA are perfect equalizers, up to delay and phase.

Key step. For fixed ss, ∑∣gk∣4≤s2\sum |g_k|^4 \le s^2, with equality only if gg has one nonzero tap. Since κ−2<0\kappa - 2 < 0, J≥κs2−2κs+κ2=κ(s−1)2+κ(κ−1)J \ge \kappa s^2 - 2\kappa s + \kappa^2 = \kappa(s - 1)^2 + \kappa(\kappa - 1), with equality only for one tap and s=1s = 1. The proofs folder has the moment computation, the gradient of lines L5 and L6, and the proof that a rotated input gives the same taps.

What is not claimed. The update of line L6 is a stochastic gradient step, so for small μ\mu the taps follow the gradient flow of JJ. But a finite equalizer at one sample per symbol cannot produce g=edg = e_d exactly, and then JJ can have local minima that are poor equalizers (Ding, Kennedy, Anderson and Johnson 1991). The example shows one. Foschini (1985) proved convergence for an ideal equalizer of unbounded length. For a fractionally spaced equalizer, the review of Johnson et al. (1998) gives conditions (no noise, subchannels with no common zero, enough taps) under which the CM minima are perfect equalizers. In all other cases, convergence to the global minimum is not guaranteed.

Proof: CMA is a stochastic gradient method on the Godard cost, whose global minima for a sub-Gaussian circular alphabet are the perfect equalizers up to delay and phasefull

The symbols a[n]a[n] are independent and identically distributed, with Ea=0E a = 0, Ea2=0E a^2 = 0 (circular), E∣a∣2=1E|a|^2 = 1 and κ=E∣a∣4\kappa = E|a|^4. There is no noise. The channel hh and the taps cc have finite length, and the combined response is g=c∗hg = c * h, so the output is z[n]=∑ici y[n−i]=∑kgk a[n−k]z[n] = \sum_i c_i\, y[n-i] = \sum_k g_k\, a[n-k]. The dispersion constant is R2=E∣a∣4/E∣a∣2=κR_2 = E|a|^4 / E|a|^2 = \kappa. The cost is J=E(∣z∣2−R2)2J = E(|z|^2 - R_2)^2, and J(g)J(g) means the cost as a function of the combined response.

Lemma 1 (fourth moment). E∣z∣2=sE|z|^2 = s and E∣z∣4=2s2+(κ−2)∑k∣gk∣4E|z|^4 = 2 s^2 + (\kappa - 2) \sum_k |g_k|^4, where s=∑k∣gk∣2s = \sum_k |g_k|^2.

Proof. E∣z∣2=∑k,lgkgˉl E[akaˉl]=∑k∣gk∣2E|z|^2 = \sum_{k, l} g_k \bar g_l\, E[a_k \bar a_l] = \sum_k |g_k|^2, with ak=a[n−k]a_k = a[n-k]. For the fourth moment,

E∣z∣4=∑i,j,k,lgigjgˉkgˉl E[aiajaˉkaˉl].E|z|^4 = \sum_{i, j, k, l} g_i g_j \bar g_k \bar g_l\, E[a_i a_j \bar a_k \bar a_l].

If one index value appears exactly once among i,j,k,li, j, k, l, the expectation is a product with a factor Ea=0E a = 0 or Eaˉ=0E \bar a = 0, by independence. So each index value appears at least twice. Either all four are equal, which gives κ∣gi∣4\kappa |g_i|^4, or there are two distinct values, each twice. The pairing i=j≠k=li = j \ne k = l gives Eai2 Eaˉk2=0E a_i^2\, E \bar a_k^2 = 0, because the alphabet is circular. The pairings i=k≠j=li = k \ne j = l and i=l≠j=ki = l \ne j = k each give ∣gi∣2∣gj∣2|g_i|^2 |g_j|^2. So

E∣z∣4=κ∑i∣gi∣4+2∑i≠j∣gi∣2∣gj∣2=κ∑i∣gi∣4+2(s2−∑i∣gi∣4).□E|z|^4 = \kappa \sum_i |g_i|^4 + 2 \sum_{i \ne j} |g_i|^2 |g_j|^2 = \kappa \sum_i |g_i|^4 + 2\left(s^2 - \sum_i |g_i|^4\right). \qquad \square

Theorem 1 (the cost). J(g)=2s2+(κ−2)∑k∣gk∣4−2κs+κ2J(g) = 2 s^2 + (\kappa - 2) \sum_k |g_k|^4 - 2\kappa s + \kappa^2.

Proof. J=E∣z∣4−2R2E∣z∣2+R22J = E|z|^4 - 2 R_2 E|z|^2 + R_2^2 with R2=κR_2 = \kappa, and Lemma 1. □\square

For unit-energy 16-QAM, the raw points have E∣a∣2=10E|a|^2 = 10 and E∣a∣4=132E|a|^4 = 132, so κ=132/100=1.32\kappa = 132/100 = 1.32. For every PSK alphabet, ∣a∣=1|a| = 1 and κ=1\kappa = 1.

Theorem 2 (global minima). If 0<κ<20 < \kappa < 2, then J(g)≥κ(κ−1)J(g) \ge \kappa(\kappa - 1) for every gg, with equality if and only if g=ejθedg = e^{j\theta} e_d for some delay dd and phase θ\theta.

Proof. ∑k∣gk∣4≤(∑k∣gk∣2)2=s2\sum_k |g_k|^4 \le (\sum_k |g_k|^2)^2 = s^2, because the cross terms ∣gi∣2∣gj∣2|g_i|^2 |g_j|^2 are not negative. Equality holds if and only if at most one gkg_k is nonzero. Since κ−2<0\kappa - 2 < 0,

J(g)≥2s2+(κ−2)s2−2κs+κ2=κ(s−1)2+κ(κ−1)≥κ(κ−1).J(g) \ge 2 s^2 + (\kappa - 2) s^2 - 2\kappa s + \kappa^2 = \kappa (s - 1)^2 + \kappa(\kappa - 1) \ge \kappa(\kappa - 1).

Equality in the first step needs at most one nonzero tap, and in the second step s=1s = 1. So equality holds exactly when gg has one tap of modulus 1. Conversely, g=ejθedg = e^{j\theta} e_d has s=1s = 1 and ∑∣gk∣4=1\sum |g_k|^4 = 1, so J=2+κ−2−2κ+κ2=κ(κ−1)J = 2 + \kappa - 2 - 2\kappa + \kappa^2 = \kappa(\kappa - 1). □\square

If κ>2\kappa > 2 (a super-Gaussian alphabet), the inequality goes the other way, and spreading gg over many taps lowers JJ, so CMA does not equalize. If κ=2\kappa = 2, which is the value for a circular Gaussian, JJ depends only on ss, and no blind method based on this cost can find the channel.

Lemma 2 (the update is a stochastic gradient). For a fixed regressor uu and z=∑iciuiz = \sum_i c_i u_i, the Wirtinger derivative of (∣z∣2−R2)2(|z|^2 - R_2)^2 with respect to cˉi\bar c_i is 2(∣z∣2−R2) z uˉi2 (|z|^2 - R_2)\, z\, \bar u_i. So line L6 moves cc by −(μ/2)-(\mu/2) times this derivative, and its expected direction, over the symbols and the noise, is −(μ/2)-(\mu/2) times the gradient of JJ with respect to cˉ\bar c.

Proof. ∣z∣2=zzˉ|z|^2 = z \bar z, with ∂z/∂cˉi=0\partial z / \partial \bar c_i = 0 and ∂zˉ/∂cˉi=uˉi\partial \bar z / \partial \bar c_i = \bar u_i. So ∂∣z∣2/∂cˉi=zuˉi\partial |z|^2 / \partial \bar c_i = z \bar u_i and the chain rule gives the result. The expectation and the derivative commute because the cost is a polynomial in cc with finite moments. □\square

For a small μ\mu, stochastic approximation theory says that the taps follow the gradient flow of JJ near a stable stationary point. This page does not prove that step. It also does not claim that the flow reaches the global minimum. For a finite equalizer, the set of reachable combined responses {c∗h}\{c * h\} is a subspace that need not contain any ede_d, and JJ restricted to it can have local minima with a large residual ISI. The test test_a_finite_equalizer_has_a_worse_local_minimum finds one for h=(1,0.5)h = (1, 0.5) and two taps.

Theorem 3 (rotation). Run lines L1 to L7 on yy and on y′=ejφyy' = e^{j\varphi} y with the same NN, μ\mu and R2R_2. Then the taps are equal at every step, and z′[k]=ejφz[k]z'[k] = e^{j\varphi} z[k].

Proof. By induction on kk. Both runs start from the same spike (line L1). If c′=cc' = c before step kk, then u′=ejφuu' = e^{j\varphi} u, so z′=ejφzz' = e^{j\varphi} z (line L4), ∣z′∣=∣z∣|z'| = |z|, and e′=ejφee' = e^{j\varphi} e (line L5). The update of line L6 adds −μe′uˉi′=−μejφe e−jφuˉi=−μeuˉi-\mu e' \bar u'_i = -\mu e^{j\varphi} e\, e^{-j\varphi} \bar u_i = -\mu e \bar u_i, the same as in the first run. □\square

So CMA cannot remove a carrier phase rotation, and by Theorem 2 it does not need to: every phase gives the same minimum cost.

Remark on noise. With noise w∼CN(0,N0)w \sim \mathcal{CN}(0, N_0), the output has an extra Gaussian term, and the minimizers of JJ move away from ejθede^{j\theta} e_d. They no longer give zero ISI, as the MMSE equalizer does not. Theorem 2 is a statement about the noiseless cost.

Complexity

Lines L3 to L6 cost O(N)O(N) operations per sample: NN complex multiplications for the output and NN for the update. KK samples cost O(KN)O(K N) time in the real RAM and O(N)O(N) extra space. The number of samples needed to converge depends on μ\mu, the channel and the alphabet. In the example it is about 1000 for QPSK and about 4000 for 16-QAM with a smaller step; these are measurements.

Properties

  • Phase independent. JJ and the update see only ∣z∣|z|, so a rotation of the input gives the same taps and a rotated output. CMA can run before carrier recovery.
  • No training. The only prior knowledge is R2R_2, which depends on the alphabet and not on the data.
  • Works on nonminimum-phase channels. JJ depends on fourth-order moments of gg, through ∑∣gk∣4\sum |g_k|^4, which second-order statistics do not see.
  • Not a decision-directed method. CMA can open a closed eye, where decision-directed LMS fails. After the eye opens, decision-directed LMS gives a smaller error.
  • Excess error. For QAM, ∣a∣2|a|^2 is not constant, so the update never settles even at a perfect equalizer: J=κ(κ−1)>0J = \kappa(\kappa - 1) > 0 at the minimum. The taps move in a random way around the minimum, more so for a larger μ\mu.
  • Near the MMSE solution. With noise, the CM minima are not the MMSE taps, but they are close to them when the noise is small (Johnson et al. 1998).

Variants and improvements

  • Godard p = 1. The cost E(∣z∣−R1)2E(|z| - R_1)^2 with R1=E∣a∣2/E∣a∣R_1 = E|a|^2 / E|a| gives the error z(∣z∣−R1)/∣z∣z(|z| - R_1)/|z|. Godard's family has one algorithm for each pp.
  • The multimodulus algorithm. Separate costs on the real and imaginary parts, E(zR2−R)2+E(zI2−R)2E(z_R^2 - R)^2 + E(z_I^2 - R)^2, recover the phase up to a multiple of 90 degrees for square QAM.
  • Fractionally spaced CMA. With two samples per symbol, the equalizer can reach g=edg = e_d exactly when the subchannels have no common zero, and the local minima caused by a short equalizer go away in the noiseless case; see the fractionally spaced equalizer.
  • Switch to decision-directed mode. Run CMA until the eye opens, then switch to decision-directed LMS, as in adaptive equalization.
  • The Shalvi-Weinstein criterion. Maximize the kurtosis of zz under a power constraint. This is a fourth-order criterion like CMA.
  • CMA with a DFE. A decision feedback equalizer can run its feedforward part with CMA, but blind feedback is prone to error propagation.

When to use it

Use CMA when there is no training sequence, or when the training is too short or lost, and the carrier phase is not yet known. Typical uses are broadcast and cable receivers, receivers that join a running stream, and the start-up of a point-to-multipoint link. If a training sequence is available, use it instead: LMS or RLS converge faster and to the MMSE taps. If many samples are available in a block and the signal is oversampled, a batch method from second-order statistics, such as the subspace method, estimates the channel without the risk of a local minimum.

Pitfalls

  • A spike at the wrong place in line L1. A spike on the first tap allows only small delays, and the inverse of a nonminimum-phase channel needs a large one. Put the spike near the middle. The example with two taps shows how the start picks the minimum.
  • A step size that is too large in line L6. The update is cubic in zz, so a large μ\mu or a large input makes the taps diverge. Normalize the input power, and pick μ\mu much smaller than 1/(NE∣y∣2)1/(N E|y|^2).
  • The wrong R2 in line L5. R2=E∣a∣4/E∣a∣2R_2 = E|a|^4/E|a|^2 must use the same scale as the received signal. If the gain of the channel is unknown, CMA still converges, but to taps scaled so that the output has the modulus R2\sqrt{R_2}.
  • Forgetting the phase. CMA returns ejθa[k−d]e^{j\theta} a[k - d]. A slicer fed directly with zz makes many errors for any θ\theta that is not a symmetry of the constellation. A phase tracker must follow.
  • Taking a local minimum for a good one. A low CMA cost is not proof of a good equalizer. Watch the decision error, and restart from another spike if it stays high.

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)
constant_modulus_algorithm.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/constant-modulus-algorithm/. The authors are listed in prov/BYWJFM.jsonl.

"""The constant modulus algorithm (CMA 2-2, the Godard algorithm with p = 2).

The equalizer is an FIR filter c of N taps with output
z[k] = sum_i c[i] y[k-i]. CMA adapts c by a stochastic gradient step on the
cost J(c) = E(|z[k]|^2 - R2)^2, with the dispersion constant
R2 = E|a|^4 / E|a|^2 of the symbol alphabet. It uses no training symbols.

For the analysis, g = c * h is the combined response of the channel h and the
equalizer. For independent circular symbols with E a^2 = 0, E|a|^2 = 1 and
E|a|^4 = kappa, and no noise, the cost is
J(g) = 2 s^2 + (kappa - 2) sum |g_k|^4 - 2 kappa s + kappa^2, s = sum |g_k|^2.
"""

import cmath

import cbb


def dispersion_constant(points: list[complex]) -> float:
    """R2 = E|a|^4 / E|a|^2 for equally likely points."""
    m2 = sum(abs(p) ** 2 for p in points)
    m4 = sum(abs(p) ** 4 for p in points)
    if m2 == 0:
        raise ValueError("all points are zero")
    return m4 / m2


def cma(y: list[complex], n: int, mu: float, r2: float, spike: int | None = None) -> tuple[list[complex], list[complex]]:
    """Run CMA over the samples y. Returns the final taps c and the outputs z[k] for k = N-1, ..., len(y)-1."""
    if n < 1 or mu <= 0 or r2 <= 0:
        raise ValueError("need N >= 1, mu > 0 and R2 > 0")
    if spike is None:
        spike = n // 2
    c = [0j] * n  # @line L1
    c[spike] = 1 + 0j  # @line L1
    out = []
    for k in range(n - 1, len(y)):  # @line L2
        u = [y[k - i] for i in range(n)]  # @line L3
        z = sum(ci * ui for ci, ui in zip(c, u))  # @line L4
        e = z * (abs(z) ** 2 - r2)  # @line L5
        c = [ci - mu * e * ui.conjugate() for ci, ui in zip(c, u)]  # @line L6
        out.append(z)
    return c, out  # @line L7


def cma_cost(g: list[complex], kappa: float) -> float:
    """The exact noiseless CMA cost E(|z|^2 - R2)^2 of a combined response g, with R2 = kappa."""
    s = sum(abs(v) ** 2 for v in g)
    s4 = sum(abs(v) ** 4 for v in g)
    return 2 * s * s + (kappa - 2) * s4 - 2 * kappa * s + kappa * kappa


def cma_cost_gradient(c: list[complex], h: list[complex], kappa: float) -> list[complex]:
    """The gradient dJ/d conj(c) of the noiseless cost at the taps c, for the channel h."""
    g = cbb.conv(c, h)
    s = sum(abs(v) ** 2 for v in g)
    dg = [4 * s * v + 2 * (kappa - 2) * abs(v) ** 2 * v - 2 * kappa * v for v in g]
    return [sum(dg[i + l] * complex(h[l]).conjugate() for l in range(len(h))) for i in range(len(c))]


def mean_cma(c: list[complex], h: list[complex], kappa: float, mu: float, steps: int) -> list[complex]:
    """Deterministic gradient descent on the noiseless cost: the mean behavior of CMA for a small step."""
    for _ in range(steps):
        grad = cma_cost_gradient(c, h, kappa)
        c = [ci - mu * gi for ci, gi in zip(c, grad)]
    return c


def residual_isi(g: list[complex]) -> float:
    """(sum |g|^2 - max |g|^2) / max |g|^2: 0 for a single tap."""
    p = [abs(v) ** 2 for v in g]
    m = max(p)
    return (sum(p) - m) / m


def phase_of_cursor(g: list[complex]) -> tuple[int, complex]:
    """The index of the largest tap of g and its unit-modulus phase: the delay and the rotation CMA leaves."""
    d = max(range(len(g)), key=lambda i: abs(g[i]))
    return d, cmath.exp(1j * cmath.phase(g[d]))
test_constant_modulus_algorithm.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/constant-modulus-algorithm/. The authors are listed in prov/BYWJFM.jsonl.

import cmath
import itertools
import math
import random
from fractions import Fraction

import pytest

import cbb
from constant_modulus_algorithm import (
    cma,
    cma_cost,
    cma_cost_gradient,
    dispersion_constant,
    mean_cma,
    phase_of_cursor,
    residual_isi,
)

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


def test_dispersion_constant_check_values() -> None:
    raw = [(a, b) for a in (-3, -1, 1, 3) for b in (-3, -1, 1, 3)]
    m2 = Fraction(sum(a * a + b * b for a, b in raw), 16)
    m4 = Fraction(sum((a * a + b * b) ** 2 for a, b in raw), 16)
    assert (m2, m4) == (10, 132)
    assert m4 / m2 / m2 == Fraction(132, 100)  # R2 of unit-energy 16-QAM is 1.32 exactly
    assert abs(dispersion_constant(QAM16) - 1.32) < 1e-12
    assert abs(dispersion_constant(QPSK) - 1.0) < 1e-12
    assert abs(dispersion_constant([cmath.exp(2j * math.pi * m / 8) for m in range(8)]) - 1.0) < 1e-12


@pytest.mark.parametrize("points", [QPSK, QAM16])
def test_cost_formula_equals_the_exact_expectation(points) -> None:
    kappa = dispersion_constant(points)
    rng = random.Random(1)
    for _ in range(3):
        g = [complex(rng.gauss(0, 0.6), rng.gauss(0, 0.6)) for _ in range(3)]
        total = 0.0
        for a in itertools.product(points, repeat=3):
            z = sum(gi * ai for gi, ai in zip(g, a))
            total += (abs(z) ** 2 - kappa) ** 2
        exact = total / len(points) ** 3
        assert abs(exact - cma_cost(g, kappa)) < 1e-9


def test_gradient_matches_finite_differences() -> None:
    rng = random.Random(2)
    h = [1, 0.5j, -0.2]
    c = [complex(rng.gauss(0, 0.5), rng.gauss(0, 0.5)) for _ in range(4)]
    grad = cma_cost_gradient(c, h, 1.32)
    eps = 1e-6
    for i in range(4):
        def cost(dc):
            cc = list(c)
            cc[i] += dc
            return cma_cost(cbb.conv(cc, h), 1.32)
        dx = (cost(eps) - cost(-eps)) / (2 * eps)
        dy = (cost(1j * eps) - cost(-1j * eps)) / (2 * eps)
        assert abs(grad[i] - 0.5 * complex(dx, dy)) < 1e-6  # d/d conj(c) = (d/dx + j d/dy) / 2


def test_global_minima_are_single_taps_of_any_phase() -> None:
    # for kappa < 2 the smallest cost is kappa (kappa - 1), at one tap of modulus 1 and any phase
    rng = random.Random(3)
    for kappa in (1.0, 1.32):
        best = kappa * (kappa - 1)
        for phi in (0.0, 0.7, 2.0, -3.0):
            assert abs(cma_cost([0, cmath.exp(1j * phi), 0], kappa) - best) < 1e-12
        for _ in range(500):
            g = [complex(rng.gauss(0, 0.7), rng.gauss(0, 0.7)) for _ in range(3)]
            assert cma_cost(g, kappa) >= best - 1e-12


def test_a_phase_rotation_passes_through_unchanged() -> None:
    # CMA sees only |z|: rotating the input gives the same taps and rotated outputs
    rng = random.Random(4)
    h = [1, 0.4 - 0.3j]
    x = [rng.choice(QPSK) for _ in range(800)]
    y = cbb.awgn(rng, cbb.conv(x, h)[:800], 0.01)
    rot = cmath.exp(0.9j)
    c1, z1 = cma(y, 7, 0.01, 1.0)
    c2, z2 = cma([rot * v for v in y], 7, 0.01, 1.0)
    assert max(abs(u - v) for u, v in zip(c1, c2)) < 1e-9
    assert max(abs(rot * u - v) for u, v in zip(z1, z2)) < 1e-9


def run(h, points, n, mu, k, n0, seed):
    rng = random.Random(seed)
    x = [rng.choice(points) for _ in range(k)]
    y = cbb.awgn(rng, cbb.conv(x, h)[:k], n0)
    c, z = cma(y, n, mu, dispersion_constant(points))
    g = cbb.conv(c, h)
    d, rot = phase_of_cursor(g)
    # z[t] is the output at time t + N - 1 and estimates rot x[t + N - 1 - d]
    errors = 0
    for t in range(len(z) - 2000, len(z)):
        a = z[t] / rot
        dec = min(points, key=lambda p: abs(a - p))
        errors += dec != x[t + n - 1 - d]
    return g, errors


def test_qpsk_through_a_nonminimum_phase_channel() -> None:
    # h = (0.5, 1) has its zero outside the unit circle; second-order statistics cannot see that
    g, errors = run([0.5, 1], QPSK, 11, 0.01, 6000, 0.001, 5)
    assert residual_isi(g) < 0.01
    assert errors == 0


def test_16qam_through_a_complex_channel() -> None:
    g, errors = run([1, 0.3 + 0.25j, -0.1j], QAM16, 11, 0.002, 12000, 0.0005, 6)
    assert residual_isi(g) < 0.01
    assert errors == 0


def test_a_finite_equalizer_has_a_worse_local_minimum() -> None:
    # h = (1, 0.5), 2 taps, QPSK: the mean CMA update from a spike on tap 0 and on tap 1 ends in two minima
    h = [1, 0.5]
    lo = mean_cma([1, 0], h, 1.0, 0.01, 6000)
    hi = mean_cma([0, 1], h, 1.0, 0.01, 6000)
    j_lo = cma_cost(cbb.conv(lo, h), 1.0)
    j_hi = cma_cost(cbb.conv(hi, h), 1.0)
    assert abs(j_lo - 0.083758) < 1e-6 and abs(j_hi - 0.237492) < 1e-6
    for c in (lo, hi):
        assert max(abs(v) for v in cma_cost_gradient(c, h, 1.0)) < 1e-9
    # small random moves return to the same cost, so the worse point is a local minimum, not a saddle
    rng = random.Random(7)
    for _ in range(5):
        c = [v + complex(rng.gauss(0, 0.05), rng.gauss(0, 0.05)) for v in hi]
        c = mean_cma(c, h, 1.0, 0.01, 6000)
        assert abs(cma_cost(cbb.conv(c, h), 1.0) - j_hi) < 1e-9


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        cma([1j, 1], 0, 0.01, 1.0)
    with pytest.raises(ValueError):
        cma([1j, 1], 2, -0.01, 1.0)
    with pytest.raises(ValueError):
        dispersion_constant([0j])

History

Sato published the first blind equalizer for multilevel PAM in 1975. Godard (1980) gave a family of criteria for two-dimensional signals such as QAM, E(∣z∣p−Rp)2E(|z|^p - R_p)^2, which do not depend on the carrier phase. The case p=2p = 2 is CMA. Treichler and Agee (1983) derived the same algorithm for signals of constant envelope, such as FM, and named it the constant modulus algorithm. Foschini (1985) proved that the algorithm converges for an ideal equalizer of unbounded length. Ding, Kennedy, Anderson and Johnson (1991) showed that FIR equalizers can have local minima. The review of Johnson and coauthors (1998) collects the theory of the CM criterion, including the conditions for fractionally spaced equalizers.

References

  1. Dominique N. Godard, Self-recovering equalization and carrier tracking in two-dimensional data communication systems, IEEE Transactions on Communications 28(11), 1980, pages 1867 to 1875, the dispersion criteria E(|z|^p - R_p)^2 and their stochastic gradient algorithms
  2. John R. Treichler and Brian G. Agee, A new approach to multipath correction of constant modulus signals, IEEE Transactions on Acoustics, Speech, and Signal Processing 31(2), 1983, pages 459 to 472, the constant modulus algorithm for signals of constant envelope
  3. C. Richard Johnson, Jr., Philip Schniter, Thomas J. Endres, James D. Behm, Donald R. Brown and Raul A. Casas, Blind equalization using the constant modulus criterion: a review, Proceedings of the IEEE 86(10), 1998, starting at page 1927, the conditions under which the CM minima of a fractionally spaced equalizer are perfect equalizers, and the independence of the CM criterion from the carrier phase
  4. Zhi Ding, Rodney A. Kennedy, Brian D. O. Anderson and C. Richard Johnson, Jr., Ill-convergence of Godard blind equalizers in data communication systems, IEEE Transactions on Communications 39(9), 1991, pages 1313 to 1327, local minima of the Godard cost for FIR equalizers
  5. G. J. Foschini, Equalizing without altering or detecting data, AT&T Technical Journal 64(8), 1985, pages 1885 to 1911, convergence of the Godard algorithm for an ideal equalizer of unbounded length
  6. John G. Proakis and Masoud Salehi, Digital Communications, fifth edition, McGraw-Hill, 2008, Chapter 10 (adaptive equalization), the section on blind equalization

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