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.
- Solves
- MIMO detection
- 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
- Model
- Real RAM
- Properties
- deterministicexact mlnot needs csit
- Evidence
- Proof sketchCode in 1 languages
- 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 channel gains, the same as maximal ratio combining over branches with half the power on each. So the code reaches the full diversity order with 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 receive antennas. The gain from transmit antenna to receive antenna is known at the receiver and stays fixed for two symbol periods. The transmitter sends the codeword
where row is antenna and column is slot , and are points of a constellation of points. Receive antenna sees
with independent noise samples . When the total symbol energy is split over the two antennas, each antenna sends with amplitude , and this factor is part of the below. The output is a maximum likelihood decision on the pair .
The algorithm
ALAMOUTI-ENCODE(s1, s2) ▷ rows are antennas, columns are slots- 1
row 1 ← (s1, -conj(s2)) - 2
row 2 ← (s2, conj(s1)) ALAMOUTI-DECODE(y, h, A) ▷ y[i] = (y_i1, y_i2), h[i] = (h_i1, h_i2), i = 1..m- 3
g ← Σ_i (|h_i1|² + |h_i2|²) - 4
z1 ← Σ_i (conj(h_i1) y_i1 + h_i2 conj(y_i2)) - 5
z2 ← Σ_i (conj(h_i2) y_i1 - h_i1 conj(y_i2)) - 6
u1 ← z1 / g ; u2 ← z2 / g - 7
return (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 with independent . Line L7 can use the slicer of the minimum distance detector for PAM, square QAM or PSK.
Example
One receive antenna, QPSK. Take , , and . The noise samples are and .
| quantity | value |
|---|---|
| (line L3) | |
| (line L4) | |
| (line L5) | |
| , (line L6) | , |
The noise parts of and are and ; there is no trace of the other symbol. Line L7 returns at squared distance from , and at squared distance from . Both decisions are correct.
Error rate. With BPSK, one receive antenna, i.i.d. Rayleigh gains and a total 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: . One antenna at 10 dB gives , and one transmitter with two receive antennas at 10 dB gives . 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 with a matrix that satisfies . Lines L4 and L5 compute , and the noise has the covariance . Expanding gives a constant plus , a sum of one term for each symbol, so the joint minimum over is the pair of separate minima of line L7. A Chernoff bound on each symbol, averaged over i.i.d. Rayleigh gains, gives the diversity order . 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 receive antennas. Receive antenna sees, in the two slots of one block,
where the gains are known to the receiver and stay fixed over the block, and the noise samples are independent . The symbols are independent and uniform on a finite set . Write and assume .
Lemma 1 (the equivalent channel). Let and . Then with and
Stack the blocks into , with of size . Then , and .
Proof. The first row is the first slot as it is. The conjugate of the second slot is , which is the second row. For each , the two columns of are and . Then and . Summing over gives . If , then 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.
Lemma 2 (the combiner). The lines L4 and L5 compute . So , where are independent .
Proof. The first row of is and the second row is . Applied to , they give and , which are the terms of lines L4 and L5. So by Lemma 1. The vector is circularly symmetric Gaussian with covariance . A circularly symmetric Gaussian vector with a diagonal covariance has independent entries.
Theorem 1 (maximum likelihood). For every received block, the pair returned by line L7 minimizes over . So it is a maximum likelihood decision of .
Proof. The likelihood of is proportional to , by Lemma 1. Expand the norm and use and :
The first two terms do not depend on . The last sum has one term for and one term for , and ranges over the full product . So the minimum is reached when each is a point of nearest to , which is what lines L6 and L7 compute. Ties happen only on the boundaries between decision regions, a set of probability zero.
Theorem 2 (diversity order ). Let the gains be i.i.d. , and let each antenna send with amplitude , so that the total transmit energy per slot is on average for unit-energy symbols. Let . Then the pairwise error probability between two symbols in satisfies
and the symbol error probability falls as at high SNR.
Proof. With the amplitude included in the gains, . By Lemma 2 the decision on is a scalar decision in the channel , with noise variance . Given the channel, the probability that is nearer than to when was sent is . The bound for gives at most . The variable is a sum of independent exponential variables of mean 1, and for and . So the average is
The union bound over the wrong symbols gives a symbol error probability at most a constant times . For the lower bound, the error event contains the event that the sum of the exponential variables is below ; this event has a probability of order , and on it the conditional error probability stays above a positive constant. So the exponent is exactly .
Cost. Line L3 and lines L4 and L5 each do complex operations. Lines L6 and L7 do two divisions and two nearest-point searches; the search is by brute force and with a slicer for PAM, square QAM or PSK.
Complexity
Lines L3 to L5 each sum terms, so the combiner costs complex operations per block of two symbols. Line L7 costs with a brute force search and with a slicer. Joint maximum likelihood detection of a general 2 by 2 code costs by brute force, so the orthogonal structure removes a factor of . The extra space is .
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 with , 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 , the code sends one symbol per slot, while the 2 by channel supports two streams; its tradeoff curve on the 2 by 2 channel is , below the optimal diversity-multiplexing tradeoff for . With and Gaussian symbols, it reaches the capacity of the 2 by 1 channel with CSIR (a theorem): each symbol sees the SNR , and 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 ; 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 and . The same holds for frequency selectivity across two subcarriers in the space-frequency form.
- Conjugate the right sample. The combiner uses , not . Mixing the conventions of different textbooks (signs on or on ) 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 and , 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.
# 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
- 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)
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 04NE33 Edit this page History Report an error Markdown