0
0
SciPydata~5 mins

IIR filter design (butter, cheby1) in SciPy

Choose your learning style9 modes available
Introduction

IIR filters help clean signals by removing unwanted noise or parts. Butterworth and Chebyshev filters are common ways to design these filters.

You want to remove noise from a sound recording.
You need to smooth sensor data before analysis.
You want to keep only certain frequencies in a signal, like bass or treble.
You are working on real-time signal processing where fast filtering is needed.
Syntax
SciPy
from scipy.signal import butter, cheby1

# Butterworth filter design
b, a = butter(order, cutoff_freq, btype='low', fs=sample_rate)

# Chebyshev type 1 filter design
b, a = cheby1(order, ripple, cutoff_freq, btype='low', fs=sample_rate)

order controls filter sharpness; higher means sharper cutoff.

cutoff_freq is the frequency where filtering starts (in Hz).

Examples
Creates a 4th order Butterworth low-pass filter with cutoff at 1000 Hz for a signal sampled at 8000 Hz.
SciPy
b, a = butter(4, 1000, btype='low', fs=8000)
Creates a 3rd order Chebyshev type 1 high-pass filter with 1 dB ripple and cutoff at 2000 Hz.
SciPy
b, a = cheby1(3, 1, 2000, btype='high', fs=8000)
Sample Program

This code creates two filters: a Butterworth low-pass and a Chebyshev high-pass. It then plots their frequency responses so you can see how they affect different frequencies.

SciPy
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import butter, cheby1, freqz

# Sample rate and desired cutoff frequencies (Hz)
sample_rate = 8000
cutoff_low = 1000
cutoff_high = 2000

# Design Butterworth low-pass filter
b_butter, a_butter = butter(4, cutoff_low, btype='low', fs=sample_rate)

# Design Chebyshev type 1 high-pass filter with 1 dB ripple
b_cheby, a_cheby = cheby1(3, 1, cutoff_high, btype='high', fs=sample_rate)

# Frequency response for Butterworth
w_butter, h_butter = freqz(b_butter, a_butter, fs=sample_rate)

# Frequency response for Chebyshev
w_cheby, h_cheby = freqz(b_cheby, a_cheby, fs=sample_rate)

# Plot frequency responses
plt.figure(figsize=(8, 5))
plt.plot(w_butter, 20 * np.log10(abs(h_butter)), label='Butterworth Low-pass')
plt.plot(w_cheby, 20 * np.log10(abs(h_cheby)), label='Chebyshev High-pass')
plt.title('Frequency Response of IIR Filters')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Amplitude (dB)')
plt.ylim(-60, 5)
plt.grid(True)
plt.legend()
plt.show()
OutputSuccess
Important Notes

Butterworth filters have a smooth response with no ripples in the passband.

Chebyshev type 1 filters allow ripples in the passband but have a sharper cutoff.

Always specify the sample rate (fs) to use frequencies in Hz directly.

Summary

IIR filters help remove unwanted parts of signals.

Butterworth filters are smooth and simple.

Chebyshev filters can be sharper but have ripples.