---
title: "Modem lab: a QPSK link in Python"
heading: Building a complete QPSK modem with root-raised-cosine pulse shaping, a matched-filter receiver and an AWGN channel calibrated in Eb/N0, and measuring its bit error rate against theory
eyebrow: S8 · Lesson 52 · Modem lab
xp: 60
---

::: hook
The first half of this course derived the pieces of a digital link one formula at a time: pulse shaping, matched filtering, the AWGN channel, error probability. In this lab you'll assemble them into a working QPSK modem and check it the way a communications engineer would, by sending tens of thousands of random bits through simulated noise and counting errors. If every scale factor is right, the measured bit error rate lands on $Q(\sqrt{2E_b/N_0})$; if one is wrong, the curve shifts by decibels and the test tells you.
:::

::: predict
## The transmitter and receiver each use a root-raised-cosine filter. Why does the cascade cause no intersymbol interference at the sampling instants?

- [ ] Each RRC filter is a Nyquist pulse on its own
- [x] The two together form a raised-cosine pulse, which is zero at every other symbol instant
- [ ] The matched filter cancels all ISI by definition
- [ ] Because QPSK has constant envelope

::: reveal
An RRC pulse alone isn't Nyquist: its own samples at other symbol instants aren't zero. Convolved with itself (the matched filter), its spectrum squares into a raised cosine, which satisfies Nyquist's criterion. Splitting the shaping this way gets zero ISI and the optimal matched filter at the same time.
:::
:::

::: nameit
## The root raised cosine

With t in symbol periods and rolloff β:

$$h(t) = \frac{\sin\pi t(1 - \beta) + 4\beta t\cos\pi t(1 + \beta)}{\pi t\left[1 - (4\beta t)^2\right]}$$

with the limits $h(0) = 1 - \beta + \frac{4\beta}{\pi}$ and $h\left(\pm\frac{1}{4\beta}\right) = \frac{\beta}{\sqrt{2}}\left[\left(1 + \frac{2}{\pi}\right)\sin\frac{\pi}{4\beta} + \left(1 - \frac{2}{\pi}\right)\cos\frac{\pi}{4\beta}\right]$. Sampled at sps samples per symbol over ±span symbols and scaled to unit energy.

## The link

- **Modulator**: bits in pairs → $\frac{(1 - 2b_0) + j(1 - 2b_1)}{\sqrt{2}}$ (Gray-coded, unit energy), one symbol every sps samples, filtered by h.
- **Channel**: complex white Gaussian noise. With unit-energy symbols and pulses, the energy per symbol is 1 in sample units, so $N_0 = 1/(E_s/N_0) = 1/(2E_b/N_0)$ is the complex noise variance per sample, $N_0/2$ in each of the real and imaginary parts.
- **Demodulator**: filter by h again, sample every sps samples starting at the combined delay, len(h) − 1, and decide each bit by a sign.

Expected: $P_b = Q\left(\sqrt{2E_b/N_0}\right)$, 2.4 × 10⁻³ at 6 dB and 1.25 × 10⁻² at 4 dB.
:::

::: example
## How many bits must be simulated to measure a 10⁻³ error rate to about ±20%?

::: solution
1. **Spread of an error count.** Error counts are roughly Poisson, so the relative spread is
   $$\frac{1}{\sqrt{n_\text{errors}}}$$
2. **Errors needed.** ±20% needs about 25 errors:
   $$\frac{1}{\sqrt{25}} = 20\%$$
3. **Bits needed.** At 10⁻³ that's about
   $$\frac{25}{10^{-3}} = 25\,000\ \text{bits}$$
4. **The lab's runs.** Its 40,000-bit runs at 4 and 6 dB collect roughly 500 and 100 errors, enough to land within the tests' 20 to 25% windows.

**Answer:** about 25,000 bits.
:::
:::

::: example
## At Eb/N0 = 3 dB, what noise variance should the channel add?

::: solution
1. **Linear Eb/N0.**
   $$10^{0.3} = 1.995$$
2. **Per symbol.**
   $$E_s/N_0 = 3.99$$
3. **Noise density.**
   $$\begin{aligned} N_0 &= 1/3.99 \\ &= 0.2506 \end{aligned}$$
   per complex sample.
4. **Per component.**
   $$\sqrt{0.2506/2} = 0.354$$
   That's the standard deviation in each of the real and imaginary parts.

**Answer:** $N_0$ = 0.2506 per complex sample: a standard deviation of 0.354 in each of the real and imaginary parts.
:::
:::

::: check
kind: python

## Step 1. Write `rrc(beta, span, sps)`: unit-energy root-raised-cosine taps.

```python starter
import numpy as np

def rrc(beta, span, sps):
    # Root-raised-cosine taps for rolloff beta, spanning +-span symbols at sps samples per symbol,
    # normalized to unit energy (sum of squares = 1). Length 2*span*sps + 1.
    return np.zeros(2*span*sps + 1)

h = rrc(0.35, 8, 8)
print(len(h), np.sum(h**2))
```

```python solution
import numpy as np

def rrc(beta, span, sps):
    t = np.arange(-span*sps, span*sps + 1)/sps
    h = np.zeros(len(t))
    for i, x in enumerate(t):
        if abs(x) < 1e-12:
            h[i] = 1 - beta + 4*beta/np.pi
        elif abs(abs(x) - 1/(4*beta)) < 1e-12:
            h[i] = beta/np.sqrt(2)*((1 + 2/np.pi)*np.sin(np.pi/(4*beta)) + (1 - 2/np.pi)*np.cos(np.pi/(4*beta)))
        else:
            h[i] = (np.sin(np.pi*x*(1 - beta)) + 4*beta*x*np.cos(np.pi*x*(1 + beta)))/(np.pi*x*(1 - (4*beta*x)**2))
    return h/np.sqrt(np.sum(h**2))

h = rrc(0.35, 8, 8)
print(len(h), np.sum(h**2))
```

```python tests
import numpy as np
h = rrc(0.35, 8, 8)
assert len(h) == 129, f"Span ±8 symbols at 8 samples per symbol gives 129 taps; got {len(h)}."
assert abs(np.sum(h**2) - 1) < 1e-9, "Normalize the taps to unit energy."
assert np.allclose(h, h[::-1]), "The pulse is symmetric."
g = np.convolve(h, h); c = len(g)//2
isi = max(abs(g[c + k*8]) for k in range(-7, 8) if k != 0)
assert abs(g[c] - 1) < 1e-9 and isi < 0.01, f"An RRC filtered by itself must be a Nyquist pulse: zero at every other symbol instant. The largest ISI sample is {isi:.4f}."
h2 = rrc(0.25, 6, 4)
assert np.all(np.isfinite(h2)) and abs(np.sum(h2**2) - 1) < 1e-9, "Handle t = ±1/(4β), where the formula is 0/0 (for β = 0.25 and 4 samples per symbol it falls on a sample)."
g2 = np.convolve(h2, h2); c2 = len(g2)//2
assert max(abs(g2[c2 + k*4]) for k in range(-5, 6) if k != 0) < 0.02, "β = 0.25 must also give a Nyquist pulse."
```

::: right
Right. Your pulse, convolved with itself, is zero at every other symbol instant: a Nyquist pulse from two non-Nyquist halves.
:::
:::

::: check
kind: python

## Step 2. Write `qpsk_mod` and `qpsk_demod`: Gray-coded QPSK with pulse shaping and a matched-filter receiver.

```python starter
import numpy as np

def qpsk_mod(bits, h, sps):
    # Map bit pairs (b0, b1) to ((1 - 2*b0) + 1j*(1 - 2*b1))/sqrt(2), place one symbol every sps samples,
    # and filter with h (full convolution).
    return np.zeros(1, dtype=complex)

def qpsk_demod(r, h, sps, nsym):
    # Matched-filter with h, sample nsym symbols starting at delay len(h) - 1, every sps samples,
    # and decide each bit from the sign of the real and imaginary parts.
    return np.zeros(2*nsym, dtype=int)

print(qpsk_mod(np.array([0, 1]), np.array([1.0]), 1))
```

```python solution
import numpy as np

def qpsk_mod(bits, h, sps):
    b = np.asarray(bits).reshape(-1, 2)
    a = ((1 - 2*b[:, 0]) + 1j*(1 - 2*b[:, 1]))/np.sqrt(2)
    up = np.zeros(len(a)*sps, dtype=complex)
    up[::sps] = a
    return np.convolve(up, h)

def qpsk_demod(r, h, sps, nsym):
    y = np.convolve(r, h)
    d = len(h) - 1
    s = y[d:d + nsym*sps:sps]
    out = np.zeros(2*nsym, dtype=int)
    out[0::2] = (s.real < 0).astype(int)
    out[1::2] = (s.imag < 0).astype(int)
    return out

print(qpsk_mod(np.array([0, 1]), np.array([1.0]), 1))
```

```python tests
import numpy as np
x = qpsk_mod(np.array([0, 0, 1, 1, 0, 1]), np.array([1.0]), 1)
assert np.allclose(x, np.array([1 + 1j, -1 - 1j, 1 - 1j])/np.sqrt(2)), f"With a one-tap filter, bits 00 11 01 map to (1+j, −1−j, 1−j)/√2; got {np.round(x, 3)}."
def rrc_ref(beta, span, sps):
    t = np.arange(-span*sps, span*sps + 1)/sps
    h = np.where(np.abs(t) < 1e-12, 1 - beta + 4*beta/np.pi, 0.0)
    m = (np.abs(t) > 1e-12) & (np.abs(np.abs(t) - 1/(4*beta)) > 1e-12)
    tm = t[m]
    h[m] = (np.sin(np.pi*tm*(1 - beta)) + 4*beta*tm*np.cos(np.pi*tm*(1 + beta)))/(np.pi*tm*(1 - (4*beta*tm)**2))
    return h/np.sqrt(np.sum(h**2))
h = rrc_ref(0.35, 8, 8)
rng = np.random.default_rng(4)
bits = rng.integers(0, 2, 2000)
tx = qpsk_mod(bits, h, 8)
rx = qpsk_demod(tx, h, 8, 1000)
assert len(rx) == 2000 and np.array_equal(rx, bits), f"With no noise the modem must return every bit; {np.sum(rx != bits)} of 2000 differ."
assert abs(np.mean(np.abs(tx)**2)*8 - 1) < 0.05, "With unit-energy pulses, each symbol carries unit energy."
```

::: right
Right. Two thousand bits through the noiseless link come back exactly.
:::
:::

::: check
kind: python

## Step 3. Write `awgn(x, ebn0_db, sps, rng)`: complex noise scaled to a given Eb/N0.

```python starter
import numpy as np

def awgn(x, ebn0_db, sps, rng):
    # Add complex white Gaussian noise to a QPSK signal whose symbols have unit energy and whose pulses
    # have unit energy, so that the matched-filter output has the given Eb/N0 (2 bits per symbol).
    return x

print(np.std(awgn(np.zeros(10000, dtype=complex), 10.0, 8, np.random.default_rng(0))))
```

```python solution
import numpy as np

def awgn(x, ebn0_db, sps, rng):
    esn0 = 2*10**(ebn0_db/10)
    sigma = np.sqrt(1/(2*esn0))
    return x + sigma*(rng.normal(size=len(x)) + 1j*rng.normal(size=len(x)))

print(np.std(awgn(np.zeros(10000, dtype=complex), 10.0, 8, np.random.default_rng(0))))
```

```python tests
import numpy as np
from math import erfc, sqrt
def rrc_ref(beta, span, sps):
    t = np.arange(-span*sps, span*sps + 1)/sps
    h = np.where(np.abs(t) < 1e-12, 1 - beta + 4*beta/np.pi, 0.0)
    m = (np.abs(t) > 1e-12) & (np.abs(np.abs(t) - 1/(4*beta)) > 1e-12)
    tm = t[m]
    h[m] = (np.sin(np.pi*tm*(1 - beta)) + 4*beta*tm*np.cos(np.pi*tm*(1 + beta)))/(np.pi*tm*(1 - (4*beta*tm)**2))
    return h/np.sqrt(np.sum(h**2))
def mod(bits, h, sps):
    b = bits.reshape(-1, 2); a = ((1 - 2*b[:, 0]) + 1j*(1 - 2*b[:, 1]))/np.sqrt(2)
    up = np.zeros(len(a)*sps, dtype=complex); up[::sps] = a
    return np.convolve(up, h)
def demod(r, h, sps, n):
    y = np.convolve(r, h); d = len(h) - 1; s = y[d:d + n*sps:sps]
    out = np.zeros(2*n, dtype=int); out[0::2] = s.real < 0; out[1::2] = s.imag < 0
    return out
Q = lambda x: 0.5*erfc(x/sqrt(2))
z = awgn(np.zeros(200000, dtype=complex), 3.0, 8, np.random.default_rng(1))
var = np.mean(np.abs(z)**2)
want = 1/(2*10**0.3)
assert abs(var/want - 1) < 0.02, f"At Eb/N0 = 3 dB the complex noise variance per sample should be N0 = 1/(2·Eb/N0) = {want:.4f}; got {var:.4f}."
h = rrc_ref(0.35, 8, 8)
rng = np.random.default_rng(7)
for e in (4.0, 6.0):
    bits = rng.integers(0, 2, 40000)
    rx = demod(awgn(mod(bits, h, 8), e, 8, rng), h, 8, 20000)
    ber = np.mean(rx != bits)
    th = Q(sqrt(2*10**(e/10)))
    assert 0.8*th < ber < 1.25*th, f"At {e} dB the measured bit error rate {ber:.5f} should match Q(√(2Eb/N0)) = {th:.5f}."
```

::: right
Right. Your channel puts the measured bit error rate on $Q(\sqrt{2E_b/N_0})$ at both test points: every scale factor in the link is right.
:::
:::

::: explain
## Why does the modem sample at delay len(h) − 1?

::: model
Each filter in the chain is a symmetric pulse with its peak at its center tap, (len(h) − 1)/2 samples from its start. The transmit filter delays a symbol's peak by that much and the receive filter by the same again, so the peak of the combined raised-cosine pulse appears len(h) − 1 samples after the symbol was placed. Sampling there catches each symbol at its peak, where the other symbols' pulses all pass through zero, so the decision sees only its own symbol plus noise. Sampling even one sample early or late would catch the neighbors' tails and add intersymbol interference.
:::
:::

::: practice

::: check
given: E = 3 | 6 | 9
answer: Q(sqrt(2*10^(E/10)))
tolerance: 1%

## QPSK bit error rate at {E} dB?

::: misses
- [any] $Q(\sqrt{2E_b/N_0})$.
:::
:::

::: check
given: E = 2 | 5 | 8
answer: 1/(2*10^(E/10))
tolerance: 0.5%

## Complex noise variance per sample for Eb/N0 = {E} dB (unit-energy QPSK)?

::: misses
- [any] $N_0 = 1/(2E_b/N_0)$.
:::
:::

::: check
given: b = 0.2 | 0.35 | 0.5
answer: 1 - b + 4*b/pi
tolerance: 0.5%

## Unnormalized RRC value at t = 0 for β = {b}?

::: misses
- [any] $1 - \beta + 4\beta/\pi$.
:::
:::
:::
