0
0
SciPydata~5 mins

FIR filter design (firwin) in SciPy

Choose your learning style9 modes available
Introduction

We use FIR filters to clean signals by removing unwanted parts like noise. The firwin function helps us create these filters easily.

You want to remove noise from a sound recording.
You need to smooth sensor data before analysis.
You want to isolate a specific frequency range in a signal.
You are preparing data for machine learning by filtering out irrelevant frequencies.
Syntax
SciPy
scipy.signal.firwin(numtaps, cutoff, window='hamming', pass_zero=True, fs=2.0)

numtaps is the number of filter coefficients (length of the filter).

cutoff is the cutoff frequency or frequencies in Hz.

Examples
Creates a low-pass FIR filter with 31 taps and cutoff at 0.3 times the Nyquist frequency.
SciPy
firwin(31, 0.3)
Creates a band-pass FIR filter with 51 taps passing frequencies between 0.2 and 0.5 times Nyquist.
SciPy
firwin(51, [0.2, 0.5], pass_zero=False)
Creates a low-pass FIR filter with cutoff at 1000 Hz when sampling rate is 8000 Hz.
SciPy
firwin(41, 1000, fs=8000)
Sample Program

This code creates a low-pass FIR filter with a cutoff at 1000 Hz for a signal sampled at 8000 Hz. It then plots how the filter affects different frequencies.

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

# Design a low-pass FIR filter
numtaps = 31
cutoff_hz = 1000
fs = 8000  # Sampling frequency

# Create filter coefficients
fir_coeff = firwin(numtaps, cutoff_hz, fs=fs)

# Frequency response
w, h = freqz(fir_coeff, worN=8000, fs=fs)

# Plot filter response
plt.plot(w, 20 * np.log10(abs(h)))
plt.title('Low-pass FIR filter frequency response')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Gain (dB)')
plt.grid(True)
plt.show()
OutputSuccess
Important Notes

The number of taps (numtaps) affects how sharp the filter is and how much delay it adds.

Cutoff frequencies must be less than half the sampling rate (Nyquist frequency).

Use pass_zero=True for low-pass or high-pass filters, and pass_zero=False for band-pass or band-stop filters.

Summary

FIR filters help clean signals by removing unwanted frequencies.

firwin creates filter coefficients easily by specifying taps and cutoff.

Always consider sampling rate and filter length for good results.