IIR filter python code | LPF, HPF, BPF, BSF types

This IIR filter python code script covers simulation of LPF, HPF, BPF and BSF filter types in python. The plots are provided as outputs of this IIR python script.

Introduction : IIR filter uses current input sample value, past input and output samples to obtain current output sample value.

IIR filter

Simple IIR equation is mention below.
y(n)= b(0)x(n) + b(1)x(n-1) + b(2)x(n-2) + b(3)x(n-3) + a(1)y(n-1) + a(2)y(n-2) + a(3)y(n-3)
Refer FIR vs IIR filter for more information.

IIR filter python code

import matplotlib.pyplot as plt
import scipy.signal as sig
import numpy as np
from math import pi
plt.close('all')
# IIR filter design as per butterworth specifications
Fs = 1000 # sampling frequency
n = 7 # Number of orders of the filter
fc = 100 # Cutoff frequency of the filter (For LPF/HPF)
fc1 = np.array([200, 400]) # Start and Stop frequencies for BPF/BSF
w_c = 2 * fc/Fs
w_c1 = 2 * fc1/Fs
# IIR filter configurations of different types
[b1, a1] = sig.butter(n, w_c, btype='lowpass')
[b2, a2] = sig.butter(n, w_c, btype='highpass')
[b3, a3] = sig.butter(n, w_c1, btype='bandpass')
[b4, a4] = sig.butter(n, w_c1, btype='bandstop')
# Frequency response of IIR filter (LPF type)
[w1, h1] = sig.freqz(b1, a1, worN=2000)
w_lpf = Fs*w1/(2*pi)
h_db_lpf = 20 * np.log10(abs(h1))
# Frequency response of IIR filter (HPF type)
[w2, h2] = sig.freqz(b2, a2, worN=2000)
w_hpf = Fs*w2/(2*pi)
h_db_hpf = 20 * np.log10(abs(h2))
# Frequency response of IIR filter (BPF type)
[w3, h3] = sig.freqz(b3, a3, worN=2000)
w_bpf = Fs*w3/(2*pi)
h_db_bpf = 20 * np.log10(abs(h3))
# Frequency response of IIR filter (BSF type)
[w4, h4] = sig.freqz(b4, a4, worN=2000)
w_bsf = Fs*w4/(2*pi)
h_db_bsf = 20 * np.log10(abs(h4))
# Plots
figure, axis = plt.subplots(2, 2)
axis[0, 0].plot(w_lpf, h_db_lpf)
axis[0, 0].set_title("IIR filter response (LPF type)")
axis[0, 0].set_xlabel("Frequency (Hz)")
axis[0, 0].set_ylabel("Magnitude (dB)")
axis[0, 1].plot(w_hpf, h_db_hpf)
axis[0, 1].set_title("IIR filter response (HPF type)")
axis[0, 1].set_xlabel("Frequency (Hz)")
axis[0, 1].set_ylabel("Magnitude (dB)")
axis[1, 0].plot(w_bpf, h_db_bpf)
axis[1, 0].set_title("IIR filter response (BPF type)")
axis[1, 0].set_xlabel("Frequency (Hz)")
axis[1, 0].set_ylabel("Magnitude (dB)")
axis[1, 1].plot(w_bsf, h_db_bsf)
axis[1, 1].set_title("IIR filter response (BSF type)")
axis[1, 1].set_xlabel("Frequency (Hz)")
axis[1, 1].set_ylabel("Magnitude (dB)")
plt.tight_layout()
plt.show()

IIR python Output plots

Following are the plots of above IIR python code.

IIR Filter Python output plots

Other useful DSP codes in Python

Useful Links to MATLAB codes

RF and Wireless tutorials