from
scipy
import
signal
from
scipy.fft
import
fft
import
numpy as np
import
matplotlib.pyplot as plt
N_sample
=
512
fs
=
10000
dt
=
1
/
fs
t
=
np.arange(
0
, N_sample)
*
dt
Signal
=
np.sin(
2
*
np.pi
*
50
*
t)
+
np.sin(
2
*
np.pi
*
1023
*
t)
+
np.sin(
2
*
np.pi
*
1735
*
t)
Signal
=
Signal
+
np.random.normal(
0
, .
1
, Signal.shape)
fstop_L
=
500
fpass_L
=
800
fstop_U
=
1500
fpass_U
=
1200
del_f1
=
abs
(fpass_L
-
fstop_L)
/
fs
del_f2
=
abs
(fpass_U
-
fstop_U)
/
fs
N1
=
3.3
/
del_f1
N2
=
3.3
/
del_f2
print
(
'Filter length based on lower transition band:'
, N1)
print
(
'Filter length based on upper transition band:'
, N2)
N
=
int
(np.ceil(
max
(N1, N2)))
if
(N
%
2
=
=
0
):
N
=
N
+
1
print
(
'Selected filter length :'
, N)
fL
=
(fstop_L
+
fpass_L)
/
2
fU
=
(fstop_U
+
fpass_U)
/
2
wL
=
2
*
fL
/
fs
wU
=
2
*
fU
/
fs
cutoff
=
[wL, wU]
b_ham
=
signal.firwin(N, cutoff, window
=
"hamming"
, pass_zero
=
"bandpass"
)
w, h_ham
=
signal.freqz(b_ham, a
=
1
)
h_dB_ham
=
20
*
np.log10(
abs
(h_ham))
a
=
[
1
]
filtOut
=
signal.filtfilt(b_ham, a, Signal)
fig
=
plt.figure(figsize
=
(
12
,
18
))
sub1
=
plt.subplot(
5
,
1
,
1
)
sub1.plot(t[
0
:
200
], Signal[
0
:
200
])
sub1.set_ylabel(
'Amplitude'
)
sub1.set_xlabel(
'Time'
)
sub1.set_title(
'Noisy signal'
, fontsize
=
20
)
sub2
=
plt.subplot(
5
,
1
,
2
)
sub2.plot(w
*
fs
/
(
2
*
np.pi), h_dB_ham,
'r'
, label
=
'Bandpass filter'
,
linewidth
=
'2'
)
sub2.set_ylabel(
'Magnitude (db)'
)
sub2.set_xlabel(
'Frequency in Hz'
)
sub2.set_title(
'Frequency response of Bandpass Filter'
, fontsize
=
20
)
sub2.axis
=
([
0
, fs
/
2
,
-
110
,
5
])
sub2.grid()
sub3
=
plt.subplot(
5
,
1
,
3
)
sub3.plot(t[
0
:
200
], filtOut[
0
:
200
],
'g'
, label
=
'Filtered signal'
,
linewidth
=
'2'
)
sub3.set_ylabel(
'Magnitude '
)
sub3.set_xlabel(
'Time'
)
sub3.set_title(
'Filtered output of Band pass Filter'
, fontsize
=
20
)
Sigf
=
fft(Signal)
sub4
=
plt.subplot(
5
,
1
,
4
)
xf
=
np.linspace(
0.0
,
1.0
/
(
2.0
*
dt), (N_sample
-
1
)
/
/
2
)
sub4.plot(xf,
2.0
/
N_sample
*
np.
abs
(Sigf[
0
:(N_sample
-
1
)
/
/
2
]))
sub4.set_ylabel(
'Magnitude'
)
sub4.set_xlabel(
'Frequency in Hz'
)
sub4.set_title(
'Frequency Spectrum of Original Signal'
, fontsize
=
20
)
sub4.grid()
Outf
=
fft(filtOut)
sub5
=
plt.subplot(
5
,
1
,
5
)
xf
=
np.linspace(
0.0
,
1.0
/
(
2.0
*
dt), (N_sample
-
1
)
/
/
2
)
sub5.plot(xf,
2.0
/
N_sample
*
np.
abs
(Outf[
0
:(N_sample
-
1
)
/
/
2
]))
sub5.set_ylabel(
'Magnitude'
)
sub5.set_xlabel(
'Frequency in Hz'
)
sub5.set_title(
'Frequency Spectrum of Filtered Signal'
, fontsize
=
20
)
sub5.grid()
fig.tight_layout()
plt.show()