-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapproximation.py
More file actions
192 lines (170 loc) · 8.24 KB
/
approximation.py
File metadata and controls
192 lines (170 loc) · 8.24 KB
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
from IPython.display import display
import matplotlib.pyplot as plt
from sympy import symbols
from scipy import signal
import numpy as np
s=symbols("s")
def eliptic(n=5,rp=1,rs=10,wn=3911.5,btype='lowpass'):
""" normal eliptic designer
Args:
n (int, optional): order_of_the_filter. Defaults to 5.
rp (int, optional): The maximum ripple allowed below unity gain in the passband. Defaults to 1.
rs (int, optional): The minimum attenuation required in the stop band. Defaults to 10.
wn (float, optional): critical frequencies. Defaults to 3911.5.
btype (str, optional): {‘lowpass’, ‘highpass’, ‘bandpass’, ‘bandstop’}. Defaults to 'low'.
Returns:
sympy functions: Numerator, denominator
"""
Numerator, denominator= signal.ellip(n, rp, rs,wn,btype, analog=True)
denominator_ = sum(co*s**i for i, co in enumerate(reversed(denominator)))
Numerator_ = sum(co*s**i for i, co in enumerate(reversed(Numerator)))
print("transfer function :")
display(Numerator_ /denominator_)
Zeros,poles,system_gain=signal.ellip(n, rp, rs,wn, 'low', analog=True,output='zpk')
print("\n Zeros :",Zeros,"\n","Poles :",poles,"\n","Gain :",system_gain)
wz, mag, phase =signal.bode((Numerator, denominator))
fig = plt.figure(figsize=(12, 6))
ax=fig.add_subplot(121)
ax.semilogx(wz, mag) # Bode magnitude plot
plt.xscale('log')
plt.title('Elliptic filter frequency response rs='+str(rs)+" rp="+str(rp))
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Magnitude [dB]')
plt.margins(0, 0.1)
plt.grid(which='both', axis='both')
plt.axvline(wn, color='red') # cutoff frequency
plt.axhline(-1*rs, color='red') # rs
plt.axhline(-1*rp, color='red') # rp
ax2=fig.add_subplot(122)
ax2.semilogx(wz, phase) # Bode phase plot
plt.xscale('log')
plt.title('Elliptic filter frequency response rs='+str(rs)+" rp="+str(rp))
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Phase radians')
plt.margins(0, 0.1)
plt.grid(which='both', axis='both')
plt.axvline(wn, color='red') # cutoff frequency
plt.show(block=False)
return Numerator_, denominator_
def reversechebishev(n=5 ,rs=10,stopband=(3700,4000),btype="bandpass"):
""" reverse chebishev designer
Args:
n (int, optional): order_of_the_filter. Defaults to 5.
rs (int, optional): minimum attenuation required in the stop band. Defaults to 10.
stopband (tuple, optional): stopband frequencies. Defaults to (3700,4000).
btype (str, optional): {‘lowpass’, ‘highpass’, ‘bandpass’, ‘bandstop’}. Defaults to "bandpass".
Returns:
sympy functions: Numerator, denominator
"""
Numerator, denominator= signal.cheby2(n, rs, stopband, btype, analog=True)
denominator_ = sum(co*s**i for i, co in enumerate(reversed(denominator)))
Numerator_ = sum(co*s**i for i, co in enumerate(reversed(Numerator)))
print("transfer function :")
display(Numerator_ /denominator_)
Zeros,poles,system_gain=signal.cheby2(n, rs, stopband, 'bandstop', analog=True,output='zpk')
print("\n Zeros :",Zeros,"\n","Poles :",poles,"\n","Gain :",system_gain)
wz, mag, phase =signal.bode((Numerator, denominator))
fig = plt.figure(figsize=(12, 6))
ax=fig.add_subplot(121)
ax.semilogx(wz, mag) # Bode magnitude plot
plt.xscale('log')
plt.title('Chebyshev Type II magnitude response (rp=0.5)')
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Magnitude [dB]')
plt.margins(0, 0.1)
plt.grid(which='both', axis='both')
plt.axvline(np.sqrt(stopband[0]*stopband[1]), color='red') # cutoff frequency
plt.axhline(-1*rs, color='red') # rp
ax2=fig.add_subplot(122)
ax2.semilogx(wz, phase) # Bode phase plot
plt.xscale('log')
plt.title('Chebyshev Type II Phase response (rp=0.5)')
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Phase radians')
plt.margins(0, 0.1)
plt.grid(which='both', axis='both')
plt.axvline(np.sqrt(stopband[0]*stopband[1]), color='red') # cutoff frequency
plt.axhline(-1*rs, color='red') # rp
plt.show(block=False)
return Numerator_, denominator_
def chebishev(n=5,ps=1,stopband=(3700,4000),btype='bandstop'):
""" normal chebishev designer
Args:
n (int, optional): order_of_the_filter. Defaults to 5.
ps (int, optional): The maximum ripple allowed below unity gain in the passband. Defaults to 1.
stopband (tuple, optional): stopband domain. Defaults to (3700,4000).
btype (str, optional): {‘lowpass’, ‘highpass’, ‘bandpass’, ‘bandstop’}. Defaults to 'bandstop'.
Returns:
sympy functions: Numerator, denominator
"""
Numerator, denominator = signal.cheby1(n, ps, stopband, btype, analog=True)
denominator_ = sum(co*s**i for i, co in enumerate(reversed(denominator)))
Numerator_ = sum(co*s**i for i, co in enumerate(reversed(Numerator)))
print("transfer function :")
display(Numerator_ /denominator_)
Zeros,poles,system_gain=signal.cheby1(n, ps, stopband, btype, analog=True,output='zpk')
print("\n Zeros :",Zeros,"\n","Poles :",poles,"\n","Gain :",system_gain)
#w, h = signal.freqs(Numerator, denominator)
wz, mag, phase =signal.bode((Numerator, denominator))
fig = plt.figure(figsize=(12, 6))
ax=fig.add_subplot(121)
ax.semilogx(wz, mag) # Bode magnitude plot
plt.xscale('log')
plt.title('Chebyshev Type I magnitude response (rp=0.5)')
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Magnitude [dB]')
plt.margins(0, 0.1)
plt.grid(which='both', axis='both')
plt.axvline(np.sqrt(stopband[0]*stopband[1]), color='red') # cutoff frequency
plt.axhline(-1*ps, color='red') # rp
ax2=fig.add_subplot(122)
ax2.semilogx(wz, phase) # Bode phase plot
plt.xscale('log')
plt.title('Chebyshev Type I Phase response (rp=0.5)')
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Phase radians')
plt.margins(0, 0.1)
plt.grid(which='both', axis='both')
plt.axvline(np.sqrt(stopband[0]*stopband[1]), color='red') # cutoff frequency
plt.axhline(-1*ps, color='red') # rp
plt.show(block=False)
return Numerator_, denominator_
def butterworthandbessel(n=4, wn=100, btype='lowpass'):
""" butterworth and bessel on same plot
Args:
n (int, optional): [description]. Defaults to 4.
wn (int, optional): The critical frequency. Defaults to 100.
n (int, optional): order_of_the_filter. Defaults to 5.
ps (int, optional): The maximum ripple allowed below unity gain in the passband. Defaults to 1.
btype (str, optional): {‘lowpass’, ‘highpass’, ‘bandpass’, ‘bandstop’}. Defaults to 'bandstop'.
Returns:
sympy functions: butterNumerator, butterdenominator ,besselNumerator, besseldenominator
"""
fig = plt.figure(figsize=(12, 6))
ax=fig.add_subplot(121)
butterNumerator, butterdenominator= signal.butter(n, wn,btype, analog=True)
w1, h1 = signal.freqs(butterNumerator, butterdenominator)
plt.semilogx(w1, 20 * np.log10(np.abs(h1)), color='silver', ls='dashed')
besselNumerator, besseldenominator= signal.bessel(n,wn,btype, analog=True, norm='phase')
w2, h2 = signal.freqs(besselNumerator, besseldenominator)
ax.semilogx(w2, 20 * np.log10(np.abs(h2)))
plt.title('Bessel filter magnitude response (with Butterworth)')
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Amplitude [dB]')
plt.margins(0, 0.1)
plt.grid(which='both', axis='both')
plt.axvline(wn, color='red') # cutoff frequency
plt.axhline(-n, color='red') # -3 dB magnitude
ax2=fig.add_subplot(122)
ax2.semilogx(w1, np.unwrap(np.angle(h1)), color='silver', ls='dashed')
ax2.semilogx(w2, np.unwrap(np.angle(h2)))
plt.axvline(wn, color='red') # cutoff frequency
plt.axhline(-np.pi, color='red') # phase midpoint
plt.title('Bessel filter phase response (with Butterworth)')
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Phase [radians]')
plt.margins(0, 0.1)
plt.grid(which='both', axis='both')
plt.legend(["Butterworth", "Bessel/Thomson"], loc ="lower right")
plt.show()
return butterNumerator, butterdenominator ,besselNumerator, besseldenominator