Python Scipy IIR Filter + Examples

We will learn about the “Python Scipy IIR Filter” in this tutorial so that we may design and create IIR filters that are analogue and digital with various orders and hertz. Include the following topics as well.

  • What is IIR Filter?
  • Python Scipy IIR Filter Design
  • Python Scipy IIR Filter Freqz
  • Python Scipy IIR Filter Sos
  • Python Scipy IIR Filter Bandpass
  • Python Scipy IIR Filter Coefficients
  • Python Scipy IIR Filter Digital

Also, check the latest Python Scipy tutorial: Python Scipy Softmax

What is IIR Filter?

Digital signal processing (DSP) applications use one of two main types of digital filters, IIR filters (the other type being FIR). Infinite Impulse Response is referred to as “IIR.”

Due to feedback in the filter, the impulse response is “infinite,” meaning that if you apply an impulse (a single “1” sample followed by several “0” samples), you will get an endless number of non-zero values.

IIR filters use less memory and computation to accomplish a given filtering characteristic than a comparable FIR filter.

Python Scipy IIR Filter Freqz

In the part above, we learned about the IIR Filter concept. In this section, we will use that method to create a filter and then use the output to compute the frequency response of a digital filter using the freqz() function.

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

import numpy as np
from scipy.signal import iirfilter, freqz

Create a 50 Hz–200 Hz 15th-order Chebyshev II analogue bandpass filter using the below code.

b, a = iirfilter(15, [2*np.pi*50, 2*np.pi*200], rs=50,
                        btype='band', analog=True, ftype='cheby2')

Now compute a digital filter’s frequency response using the below code.

w, h = freqz(b, a, 1000)
print("w = {},h={}".format(w,h))
Python Scipy IIR Filter Freqz
Python Scipy IIR Filter Freqz

From the above output, we can take the values and plot it to see how the IIR filter looks, this is how to create IIR Filter using the method iirfilter() of Python Scipy.

Read: Python Scipy Stats Fit + Examples

Python Scipy IIR Filter Sos

To calculate a digital filter’s frequency response in SOS format or calculate the system function’s frequency response given sos, an array of second-order digital filter sections with the shape (n, 6) that has been provided. The Python Scipy module scipy.signal has a method sosfreqz().

The syntax is given below.

scipy.signal.sosfreqz(sos, whole=False, worN=512, fs=6.283185307179586)

Where parameters are:

  • sos(array_data): A second-order filter coefficient array with the shape (n sections, 6) is required. The first three columns give the numerator coefficients and the final three give the denominator coefficients, and each row represents a second-order section.
  • whole(boolean): The Nyquist frequency, fs/2, is the standard range from which frequencies are calculated (upper-half of unit-circle). Do a frequency calculation from 0 to fs if the entire is True. ignored if worN is array-like.
  • wordN(int, array, None): Calculate at that many frequencies if there is only one integer (the default N value is 512). This is a practical substitution for: “np.linspace(0, fs if whole else fs/2, N, endpoint=include_nyquist)”. It is possible to accelerate computations by using a fast number for FFT calculations. Calculate the response at the specified frequencies if the data is array-like. These are measured in fs-compatible units.
  • fs(float): the system’s sampling rate in digital form. defaults to radians/sample at 2*pi (so w is from 0 to pi).
READ:  Django CRUD Example with PostgreSQL

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

from scipy.signal import ellip, sosfreqz

Create an SOS-formatted 20th-order bandpass filter using the below code.

sos_format = ellip(20, 0.4, 70, (0.3, 0.5), btype='bandpass',
                   output='sos')

Calculate the frequency response between DC and Nyquist at 2000 points using the below code.

w, h = sosfreqz(sos_format, worN=2000)
print("w = {},h={}".format(w,h))
Python Scipy Freqz Sos
Python Scipy Freqz Sos

This is how to compute the digital filter’s frequency response using the method sosfreqz() of Python Scipy.

Read: Python Scipy ttest_ind – Complete Guide

Python Scipy IIR Filter Design

The method iirdesign() of Python Scipy that exists in a module scipy.signal is used to complete the design of IIR digital and analogue filters.

It creates an analogue or digital IIR filter of the required minimum order for the specified basic type, given the passband and stopband frequencies and gains. Return the result in the numerator, denominator, pole-zero, second-order sections, or pole-zero (‘ba’) form.

The syntax is given below.

scipy.signal.iirdesign(wp, ws, gpass, gstop, analog=False, ftype='ellip', output='ba', fs=None)

Where parameters are:

  • wp,ws(float): Edge frequencies for stopband and passband. Scalars (for lowpass and highpass filters) or ranges are potential values (for bandpass and bandstop filters). These are in the same units as fs for digital filters. The samples are normalized from 0 to 1, where 1 is the Nyquist frequency since fs by default is 2 half-cycles per sample.
  • gpass: Passband’s maximum loss at its maximum (dB).
  • gstop: The stopband’s minimal attenuation (dB).
  • analog(boolean): Return an analogue filter if True; else, return a digital filter.
  • ftype(str): The kind of IIR filter to create: cheby1, butter, cheby2, ellip and bessel.
  • output: Form of the output filter: 'sos' for second-order sections, The default numerator and denominator is "ba" and Zero pole: "zpk".
  • fs(float): The system’s sampling rate in digital form.
READ:  Python Tkinter Progress bar widget - How to use

Let’s see with an example by following the below steps:

Import the required libraries or methods using the below python code.

from scipy.signal import freqz, iirdesign

Assign the values to the parameters of the method iirdesign() using the below code.

wp_ = 0.3
ws_ = 0.2
gpass_ = 2
gstop_ = 45

Create the design of the IIR filter using the below code.

system_ = iirdesign(wp_, ws_, gpass_, gstop_)
w_, h_ = freqz(*system_)

print(w_)
print(h_)
Python Scipy IIR Filter Design
Python Scipy IIR Filter Design

This is how to design the analog and digital filter using the method iirdesign() of Python Scipy.

Read: Python Scipy Mann Whitneyu

Python Scipy IIR Filter Bandpass

A bandpass filter is an electrical component or circuit that discriminates against signals at other frequencies while permitting signals between two designated frequencies to pass.

Active bandpass filters are those bandpass filters that use active parts like transistors and integrated circuits that need an external power source. Passive bandpass filters are those that don’t require an external power source and are made entirely of passive parts like capacitors and inductors.

The Python Scipy method iirfilter() accepts a parameter btype to specify the type of filters like lowpass, bandpass, bandstop and highpass.

Here in this section, we will create the IIR Filter of type bandpass signal by following the below steps:

Import the required libraries using the below python code.

import numpy as np
from scipy.signal import iirfilter, freqz

Use the code below to create an analogue 14th-order of 30 Hz-150 Hz bandpass filter.

b, a = iirfilter(14, [2*np.pi*30, 2*np.pi*150], rs=50,
                        btype='band', analog=True, ftype='cheby2')

In the above code, the parameter btype is equal to band which means bandpass.

Now use the code below to calculate a digital filter’s frequency response.

w, h = freqz(b, a, 600)
print("w = {},h={}".format(w,h))
Python Scipy IIR Filter Bandpass
Python Scipy IIR Filter Bandpass

This is how to build an IIR filter of type bandpass filter using the method iirfilter() with parameter btype of Python Scipy.

Read: Python Scipy Stats Poisson

Python Scipy IIR Filter Coefficients

The Python Scipy method iirfilter() accepts a parameter output to return the different types of results like 'sos' for second-order sections, The default numerator and denominator is "ba" and Zero pole: "zpk". So here in this section, we will get the values of the coefficients numerator and denominator as output by specifying the output = 'ba'.

The difference equation’s coefficients are the filter coefficients. If your filter is an FIR filter, the impulse response values are the filter coefficients. The filter coefficients and impulse response are not the same if you have an IIR filter.

READ:  Modulenotfounderror no module named ‘tensorflow.keras.utils.np_utils’

Let’s compute the coefficients of the IIR filter by following the below steps:

Import the required libraries using the below python code.

from scipy.signal import iirfilter
import numpy as np

Generate an analogue 10th-order of 20 Hz-100 Hz bandpass filter.

b_num, a_deno = iirfilter(10, [2*np.pi*20, 2*np.pi*100], rs=40,
                        btype='band', analog=True, ftype='cheby2',output='ba')

print('Numerator Coeffiecints',b_num)
print('Denominator Coeffiecints',b_num)

In the above code, the parameter output is equal to ba which means numerator and denominator coeffiecints .

Python Scipy IIR Filter Coefficients
Python Scipy IIR Filter Coefficients

This is how to compute the coefficients of the IIR filter using the method iirfilter() with parameter output of Python Scipy.

Read: Python Scipy Eigenvalues

Python Scipy IIR Filter Digital

The parameter analog of type boolean is accepted by the method iirfilter() to specify what kind of IIR filter, we want to create like analogue or digital. The parameter accepts two values True or False, the true values are for the analogue filter and otherwise digital filter for false values.

Let’s take an example and build the IIR analogue filter by following the below steps:

Import the required libraries or methods using the below python code.

from scipy.signal import iirfilter

Create a digital IIR filter using the below code.

iirfilter(15,[0.2, 0.9], rs=60,
                        btype='band', analog=False, ftype='cheby2')
Python Scipy IIR Filter Digital
Python Scipy IIR Filter Digital

In the above code, we have specified analog equal False which means the above output is values of the digital IIR filter. This is how to create a digital IIR Filter using the method iirfilter() with the parameter analog of Python Scipy.

Also, take a look at some more Python SciPy tutorials.

So, in this tutorial, we have learned about the “Python Scipy IIR Filter” and covered the following topics.

  • What is IIR Filter?
  • Python Scipy IIR Filter Design
  • Python Scipy IIR Filter Freqz
  • Python Scipy IIR Filter Sos
  • Python Scipy IIR Filter Bandpass
  • Python Scipy IIR Filter Coefficients
  • Python Scipy IIR Filter Digital