Algorithm Search⌘K

Algorithmresearch

Expectation propagation detection

Also called EP detector.

Approximates the posterior of the symbol vector by a Gaussian that expectation propagation refines one symbol at a time, then decides each symbol. It starts from the MMSE estimate.

Time
O(n^2 m + T (n^3 + n M)) worst
Space
O(n^2 + n m) extra
Where
M = the constellation size; T = the number of iterations; m = the number of receive antennas; n = the number of transmitted streams
Properties
deterministicnot exact mlneeds matrix inverseneeds noise level
Origin
Javier Céspedes, Pablo M. Olmos, Matilde Sánchez Fernández, Fernando Pérez Cruz, 2014

Expectation propagation (EP) detection solves the MIMO detection problem by an approximation of the posterior distribution of the transmitted vector. The true posterior is a Gaussian likelihood times a discrete prior, one factor for each symbol. EP replaces each discrete prior factor by a Gaussian factor and then improves the Gaussian factors one at a time. For each symbol it removes that symbol's Gaussian factor, puts in the true discrete factor, computes the mean and variance of the result, and picks the new Gaussian factor that gives the same mean and variance. The first approximation is the linear MMSE estimate, and the next ones use the constellation. The detector of this page is the one of Céspedes, Olmos, Sánchez-Fernández and Pérez-Cruz (2014). The general method, for any model with factors, is on the expectation propagation page. This page gives the MIMO form, with the cavity and moment formulas for a PAM alphabet, the safeguards that the detector needs, and the results that are true for this model. AMP detection has a similar aim and costs less per step, but it needs a large channel with i.i.d. entries.

In plain words

The receiver wants to know which symbol vector was sent. It can compute the best Gaussian guess, which is what the MMSE detector does. But the true symbols are not Gaussian: each one is one of a few points. EP corrects the Gaussian guess one symbol at a time. For symbol ii, it asks what the rest of the system says about xix_i. This is a Gaussian bump, the cavity. It then multiplies the bump by the true rule "xix_i is one of the points" and gets a small discrete distribution. It makes the Gaussian factor of symbol ii agree with the mean and the variance of that distribution. After a few rounds, the means of the Gaussian are usually much closer to the true symbols than the MMSE estimate.

The problem

The model is y=Hx+wy = H x + w with H∈Cm×nH \in \mathbb{C}^{m \times n} known, x∈Snx \in \mathcal{S}^n for a square QAM constellation S\mathcal{S} of MM equally likely points with energy EsE_s, and w∼CN(0,N0I)w \sim \mathcal{CN}(0, N_0 I). EP works on the real form yr=Hrxr+wry_r = H_r x_r + w_r with

yr=(Re yIm y),Hr=(Re H−Im HIm HRe H),xr=(Re xIm x).y_r = \begin{pmatrix} \mathrm{Re}\, y \\ \mathrm{Im}\, y \end{pmatrix}, \quad H_r = \begin{pmatrix} \mathrm{Re}\, H & -\mathrm{Im}\, H \\ \mathrm{Im}\, H & \mathrm{Re}\, H \end{pmatrix}, \quad x_r = \begin{pmatrix} \mathrm{Re}\, x \\ \mathrm{Im}\, x \end{pmatrix}.

Now xrx_r has d=2nd = 2n entries, each in the PAM alphabet A\mathcal{A} of M\sqrt M levels with energy es=Es/2e_s = E_s/2, and wrw_r has i.i.d. N(0,σ2)\mathcal{N}(0, \sigma^2) entries with σ2=N0/2\sigma^2 = N_0/2. For real symbols (BPSK or PAM), xr=xx_r = x and Hr=(Re H;Im H)H_r = (\mathrm{Re}\, H; \mathrm{Im}\, H). The posterior is

p(xr∣yr)∝exp⁡(−∥yr−Hrxr∥22σ2)∏i=1d1[xi∈A].p(x_r \mid y_r) \propto \exp\Big(-\frac{\|y_r - H_r x_r\|^2}{2\sigma^2}\Big) \prod_{i=1}^{d} \mathbb{1}[x_i \in \mathcal{A}].

The detector returns one decision in S\mathcal{S} for each stream and, for soft output, the mean and variance of each real symbol.

The algorithm

EP replaces each factor 1[xi∈A]\mathbb{1}[x_i \in \mathcal{A}] by a Gaussian site exp⁡(γixi−Λixi2/2)\exp(\gamma_i x_i - \Lambda_i x_i^2 / 2) with Λi>0\Lambda_i > 0. The approximation is then the Gaussian q(xr)=N(μ,Σ)q(x_r) = \mathcal{N}(\mu, \Sigma) with

Σ=(σ−2HrTHr+diag(Λ))−1,μ=Σ(σ−2HrTyr+γ).\Sigma = \big(\sigma^{-2} H_r^T H_r + \mathrm{diag}(\Lambda)\big)^{-1}, \qquad \mu = \Sigma \big(\sigma^{-2} H_r^T y_r + \gamma\big).

For a site ii, the cavity is the marginal of qq divided by site ii. It is N(ti,hi2)\mathcal{N}(t_i, h_i^2) with

hi2=Σii1−ΣiiΛi,ti=hi2(μiΣii−γi).h_i^2 = \frac{\Sigma_{ii}}{1 - \Sigma_{ii} \Lambda_i}, \qquad t_i = h_i^2 \Big(\frac{\mu_i}{\Sigma_{ii}} - \gamma_i\Big).

The tilted distribution puts the weight ∝exp⁡(−(a−ti)2/(2hi2))\propto \exp(-(a - t_i)^2 / (2 h_i^2)) on each a∈Aa \in \mathcal{A}. Let μp\mu_{p} and σp2\sigma_{p}^2 be its mean and variance.

  1. EP-DETECT(y_r, H_r, A, σ², T, β, ε)
  2. 1γ ← 0; Λ ← (1/e_s, ..., 1/e_s)
  3. 2for t ← 1 to T
  4. 3Σ ← (Hᵀ H / σ² + diag Λ)⁻¹; μ ← Σ (Hᵀ y / σ² + γ)
  5. 4for each i: h²_i ← Σ_ii / (1 - Σ_ii Λ_i); t_i ← h²_i (μ_i / Σ_ii - γ_i)
  6. 5(μ_p, σ²_p) ← mean and variance of the tilted distribution on A; σ²_p ← max(σ²_p, ε)
  7. 6Λ' ← 1/σ²_p - 1/h²_i; γ' ← μ_p/σ²_p - t_i/h²_i
  8. 7if Λ' > 0: Λ_i ← β Λ' + (1 - β) Λ_i; γ_i ← β γ' + (1 - β) γ_i
  9. 8for each stream k: decide the level of A nearest to μ_k (and to μ_{n+k} for the imaginary part)
  10. 9return the decisions

Line L1 sets every site to the prior variance ese_s with mean 0, so the first qq is the linear MMSE estimate. Line L3 is one solve with a d×dd \times d symmetric positive definite matrix. Line L4 forms the cavity. Line L5 computes M\sqrt M weights per real symbol, with the largest exponent subtracted first so that nothing underflows. Line L6 gives the site that makes the marginal of qq have the tilted mean and variance. Line L7 keeps the old site when the new precision is not positive, and damps the update with a factor β∈(0,1]\beta \in (0, 1]. All sites in one iteration use the same qq; this is a parallel schedule. The implementation uses β=0.7\beta = 0.7, ε=10−9\varepsilon = 10^{-9} and T=10T = 10 by default. Céspedes et al. also use damping, a variance floor and a fixed small number of iterations; their exact values are not repeated here. Line L8 rounds each mean to the nearest level.

Example

A small channel, where EP corrects MMSE. Take BPSK, m=n=2m = n = 2,

H=(10.50.51),y=(0.2,0.6),N0=0.6.H = \begin{pmatrix} 1 & 0.5 \\ 0.5 & 1 \end{pmatrix}, \qquad y = (0.2, 0.6), \qquad N_0 = 0.6.

The four metrics ∥y−Hx∥2\|y - H x\|^2 are 2.5 for (+1,+1)(+1, +1), 1.3 for (+1,−1)(+1, -1), 0.5 for (−1,+1)(-1, +1) and 7.3 for (−1,−1)(-1, -1), so ML decides (−1,+1)(-1, +1). The real model has σ2=0.3\sigma^2 = 0.3 and es=1e_s = 1. With HTH=(1.25111.25)H^T H = \begin{pmatrix} 1.25 & 1 \\ 1 & 1.25 \end{pmatrix} and HTy=(0.5,0.7)H^T y = (0.5, 0.7), line L3 gives

Σ=115.583(5.1667−3.3333−3.33335.1667),μ=(0.0535,0.4171).\Sigma = \frac{1}{15.583} \begin{pmatrix} 5.1667 & -3.3333 \\ -3.3333 & 5.1667 \end{pmatrix}, \qquad \mu = (0.0535, 0.4171).

This is the MMSE estimate, and its signs give (+1,+1)(+1, +1), which is wrong. Now take one EP iteration with β=1\beta = 1. For BPSK the tilted mean is tanh⁡(ti/hi2)\tanh(t_i / h_i^2) and the tilted variance is 1−tanh⁡2(ti/hi2)1 - \tanh^2(t_i / h_i^2).

site hi2h_i^2 tit_i μp\mu_p σp2\sigma_p^2 Λ′\Lambda' action
1 0.4960 0.0800 0.1600 0.9744 −0.990-0.990 keep Λ1=1\Lambda_1 = 1, γ1=0\gamma_1 = 0
2 0.4960 0.6240 0.8505 0.2766 1.599 set Λ2=1.599\Lambda_2 = 1.599, γ2=1.817\gamma_2 = 1.817

The new qq has μ=(−0.2261,0.8505)\mu = (-0.2261, 0.8505) and the variances (0.3087,0.2766)(0.3087, 0.2766). The site of symbol 1 did not change, but the stronger belief that x2=+1x_2 = +1 pulls μ1\mu_1 below 0 through the correlation of the columns. The decisions are (−1,+1)(-1, +1), the ML vector. More iterations do not change qq, because site 2 already matches its tilted moments and the update of site 1 is still negative. The test checks the means and the variances of qq after 0 and 1 iterations within 10−410^{-4}, and the decisions.

Correctness

The proof is in proofs/correctness.md. It shows the following, for every channel unless stated. First, the cavity formulas of line L4 are the marginal of qq divided by site ii, and line L6 gives the site that makes the marginal of qq equal in mean and variance to the tilted distribution. Second, all Λi\Lambda_i stay positive, so Σ\Sigma always exists, and the cavity is a proper Gaussian when column ii of HrH_r is not zero. Third, the first qq has the mean (HHH+(N0/Es)I)−1HHy(H^H H + (N_0/E_s) I)^{-1} H^H y in real form, the linear MMSE estimate. Fourth, at a fixed point where every site was kept, each marginal of qq has the mean and variance of its tilted distribution. Fifth, if HHHH^H H is diagonal and every update is kept, which is true when σ2/∥hi∥2>max⁡aa2\sigma^2 / \|h_i\|^2 > \max_a a^2, the means and variances of qq converge to the exact posterior marginals. EP is not an exact ML detector in general, and it need not converge. Its good error rate on random channels is a measurement, not a theorem.

Proof: The EP updates match moments, the sites stay proper, the first iterate is the linear MMSE estimate, and the marginals are exact on orthogonal channelsfull

The model is the real form yr=Hrxr+wry_r = H_r x_r + w_r of the page, with dd real symbols in the alphabet A\mathcal{A}, wr∼N(0,σ2I)w_r \sim \mathcal{N}(0, \sigma^2 I) and ese_s the mean of a2a^2 over A\mathcal{A}. Write G=HrTHrG = H_r^T H_r and b=HrTyrb = H_r^T y_r. The lines L1 to L9 are those of the pseudocode on the page. A Gaussian factor exp⁡(γx−Λx2/2)\exp(\gamma x - \Lambda x^2/2) is written in natural parameters (γ,Λ)(\gamma, \Lambda). For Λ>0\Lambda > 0 it is proportional to N(x;γ/Λ,1/Λ)\mathcal{N}(x; \gamma/\Lambda, 1/\Lambda). This file claims only the results below. It does not claim that EP converges in general or that it finds the ML vector; the page shows a case where it does not.

Lemma 1 (the sites stay positive and qq exists)

At every point of the algorithm, Λi>0\Lambda_i > 0 for all ii, and A=G/σ2+diag(Λ)A = G/\sigma^2 + \mathrm{diag}(\Lambda) is positive definite. If column ii of HrH_r is not zero, the cavity precision 1/Σii−Λi1/\Sigma_{ii} - \Lambda_i is positive.

Proof. Line L1 sets Λi=1/es>0\Lambda_i = 1/e_s > 0. Line L7 changes Λi\Lambda_i only when Λ′>0\Lambda' > 0, and then to βΛ′+(1−β)Λi\beta \Lambda' + (1 - \beta) \Lambda_i with β∈(0,1]\beta \in (0, 1], a convex combination of two positive numbers. So Λi>0\Lambda_i > 0 always, by induction. For v≠0v \ne 0, vTAv=∥Hrv∥2/σ2+∑jΛjvj2>0v^T A v = \|H_r v\|^2/\sigma^2 + \sum_j \Lambda_j v_j^2 > 0, so AA is positive definite and Σ=A−1\Sigma = A^{-1} exists.

For the cavity, let A−iA_{-i} be AA with Λi\Lambda_i replaced by 0. By the Schur complement, 1/Σii=Aii−aTB−1a1/\Sigma_{ii} = A_{ii} - a^T B^{-1} a, where BB is AA without row and column ii and aa is column ii of AA without its entry ii. The same formula for A−iA_{-i} has the same BB and aa and the entry Aii−ΛiA_{ii} - \Lambda_i. So 1/Σii−Λi1/\Sigma_{ii} - \Lambda_i is the Schur complement of BB in A−iA_{-i}. It is positive if A−iA_{-i} is positive definite. Now vTA−iv=∥Hrv∥2/σ2+∑j≠iΛjvj2v^T A_{-i} v = \|H_r v\|^2/\sigma^2 + \sum_{j \ne i} \Lambda_j v_j^2, which is 0 only if vj=0v_j = 0 for j≠ij \ne i and viHrei=0v_i H_r e_i = 0. When column ii is not zero, this forces v=0v = 0. □\square

Theorem 2 (the cavity and the moment-matching site)

Line L4 gives the Gaussian N(ti,hi2)\mathcal{N}(t_i, h_i^2) proportional to qi(xi)/si(xi)q_i(x_i) / s_i(x_i), where qi=N(μi,Σii)q_i = \mathcal{N}(\mu_i, \Sigma_{ii}) is the marginal of qq and sis_i is site ii. If site ii is replaced by the site (γ′,Λ′)(\gamma', \Lambda') of line L6, with no damping, the new marginal of qq for xix_i is N(μp,σp2)\mathcal{N}(\mu_p, \sigma_p^2), the Gaussian with the mean and variance of the tilted distribution ∝N(a;ti,hi2)\propto \mathcal{N}(a; t_i, h_i^2) on A\mathcal{A}.

Proof. In natural parameters, dividing Gaussian factors subtracts parameters. The marginal qiq_i has (μi/Σii,1/Σii)(\mu_i / \Sigma_{ii}, 1/\Sigma_{ii}). So the cavity has the precision 1/Σii−Λi1/\Sigma_{ii} - \Lambda_i, which is positive by Lemma 1, and the linear term μi/Σii−γi\mu_i/\Sigma_{ii} - \gamma_i. Its variance is hi2=1/(1/Σii−Λi)=Σii/(1−ΣiiΛi)h_i^2 = 1/(1/\Sigma_{ii} - \Lambda_i) = \Sigma_{ii}/(1 - \Sigma_{ii}\Lambda_i), and its mean is hi2(μi/Σii−γi)=tih_i^2 (\mu_i/\Sigma_{ii} - \gamma_i) = t_i, as in line L4.

The density qq is proportional to the likelihood times all sites. Write it as q(x)∝si(xi) r(x)q(x) \propto s_i(x_i)\, r(x), where rr collects the likelihood and the other sites. Then the marginal of qq is qi(xi)∝si(xi)∫r(x) dx−iq_i(x_i) \propto s_i(x_i) \int r(x)\, dx_{-i}, so ∫r dx−i∝qi/si\int r\, dx_{-i} \propto q_i / s_i, the cavity. Replacing sis_i by a new site si′s_i' does not change rr, so the new marginal is proportional to si′(xi)⋅N(xi;ti,hi2)s_i'(x_i) \cdot \mathcal{N}(x_i; t_i, h_i^2). With si′s_i' of parameters (μp/σp2−ti/hi2,  1/σp2−1/hi2)(\mu_p/\sigma_p^2 - t_i/h_i^2,\; 1/\sigma_p^2 - 1/h_i^2), the product has the parameters (μp/σp2,1/σp2)(\mu_p/\sigma_p^2, 1/\sigma_p^2), which is N(μp,σp2)\mathcal{N}(\mu_p, \sigma_p^2). These are the formulas of line L6. □\square

A negative Λ′\Lambda' can make the joint qq improper, because the proof of Lemma 1 then fails, and then the marginal of qq is not defined. That is why line L7 keeps the old site in that case. Among all Gaussians, N(μp,σp2)\mathcal{N}(\mu_p, \sigma_p^2) minimizes the Kullback-Leibler divergence from the tilted distribution, which is the general EP rule (Minka 2001).

Theorem 3 (the first iterate is the linear MMSE estimate)

On the first pass of line L3, μ=(G+(σ2/es)I)−1b\mu = (G + (\sigma^2/e_s) I)^{-1} b. For the real form of a complex model with square QAM, this is the real form of (HHH+(N0/Es)I)−1HHy(H^H H + (N_0/E_s) I)^{-1} H^H y.

Proof. Line L1 gives γ=0\gamma = 0 and Λ=(1/es)1\Lambda = (1/e_s) \mathbf{1}. So μ=(G/σ2+I/es)−1b/σ2=(G+(σ2/es)I)−1b\mu = (G/\sigma^2 + I/e_s)^{-1} b/\sigma^2 = (G + (\sigma^2/e_s) I)^{-1} b. For the complex model, σ2=N0/2\sigma^2 = N_0/2 and es=Es/2e_s = E_s/2, since the real and imaginary parts of a square QAM point are independent and share the energy equally. So σ2/es=N0/Es\sigma^2/e_s = N_0/E_s. The map C↦Cr=(Re C−Im CIm CRe C)C \mapsto C_r = \begin{pmatrix} \mathrm{Re}\, C & -\mathrm{Im}\, C \\ \mathrm{Im}\, C & \mathrm{Re}\, C \end{pmatrix} respects sums and products, sends CHC^H to CrTC_r^T and the identity to the identity, and acts on vectors by stacking the real and imaginary parts in the same way. So G=(HHH)rG = (H^H H)_r, bb is the stacked HHyH^H y, and (HHH+cI)r−1=((HHH+cI)−1)r(H^H H + c I)_r^{-1} = ((H^H H + c I)^{-1})_r. Hence μ\mu is the stacked (HHH+(N0/Es)I)−1HHy(H^H H + (N_0/E_s) I)^{-1} H^H y. □\square

The test checks this within 10−910^{-9} on five channels with n=4n = 4 and m=6m = 6. The MMSE detector of the MMSE page rounds this estimate, after a bias correction that does not change the signs. For a constellation with more than two levels per dimension, the bias correction can change the decision, so EP with T=0T = 0 equals the MMSE detector without that correction.

Theorem 4 (fixed points match moments)

Suppose that in an iteration with β∈(0,1]\beta \in (0, 1], every site was kept (Λ′>0\Lambda' > 0) and no site changed. Then for every ii, the marginal of qq for xix_i has the mean and variance of its tilted distribution.

Proof. No change with β>0\beta > 0 means Λ′=Λi\Lambda' = \Lambda_i and γ′=γi\gamma' = \gamma_i for every ii. All sites in the iteration were computed from the same qq, so by Theorem 2 the marginal of qq divided by the cavity is the site (γ′,Λ′)=(γi,Λi)(\gamma', \Lambda') = (\gamma_i, \Lambda_i). So the marginal is the cavity times the site, which by the proof of Theorem 2 is N(μp,σp2)\mathcal{N}(\mu_p, \sigma_p^2). □\square

The floor ε\varepsilon of line L5 changes σp2\sigma_p^2 only when it is below ε\varepsilon. In that case the statement holds with σp2\sigma_p^2 replaced by ε\varepsilon.

Theorem 5 (exact marginals on orthogonal channels)

Suppose G=diag(g1,…,gd)G = \mathrm{diag}(g_1, \dots, g_d) with all gi>0g_i > 0, and σ2/gi>max⁡a∈Aa2\sigma^2 / g_i > \max_{a \in \mathcal{A}} a^2 for every ii. Then every update of line L7 is kept, and as T→∞T \to \infty the mean and variance of each marginal of qq converge to the mean and variance of xix_i under the exact posterior. With β=1\beta = 1 they are equal after one iteration (ignoring the floor ε\varepsilon).

Proof. With GG diagonal, AA is diagonal, so Σii=1/(gi/σ2+Λi)\Sigma_{ii} = 1/(g_i/\sigma^2 + \Lambda_i) and μi=Σii(bi/σ2+γi)\mu_i = \Sigma_{ii}(b_i/\sigma^2 + \gamma_i). Then line L4 gives hi2=σ2/gih_i^2 = \sigma^2/g_i and ti=bi/git_i = b_i/g_i, whatever the sites are.

The exact posterior factorizes. Indeed, ∥yr−Hrx∥2=∥yr∥2−2bTx+∑igixi2\|y_r - H_r x\|^2 = \|y_r\|^2 - 2 b^T x + \sum_i g_i x_i^2, so

p(x∣yr)∝∏iexp⁡(−gixi2−2bixi2σ2)1[xi∈A]∝∏iN(xi;ti,hi2) 1[xi∈A].p(x \mid y_r) \propto \prod_i \exp\Big(-\frac{g_i x_i^2 - 2 b_i x_i}{2\sigma^2}\Big) \mathbb{1}[x_i \in \mathcal{A}] \propto \prod_i \mathcal{N}(x_i; t_i, h_i^2)\, \mathbb{1}[x_i \in \mathcal{A}].

So the exact marginal of xix_i is the tilted distribution of site ii, and it does not depend on the sites. Let (μp,σp2)(\mu_p, \sigma_p^2) be its moments. The variance σp2\sigma_p^2 is at most E[xi2]≤max⁡aa2<hi2E[x_i^2] \le \max_a a^2 < h_i^2, so Λ′=1/σp2−1/hi2>0\Lambda' = 1/\sigma_p^2 - 1/h_i^2 > 0 and every update is kept. The targets (γ′,Λ′)(\gamma', \Lambda') are the same at every iteration, so line L7 gives Λi(t)−Λ′=(1−β)t(Λi(0)−Λ′)\Lambda_i^{(t)} - \Lambda' = (1 - \beta)^t (\Lambda_i^{(0)} - \Lambda'), and the same for γi\gamma_i. Both go to 0 for β∈(0,1]\beta \in (0, 1], and they are 0 after one step when β=1\beta = 1. With the limit site, the marginal of qq is the cavity times the site, which is N(μp,σp2)\mathcal{N}(\mu_p, \sigma_p^2) by Theorem 2. The mean and variance of qiq_i are continuous in (γi,Λi)(\gamma_i, \Lambda_i), so they converge to (μp,σp2)(\mu_p, \sigma_p^2). □\square

For the complex model, GG is diagonal exactly when HHHH^H H is diagonal, since G=(HHH)rG = (H^H H)_r and the off-diagonal blocks are ±Im(HHH)\pm \mathrm{Im}(H^H H), whose diagonal is 0. The test builds H=U diag(d)H = U\, \mathrm{diag}(d) with UU a rotation, ∣d1∣=0.6|d_1| = 0.6, ∣d2∣=0.5|d_2| = 0.5, 16-QAM and N0=1N_0 = 1, so σ2/gi≥0.5/0.36=1.39>0.9=max⁡aa2\sigma^2/g_i \ge 0.5/0.36 = 1.39 > 0.9 = \max_a a^2. It compares the means and variances with a sum over all 256 vectors, within 10−610^{-6}.

What the tests check

  • Theorem 2 with BPSK: the tilted mean and variance equal tanh⁡(t/h2)\tanh(t/h^2) and 1−tanh⁡2(t/h2)1 - \tanh^2(t/h^2) within 10−1210^{-12}.
  • Theorem 3: the first iterate against the complex linear MMSE solve, within 10−910^{-9}.
  • Theorem 5: exact posterior means and variances on orthogonal channels, within 10−610^{-6}.
  • The page example, step by step, within 10−410^{-4}, and that further steps do not change qq (Theorem 4 in a concrete case).
  • Measurements: agreement with brute-force ML on at least 92 of 100 vectors for 4-QAM, n=m=4n = m = 4, 15 dB (seed 2204; 97 in the run), at most 3/53/5 of the MMSE symbol errors for n=m=8n = m = 8 at 10 dB (seed 2206; 19 against 38), and the strongly correlated case where EP settles on a non-ML vector.

Complexity

The Gram matrix HrTHrH_r^T H_r and the vector HrTyrH_r^T y_r cost O(n2m)O(n^2 m) once. Each iteration inverts a 2n×2n2n \times 2n matrix in O(n3)O(n^3) and computes 2n2n tilted moments of M\sqrt M terms each. So TT iterations cost O(n2m+T(n3+nM))O(n^2 m + T(n^3 + n \sqrt M)) in the real RAM, which the front matter bounds by O(n2m+T(n3+nM))O(n^2 m + T(n^3 + n M)). The space is O(n2+nm)O(n^2 + n m). The cost is that of the MMSE detector times TT, and it grows only with M\sqrt M in the constellation size. A sphere search, by contrast, can grow fast with MM at low SNR. A rank-one update of Σ\Sigma after each site gives a sequential schedule at O(n2)O(n^2) per site, the same order per iteration.

Properties

  • MMSE start. The first iterate is the linear MMSE estimate (theorem). So EP with T=0T = 0 is the MMSE detector without the bias correction.
  • Moment matching. At a fixed point where all sites were kept, the mean and variance of each marginal of qq match the tilted distribution (theorem).
  • Exact on orthogonal channels. When HHHH^H H is diagonal and the cavity variance is above max⁡aa2\max_a a^2, EP gives the exact posterior marginals. The test checks this against a sum over all 256 vectors of 16-QAM with n=2n = 2, within 10−610^{-6}.
  • Measured agreement with ML. For 4-QAM, n=m=4n = m = 4, i.i.d. CN(0,1/m)\mathcal{CN}(0, 1/m) entries and Es/N0=15E_s/N_0 = 15 dB, the test with seed 2204 runs 100 vectors, and EP with 10 iterations agrees with brute-force ML on 97 (measurement; the test asks for at least 92).
  • Measured gain over MMSE. For 4-QAM, n=m=8n = m = 8 and Es/N0=10E_s/N_0 = 10 dB, EP made 19 symbol errors on 320 symbols and the MMSE start made 38 (seed 2206, measurement).
  • No guarantee. On a strongly correlated channel EP can settle on a wrong vector, as Pitfalls shows.

Variants and improvements

  • Sequential schedule. Update one site at a time and change Σ\Sigma by a rank-one formula. The parallel schedule of this page is simpler; the sequential one often needs fewer iterations.
  • Soft output for coding. The pairs (ti,hi2)(t_i, h_i^2) of the cavity are extrinsic values for each real symbol. They feed a soft demapper and a channel decoder, and the decoder output can come back as a new prior, as in turbo equalization.
  • Complex form. EP can also work with complex Gaussian sites on the complex model. For square QAM the real form is equivalent and simpler.
  • Lower cost for large systems. For massive MIMO, later work looks for cheaper ways to compute or approximate Σ\Sigma than the O(n3)O(n^3) inverse. These change the cost and the accuracy, and this page does not cover them.
  • Other site families. EP can use a full covariance per site or a mixture, at more cost.

When to use it

Use EP when nn is moderate (up to a few tens of streams), the constellation is large (16-QAM to 256-QAM), and the channel may be correlated, so that AMP is not safe and a sphere search is too slow. It costs a small multiple of the MMSE detector and is often much more accurate. For small nn with a low-order constellation, an exact search such as Schnorr-Euchner enumeration or the K-best detector is affordable and better. For very large i.i.d. systems, AMP detection avoids the inverse.

Pitfalls

  • Negative site precision. The update Λ′\Lambda' can be negative, for example when the cavity sits between two points and the tilted distribution is wider than the cavity. Then qq may stop being a proper Gaussian. Keep the old site, as line L7 does.
  • Too small a tilted variance. At high SNR the tilted variance can be 0 in floating point. Without the floor ε\varepsilon the update divides by 0.
  • No damping. Without damping the parallel schedule can oscillate. Choose β<1\beta < 1, and check the choice by measurement on the channels of interest.
  • Strong correlation. Take BPSK, H=(2111)H = \begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix}, y=(0.5,0.6)y = (0.5, 0.6) and N0=0.25N_0 = 0.25. The columns have the correlation 3/10=0.9493/\sqrt{10} = 0.949. ML decides (+1,−1)(+1, -1) with metric 0.61, and the exact posterior means are (0.9993,−0.9993)(0.9993, -0.9993). EP with β=1\beta = 1 goes to μ=(−1,+1)\mu = (-1, +1) and decides (−1,+1)(-1, +1), with metric 2.61. The test checks this case.
  • Wrong real form. For real symbols (BPSK, PAM), do not add imaginary parts as unknowns: they are 0, and treating them as ±1\pm 1 breaks the model. The implementation uses Hr=(Re H;Im H)H_r = (\mathrm{Re}\, H; \mathrm{Im}\, H) in that case.
  • Wrong noise variance. The real model has σ2=N0/2\sigma^2 = N_0 / 2 per real dimension, and each real level has energy Es/2E_s/2. Mixing the complex and the real values gives the wrong first iterate.

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)
constel.py 117 lines
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Constellations, Gray labels and brute-force maximum likelihood detection.

Each constellation function returns a list of M complex points with unit
average energy, ordered by label: points[i] is the point whose bit label is
the integer i, and bits(i, log2 M) gives that label, most significant bit
first. The labels follow the communications area rules:

- M-PAM: the point with amplitude index m = 0, ..., M-1 (raw amplitude
  M - 1 - 2m, from the most positive) gets the Gray label gray(m).
  So 2-PAM maps bit 0 to +1 and bit 1 to -1.
- Square M-QAM, M = 4^k: the label is the in-phase PAM label followed by the
  quadrature PAM label, each of log2(sqrt(M)) bits.
- M-PSK: the point e^(j(2 pi m / M + phase0)) gets the label gray(m).

PAM points are returned as complex numbers with zero imaginary part.
This file imports nothing from cbb.py. It holds no demapper: soft and
max-log demapping are algorithm pages of their own.
"""

import cmath
import itertools
import math


def gray(n: int) -> int:
    """The binary reflected Gray code of n: n XOR (n >> 1)."""
    return n ^ (n >> 1)


def _gray_inv(g: int) -> int:
    n = 0
    while g:
        n ^= g
        g >>= 1
    return n


def bits(i: int, m: int) -> list[int]:
    """The m bits of the integer i, most significant bit first."""
    if i < 0 or i >= 1 << m:
        raise ValueError("i does not fit in m bits")
    return [(i >> (m - 1 - t)) & 1 for t in range(m)]


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


def pam(m: int) -> list[complex]:
    """Unit-energy M-PAM, ordered by Gray label."""
    _log2(m)
    s = math.sqrt((m * m - 1) / 3.0)
    return [complex((m - 1 - 2 * _gray_inv(lab)) / s, 0.0) for lab in range(m)]


def qam(m: int) -> list[complex]:
    """Unit-energy square M-QAM (M = 4, 16, 64, ...), ordered by label (in-phase bits first)."""
    k = _log2(m)
    if k % 2:
        raise ValueError("square QAM needs M = 4^k")
    side = 1 << (k // 2)
    s = math.sqrt(2.0 * (m - 1) / 3.0)
    raw = [side - 1 - 2 * _gray_inv(lab) for lab in range(side)]
    return [complex(raw[lab // side], raw[lab % side]) / s for lab in range(m)]


def psk(m: int, phase0: float = 0.0) -> list[complex]:
    """Unit-energy M-PSK with first point at angle phase0, ordered by Gray label."""
    _log2(m)
    return [cmath.exp(1j * (2.0 * math.pi * _gray_inv(lab) / m + phase0)) for lab in range(m)]


def energy(points: list[complex]) -> float:
    """The average energy (1/M) sum |p|^2 of equally likely points."""
    return sum(abs(p) ** 2 for p in points) / len(points)


def ml_detect(y: complex, points: list[complex], h: complex = 1) -> int:
    """The index of the point p that minimizes |y - h p|^2, by brute force (lowest index on a tie)."""
    best, arg = math.inf, -1
    for i, p in enumerate(points):
        d = abs(y - h * p) ** 2
        if d < best:
            best, arg = d, i
    return arg


def ml_vector(y: list[complex], h: list[list[complex]], points: list[complex]) -> list[int]:
    """The index vector that minimizes ||y - H x||^2 over all M^n vectors x, by brute force.

    h is the m by n channel matrix as a list of rows; the result has n indices.
    The first minimizer in lexicographic order of the indices wins a tie.
    """
    n = len(h[0])
    best, arg = math.inf, None
    for idx in itertools.product(range(len(points)), repeat=n):
        x = [points[i] for i in idx]
        d = 0.0
        for yi, row in zip(y, h):
            d += abs(yi - sum(a * b for a, b in zip(row, x))) ** 2
        if d < best:
            best, arg = d, idx
    return list(arg)


def bit_errors(a, b) -> int:
    """The number of differing bits between two integer labels, or summed over two equal-length lists."""
    if isinstance(a, int) and isinstance(b, int):
        return bin(a ^ b).count("1")
    if len(a) != len(b):
        raise ValueError("lengths differ")
    return sum(bit_errors(x, y) for x, y in zip(a, b))
expectation_propagation_detection.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/expectation-propagation-detection/. The authors are listed in prov/R4B3XS.jsonl.

"""Expectation propagation (EP) MIMO detection, in the real-valued form.

The complex model y = H x + w, with H an m by n matrix, x in S^n for a square
QAM constellation S and w ~ CN(0, N0 I), is first written as a real model
y_r = H_r x_r + w_r of size 2m by 2n. Each real symbol takes values in a PAM
alphabet A, and the noise has variance s2 = N0 / 2 per real dimension.

EP replaces the prior factor 1{x_i in A} of each real symbol by a Gaussian
factor exp(gamma_i x_i - Lambda_i x_i^2 / 2). The product with the Gaussian
likelihood is a Gaussian q(x) = N(mu, Sigma) with
    Sigma = (H_r^T H_r / s2 + diag(Lambda))^(-1),  mu = Sigma (H_r^T y_r / s2 + gamma).
Each iteration removes factor i from the marginal of q (the cavity),
multiplies the cavity by the true prior factor, matches the mean and the
variance of the result, and updates (gamma_i, Lambda_i) with damping.
This is the detector of Cespedes, Olmos, Sanchez-Fernandez and Perez-Cruz,
IEEE Trans. Comm. 62(8), 2014.
"""

import math

import cbb


def real_model(y: list[complex], h: list[list[complex]], real_symbols: bool = False) -> tuple[list[float], list[list[float]]]:
    """(y_r, H_r) with y_r = (Re y, Im y) and H_r = [[Re H, -Im H], [Im H, Re H]].

    If the symbols are real (PAM), x has no imaginary part and H_r = [Re H; Im H].
    """
    m, n = len(h), len(h[0])
    yr = [complex(v).real for v in y] + [complex(v).imag for v in y]
    hr = []
    for i in range(m):
        row = [complex(h[i][k]).real for k in range(n)]
        hr.append(row if real_symbols else row + [-complex(h[i][k]).imag for k in range(n)])
    for i in range(m):
        row = [complex(h[i][k]).imag for k in range(n)]
        hr.append(row if real_symbols else row + [complex(h[i][k]).real for k in range(n)])
    return yr, hr


def real_alphabet(points: list[complex]) -> list[float]:
    """The sorted levels of the real part of a square QAM (or real PAM) constellation."""
    return sorted({round(complex(p).real, 12) for p in points})


def tilted_moments(t: float, h2: float, alphabet: list[float]) -> tuple[float, float]:
    """Mean and variance of p(a) proportional to exp(-(a - t)^2 / (2 h2)) on the alphabet."""
    logs = [-(a - t) ** 2 / (2.0 * h2) for a in alphabet]
    top = max(logs)
    ws = [math.exp(v - top) for v in logs]
    tot = sum(ws)
    mean = sum(w * a for w, a in zip(ws, alphabet)) / tot
    var = sum(w * (a - mean) ** 2 for w, a in zip(ws, alphabet)) / tot
    return mean, var


def gaussian_q(gram: list[list[float]], hty: list[float], s2: float, gamma: list[float], lam: list[float]) -> tuple[list[float], list[list[float]]]:
    """(mu, Sigma) of q: Sigma = (G / s2 + diag(Lambda))^(-1), mu = Sigma (H^T y / s2 + gamma)."""
    d = len(gram)
    a = [[gram[i][k] / s2 + (lam[i] if i == k else 0.0) for k in range(d)] for i in range(d)]
    sig = [[v.real for v in row] for row in cbb.inv(a)]
    b = [hty[i] / s2 + gamma[i] for i in range(d)]
    mu = [sum(sig[i][k] * b[k] for k in range(d)) for i in range(d)]
    return mu, sig


def ep_real(yr: list[float], hr: list[list[float]], alphabet: list[float], s2: float, iters: int = 10, damping: float = 0.7, eps: float = 1e-9) -> tuple[list[float], list[float]]:
    """Run EP on a real model. Returns (mu, diag Sigma) of the final Gaussian approximation q."""
    m2, d = len(hr), len(hr[0])
    es = sum(a * a for a in alphabet) / len(alphabet)
    gram = [[sum(hr[r][i] * hr[r][k] for r in range(m2)) for k in range(d)] for i in range(d)]
    hty = [sum(hr[r][i] * yr[r] for r in range(m2)) for i in range(d)]
    gamma = [0.0] * d  # @line L1
    lam = [1.0 / es] * d
    for _ in range(iters):  # @line L2
        mu, sig = gaussian_q(gram, hty, s2, gamma, lam)  # @line L3
        for i in range(d):
            h2 = sig[i][i] / (1.0 - sig[i][i] * lam[i])  # @line L4
            t = h2 * (mu[i] / sig[i][i] - gamma[i])
            mp, vp = tilted_moments(t, h2, alphabet)  # @line L5
            vp = max(vp, eps)
            lam_new = 1.0 / vp - 1.0 / h2  # @line L6
            gam_new = mp / vp - t / h2
            if lam_new > 0.0:  # @line L7
                lam[i] = damping * lam_new + (1.0 - damping) * lam[i]
                gamma[i] = damping * gam_new + (1.0 - damping) * gamma[i]
    mu, sig = gaussian_q(gram, hty, s2, gamma, lam)
    return mu, [sig[i][i] for i in range(d)]


def ep_detect(y: list[complex], h: list[list[complex]], points: list[complex], n0: float, iters: int = 10, damping: float = 0.7) -> list[int]:
    """EP decisions for a complex model with a square QAM (or PAM) constellation, as point indices."""
    n = len(h[0])
    real_only = all(abs(complex(p).imag) < 1e-12 for p in points)
    yr, hr = real_model(y, h, real_only)
    alphabet = real_alphabet(points)
    mu, _ = ep_real(yr, hr, alphabet, n0 / 2.0, iters, damping)
    out = []
    for k in range(n):  # @line L8
        re = min(alphabet, key=lambda a: abs(mu[k] - a))
        im = 0.0 if real_only else min(alphabet, key=lambda a: abs(mu[n + k] - a))
        out.append(min(range(len(points)), key=lambda i: abs(points[i] - complex(re, im))))
    return out  # @line L9
test_expectation_propagation_detection.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/expectation-propagation-detection/. The authors are listed in prov/R4B3XS.jsonl.

import itertools
import math
import random
import unittest

import cbb
import constel
from expectation_propagation_detection import ep_detect, ep_real, real_alphabet, real_model, tilted_moments


def iid(rng: random.Random, m: int, n: int) -> list[list[complex]]:
    return [[cbb.cn(rng, 1.0 / m) for _ in range(n)] for _ in range(m)]


def posterior_moments(y, h, points, n0):
    """Exact marginal means and variances of Re x_k and Im x_k, by summing over all M^n vectors."""
    n = len(h[0])
    ws, xs = [], []
    for xv in itertools.product(points, repeat=n):
        r = cbb.sub(y, cbb.matvec(h, list(xv)))
        ws.append(-cbb.norm2(r) / n0)
        xs.append(xv)
    top = max(ws)
    ws = [math.exp(w - top) for w in ws]
    tot = sum(ws)
    comps = [lambda v: v.real, lambda v: v.imag]
    mean, var = [], []
    for part in comps:
        for k in range(n):
            mk = sum(w * part(xv[k]) for w, xv in zip(ws, xs)) / tot
            vk = sum(w * (part(xv[k]) - mk) ** 2 for w, xv in zip(ws, xs)) / tot
            mean.append(mk)
            var.append(vk)
    return mean, var


class TestExpectationPropagationDetection(unittest.TestCase):
    def test_tilted_moments_bpsk(self):
        for t, h2 in [(0.3, 0.5), (-1.2, 0.1), (2.0, 3.0), (40.0, 0.01)]:
            mean, var = tilted_moments(t, h2, [-1.0, 1.0])
            self.assertAlmostEqual(mean, math.tanh(t / h2), delta=1e-12)
            self.assertAlmostEqual(var, 1.0 - math.tanh(t / h2) ** 2, delta=1e-12)

    def test_first_q_is_lmmse(self):
        rng = random.Random(2201)
        pts = constel.qam(4)
        n0 = 0.3
        for _ in range(5):
            h = iid(rng, 6, 4)
            y = cbb.awgn(rng, cbb.matvec(h, [pts[rng.randrange(4)] for _ in range(4)]), n0)
            yr, hr = real_model(y, h)
            mu, _ = ep_real(yr, hr, real_alphabet(pts), n0 / 2.0, iters=0)
            a = cbb.add(cbb.matmul(cbb.herm(h), h), cbb.scale(n0, cbb.eye(4)))
            want = cbb.solve(a, cbb.matvec(cbb.herm(h), y))
            for k in range(4):
                self.assertAlmostEqual(mu[k], want[k].real, delta=1e-9)
                self.assertAlmostEqual(mu[4 + k], want[k].imag, delta=1e-9)

    def test_page_example(self):
        h = [[1.0, 0.5], [0.5, 1.0]]
        y = [0.2, 0.6]
        bpsk = constel.pam(2)
        yr, hr = real_model(y, h, True)
        mu0, var0 = ep_real(yr, hr, [-1.0, 1.0], 0.3, iters=0)
        for got, want in zip(mu0 + var0, [0.0535, 0.4171, 0.3316, 0.3316]):
            self.assertAlmostEqual(got, want, delta=1e-4)
        mu1, var1 = ep_real(yr, hr, [-1.0, 1.0], 0.3, iters=1, damping=1.0)
        for got, want in zip(mu1 + var1, [-0.2261, 0.8505, 0.3087, 0.2766]):
            self.assertAlmostEqual(got, want, delta=1e-4)
        mu5, _ = ep_real(yr, hr, [-1.0, 1.0], 0.3, iters=5, damping=1.0)
        for a, b in zip(mu1, mu5):
            self.assertAlmostEqual(a, b, delta=1e-12)
        self.assertEqual(constel.ml_vector(y, h, bpsk), [1, 0])
        self.assertEqual(ep_detect(y, h, bpsk, 0.6, damping=1.0), [1, 0])

    def test_correlated_channel_can_fail(self):
        # Columns with correlation 3 / sqrt(10): EP settles on (-1, +1), ML is (+1, -1).
        h = [[2.0, 1.0], [1.0, 1.0]]
        y = [0.5, 0.6]
        bpsk = constel.pam(2)
        self.assertEqual(constel.ml_vector(y, h, bpsk), [0, 1])
        self.assertEqual(ep_detect(y, h, bpsk, 0.25, damping=1.0), [1, 0])
        yr, hr = real_model(y, h, True)
        mu, _ = ep_real(yr, hr, [-1.0, 1.0], 0.125, iters=10, damping=1.0)
        self.assertAlmostEqual(mu[0], -1.0, delta=1e-3)
        self.assertAlmostEqual(mu[1], 1.0, delta=1e-3)

    def test_orthogonal_channel_gives_exact_marginals(self):
        # H = U diag(d) with U a rotation, so H^H H is diagonal. The gains are small enough
        # that the cavity variance s2 / |d|^2 is above 0.9 = max a^2, so every update is kept.
        rng = random.Random(2202)
        pts = constel.qam(16)
        n0 = 1.0
        for _ in range(4):
            d = [0.6 * complex(math.cos(p), math.sin(p)) for p in (rng.uniform(0, 6.3), rng.uniform(0, 6.3))]
            d[1] *= 5.0 / 6.0
            phi = rng.uniform(0, 6.3)
            c, s = math.cos(phi), math.sin(phi)
            h = [[c * d[0], -s * d[1]], [s * d[0], c * d[1]]]
            y = cbb.awgn(rng, cbb.matvec(h, [pts[rng.randrange(16)] for _ in range(2)]), n0)
            yr, hr = real_model(y, h)
            mu, var = ep_real(yr, hr, real_alphabet(pts), n0 / 2.0, iters=40)
            mean, vexact = posterior_moments(y, h, pts, n0)
            for a, b in zip(mu, mean):
                self.assertAlmostEqual(a, b, delta=1e-6)
            for a, b in zip(var, vexact):
                self.assertAlmostEqual(a, b, delta=1e-6)

    def test_agrees_with_ml_at_high_snr(self):
        # 4-QAM, n = 4, m = 4, 15 dB, seed 2204: 97 of 100 in the reference run.
        rng = random.Random(2204)
        pts = constel.qam(4)
        n0 = cbb.undb(-15.0)
        agree = 0
        for _ in range(100):
            h = iid(rng, 4, 4)
            y = cbb.awgn(rng, cbb.matvec(h, [pts[rng.randrange(4)] for _ in range(4)]), n0)
            agree += ep_detect(y, h, pts, n0) == constel.ml_vector(y, h, pts)
        self.assertGreaterEqual(agree, 92)

    def test_fewer_errors_than_lmmse(self):
        # 4-QAM, n = m = 8, 10 dB, seed 2206, 40 vectors (320 symbols): 19 errors against 38.
        rng = random.Random(2206)
        pts = constel.qam(4)
        n0 = cbb.undb(-10.0)
        e_ep = e_lin = 0
        for _ in range(40):
            h = iid(rng, 8, 8)
            idx = [rng.randrange(4) for _ in range(8)]
            y = cbb.awgn(rng, cbb.matvec(h, [pts[i] for i in idx]), n0)
            e_ep += sum(a != b for a, b in zip(ep_detect(y, h, pts, n0), idx))
            e_lin += sum(a != b for a, b in zip(ep_detect(y, h, pts, n0, iters=0), idx))
        self.assertLessEqual(5 * e_ep, 3 * e_lin)


if __name__ == "__main__":
    unittest.main()

History

Minka (2001) introduced expectation propagation as a general method for approximate Bayesian inference, an extension of assumed-density filtering that can revisit each factor. It has been used for many models since. Céspedes, Olmos, Sánchez-Fernández and Pérez-Cruz (2014) applied EP to MIMO detection with high-order constellations, with the real-valued model, the rule for negative precisions and damping. They reported a large gain over MMSE at a complexity of the same cubic order. Later work extended EP detection to massive MIMO with lower-cost inverses and to iterative receivers with channel decoding.

References

  1. Javier Céspedes, Pablo M. Olmos, Matilde Sánchez-Fernández and Fernando Pérez-Cruz, Expectation propagation detection for high-order high-dimensional MIMO systems, IEEE Transactions on Communications 62(8), 2840-2849, 2014, the EP detector for the real-valued MIMO model: the Gaussian site factors, the cavity and moment-matching updates, the rule that keeps the old site when the new precision is negative, the damping, and the comparison with MMSE and other detectors
  2. Thomas P. Minka, Expectation propagation for approximate Bayesian inference, Proc. 17th Conference on Uncertainty in Artificial Intelligence (UAI), 2001, the general EP algorithm: exponential-family approximation, removal of one site, moment matching and the site update

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