-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
207 lines (173 loc) · 7.89 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
from numpy import *
from scipy import signal
import matplotlib
matplotlib.use('WXAgg')
from matplotlib import pyplot
from matplotlib.patches import Circle
class Filter(object):
def __init__(self, fp, fs, gpass, gstop, ftype, btype):
#Variables init.
self.fp = fp
self.fs = fs
self.gpass = gpass
self.gstop = gstop
self.ftype = ftype
self.btype = btype
#Filter type for plot's title.
types_dict = {"butter":"Butterworth", "cheby1":"Chebyshev I", "cheby2":"Chebyshev II", "ellip": "Cauer"}
self.ftype_plot = types_dict[ftype]
self.__wsk()
self.__filter_order()
#Designing filter.
(self.b, self.a) = signal.iirfilter(self.ord,
self.wn,
rp=self.gpass,
rs=self.gstop,
btype=self.btype,
analog=True,
output='ba',
ftype=ftype)
#Frequency response of analog filter.
(self.w, self.h) = signal.freqs(self.b, self.a, worN=1000)
#Denormalizing variabels for ploting. Pulsation to frequency.
self.w = (self.w * (self.sampling_w / 2)) / (2 * pi)
self.wn = (self.wn * (self.sampling_w / 2)) / (2 * pi)
def phase_response(self):
"""Plotting PHASE response of the filter."""
pyplot.figure()
pyplot.plot(self.w, unwrap((angle(self.h))))
pyplot.grid(True)
pyplot.xlim(min(self.w), max(self.w))
pyplot.title('Phase Response' + "\n" + str(self.ord) + "th order " + self.btype + " " + self.ftype_plot + " filter")
def freq_response(self):
"""Plotting FREQUENCY response of filter."""
pyplot.figure()
pyplot.plot(self.w, abs(self.h))
pyplot.title('Frequency Response' + "\n" + str(self.ord) + "th order " + self.btype + " " + self.ftype_plot + " filter")
pyplot.xlabel('Frequency')
pyplot.ylabel('Magnitude')
pyplot.grid(True)
self.axis_formatter = [min(self.w), max(self.w)*self.xaxis_max, 0, 1.2]
pyplot.axis(self.axis_formatter)
pyplot.vlines(self.wn, 0, 1.2, color='k', linestyles='dashdot', label="wn")
def poles_zeros(self):
"""Computing and plotting POLES-ZEROS of the filter"""
pyplot.figure(figsize=(6, 6))
(p, z, k) = signal.tf2zpk(self.b, self.a)
if self.ftype == 'butter':
z = -(z / min(real(z)))
circle = Circle((0, 0), radius=abs(max(z)), linestyle='dotted', fill=False)
try:
p = -(p / min(real(p)))
except ValueError:
pass
else:
circle = Circle((0, 0), radius=1, linestyle='dotted', fill=False)
#Plotting Poles-zeros
#pyplot.scatter(real(p), imag(p), marker='o', s=50)
pyplot.scatter(real(z), imag(z), marker='x', s=100)
pyplot.xlabel('Real Part')
pyplot.ylabel('Imaginary Part')
pyplot.title('Pole-zeros' + "\n" + str(self.ord) + "th order " + self.btype + " " + self.ftype_plot + " filter")
#Formatting plot.
pyplot.gca().add_patch(circle)
limits = []
limits.append(max(pyplot.gca().get_xlim()))
limits.append(max(pyplot.gca().get_ylim()))
max_limit = max(limits)
if max_limit < 1.2:
max_limit = 1.2
pyplot.axis([-max_limit, max_limit, -max_limit, max_limit])
pyplot.vlines(0, -max_limit, max_limit, color='k', linestyles='dotted')
pyplot.hlines(0, -max_limit, max_limit, color='k', linestyles='dotted')
def step_response(self):
"""Computing and plotting STEP response of the filter."""
(T, yout) = signal.step((self.b, self.a))
#Plotting step response
pyplot.figure()
try:
pyplot.plot(T, yout)
except ComplexWarning:
pass
pyplot.grid(True)
pyplot.xlabel('Time')
pyplot.xlim(min(T), max(T))
pyplot.title('Impulse response' + "\n" + str(self.ord) + "th order " + self.btype + " " + self.ftype_plot + " filter")
""" PRIVATE METHODS """
def __filter_order(self):
""" Computing filters order and maximum value of X axis. """
if self.ftype == "butter":
if self.btype == 'highpass':
self.xaxis_max = 0.2
else:
self.xaxis_max = 0.15
(self.ord, self.wn) = signal.buttord(self.wp_norm,
self.ws_norm,
self.gpass,
self.gstop,
analog=True)
elif self.ftype == "cheby1":
if self.btype == 'highpass':
self.xaxis_max = 0.6
else:
self.xaxis_max = 0.15
(self.ord, self.wn) = signal.cheb1ord(self.wp_norm,
self.ws_norm,
self.gpass,
self.gstop,
analog=True)
elif self.ftype == "cheby2":
if self.btype == 'highpass':
self.xaxis_max = 0.2
else:
self.xaxis_max = 0.3
(self.ord, self.wn) = signal.cheb2ord(self.wp_norm,
self.ws_norm,
self.gpass,
self.gstop,
analog=True)
elif self.ftype == "ellip":
if self.btype == 'highpass':
self.xaxis_max = 0.6
else:
self.xaxis_max = 0.2
(self.ord, self.wn) = signal.ellipord(self.wp_norm,
self.ws_norm,
self.gpass,
self.gstop,
analog=True)
def __wsk(self):
""" Compute sampling frequency due to Whittaker-Nyquist-Kotelnikov-Shannon law. """
if type(self.fp) and type(self.fs) is list:
#Computing omegas [rad/s]
self.wp = [fp * 2 * pi for fp in self.fp]
self.ws = [fs * 2 * pi for fs in self.fs]
#Computing sampling frequency due to Whittaker-Nyquist-Kotelnikov-Shannon law.
if max(self.wp) > max(self.ws):
self.sampling_w = 2 * max(self.wp)
else:
self.sampling_w = 2 * max(self.ws)
#Normalizing omegas due to Nyquist frequency.
self.wp_norm = [wp / (self.sampling_w / 2) for wp in self.wp]
self.ws_norm = [ws / (self.sampling_w / 2) for ws in self.ws]
else:
#Computing omegas [rad/s]
self.wp = 2 * pi * self.fp
self.ws = 2 * pi * self.fs
#Computing sampling frequency due to Whittaker-Nyquist-Kotelnikov-Shannon law.
if self.wp > self.ws:
self.sampling_w = 2 * self.wp
self.btype = "highpass"
else:
self.sampling_w = 2 * self.ws
self.btype = 'lowpass'
#Normalizing omegas due to Nyquist frequency.
self.wp_norm = self.wp / (self.sampling_w / 2)
self.ws_norm = self.ws / (self.sampling_w / 2)
if __name__ == '__main__':
filter1 = Filter([500, 1000], [600, 900], 1.0, 20.0, ftype="butter", btype='bandstop')
filter1.poles_zeros()
filter1.freq_response()
filter1.step_response()
filter1.phase_response()
pyplot.show()