---
title: "Fading lab: Rayleigh channels, diversity and outage"
heading: Simulating BPSK with maximal-ratio combining over Rayleigh fading, outage probability with diversity, Clarke's Doppler channel with its autocorrelation and level crossings, and Alamouti transmit diversity
eyebrow: S8 · Lesson 50 · Fading lab
xp: 60
---

::: hook
The formulas of lessons 43 to 46 describe fading channels through their statistics: an exponential distribution of power, a Bessel-function autocorrelation, a gamma distribution after combining. In this lab you'll generate fading channels sample by sample and check those statistics directly, then measure what diversity buys: error rates that fall as the SNR to the power L, outages that vanish, and Alamouti's trick of getting two-antenna diversity from the transmitter side with nothing to feed back.
:::

::: play
- The curves are the outage probability at rate R of a Rayleigh channel with L independent branches combined: $1 - e^{-x}\sum_{k=0}^{L-1}x^k/k!$ with $x = (2^R - 1)/\text{SNR}$.
- Each extra branch steepens the curve: at high SNR the outage falls as $\text{SNR}^{-L}$.
- At 20 dB and 2 bit/s/Hz, one branch is out 3% of the time, two branches 0.04%, four less than one in ten million.
:::

```sim plot
view: graph
x: S = 0..40 dB
y: P = 1e-8..1 log
slider: R = 0.5..6 = 2
plot: 1 - exp(-(2^R - 1)/10^(S/10)) | label: L = 1
plot: 1 - exp(-(2^R - 1)/10^(S/10))*(1 + (2^R - 1)/10^(S/10)) | label: L = 2
plot: 1 - exp(-(2^R - 1)/10^(S/10))*(1 + (2^R - 1)/10^(S/10) + ((2^R - 1)/10^(S/10))^2/2 + ((2^R - 1)/10^(S/10))^3/6) | label: L = 4
```

::: predict
## A base station can either receive with two antennas (MRC) or transmit from two antennas with the Alamouti code, at the same total power. How do they compare?

- [ ] Alamouti is better: it uses both antennas at the transmitter
- [x] They have the same diversity order, but receive combining is 3 dB better
- [ ] Only receive combining gives diversity
- [ ] They're identical

::: reveal
Both make the decision statistic depend on $|h_1|^2 + |h_2|^2$, so both give diversity order two. But Alamouti must split the power between its two antennas without knowing the channel, while two receive antennas each collect the full transmitted power. Alamouti's error curve is the MRC curve shifted 3 dB to the right.
:::
:::

::: nameit
## What the lab computes

- **Rayleigh gains**: $h = (X + jY)/\sqrt2$ with X and Y standard Gaussian, so $E|h|^2 = 1$. BPSK with MRC decides on $\text{Re}\sum_l h_l^*y_l$, with exact error probability (lesson 44) $\left(\frac{1 - \mu}{2}\right)^L\sum_{k=0}^{L-1}\binom{L - 1 + k}{k}\left(\frac{1 + \mu}{2}\right)^k$, $\mu = \sqrt{\bar\gamma/(1 + \bar\gamma)}$.
- **Outage**: the combined gain $\sum|h_l|^2$ has a gamma distribution, giving the formula in the plot.
- **Clarke's channel** as a sum of M sinusoids with arrival angles $\alpha_m = 2\pi(m + \frac14)/M$ and random phases $\phi_m$:
$$h_n = \frac{1}{\sqrt M}\sum_m e^{j(2\pi f_d\cos\alpha_m\,n/f_s + \phi_m)}$$
Its autocorrelation approaches $J_0(2\pi f_d\tau)$, and its envelope crosses a level ρ (relative to rms) upward $\sqrt{2\pi}f_d\rho e^{-\rho^2}$ times a second.
- **Alamouti**: send $(x_1, x_2)$, then $(-x_2^*, x_1^*)$, each antenna at half power; combine $z_1 = h_1^*y_1 + h_2y_2^*$ and $z_2 = h_2^*y_1 - h_1y_2^*$.
:::

::: check
kind: python

## Write `mrc_ber(EbN0_db, L, n, seed)`: BPSK over L independent Rayleigh branches, each with average Eb/N0 as given, combined by MRC; return the bit error rate over n bits (`random.Random(seed)`).

```python starter
def mrc_ber(EbN0_db, L, n, seed):
    return 0.0
```

```python solution
import math, random

def mrc_ber(EbN0_db, L, n, seed):
    r = random.Random(seed)
    s = math.sqrt(1 / (2 * 10 ** (EbN0_db / 10)))
    a = math.sqrt(0.5)
    e = 0
    for _ in range(n):
        b = r.random() < 0.5
        x = 1 if b else -1
        z = 0.0
        for _ in range(L):
            h = complex(r.gauss(0, a), r.gauss(0, a))
            y = h * x + complex(r.gauss(0, s), r.gauss(0, s))
            z += (h.conjugate() * y).real
        e += (z > 0) != b
    return e / n
```

```python tests
import math
def exact(g, L):
    mu = math.sqrt(g / (1 + g))
    return ((1 - mu) / 2) ** L * sum(math.comb(L - 1 + k, k) * ((1 + mu) / 2) ** k for k in range(L))
for L, E in ((1, 10), (2, 10), (2, 15)):
    p = exact(10 ** (E / 10), L)
    assert abs(mrc_ber(E, L, 80000, 4) - p) < 4 * math.sqrt(p / 80000), f"L = {L} at {E} dB: {p:.2e}."
```

::: right
Right. Going from 10 to 15 dB with two branches cuts the error rate about tenfold, as the $\bar\gamma^{-2}$ slope predicts; one branch would have cut it only about threefold.
:::
:::

::: check
kind: python

## Write `outage_mc(R, snr_db, L, n, seed)`: the fraction of n channel draws in which $\log_2(1 + \text{SNR}\sum_l|h_l|^2) < R$ for L independent Rayleigh branches.

```python starter
def outage_mc(R, snr_db, L, n, seed):
    return 0.0
```

```python solution
import math, random

def outage_mc(R, snr_db, L, n, seed):
    r = random.Random(seed)
    S = 10 ** (snr_db / 10)
    c = 0
    for _ in range(n):
        g = sum(r.expovariate(1) for _ in range(L))
        c += math.log2(1 + S * g) < R
    return c / n
```

```python tests
import math
x = (2 ** 2 - 1) / 10
for L, p in ((1, 1 - math.exp(-x)), (2, 1 - math.exp(-x) * (1 + x))):
    assert abs(outage_mc(2, 10, L, 100000, 9) - p) < 4 * math.sqrt(p / 100000), f"L = {L}, 2 bit/s/Hz at 10 dB: {p:.4f}."
```

::: right
Right. $|h|^2$ of a Rayleigh gain is exponential with mean one, so drawing it directly is the same as drawing the complex gain and squaring.
:::
:::

::: check
kind: python

## Write `clarke(fd, fs, N, M, seed)`: N samples of Clarke's sum-of-sinusoids channel with arrival angles $2\pi(m + \frac14)/M$ and phases from `random.Random(seed)`, and `autocorr(h, lag)`: the time-averaged $\text{Re}\,h_{n+\text{lag}}h_n^*$ divided by the average power.

```python starter
def clarke(fd, fs, N, M, seed):
    return [1 + 0j] * N

def autocorr(h, lag):
    return 1.0
```

```python solution
import cmath, math, random

def clarke(fd, fs, N, M, seed):
    r = random.Random(seed)
    ph = [r.uniform(0, 2 * math.pi) for _ in range(M)]
    w = [2 * math.pi * fd * math.cos(2 * math.pi * (m + 0.25) / M) / fs for m in range(M)]
    return [sum(cmath.exp(1j * (w[m] * n + ph[m])) for m in range(M)) / math.sqrt(M) for n in range(N)]

def autocorr(h, lag):
    N = len(h)
    P = sum(abs(v) ** 2 for v in h) / N
    return sum((h[n + lag] * h[n].conjugate()).real for n in range(N - lag)) / (N - lag) / P
```

```python tests
import math
J0 = lambda x: sum(math.cos(x * math.sin(math.pi * (k + 0.5) / 200)) for k in range(200)) / 200
h = clarke(10, 1000, 20000, 16, 1)
for lag in (10, 20, 38, 60):
    assert abs(autocorr(h, lag) - J0(2 * math.pi * 10 * lag / 1000)) < 0.02, f"Autocorrelation at lag {lag} follows J0."
rms = math.sqrt(sum(abs(v) ** 2 for v in h) / len(h))
for rho in (0.3, 1.0):
    up = sum(1 for n in range(1, len(h)) if abs(h[n - 1]) < rho * rms <= abs(h[n]))
    lcr = math.sqrt(2 * math.pi) * 10 * rho * math.exp(-rho * rho)
    assert abs(up / 20 - lcr) < 0.15 * lcr, f"Level crossings at ρ = {rho}: about {lcr:.1f} per second."
```

::: right
Right. The correlation first crosses zero near $2\pi f_d\tau = 2.405$, at τ = 38 ms for a 10 Hz Doppler: samples that far apart fade nearly independently, which is what time diversity and interleaving rely on.
:::
:::

::: check
kind: python

## Write `alamouti_ber(EbN0_db, n, seed)`: BPSK sent with the Alamouti code from two antennas, each at half power, to one receive antenna; independent Rayleigh gains per symbol pair; return the bit error rate over n bits.

```python starter
def alamouti_ber(EbN0_db, n, seed):
    return 0.0
```

```python solution
import math, random

def alamouti_ber(EbN0_db, n, seed):
    r = random.Random(seed)
    s = math.sqrt(1 / (2 * 10 ** (EbN0_db / 10)))
    a = math.sqrt(0.5)
    e = 0
    for _ in range(n // 2):
        b1, b2 = r.random() < 0.5, r.random() < 0.5
        x1, x2 = (1 if b1 else -1), (1 if b2 else -1)
        h1 = complex(r.gauss(0, a), r.gauss(0, a))
        h2 = complex(r.gauss(0, a), r.gauss(0, a))
        y1 = (h1 * x1 + h2 * x2) / math.sqrt(2) + complex(r.gauss(0, s), r.gauss(0, s))
        y2 = (-h1 * x2 + h2 * x1) / math.sqrt(2) + complex(r.gauss(0, s), r.gauss(0, s))
        z1 = (h1.conjugate() * y1 + h2 * y2.conjugate()).real
        z2 = (h2.conjugate() * y1 - h1 * y2.conjugate()).real
        e += ((z1 > 0) != b1) + ((z2 > 0) != b2)
    return e / n
```

```python tests
import math
def exact(g, L):
    mu = math.sqrt(g / (1 + g))
    return ((1 - mu) / 2) ** L * sum(math.comb(L - 1 + k, k) * ((1 + mu) / 2) ** k for k in range(L))
p = exact(10 ** (10 / 10) / 2, 2)
assert abs(alamouti_ber(10, 100000, 3) - p) < 4 * math.sqrt(p / 100000), "Alamouti at 10 dB matches two-branch MRC at 7 dB."
assert alamouti_ber(10, 100000, 3) < exact(10, 1) / 3, "Far better than one antenna at the same power."
```

::: right
Right. The orthogonal code makes each symbol's statistic $(|h_1|^2 + |h_2|^2)x/\sqrt2$ plus noise: two-branch diversity at half the power per branch.
:::
:::

::: explain
## Why does diversity change the slope of the error-rate curve, while more transmit power only shifts along it?

::: model
On a Rayleigh channel, errors come almost entirely from deep fades, and the chance of a fade deep enough to cause an error falls only in proportion to the inverse of the average SNR. More power pushes every fade up equally, so it shifts the curve but leaves that inverse dependence alone. With L independently fading branches, an error needs all of them to be deep at once, and since they're independent the probabilities multiply, giving a dependence on the SNR to the minus L. That steeper slope is why a second antenna can be worth ten or more decibels of power at low error rates.
:::
:::
