on
DSP 104
Notch filters are a type of filter that removes only a very narrow frequency band from a signal. This is useful, for example, when you have a low level microphone or ECG/EEG signal that is contaminated with 50 or 60 Hz line noise; one can just notch out the 50 or 60 Hz signal. Other applications include notching out narrow band interference in communications receivers.
A second-order notch filter
A simple tunable second order notch filter can be implemented by a biquad filter structure. The coefficients are as follows: $$ b_0 = 1 $$ $$ b_1 = -2\cdot \cos(w_c) $$ $$ b_2 = 1 $$ $$ a_1 = -2\cdot \alpha \cdot \cos(w_c) $$ $$ a_2 = \alpha^2 $$ with $w_c = \dfrac{2\cdot\pi\cdot fc}{fs}$, where $f_c$ is the notch frequency in Hz and $f_s$ is the sample rate.
The variable $\alpha$ sets the bandwidth of the notch: $\alpha = \exp \left ( \dfrac{-\pi\cdot bw}{f_s}\right )$, where $bw$ is the notch bandwidth in Hz.
Note that $\alpha$ depends only on the desired notch bandwidth $bw$ and not on the notch frequency $f_c$, so it can be pre-calculated if the desired notch bandwidth is always constant.
The following Python script calculates the coefficients and plots the frequency response:
import numpy as np
import scipy.signal as signal
import matplotlib.pyplot as plt
fs = 48000 # the sample rate in Hz
fc = 1000 # the notch frequency in Hz
bw = 100 # bandwidth of filter in Hz
# calculate the cutoff in radians per sample
wc = 2*3.1415927*fc/fs
# calculate alpha to set the bandwidth
alpha = np.exp(-3.1415927*bw/fs)
# calculate biquad coefficients
b0 = 1
b1 = -2*np.cos(wc)
b2 = 1
a1 = alpha*b1
a2 = alpha*alpha
# build second order sections array
sos = [[b0,b1,b2,1.0,a1,a2]]
print(f"Biquad coefficients: {sos[0]}")
# plot the frequency response
w,h = signal.sosfreqz(sos, worN=4096, fs=fs)
plt.figure(1)
plt.semilogx(w, 20*np.log10(np.abs(h)))
plt.grid()
plt.title("Notch filter frequency response")
plt.xlabel("Frequency [Hz]")
plt.ylabel("Magnitude [dB]")
plt.show()
The output of the script gives the biquad coefficients:
Biquad coefficients: [1, -1.9828897222428086, 1, 1.0, -1.9699541170135817, 0.9869953314668142]
and the following plot:

Figure 1: Frequency response of the notch filter