IN PYTHON: The scipy library of matplotlib in Python 3 contains a function \"sci
ID: 3872585 • Letter: I
Question
IN PYTHON:
The scipy library of matplotlib in Python 3 contains a function "scipy.signal.freqz" which computes the frequency response of a digital filter. I am trying to write my own version of this function, to relay the same output as this imbedded function. I plan to use the inputs: freqz(b, a = 1, worN=None, whole=None): [b=numerator of linear filter; a=denominator of linear filter; worN=at none, compute at 512 frequencies equally spaced around the unit circle; whole=at none, frequency computed around upper half of unit circle, from 0 to pi]. This function should output two outputs: w and h
After implementing the function, it should pass all the tests provided in the last part of code. Need to implement scipy.signal.freqz using different ways other than source code and FFT.
I am going to provide the code that I am given. Supposed to translate the equation into code.
Code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sig
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (5,3)
%matplotlib inline
# Implementation of freqz using different way.
Please use the same variables
def my_freqz(b, a = 1, worN=None, whole=None):
#replace with your answer
pass
Testing code:
from collections import namedtuple
Test = namedtuple('Test',['b','a','worN','whole'])
tests = [ Test([1,0.5,0.1], [1,1], 256, None),
Test(1,1,None, True),
Test(1,1,12, False),
Test([1,2],1,[0,1,2,3], None) ]
b,a = sig.iirdesign(0.2, 0.3, 1, 20)
tests.append(Test(b,a,None,None))
b = sig.firwin(63, 0.25)
tests.append(Test(b,1,1024,None))
for test in tests:
w, h = sig.freqz(test.b, test.a, test.worN, test.whole)
my_w, my_h = my_freqz(test.b, test.a, test.worN, test.whole)
print(np.allclose(w, my_w), np.allclose(h, my_h))
Tests should output TRUE for all.
Output should look like
True True
True True
True True
True True
jll jw jwM h(e )= -= jw jwN jll A(eala[1]e + a[N]eExplanation / Answer
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sig
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (5,3)
%matplotlib inline
def my_freqz(b, a = 1, worN=None, whole=None):
from collections import namedtuple
Test = namedtuple('Test',['b','a','worN','whole'])
tests = [ Test([1,0.5,0.1], [1,1], 256, None),
Test(1,1,None, True),
Test(1,1,12, False),
Test([1,2],1,[0,1,2,3], None) ]
b,a = sig.iirdesign(0.2, 0.3, 1, 20)
tests.append(Test(b,a,None,None))
b = sig.firwin(63, 0.25)
tests.append(Test(b,1,1024,None))
for test in tests:
w, h = sig.freqz(test.b, test.a, test.worN, test.whole)
my_w, my_h = my_freqz(test.b, test.a, test.worN, test.whole)
print(np.allclose(w, my_w), np.allclose(h, my_h))