Algorithm Search⌘K

Algorithmcore

Alamouti code

Also called Alamouti scheme.

A space-time block code for two transmit antennas that gets full diversity at full rate with simple linear decoding.

Time
Θ(m + M) worst
Space
Θ(1) extra
Counts
time with slicer Θ(m) worst
Where
M = the number of constellation points; m = the number of receive antennas
Properties
deterministicexact mlnot needs csit
Origin
Siavash M. Alamouti, 1998

The Alamouti code sends two symbols from two transmit antennas over two time slots, with the second slot a conjugated and swapped copy of the first. The receiver needs no joint search: a linear combiner separates the two symbols, and each one sees a channel with the sum of all 2m2m channel gains, the same as maximal ratio combining over 2m2m branches with half the power on each. So the code reaches the full diversity order 2m2m with mm receive antennas at a rate of one symbol per slot, and the transmitter needs no channel knowledge. The Alamouti code is the 2 by 2 case of the orthogonal space-time block codes; OSTBCs for more antennas keep the linear decoder but lose rate. The rank and determinant criteria explain why the code has full diversity. Space-time trellis codes add coding gain at the cost of a trellis search, and the golden code sends two symbols per slot on a 2 by 2 channel at the cost of a joint decoder.

In plain words

A base station has two antennas, and a phone has one. If the phone sits in a deep fade from one antenna, the other antenna may still reach it well. The Alamouti code makes use of both paths without the base station knowing which one is good.

In the first time slot, the two antennas send two different symbols. In the second slot, they send the same two symbols again, but swapped, with one sign flipped and both mirrored. The phone receives two mixed values. It adds and subtracts them with weights from the channel, and the mixing cancels exactly: one output holds only the first symbol and the other holds only the second. Each symbol arrives as strong as the two paths together. The phone then picks the nearest point for each symbol, one at a time.

The problem

The channel has two transmit antennas and mm receive antennas. The gain hikh_{ik} from transmit antenna kk to receive antenna ii is known at the receiver and stays fixed for two symbol periods. The transmitter sends the codeword

X=(s1−s2∗s2s1∗),X = \begin{pmatrix} s_1 & -s_2^* \\ s_2 & s_1^* \end{pmatrix},

where row kk is antenna kk and column tt is slot tt, and s1,s2s_1, s_2 are points of a constellation A\mathcal{A} of MM points. Receive antenna ii sees

yi1=hi1s1+hi2s2+wi1,yi2=−hi1s2∗+hi2s1∗+wi2,y_{i1} = h_{i1} s_1 + h_{i2} s_2 + w_{i1}, \qquad y_{i2} = -h_{i1} s_2^* + h_{i2} s_1^* + w_{i2},

with independent noise samples w∼CN(0,N0)w \sim \mathcal{CN}(0, N_0). When the total symbol energy EsE_s is split over the two antennas, each antenna sends with amplitude Es/2\sqrt{E_s/2}, and this factor is part of the hikh_{ik} below. The output is a maximum likelihood decision on the pair (s1,s2)(s_1, s_2).

The algorithm

  1. ALAMOUTI-ENCODE(s1, s2) ▷ rows are antennas, columns are slots
  2. 1row 1 ← (s1, -conj(s2))
  3. 2row 2 ← (s2, conj(s1))
  4. ALAMOUTI-DECODE(y, h, A) ▷ y[i] = (y_i1, y_i2), h[i] = (h_i1, h_i2), i = 1..m
  5. 3g ← Σ_i (|h_i1|² + |h_i2|²)
  6. 4z1 ← Σ_i (conj(h_i1) y_i1 + h_i2 conj(y_i2))
  7. 5z2 ← Σ_i (conj(h_i2) y_i1 - h_i1 conj(y_i2))
  8. 6u1 ← z1 / g ; u2 ← z2 / g
  9. 7return (nearest point of A to u1, nearest point of A to u2)

Lines L4 and L5 are the matched filter of the equivalent channel: after the second slot is conjugated, the two symbols see orthogonal columns of equal norm. So zk=gsk+nkz_k = g s_k + n_k with n1,n2n_1, n_2 independent CN(0,gN0)\mathcal{CN}(0, g N_0). Line L7 can use the slicer of the minimum distance detector for PAM, square QAM or PSK.

Example

One receive antenna, QPSK. Take h11=0.6+0.8jh_{11} = 0.6 + 0.8j, h12=−1+0.5jh_{12} = -1 + 0.5j, s1=(1+j)/2s_1 = (1 + j)/\sqrt2 and s2=(−1+j)/2s_2 = (-1 + j)/\sqrt2. The noise samples are w11=0.1−0.2jw_{11} = 0.1 - 0.2j and w12=−0.15+0.05jw_{12} = -0.15 + 0.05j.

quantity value
y11y_{11} 0.3121−0.2707j0.3121 - 0.2707j
y12y_{12} −0.6450+2.1006j-0.6450 + 2.1006j
gg (line L3) 0.36+0.64+1+0.25=2.250.36 + 0.64 + 1 + 0.25 = 2.25
z1z_1 (line L4) 1.6660+1.3660j1.6660 + 1.3660j
z2z_2 (line L5) −1.7410+1.8910j-1.7410 + 1.8910j
u1u_1, u2u_2 (line L6) 0.7404+0.6071j0.7404 + 0.6071j, −0.7738+0.8404j-0.7738 + 0.8404j

The noise parts of z1z_1 and z2z_2 are h11∗w11+h12w12∗=0.075−0.225jh_{11}^* w_{11} + h_{12} w_{12}^* = 0.075 - 0.225j and h12∗w11−h11w12∗=−0.15+0.3jh_{12}^* w_{11} - h_{11} w_{12}^* = -0.15 + 0.3j; there is no trace of the other symbol. Line L7 returns (1+j)/2(1 + j)/\sqrt2 at squared distance 0.01110.0111 from u1u_1, and (−1+j)/2(-1 + j)/\sqrt2 at squared distance 0.02220.0222 from u2u_2. Both decisions are correct.

Error rate. With BPSK, one receive antenna, i.i.d. Rayleigh gains and a total Es/N0E_s/N_0 of 10 dB, the bit error rate of the Alamouti code is that of maximal ratio combining over two branches at 5 (7 dB) each: 0.00552820.0055282. One antenna at 10 dB gives 0.0232690.023269, and one transmitter with two receive antennas at 10 dB gives 0.00159910.0015991. The 3 dB gap to receive combining is the price of splitting the power without channel knowledge (closed forms, Rayleigh fading).

Correctness

The decoder returns a maximum likelihood decision of the pair. Conjugate the second slot of each receive antenna, and the block becomes y~=Gs+w~\tilde y = G s + \tilde w with a 2m×22m \times 2 matrix GG that satisfies GHG=gIG^H G = g I. Lines L4 and L5 compute z=GHy~=gs+GHw~z = G^H \tilde y = g s + G^H \tilde w, and the noise GHw~G^H \tilde w has the covariance gN0Ig N_0 I. Expanding ∥y~−Gs∥2\|\tilde y - G s\|^2 gives a constant plus g∑k∣sk−zk/g∣2g \sum_k |s_k - z_k/g|^2, a sum of one term for each symbol, so the joint minimum over A2\mathcal{A}^2 is the pair of separate minima of line L7. A Chernoff bound on each symbol, averaged over 2m2m i.i.d. Rayleigh gains, gives the diversity order 2m2m. The full proof is below.

Proof: The Alamouti combiner decouples the two symbols, its decisions are maximum likelihood, and the diversity order is 2mfull

The model has two transmit antennas and mm receive antennas. Receive antenna ii sees, in the two slots of one block,

yi1=hi1s1+hi2s2+wi1,yi2=−hi1s2∗+hi2s1∗+wi2,y_{i1} = h_{i1} s_1 + h_{i2} s_2 + w_{i1}, \qquad y_{i2} = -h_{i1} s_2^* + h_{i2} s_1^* + w_{i2},

where the gains hikh_{ik} are known to the receiver and stay fixed over the block, and the 2m2m noise samples are independent CN(0,N0)\mathcal{CN}(0, N_0). The symbols s1,s2s_1, s_2 are independent and uniform on a finite set A\mathcal{A}. Write g=∑i(∣hi1∣2+∣hi2∣2)g = \sum_i (|h_{i1}|^2 + |h_{i2}|^2) and assume g>0g > 0.

Lemma 1 (the equivalent channel). Let y~i=(yi1,yi2∗)T\tilde y_i = (y_{i1}, y_{i2}^*)^T and w~i=(wi1,wi2∗)T\tilde w_i = (w_{i1}, w_{i2}^*)^T. Then y~i=Gis+w~i\tilde y_i = G_i s + \tilde w_i with s=(s1,s2)Ts = (s_1, s_2)^T and

Gi=(hi1hi2hi2∗−hi1∗).G_i = \begin{pmatrix} h_{i1} & h_{i2} \\ h_{i2}^* & -h_{i1}^* \end{pmatrix}.

Stack the mm blocks into y~=Gs+w~\tilde y = G s + \tilde w, with GG of size 2m×22m \times 2. Then GHG=gI2G^H G = g I_2, and w~∼CN(0,N0I2m)\tilde w \sim \mathcal{CN}(0, N_0 I_{2m}).

Proof. The first row is the first slot as it is. The conjugate of the second slot is yi2∗=−hi1∗s2+hi2∗s1+wi2∗y_{i2}^* = -h_{i1}^* s_2 + h_{i2}^* s_1 + w_{i2}^*, which is the second row. For each ii, the two columns of GiG_i are c1=(hi1,hi2∗)Tc_1 = (h_{i1}, h_{i2}^*)^T and c2=(hi2,−hi1∗)Tc_2 = (h_{i2}, -h_{i1}^*)^T. Then c1Hc1=c2Hc2=∣hi1∣2+∣hi2∣2c_1^H c_1 = c_2^H c_2 = |h_{i1}|^2 + |h_{i2}|^2 and c1Hc2=hi1∗hi2−hi2hi1∗=0c_1^H c_2 = h_{i1}^* h_{i2} - h_{i2} h_{i1}^* = 0. Summing over ii gives GHG=gI2G^H G = g I_2. If w∼CN(0,N0)w \sim \mathcal{CN}(0, N_0), then w∗w^* has the same law, because the law is invariant under conjugation (the real and imaginary parts are independent with equal variance). Conjugation of one sample does not change the independence of the samples. □\square

Lemma 2 (the combiner). The lines L4 and L5 compute (z1,z2)T=GHy~(z_1, z_2)^T = G^H \tilde y. So zk=gsk+nkz_k = g s_k + n_k, where n1,n2n_1, n_2 are independent CN(0,gN0)\mathcal{CN}(0, g N_0).

Proof. The first row of GiHG_i^H is (hi1∗,hi2)(h_{i1}^*, h_{i2}) and the second row is (hi2∗,−hi1)(h_{i2}^*, -h_{i1}). Applied to y~i\tilde y_i, they give hi1∗yi1+hi2yi2∗h_{i1}^* y_{i1} + h_{i2} y_{i2}^* and hi2∗yi1−hi1yi2∗h_{i2}^* y_{i1} - h_{i1} y_{i2}^*, which are the terms of lines L4 and L5. So GHy~=GHGs+GHw~=gs+nG^H \tilde y = G^H G s + G^H \tilde w = g s + n by Lemma 1. The vector n=GHw~n = G^H \tilde w is circularly symmetric Gaussian with covariance GH(N0I)G=gN0I2G^H (N_0 I) G = g N_0 I_2. A circularly symmetric Gaussian vector with a diagonal covariance has independent entries. □\square

Theorem 1 (maximum likelihood). For every received block, the pair returned by line L7 minimizes ∥y~−Gs∥2\|\tilde y - G s\|^2 over s∈A2s \in \mathcal{A}^2. So it is a maximum likelihood decision of (s1,s2)(s_1, s_2).

Proof. The likelihood of ss is proportional to exp⁡(−∥y~−Gs∥2/N0)\exp(-\|\tilde y - G s\|^2 / N_0), by Lemma 1. Expand the norm and use GHG=gIG^H G = g I and GHy~=zG^H \tilde y = z:

∥y~−Gs∥2=∥y~∥2−2 Re(sHz)+g∥s∥2=∥y~∥2−∥z∥2g+g∑k=12∣sk−zkg∣2.\|\tilde y - G s\|^2 = \|\tilde y\|^2 - 2\,\mathrm{Re}(s^H z) + g \|s\|^2 = \|\tilde y\|^2 - \frac{\|z\|^2}{g} + g \sum_{k=1}^{2} \left| s_k - \frac{z_k}{g} \right|^2.

The first two terms do not depend on ss. The last sum has one term for s1s_1 and one term for s2s_2, and ss ranges over the full product A×A\mathcal{A} \times \mathcal{A}. So the minimum is reached when each sks_k is a point of A\mathcal{A} nearest to zk/gz_k / g, which is what lines L6 and L7 compute. Ties happen only on the boundaries between decision regions, a set of probability zero. ■\blacksquare

Theorem 2 (diversity order 2m2m). Let the 2m2m gains be i.i.d. CN(0,1)\mathcal{CN}(0, 1), and let each antenna send with amplitude Es/2\sqrt{E_s/2}, so that the total transmit energy per slot is EsE_s on average for unit-energy symbols. Let γˉ=Es/N0\bar\gamma = E_s/N_0. Then the pairwise error probability between two symbols a≠ba \ne b in A\mathcal{A} satisfies

P(a→b)≤(1+γˉ ∣a−b∣28)−2m,P(a \to b) \le \left(1 + \frac{\bar\gamma\,|a - b|^2}{8}\right)^{-2m},

and the symbol error probability falls as γˉ−2m\bar\gamma^{-2m} at high SNR.

Proof. With the amplitude included in the gains, g=(Es/2)∑i(∣hi1∣2+∣hi2∣2)g = (E_s/2) \sum_i (|h_{i1}|^2 + |h_{i2}|^2). By Lemma 2 the decision on sks_k is a scalar decision in the channel zk/g=sk+nk/gz_k / g = s_k + n_k / g, with noise variance N0/gN_0 / g. Given the channel, the probability that bb is nearer than aa to zk/gz_k / g when aa was sent is Q(g∣a−b∣2/(2N0))Q\big(\sqrt{g |a - b|^2 / (2 N_0)}\big). The bound Q(x)≤exp⁡(−x2/2)Q(x) \le \exp(-x^2/2) for x≥0x \ge 0 gives at most exp⁡(−g∣a−b∣2/(4N0))\exp(-g |a - b|^2 / (4 N_0)). The variable ∑i(∣hi1∣2+∣hi2∣2)\sum_i (|h_{i1}|^2 + |h_{i2}|^2) is a sum of 2m2m independent exponential variables of mean 1, and E e−tX=1/(1+t)\mathbb{E}\, e^{-t X} = 1/(1 + t) for X∼Exp(1)X \sim \mathrm{Exp}(1) and t≥0t \ge 0. So the average is

Eexp⁡ ⁣(−γˉ∣a−b∣28∑i(∣hi1∣2+∣hi2∣2))=(1+γˉ∣a−b∣28)−2m.\mathbb{E} \exp\!\left(-\frac{\bar\gamma |a - b|^2}{8} \sum_i (|h_{i1}|^2 + |h_{i2}|^2)\right) = \left(1 + \frac{\bar\gamma |a - b|^2}{8}\right)^{-2m}.

The union bound over the ∣A∣−1|\mathcal{A}| - 1 wrong symbols gives a symbol error probability at most a constant times γˉ−2m\bar\gamma^{-2m}. For the lower bound, the error event contains the event that the sum of the 2m2m exponential variables is below 1/γˉ1/\bar\gamma; this event has a probability of order γˉ−2m\bar\gamma^{-2m}, and on it the conditional error probability stays above a positive constant. So the exponent is exactly 2m2m. □\square

Cost. Line L3 and lines L4 and L5 each do Θ(m)\Theta(m) complex operations. Lines L6 and L7 do two divisions and two nearest-point searches; the search is Θ(∣A∣)\Theta(|\mathcal{A}|) by brute force and Θ(1)\Theta(1) with a slicer for PAM, square QAM or PSK.

Complexity

Lines L3 to L5 each sum mm terms, so the combiner costs Θ(m)\Theta(m) complex operations per block of two symbols. Line L7 costs Θ(M)\Theta(M) with a brute force search and Θ(1)\Theta(1) with a slicer. Joint maximum likelihood detection of a general 2 by 2 code costs Θ(mM2)\Theta(m M^2) by brute force, so the orthogonal structure removes a factor of MM. The extra space is Θ(1)\Theta(1).

Properties

  • Rate one. Two symbols in two slots, the highest rate of any complex orthogonal design.
  • Full diversity. The difference of two distinct codewords is Δ=(e1−e2∗e2e1∗)\Delta = \begin{pmatrix} e_1 & -e_2^* \\ e_2 & e_1^* \end{pmatrix} with ΔΔH=(∣e1∣2+∣e2∣2)I\Delta \Delta^H = (|e_1|^2 + |e_2|^2) I, so it has rank 2 for every pair; see the rank and determinant criteria.
  • No channel knowledge at the transmitter. Compare maximum ratio transmission, which needs the channel at the transmitter and has a 3 dB array gain over the Alamouti code with one receive antenna.
  • Not capacity achieving for two or more receive antennas. With m≥2m \ge 2, the code sends one symbol per slot, while the 2 by mm channel supports two streams; its tradeoff curve on the 2 by 2 channel is 4(1−r)4(1 - r), below the optimal diversity-multiplexing tradeoff for r>0r > 0. With m=1m = 1 and Gaussian symbols, it reaches the capacity of the 2 by 1 channel with CSIR (a theorem): each symbol sees the SNR (ρ/2)(∣h11∣2+∣h12∣2)(\rho/2)(|h_{11}|^2 + |h_{12}|^2), and log⁡2\log_2 of one plus this SNR is the 2 by 1 capacity with equal power.
  • Unit-modulus not needed. The decoupling holds for any complex symbols, including QAM.

Variants and improvements

  • Space-frequency block coding. In OFDM, the two columns go on two adjacent subcarriers instead of two slots. The channel must then be flat over the two subcarriers.
  • Orthogonal designs for more antennas. For three or four antennas, the rate drops to 3/43/4; see orthogonal space-time block codes.
  • Differential Alamouti. Tarokh and Jafarkhani built a differential version that needs no channel estimate. As for other differential schemes, it loses about 3 dB against coherent detection.
  • Quasi-orthogonal codes. Jafarkhani's quasi-orthogonal codes reach rate one for four antennas by giving up full orthogonality, so pairs of symbols must be decoded jointly.
  • Full-rate codes. For two receive antennas, the golden code sends four symbols in two slots with full diversity and a nonvanishing determinant.

When to use it

Use the Alamouti code when a transmitter has two antennas, has no channel knowledge, and wants diversity at a low decoder cost: downlink transmit diversity in cellular systems is the standard case. When the receiver has two or more antennas and the SNR is high, spatial multiplexing or the golden code gives more rate. When the transmitter knows the channel, beamforming such as maximum ratio transmission gives an extra array gain.

Pitfalls

  • The channel must stay constant over two slots. Fast fading breaks the orthogonality and leaves interference between s1s_1 and s2s_2. The same holds for frequency selectivity across two subcarriers in the space-frequency form.
  • Conjugate the right sample. The combiner uses yi2∗y_{i2}^*, not yi2y_{i2}. Mixing the conventions of different textbooks (signs on s2∗s_2^* or on s1∗s_1^*) gives a combiner that does not decouple.
  • Power normalization. Each antenna must send with half the power, so that the total equals the one-antenna case. Without this, the gain over one antenna looks 3 dB better than it is.
  • Channel estimation. The decoder needs both hi1h_{i1} and hi2h_{i2}, so the pilots must be orthogonal across the two antennas.
  • Diversity is not rate. With two receive antennas, the code gives no multiplexing gain; see spatial multiplexing.

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.

alamouti_code.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alamouti-code/. The authors are listed in prov/04NE33.jsonl.

"""The Alamouti space-time block code: encoder, linear combiner and detector.

A codeword is the 2 by 2 matrix X = [[s1, -conj(s2)], [s2, conj(s1)]]. Row k
is transmit antenna k and column t is time slot t. Receive antenna i sees

    y[i][0] = h[i][0] s1 + h[i][1] s2 + w
    y[i][1] = -h[i][0] conj(s2) + h[i][1] conj(s1) + w

where h[i][k] is the effective gain from transmit antenna k to receive
antenna i. The effective gain includes any amplitude scale, for example
sqrt(Es / 2) when the total symbol energy Es is split over two antennas.
The channel must stay constant over the two slots.

The combiner returns z_k = g s_k + noise with g = sum |h[i][k]|^2, and the
detector picks the point nearest to z_k / g for each k. Because the two
columns of the equivalent channel are orthogonal and have the same norm, this
is the joint maximum likelihood decision of the pair (s1, s2).
"""


def encode(s1: complex, s2: complex) -> list[list[complex]]:
    """The codeword X, with rows as antennas and columns as time slots."""
    s1, s2 = complex(s1), complex(s2)
    return [[s1, -s2.conjugate()],  # @line L1
            [s2, s1.conjugate()]]  # @line L2


def transmit(x: list[list[complex]], h: list[list[complex]]) -> list[list[complex]]:
    """The noiseless received block: y[i][t] = sum over k of h[i][k] x[k][t]."""
    return [[sum(row[k] * x[k][t] for k in range(2)) for t in range(2)] for row in h]


def combine(y: list[list[complex]], h: list[list[complex]]) -> tuple[complex, complex, float]:
    """The combiner outputs (z1, z2, g) for the received block y and the channel h (one row per receive antenna)."""
    if len(y) != len(h) or not h:
        raise ValueError("y and h need one row for each receive antenna")
    hp = [(complex(row[0]), complex(row[1])) for row in h]
    yp = [(complex(row[0]), complex(row[1])) for row in y]
    g = sum(abs(a) ** 2 + abs(b) ** 2 for a, b in hp)  # @line L3
    z1 = sum(a.conjugate() * r1 + b * r2.conjugate() for (a, b), (r1, r2) in zip(hp, yp))  # @line L4
    z2 = sum(b.conjugate() * r1 - a * r2.conjugate() for (a, b), (r1, r2) in zip(hp, yp))  # @line L5
    return z1, z2, g


def _nearest(u: complex, points: list[complex]) -> int:
    best, arg = float("inf"), -1
    for i, p in enumerate(points):
        d = abs(u - p) ** 2
        if d < best:
            best, arg = d, i
    return arg


def decode(y: list[list[complex]], h: list[list[complex]], points: list[complex]) -> tuple[int, int]:
    """The indices into points of the decisions on s1 and s2."""
    z1, z2, g = combine(y, h)
    if g == 0:
        raise ValueError("the channel is zero")
    u1, u2 = z1 / g, z2 / g  # @line L6
    return _nearest(u1, points), _nearest(u2, points)  # @line L7
cbb.py 315 lines
# 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))
test_alamouti_code.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alamouti-code/. The authors are listed in prov/04NE33.jsonl.

import math
import random

import cbb
import constel
from alamouti_code import combine, decode, encode, transmit


def _rayleigh(rng: random.Random, nr: int, amp: float = 1.0) -> list[list[complex]]:
    return [[amp * cbb.cn(rng, 1.0), amp * cbb.cn(rng, 1.0)] for _ in range(nr)]


def _noisy(rng: random.Random, x, h, n0: float):
    return [cbb.awgn(rng, row, n0) for row in transmit(x, h)]


def _mrc_bpsk(branches: int, snr: float) -> float:
    """The exact BPSK bit error rate of maximal ratio combining over i.i.d. Rayleigh branches of mean SNR snr."""
    mu = math.sqrt(snr / (1 + snr))
    return ((1 - mu) / 2) ** branches * sum(
        math.comb(branches - 1 + k, k) * ((1 + mu) / 2) ** k for k in range(branches))


def test_encoder_is_orthogonal() -> None:
    rng = random.Random(1)
    for _ in range(50):
        s1, s2 = cbb.cn(rng, 1.0), cbb.cn(rng, 1.0)
        x = encode(s1, s2)
        assert x == [[s1, -s2.conjugate()], [s2, s1.conjugate()]]
        gram = cbb.matmul(x, cbb.herm(x))
        e = abs(s1) ** 2 + abs(s2) ** 2
        assert cbb.norm2(cbb.sub(gram, cbb.scale(e, cbb.eye(2)))) < 1e-24


def test_worked_example() -> None:
    h = [[0.6 + 0.8j, -1 + 0.5j]]
    s = 1 / math.sqrt(2)
    s1, s2 = complex(s, s), complex(-s, s)
    y = transmit(encode(s1, s2), h)
    y = [[y[0][0] + (0.1 - 0.2j), y[0][1] + (-0.15 + 0.05j)]]
    z1, z2, g = combine(y, h)
    assert abs(g - 2.25) < 1e-12
    assert abs(z1 - (1.66599026 + 1.36599026j)) < 1e-7
    assert abs(z2 - (-1.74099026 + 1.89099026j)) < 1e-7
    pts = constel.qam(4)
    assert decode(y, h, pts) == (pts.index(min(pts, key=lambda p: abs(p - s1))),
                                 pts.index(min(pts, key=lambda p: abs(p - s2))))


def test_noiseless_round_trip() -> None:
    rng = random.Random(2)
    for pts in (constel.qam(4), constel.qam(16), constel.psk(8)):
        for nr in (1, 2, 3):
            for _ in range(40):
                h = _rayleigh(rng, nr)
                i1, i2 = rng.randrange(len(pts)), rng.randrange(len(pts))
                y = transmit(encode(pts[i1], pts[i2]), h)
                z1, z2, g = combine(y, h)
                assert abs(z1 - g * pts[i1]) < 1e-9 and abs(z2 - g * pts[i2]) < 1e-9
                assert decode(y, h, pts) == (i1, i2)


def test_matches_brute_force_ml() -> None:
    # The stacked real model per receive antenna i:
    # [y_i1; conj(y_i2)] = [[h_i1, h_i2], [conj(h_i2), -conj(h_i1)]] [s1; s2] + noise.
    rng = random.Random(3)
    for pts, n0 in ((constel.qam(4), 0.5), (constel.qam(16), 0.1), (constel.psk(8), 0.2)):
        for nr in (1, 2):
            for _ in range(60):
                h = _rayleigh(rng, nr)
                x = encode(rng.choice(pts), rng.choice(pts))
                y = _noisy(rng, x, h, n0)
                stack_y, stack_h = [], []
                for (a, b), (r1, r2) in zip(h, y):
                    stack_y += [r1, r2.conjugate()]
                    stack_h += [[a, b], [b.conjugate(), -a.conjugate()]]
                assert list(decode(y, h, pts)) == constel.ml_vector(stack_y, stack_h, pts)


def test_combined_noise_variance() -> None:
    # With x = 0, z_k is pure noise of variance g N0 for a fixed channel.
    rng = random.Random(4)
    h = [[0.6 + 0.8j, -1 + 0.5j], [0.3j, 0.9]]
    n0, n = 0.4, 6000
    zero = encode(0, 0)
    acc1 = acc2 = cross = 0.0
    g = 0.0
    for _ in range(n):
        z1, z2, g = combine(_noisy(rng, zero, h, n0), h)
        acc1 += abs(z1) ** 2
        acc2 += abs(z2) ** 2
        cross += (z1 * z2.conjugate()).real
    assert abs(acc1 / n / (g * n0) - 1) < 0.07
    assert abs(acc2 / n / (g * n0) - 1) < 0.07
    assert abs(cross / n) < 0.07 * g * n0


def test_bpsk_bit_error_rate_equals_mrc_of_order_2nr() -> None:
    # Total Es/N0 = gamma, each antenna sends with amplitude sqrt(1/2). The
    # combiner output has the error rate of MRC over 2 Nr branches of mean SNR gamma / 2.
    pts = constel.pam(2)
    for seed, nr, snr_db, blocks in ((5, 1, 10.0, 10000), (6, 2, 4.0, 8000)):
        rng = random.Random(seed)
        gamma = cbb.undb(snr_db)
        n0 = 1 / gamma
        errors = 0
        for _ in range(blocks):
            h = _rayleigh(rng, nr, math.sqrt(0.5))
            i1, i2 = rng.randrange(2), rng.randrange(2)
            y = _noisy(rng, encode(pts[i1], pts[i2]), h, n0)
            d1, d2 = decode(y, h, pts)
            errors += (d1 != i1) + (d2 != i2)
        expect = _mrc_bpsk(2 * nr, gamma / 2)
        assert expect * 2 * blocks >= 100
        lo, hi = cbb.wilson(errors, 2 * blocks)
        assert lo <= expect <= hi
    assert abs(_mrc_bpsk(2, 5.0) - 0.0055282) < 5e-7
    assert abs(_mrc_bpsk(4, cbb.undb(4.0) / 2) - 0.0065994) < 5e-7


def test_rejects_bad_input() -> None:
    try:
        decode([[1, 1]], [[0, 0]], constel.qam(4))
    except ValueError:
        pass
    else:
        raise AssertionError("a zero channel must raise")
    try:
        combine([[1, 1]], [[1, 1], [1, 1]])
    except ValueError:
        pass
    else:
        raise AssertionError("mismatched rows must raise")

History

Siavash Alamouti published the scheme in October 1998 in the IEEE Journal on Selected Areas in Communications, as a two-branch transmit diversity method whose performance with one receiver equals that of two-branch receive combining with the same total power, minus 3 dB. Tarokh, Seshadri and Calderbank had given the rank and determinant criteria for space-time codes earlier in 1998, and in 1999 Tarokh, Jafarkhani and Calderbank showed that the code is an instance of a complex orthogonal design and generalized it to more antennas. The code entered the third-generation cellular standards as space-time transmit diversity, and its space-frequency form is the two-antenna transmit diversity mode of LTE.

References

  1. Siavash M. Alamouti, A simple transmit diversity technique for wireless communications, IEEE Journal on Selected Areas in Communications 16(8), 1451-1458, 1998, the whole paper (the two-branch transmit scheme with one receiver, its extension to M receivers and the comparison with maximal ratio combining)
  2. Vahid Tarokh, Hamid Jafarkhani and A. Robert Calderbank, Space-time block codes from orthogonal designs, IEEE Transactions on Information Theory 45(5), 1456-1467, 1999, the definition of orthogonal designs and the linear maximum likelihood decoder, of which the Alamouti code is the 2 by 2 complex case
  3. David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, Section 3.3.2, Transmit diversity - space-time codes (the Alamouti scheme and the determinant criterion)
  4. Arogyaswami Paulraj, Rohit Nabar and Dhananjay Gore, Introduction to Space-Time Wireless Communications, Cambridge University Press, 2003, Chapter 5, Spatial diversity, and Chapter 6, Space-time coding without channel knowledge at the transmitter

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of time_with_slicer.worst
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