design a band pass filter in python

To design a band pass filter in Python, we can use the scipy library. Specifically, we will use the scipy.signal module to construct a digital filter. The steps to design a band pass filter are:

  1. Specify the desired filter characteristics, such as the filter type, frequency range, and transition bandwidth.
  2. Determine the filter order and passband ripple based on the desired response.
  3. Use the filter design function to generate the filter coefficients.
  4. Apply the filter to the input signal using the lfilter function.

Here is an example code snippet that designs and applies a band pass filter to a signal:

main.py
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

# Generate a signal with noise
t = np.linspace(0, 1, 1000, False)
sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t) + 0.5*np.random.randn(len(t))

# Specify the filter parameters
fs = 1000 # Sampling rate
fpass = [15, 25] # Passband frequency range
fstop = [10, 30] # Stopband frequency range
transition_width = 100 # Width of transition region in Hz
ripple_db = 1 # Passband ripple in dB

# Compute the filter order and passband ripple based on the desired response
N, Wn = signal.buttord(2*np.pi*np.array(fpass)/fs, 2*np.pi*np.array(fstop)/fs, ripple_db, transition_width)

# Design the filter coefficients
b, a = signal.butter(N, Wn, 'bandpass', analog=False, fs=fs)

# Apply the filter to the signal
filtered_sig = signal.lfilter(b, a, sig)

# Plot the original and filtered signals
plt.figure()
plt.plot(t, sig, label='Original signal')
plt.plot(t, filtered_sig, label='Filtered signal')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.legend()
plt.show()
1041 chars
33 lines

Here, we first generate a signal with noise that contains two sine waves at 10 Hz and 20 Hz. We then specify the desired filter parameters, which include a passband frequency range of 15-25 Hz and a transition region of 100 Hz. We use the buttord function to compute the filter order and passband ripple, and then use the butter function to design the filter coefficients. Finally, we apply the filter to the signal using the lfilter function and plot the original and filtered signals.

gistlibby LogSnag