---
title: ECG processing lab
heading: "Three stages of an ECG front end in NumPy: a first-order high-pass that removes baseline wander, a second-order notch that removes power-line interference, and a Pan–Tompkins-style detector that finds every heartbeat in a noisy, wandering record"
eyebrow: S15 · Lesson 52 · ECG processing lab
xp: 100
---

::: hook
Every bedside monitor and wearable patch runs a version of the same pipeline: strip off the slow wander from breathing and electrode drift, remove what's left of the power line, and find the QRS complexes to count the heart rate. In this lab you'll build each stage in Python and test it against the exact frequency response it should have, then against synthetic ECG records with known beat times, wandering baselines and noise, where a detector must find every beat and nothing else.
:::

::: predict
## Your detector differentiates the ECG and squares it to emphasize the QRS. Without any smoothing first, what goes wrong on a record with 50 µV of broadband noise?

- [ ] Nothing: the QRS is a millivolt and the noise only 50 µV
- [x] The derivative amplifies the high-frequency noise until its energy rivals the QRS's, and false detections appear
- [ ] The T waves disappear
- [ ] The baseline wander dominates

::: reveal
Differentiating multiplies each frequency component by its frequency, so white noise, spread up to half the sample rate, is boosted far more than the QRS, whose energy sits around 10 to 20 Hz. After squaring and averaging, noise and QRS energies become comparable, and the threshold catches noise. Smoothing over about 20 ms first, as Pan and Tompkins do with their 5 to 15 Hz band-pass, removes the noise before the derivative can amplify it.
:::
:::

::: nameit
## Task 1: baseline removal

The analog RC high-pass of lesson 18 becomes, with time step T and τ = 1/(2πf_c),

$$y[n] = a\left(y[n - 1] + x[n] - x[n - 1]\right), \qquad a = \frac{\tau}{\tau + T}$$

Its gain at frequency f is $|a(1 - z^{-1})/(1 - az^{-1})|$ with $z = e^{j2\pi f/f_s}$, which the tests check at 0.2, 1 and 10 Hz.

## Task 2: the notch

Zeros on the unit circle at ±ω₀ = ±2πf₀/f_s remove f₀ completely; poles just inside, at radius r, restore the response elsewhere:

$$y[n] = g\left(x[n] - 2\cos\omega_0\,x[n - 1] + x[n - 2]\right) + 2r\cos\omega_0\,y[n - 1] - r^2y[n - 2]$$

with $g = (1 - 2r\cos\omega_0 + r^2)/(2 - 2\cos\omega_0)$ for unit gain at DC. The notch's width is about $(1 - r)f_s/\pi$.

## Task 3: beat detection

Smooth over about 20 ms, take a central difference, square, average over 150 ms, and find the peaks above a threshold with a 250 ms refractory period; then move each detection to the largest ECG sample within 75 ms. The tests use synthetic beats with P, QRS and T waves, RR intervals from 0.6 to 1.1 s, 0.3 mV of baseline wander and 50 µV of noise.
:::

::: example
## What should task 1 give for a 0.5 Hz corner at 500 samples/s?

::: solution
1. **Time constant.** For a 0.5 Hz corner:
   $$\tau = 0.318\ \text{s}$$
2. **Filter coefficient.** At 500 samples/s the sample interval is 0.002 s:
   $$\begin{aligned} a &= \frac{\tau}{\tau + 0.002} \\ &= 0.99376 \end{aligned}$$
3. **Gain at three frequencies.**
   $$\begin{aligned} |H(0.2\ \text{Hz})| &= 0.371 \\ |H(1\ \text{Hz})| &= 0.892 \\ |H(10\ \text{Hz})| &= 0.996 \end{aligned}$$
   so breathing-rate wander at 0.2 Hz is cut by almost two-thirds.
4. **Against the analog filter.** These match the analog filter closely because the corner is far below the sample rate.

**Answer:** a = 0.99376, with gains of 0.371 at 0.2 Hz, 0.892 at 1 Hz and 0.996 at 10 Hz.
:::
:::

::: example
## What should task 2 give for a 60 Hz notch with r = 0.98 at 500 samples/s?

::: solution
1. **Normalizing gain.**
   $$g = 0.9807$$
2. **Gain at the test frequencies.**
   $$\begin{aligned} |H(60\ \text{Hz})| &= 0 \\ |H(58\ \text{Hz})| &= 0.780 \\ |H(55\ \text{Hz})| &= 0.953 \\ |H(10\ \text{Hz})| &= 0.99994 \end{aligned}$$
   exactly 0 at 60 Hz.
3. **Notch width.**
   $$\begin{aligned} \Delta f &\approx \frac{0.02 \times 500}{\pi} \\ &= 3.2\ \text{Hz} \end{aligned}$$
4. **Choosing r.** A larger r narrows it but makes its transient last longer.

**Answer:** g = 0.9807; the gain is exactly 0 at 60 Hz, 0.780 at 58 Hz, 0.953 at 55 Hz and 0.99994 at 10 Hz, and the notch is about 3.2 Hz wide.
:::
:::

::: check
kind: python

## Step 1. Write `highpass`: remove baseline wander with a first-order IIR filter.

```python starter
import numpy as np

def highpass(x, fs, fc):
    # First-order high-pass: y[n] = a*(y[n-1] + x[n] - x[n-1]) with a = tau/(tau + T),
    # tau = 1/(2 pi fc), T = 1/fs, and y[0] = 0. Return y as an array.
    return np.array(x, dtype=float)

fs = 500
t = np.arange(0, 4, 1/fs)
print(highpass(1.0 + np.sin(2*np.pi*10*t), fs, 0.5)[-3:])
```

```python solution
import numpy as np

def highpass(x, fs, fc):
    x = np.asarray(x, dtype=float)
    tau, T = 1/(2*np.pi*fc), 1/fs
    a = tau/(tau + T)
    y = np.zeros_like(x)
    for n in range(1, len(x)):
        y[n] = a*(y[n - 1] + x[n] - x[n - 1])
    return y

fs = 500
t = np.arange(0, 4, 1/fs)
print(highpass(1.0 + np.sin(2*np.pi*10*t), fs, 0.5)[-3:])
```

```python tests
fs, fc = 500, 0.5
t = np.arange(0, 20, 1/fs)
y = highpass(2.0 + 0*t, fs, fc)
assert np.max(np.abs(y)) < 1e-12, "A constant input should give zero output (the first difference removes it)."
tau, T = 1/(2*np.pi*fc), 1/fs
a = tau/(tau + T)
for f in (0.2, 1.0, 10.0):
    y = highpass(np.sin(2*np.pi*f*t), fs, fc)
    z = np.exp(1j*2*np.pi*f/fs)
    g = abs(a*(1 - 1/z)/(1 - a/z))
    h = len(t)//2
    M = np.column_stack([np.sin(2*np.pi*f*t[h:]), np.cos(2*np.pi*f*t[h:])])
    amp = np.hypot(*np.linalg.lstsq(M, y[h:], rcond=None)[0])
    assert abs(amp - g) < 2e-3, f"At {f} Hz the filter's gain should be {g:.4f}; your steady-state amplitude is {amp:.4f}."
```

::: right
Right. Your filter removes DC exactly and matches the theoretical gain at every frequency tested.
:::
:::

::: check
kind: python

## Step 2. Write `notch`: remove power-line interference with a second-order IIR notch.

```python starter
import numpy as np

def notch(x, fs, f0, r):
    # Second-order IIR notch: zeros on the unit circle at +-w0 = 2 pi f0/fs, poles at r e^{+-j w0}:
    # y[n] = g*(x[n] - 2cos(w0) x[n-1] + x[n-2]) + 2r cos(w0) y[n-1] - r^2 y[n-2],
    # with g chosen so the gain at DC is exactly 1. Start from zero state.
    return np.array(x, dtype=float)

fs = 500
t = np.arange(0, 2, 1/fs)
print(np.max(np.abs(notch(np.sin(2*np.pi*60*t), fs, 60, 0.98)[-200:])))
```

```python solution
import numpy as np

def notch(x, fs, f0, r):
    x = np.asarray(x, dtype=float)
    w0 = 2*np.pi*f0/fs
    c = np.cos(w0)
    g = (1 - 2*r*c + r*r)/(2 - 2*c)
    y = np.zeros_like(x)
    for n in range(len(x)):
        x1 = x[n - 1] if n >= 1 else 0.0
        x2 = x[n - 2] if n >= 2 else 0.0
        y1 = y[n - 1] if n >= 1 else 0.0
        y2 = y[n - 2] if n >= 2 else 0.0
        y[n] = g*(x[n] - 2*c*x1 + x2) + 2*r*c*y1 - r*r*y2
    return y

fs = 500
t = np.arange(0, 2, 1/fs)
print(np.max(np.abs(notch(np.sin(2*np.pi*60*t), fs, 60, 0.98)[-200:])))
```

```python tests
fs, f0, r = 500, 60, 0.98
t = np.arange(0, 4, 1/fs)
y = notch(np.ones_like(t), fs, f0, r)
assert abs(y[-1] - 1) < 1e-9, f"The gain at DC must be exactly 1; a constant input settles to {y[-1]:.6f}."
y = notch(np.sin(2*np.pi*60*t), fs, f0, r)
amp = np.max(np.abs(y[len(t)//2:]))
assert amp < 1e-6, f"A 60 Hz sine should be removed completely once the transient dies; {amp:.2e} remains."
w0 = 2*np.pi*f0/fs
c = np.cos(w0)
g = (1 - 2*r*c + r*r)/(2 - 2*c)
for f in (10.0, 40.0, 100.0):
    z = np.exp(1j*2*np.pi*f/fs)
    H = g*(1 - 2*c/z + 1/z**2)/(1 - 2*r*c/z + r*r/z**2)
    y = notch(np.sin(2*np.pi*f*t), fs, f0, r)
    h = len(t)//2
    M = np.column_stack([np.sin(2*np.pi*f*t[h:]), np.cos(2*np.pi*f*t[h:])])
    amp = np.hypot(*np.linalg.lstsq(M, y[h:], rcond=None)[0])
    assert abs(amp - abs(H)) < 2e-3, f"At {f} Hz the gain should be {abs(H):.4f}; your steady-state amplitude is {amp:.4f}."
```

::: right
Right. Your notch has unit gain at DC, removes 60 Hz completely and matches its designed response elsewhere.
:::
:::

::: check
kind: python

## Step 3. Write `detect_beats` and `heart_rate`: find every QRS complex.

```python starter
import numpy as np

def detect_beats(x, fs):
    # Return the sample indices of the R peaks in the ECG x (in mV) sampled at fs.
    # A Pan-Tompkins-style approach: smooth over about 20 ms, differentiate, square, integrate
    # over about 150 ms, find peaks of the result above a threshold (with a 250 ms refractory
    # period), then move each detection to the largest value of x within 75 ms.
    return np.array([], dtype=int)

def heart_rate(beats, fs):
    # Mean heart rate in beats per minute from the R-peak indices.
    return 0.0

rng = np.random.default_rng(0)
fs = 500
t = np.arange(0, 5, 1/fs)
x = np.exp(-((t - 1)/0.01)**2/2) + np.exp(-((t - 2)/0.01)**2/2)
b = detect_beats(x, fs)
print(b, heart_rate(b, fs))
```

```python solution
import numpy as np

def detect_beats(x, fs):
    x = np.asarray(x, dtype=float)
    k = max(1, int(0.02*fs))
    xs = np.convolve(x, np.ones(k)/k, mode='same')
    d = np.zeros_like(xs)
    d[2:-2] = xs[4:] - xs[:-4]
    s = d*d
    w = max(1, int(0.15*fs))
    m = np.convolve(s, np.ones(w)/w, mode='same')
    th = 0.3*np.max(m)
    ref = int(0.25*fs)
    beats = []
    n = 0
    while n < len(m):
        if m[n] > th:
            hi = min(len(m), n + ref)
            j = n + int(np.argmax(m[n:hi]))
            a, b = max(0, j - int(0.075*fs)), min(len(x), j + int(0.075*fs) + 1)
            r = a + int(np.argmax(x[a:b]))
            if not beats or r - beats[-1] > ref:
                beats.append(r)
            n = hi
        else:
            n += 1
    return np.array(beats, dtype=int)

def heart_rate(beats, fs):
    return 60.0/np.mean(np.diff(beats)/fs)

rng = np.random.default_rng(0)
fs = 500
t = np.arange(0, 5, 1/fs)
x = np.exp(-((t - 1)/0.01)**2/2) + np.exp(-((t - 2)/0.01)**2/2)
b = detect_beats(x, fs)
print(b, heart_rate(b, fs))
```

```python tests
def synth(rr, fs, rng):
    T = np.sum(rr) + 1.0
    t = np.arange(0, T, 1/fs)
    x = np.zeros_like(t)
    times = 0.5 + np.concatenate([[0], np.cumsum(rr[:-1])])
    for tr in times:
        x += 0.15*np.exp(-((t - tr + 0.16)/0.025)**2/2)
        x += 1.0*np.exp(-((t - tr)/0.01)**2/2) - 0.15*np.exp(-((t - tr - 0.03)/0.012)**2/2)
        x += 0.3*np.exp(-((t - tr - 0.3)/0.04)**2/2)
    x += 0.3*np.sin(2*np.pi*0.25*t) + 0.05*rng.standard_normal(len(t))
    return x, np.round(times*fs).astype(int)

rng = np.random.default_rng(4)
fs = 500
for trial in range(3):
    rr = rng.uniform(0.6, 1.1, 20)
    x, truth = synth(rr, fs, rng)
    b = np.asarray(detect_beats(x, fs))
    assert len(b) == len(truth), f"The record has {len(truth)} beats; you found {len(b)}."
    err = np.max(np.abs(b - truth))/fs
    assert err <= 0.02, f"Each detection should be within 20 ms of its R peak; the worst is {err*1000:.1f} ms off."
    hr = heart_rate(truth, fs)
    assert abs(heart_rate(b, fs) - hr) < 1.0, f"The mean heart rate should be {hr:.1f} per minute; you computed {heart_rate(b, fs):.1f}."
```

::: right
Right. Your detector finds every beat within 20 ms, with no false detections, despite baseline wander and noise.
:::
:::

::: explain
## Why does the detector square the derivative and then average it, instead of thresholding the ECG itself?

::: model
Thresholding the raw ECG fails because baseline wander can lift a T wave or even a P wave above a tall R wave elsewhere, and the R wave's height varies with posture and lead. The QRS's distinctive feature is its steepness: it changes by a millivolt in a few tens of milliseconds, far faster than the P and T waves or the baseline, so the derivative picks it out. Squaring makes every slope positive and emphasizes the steepest ones, and averaging over about the width of a QRS merges its up and down slopes into one smooth bump per beat, which a single threshold can find. The smoothing and refractory period keep noise spikes and the two halves of one QRS from counting as separate beats.
:::
:::

::: practice

::: check
given: f = 0.05 | 0.5 | 1; s = 250 | 500 | 1000
answer: (1/(2*pi*f))/((1/(2*pi*f)) + 1/s)
tolerance: 0.05%

## First-order high-pass coefficient a: corner {f} Hz, {s} samples/s?

::: misses
- [any] $a = \tau/(\tau + T)$.
:::
:::

::: check
given: r = 0.9 | 0.95 | 0.99; s = 250 | 500 | 1000
answer: (1 - r)*s/pi
unit: Hz
tolerance: 0.5%

## Approximate notch width: r = {r}, {s} samples/s?

::: misses
- [any] $(1 - r)f_s/\pi$.
:::
:::

::: check
given: n = 60 | 90; t = 50 | 90
answer: 60*n/t
tolerance: 0.5%

## {n} beats are found in {t} s. What's the mean heart rate per minute?

::: misses
- [any] Beats per second × 60.
:::
:::
:::
