---
title: "Capstone: decode a message from noisy samples"
heading: A receiver built from the course's pieces, working on raw complex samples of a QPSK signal, a matched filter that adds up each symbol's samples, a known preamble that measures and removes the carrier's phase, Gray-coded decisions, bits back to text, and a measured error rate that lands on the theory
eyebrow: D4 · Lesson 10 · Capstone
xp: 80
---

::: hook
A software-defined radio hands you nothing but a stream of complex numbers: the in-phase and quadrature samples of whatever arrived at the antenna, buried in noise and rotated by an unknown carrier phase. Somewhere in it is a message. Getting it out takes every idea in this course: a filter matched to the pulse to collect each symbol's energy, a known preamble to find the phase, decisions against the constellation's boundaries, and bits turned back into characters. Then, as a check that the receiver is as good as it can be, its measured error rate should match the formula of lesson 5.
:::

::: play
- QPSK symbols as received: rotated by an unknown carrier phase and scattered by noise. The receiver's decision regions are the four quadrants.
- Rotate by more than 45° and every symbol lands in the wrong quadrant, however strong the signal. That's why the receiver must estimate and remove the phase before deciding.
- A preamble of symbols the receiver already knows makes the estimate easy: compare what arrived with what was sent.
:::

```sim plot
view: constellation
scheme: qpsk
slider: EbN0 = 0..14 = 7 dB step 0.5
slider: theta = -180..180 = 115 ° step 5
ebn0: EbN0
phase: theta°
symbols: 600
regions: on
```

::: predict
## The receiver adds up the 8 samples of each symbol before deciding. Compared with deciding from a single sample, by how much does that improve the SNR?

- [ ] Not at all: the noise adds up too
- [ ] By 3 dB
- [x] By 9 dB
- [ ] By 18 dB

::: reveal
The signal's 8 samples add in step, so its amplitude grows 8 times and its power 64 times. The noise samples are independent, so their powers add: 8 times. The SNR improves by 64/8 = 8, or 9.0 dB. That's the matched filter at work: for rectangular pulses, integrate and dump collects all of the symbol's energy.
:::
:::

::: nameit
## The receiver chain

1. **Matched filter**: for rectangular pulses, sum each symbol's $N_s$ samples (integrate and dump). The SNR improves by $N_s$.
2. **Phase estimate**: with known preamble symbols $p_k$ and their received versions $r_k$, the carrier phase is $\hat\theta = \arg\sum_kr_kp_k^*$. Multiplying every symbol by $e^{-j\hat\theta}$ undoes the rotation. Real receivers track the phase continuously with a phase-locked loop (D5).
3. **Decisions**: for Gray-coded QPSK, $b_0$ is the sign of I and $b_1$ the sign of Q.
4. **Framing**: drop the preamble and turn each 8 bits into a character.

## Scaling the noise

With symbols of unit energy per sample, $N_s$ samples per symbol and complex Gaussian noise of standard deviation σ in each of I and Q, each QPSK bit has

$$\frac{E_b}{N_0} = \frac{N_s}{4\sigma^2}$$

so a simulation at a chosen $E_b/N_0$ uses $\sigma = \sqrt{N_s/(4E_b/N_0)}$, and its measured error rate should approach $Q(\sqrt{2E_b/N_0})$.
:::

::: example
## The message is 34 characters sent at $E_b/N_0$ = 7 dB. How many bit errors should you expect?

::: solution
1. **Bit error rate.** 7 dB is a ratio of 5.01:
   $$\begin{aligned} P_b &= Q(\sqrt{2 \times 5.01}) \\ &= Q(3.17) \\ &= 7.7 \times 10^{-4} \end{aligned}$$
2. **Bits sent.**
   $$34 \times 8 = 272\ \text{bits}$$
3. **Expected errors.**
   $$272 \times 7.7 \times 10^{-4} = 0.21$$
4. **What you see.** Most transmissions arrive perfectly. About one in five has an error, almost always a single flipped bit and so a single wrong character.

**Answer:** expect about 0.21 bit errors per message.
:::
:::

::: example
## The Python step measures 40,000 bits at 4 dB. What should it find?

::: solution
1. **Error rate at 4 dB.** 4 dB is a ratio of 2.51:
   $$Q(\sqrt{2 \times 2.51}) = 0.0125$$
2. **Expected errors.**
   $$40\,000 \times 0.0125 = 500$$
3. **Compare with the measurement.** The reference receiver counted 483, an error rate of 0.0121, within the statistical spread of $\sqrt{500} \approx 22$ errors.

**Answer:** it should find about 500 errors.
:::
:::

::: example
## The 34-character message is sent at 1200 b/s with 8 bits per character. How long does it take on the air?

::: solution
1. **Bits.**
   $$34 \times 8 = 272\ \text{bits}$$
2. **Time on the air.** At 1200 b/s:
   $$272/1200 = 0.23\ \text{s}$$
3. **Overhead.** A preamble for carrier phase and timing, and a CRC for checking, add a little more; packet radio protocols such as AX.25 send about this way.

**Answer:** about 0.23 s.
:::
:::

::: check
kind: python

## Build the receiver: integrate and dump, the phase estimate, the decisions and the text.

```python starter
import numpy as np

def integrate_dump(x, sps):
    # Matched filter for rectangular pulses: add up each block of sps samples.
    # Return one complex number per symbol.
    return x[::sps]

def phase_from_preamble(sym, pre):
    # The receiver knows the first len(pre) symbols. Estimate the carrier phase offset as the
    # angle of sum(sym[k]*conj(pre[k])) over the preamble. Return it in radians.
    return 0.0

def qpsk_bits(sym):
    # Gray-coded QPSK: each symbol (1 - 2*b0 + 1j*(1 - 2*b1))/sqrt(2) carries the bit pair
    # (b0, b1). Decide each bit from the sign of I or Q and return a flat array of 0s and 1s.
    return np.zeros(2*len(sym), dtype=int)

def bits_to_text(bits):
    # Eight bits per character, most significant bit first, as ASCII.
    return ""

def decode(x, sps, pre):
    # Put it together: integrate and dump, remove the phase offset, drop the preamble,
    # decide the bits and turn them into text.
    return ""
```

```python solution
import numpy as np

def integrate_dump(x, sps):
    n = len(x)//sps
    return x[:n*sps].reshape(n, sps).sum(axis=1)

def phase_from_preamble(sym, pre):
    return float(np.angle(np.sum(sym[:len(pre)]*np.conj(pre))))

def qpsk_bits(sym):
    b = np.empty(2*len(sym), dtype=int)
    b[0::2] = (sym.real < 0)
    b[1::2] = (sym.imag < 0)
    return b

def bits_to_text(bits):
    chars = []
    for i in range(0, len(bits) - 7, 8):
        v = 0
        for b in bits[i:i + 8]:
            v = 2*v + int(b)
        chars.append(chr(v))
    return "".join(chars)

def decode(x, sps, pre):
    sym = integrate_dump(x, sps)
    th = phase_from_preamble(sym, pre)
    sym = sym*np.exp(-1j*th)
    return bits_to_text(qpsk_bits(sym[len(pre):]))
```

```python tests
def _tx(bits, sps):
    b = np.asarray(bits).reshape(-1, 2)
    s = ((1 - 2*b[:, 0]) + 1j*(1 - 2*b[:, 1]))/np.sqrt(2)
    return np.repeat(s, sps)
def _text_bits(t):
    return [int(c) for ch in t for c in format(ord(ch), "08b")]
_rng = np.random.default_rng(2024)
_pre_bits = [0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0]
_pre = _tx(_pre_bits, 1)
_msg = "Meet at the antenna range at 0900."
_sps, _ebn0 = 8, 10**(7/10)
_sig = 0.0 + _tx(_pre_bits + _text_bits(_msg), _sps)
_sigma = np.sqrt(_sps/(4*_ebn0))
_x = _sig*np.exp(2.0j) + _sigma*(_rng.standard_normal(len(_sig)) + 1j*_rng.standard_normal(len(_sig)))
assert np.allclose(integrate_dump(np.arange(12) + 0j, 4), [6, 22, 38]), "integrate_dump(0..11, 4) should be [6, 22, 38]: the sum of each block."
assert np.array_equal(qpsk_bits(np.array([1 + 1j, -1 + 1j, -1 - 1j, 1 - 1j])), [0, 0, 1, 0, 1, 1, 0, 1]), "Positive I means b0 = 0 and positive Q means b1 = 0."
assert bits_to_text(_text_bits("Ohm")) == "Ohm", "bits_to_text should undo 8-bit ASCII, most significant bit first."
th = phase_from_preamble(integrate_dump(_x, _sps), _pre)
assert abs(np.angle(np.exp(1j*(th - 2.0)))) < 0.1, f"The carrier was rotated by 2.0 rad; your estimate is {th:.3f}."
assert decode(_x, _sps, _pre) == _msg, f"The message should decode exactly; got {decode(_x, _sps, _pre)!r}."
_bits = _rng.integers(0, 2, 40000)
_e = 10**(4/10)
_y = _tx(_bits, _sps) + np.sqrt(_sps/(4*_e))*(_rng.standard_normal(20000*_sps) + 1j*_rng.standard_normal(20000*_sps))
_ber = np.mean(qpsk_bits(integrate_dump(_y, _sps)) != _bits)
_q = 0.5*__import__("math").erfc(np.sqrt(2*_e)/np.sqrt(2))
assert abs(_ber/_q - 1) < 0.15, f"At Eb/N0 = 4 dB the measured error rate {_ber:.4f} should match Q(sqrt(2 Eb/N0)) = {_q:.4f}."
```

::: right
Right. Your receiver finds the 2.0 rad rotation, decodes the message exactly, and measures an error rate within the spread of $Q(\sqrt{2E_b/N_0})$.
:::
:::

::: check
given: n = 8 | 16 | 64
answer: 10*log(n)
unit: dB
tolerance: 0.5%

## A matched filter sums {n} samples per symbol, each with independent noise. How much does it improve the SNR?

::: right
Right. A factor of $N_s$: {answer} dB.
:::

::: misses
- [20*log(n)] The noise grows too: the gain is $N_s$ in power.
- [any] Not yet. Signal power grows as $N_s^2$, noise power as $N_s$.
:::
:::

::: check
given: n = 4 | 8 | 16; E = 4 | 7 | 9
answer: sqrt(n/(4*10^(E/10)))
tolerance: 0.5%

## A simulation has {n} samples per QPSK symbol of unit energy per sample. What noise standard deviation per component gives $E_b/N_0$ = {E} dB?

::: right
Right. $\sqrt{N_s/(4E_b/N_0)}$ = {answer}.
:::

::: misses
- [sqrt(n/(4*E))] Convert the decibels to a ratio first.
- [any] Not yet. Solve $E_b/N_0 = N_s/(4\sigma^2)$.
:::
:::

::: check
given: c = 20 | 34 | 100; E = 6 | 7 | 8
answer: 8*c*Q(sqrt(2*10^(E/10)))
tolerance: 0.5%

## A {c}-character message is sent as QPSK at $E_b/N_0$ = {E} dB. How many bit errors should you expect on average?

::: right
Right. $8c\,Q(\sqrt{2E_b/N_0})$ = {answer}.
:::

::: misses
- [c*Q(sqrt(2*10^(E/10)))] Each character is 8 bits.
- [any] Not yet. Bits times the error rate.
:::
:::

::: check
kind: parts
given: n = 20 | 34 | 100; E = 5 | 7 | 9

## A message of {n} 8-bit characters is sent by BPSK at $E_b/N_0$ = {E} dB.

::: part
answer: n*8*Q(sqrt(2*10^(E/10)))
tolerance: 1%

### How many bit errors are expected?

::: misses
- [any] Bits × error rate.
:::
:::

::: part
answer: (1 - Q(sqrt(2*10^(E/10))))^(n*8)*100
unit: %
tolerance: 0.5%

### What is the chance the whole message arrives with no errors?

::: misses
- [any] $(1 - p)^{8n}$.
:::
:::
:::

::: check
kind: parts
given: N = 10000 | 40000; E = 3 | 4 | 6

## A simulation counts errors in {N} BPSK bits at $E_b/N_0$ = {E} dB.

::: part
answer: N*Q(sqrt(2*10^(E/10)))
tolerance: 1%

### How many errors should it find on average?

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

::: part
answer: sqrt(N*Q(sqrt(2*10^(E/10))))
tolerance: 1%

### About how much does that count scatter from run to run (one standard deviation)?

::: misses
- [any] The square root of the expected count.
:::
:::
:::

::: explain
## Why does the receiver need a known preamble before it can decide QPSK symbols?

::: model
The receiver's local oscillator isn't locked to the transmitter's carrier, so every received symbol arrives rotated by an unknown phase. QPSK puts its information in the phase, and its decision boundaries are fixed lines through the origin, so a rotation of more than 45 degrees moves every symbol into a neighbor's region and every decision is wrong, however clean the signal. A preamble is a short run of symbols the receiver knows in advance; comparing what arrived with what was sent, and averaging over the preamble to beat down the noise, gives the rotation, which the receiver then removes from every symbol that follows.
:::
:::

::: practice

::: check
given: n = 2 | 4 | 8 | 10 | 16 | 100 | 1000
answer: 10*log(n)
unit: dB
tolerance: 0.5%

## Matched-filter gain, {n} samples?

::: misses
- [any] $10\log N_s$.
:::
:::

::: check
given: n = 1 | 64; E = 0.5 | 12
answer: sqrt(n/(4*10^(E/10)))
tolerance: 0.5%

## σ for {n} samples per symbol at {E} dB?

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