Friday, November 13, 2020

Signal Processing with Python GUI: Part 4

This Content is supported by BALIGE PUBLISHINGVisit this link
See Part 1    See Part 2   See Part 3

Tutorial Steps To Create GUI For Noisy Signal
Populate cbFiltering widget with two more items by double clicking on the widget as shown in figure below.


Then modify show_filtering() function to apply filtering based on what user choose in cbFiltering widget as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def show_filtering(self):
    strCB = self.cbFiltering.currentText()
        
    if strCB == 'Butterworth Highpass':
        self.butter_filter('hp')
    if strCB == 'Butterworth Lowpass':
        self.butter_filter('lp')
    if strCB == 'Chebyshev Highpass':
        self.cheby_filter('hp')
    if strCB == 'Chebyshev Lowpass':
        self.cheby_filter('lp')
    if strCB == 'Elliptic Highpass':
        self.ellip_filter('hp')
    if strCB == 'Elliptic Lowpass':
        self.ellip_filter('lp')

Define cheby_filter() and ellip_filter() functions to apply chebyshev and elliptic filtering on input signal as follows:

 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
def cheby_filter(self, param):
    global y
    fsampling=1000
    x_start = float(self.leXStart.text())
    x_end = float(self.leXEnd.text())
    t = linspace(x_start, x_end, len(y))
        
    pass_band = float(self.lePassBand.text())
    stop_band = float(self.leStopBand.text())
        
    #Butterworth filtering
    sos = signal.cheby1(stop_band, pass_band, 15, param, \
        fs=fsampling, output='sos')
        
    filtered = signal.sosfilt(sos, y)
                    
    self.widgetOutput.canvas.axis1.clear()
    self.widgetOutput.canvas.axis1.plot(t, filtered)
    self.widgetOutput.canvas.axis1.set_ylabel("$h$",fontsize=22)
        self.widgetOutput.canvas.axis1.set_xlabel("$sec$",fontsize=22)
    self.widgetOutput.canvas.axis1.set_title('Chebyshev Filtered Signal')
    self.widgetOutput.canvas.axis1.set_facecolor('lightblue')
    self.widgetOutput.canvas.axis1.grid()
    self.widgetOutput.canvas.draw()
        
    self.show_fft(filtered,self.widgetFFTAbsFiltered, \
        self.widgetFFTLogFiltered)

 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
def ellip_filter(self, param):
    global y
    fsampling=1000
    x_start = float(self.leXStart.text())
    x_end = float(self.leXEnd.text())
    t = linspace(x_start, x_end, len(y))
        
    pass_band = float(self.lePassBand.text())
    stop_band = float(self.leStopBand.text())
        
    #Butterworth filtering
    sos = signal.ellip(8, 1, 100, stop_band, \
        param, fs=1000, output='sos')
        
    filtered = signal.sosfilt(sos, y)
                    
    self.widgetOutput.canvas.axis1.clear()
    self.widgetOutput.canvas.axis1.plot(t, filtered)
    self.widgetOutput.canvas.axis1.set_ylabel("$h$",fontsize=22)
        self.widgetOutput.canvas.axis1.set_xlabel("$sec$",fontsize=22)
    self.widgetOutput.canvas.axis1.set_title('Chebyshev Filtered Signal')
    self.widgetOutput.canvas.axis1.set_facecolor('lightblue')
    self.widgetOutput.canvas.axis1.grid()
    self.widgetOutput.canvas.draw()
        
    self.show_fft(filtered,self.widgetFFTAbsFiltered, \
        self.widgetFFTLogFiltered)

Run main_fft2.py. Select one of signals and choose Noise radio button. Then, choose Chebyshev Lowpass from cbFiltering widget. The result is shown in figure below.



Then, choose Elliptic Highpass from cbFiltering widget. The result is shown in figure below.



Tutorial Steps To Create GUI For Wav Signal Filtering
At this point, you will open wav files and use it as signal samples to be filtered. In gui_fft.ui, Add one Push Button widget and set its objectName property to pbOpbenFile and set its text property to Open File.

Then, add three Label widgets on the form and set their text properties to x start, x end and File Name.

Next, add three Line Edit widgets and set their objectName properties to leXStartFile, leXEndFile, and leFileName. The newly modified version of gui_fft.ui is shown in figure below.



Next, add three Line Edit widgets and set their objectName properties to leXStartFile, leXEndFile, and leFileName. The newly modified version of gui_fft.ui is shown in figure below.

1
2
3
4
5
6
7
8
def open_file(self):
global filename
filename = QFileDialog.getOpenFileName(self, 'OpenFile')
self.leFileName.setText(filename[0])
x = np.fromfile(open(filename[0]),np.int16)[24:]
print(len(x))
self.show_wav(x)
return filename

Define show_wav() function to display wav samples and its absolute FFT and log absolute FFT on three Widgets as follows:

 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
def show_wav(self, x):
global y
x_start = int(self.leXStartFile.text())
x_end = int(self.leXEndFile.text())
x=x[x_start:x_end]
# widgetSignal
t = linspace(x_start, x_end, len(x))
# Noise
if self.rbNoise.isChecked():
y = x + np.random.randn(len(x)) * 50
else :
y = x
self.widgetSignal.canvas.axis1.clear()
self.widgetSignal.canvas.axis1.plot(t, y)
self.widgetSignal.canvas.axis1.annotate('$n$', xy=(0.98, 0), \
ha='left', va='top', xycoords='axes fraction', fontsize=20)
self.widgetSignal.canvas.axis1.annotate('$h$', xy=(0, 1), \
xytext=(-15,5), ha='left', va='top', xycoords='axes fraction', \
textcoords='offset points', fontsize=20)
self.widgetSignal.canvas.axis1.set_title('Stem Graph')
self.widgetSignal.canvas.axis1.set_facecolor('lightblue')
self.widgetSignal.canvas.axis1.grid()
self.widgetSignal.canvas.draw()
self.show_fft(y,self.widgetFFTAbs, self.widgetFFTLog)
return y

Connect clicked() signal in pbOpenFile  widget inside def __init__(self) method. This signal is sent whenever user click pbOpenFile button:

self.pbOpenFile.clicked.connect(self.open_file)

Run program. Click on Open File button, click Noise radio button, and choose one of filters to see the filtered version of wav signal, as shown in figure below.


The following is the final version of main_fft2.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#main_fft2.py
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar)
import numpy as np
from scipy import signal
from numpy import *
import matplotlib as mpl
from scipy.signal import chirp
class DemoGUIFFT(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
loadUi("gui_fft.ui",self)
self.setWindowTitle("GUI Demo for FFT")
self.pbShow.clicked.connect(self.show_graph)
self.addToolBar(NavigationToolbar(self.widgetSignal.canvas, self))
self.rbChirp.toggled.connect(self.show_chirp)
self.rbSawtooth.toggled.connect(self.show_sawtooth)
self.rbSquare.toggled.connect(self.show_square)
self.rbSweepPoly.toggled.connect(self.show_sweep_poly)
self.cbFiltering.currentIndexChanged.connect(self.show_filtering)
self.pbOpenFile.clicked.connect(self.open_file)
def show_graph(self):
global y
wc = float(self.leCutOff.text())
N = int(self.leFFTLength.text())
M = int(self.leSignalRange.text())
wc = wc*pi
# widgetSignal
n = arange(-M, M)
h = wc/pi * sinc(wc*(n)/pi)
mpl.style.use('seaborn')
# Noise
if self.rbNoise.isChecked():
y = y + np.random.randn(len(h)) * 0.1
else:
y = h
self.widgetSignal.canvas.axis1.clear()
self.widgetSignal.canvas.axis1.stem(n,y,\
basefmt='r-',use_line_collection=True)
self.widgetSignal.canvas.axis1.annotate('$n$', xy=(0.98, 0), \
ha='left', va='top', xycoords='axes fraction', fontsize=20)
self.widgetSignal.canvas.axis1.annotate('$h$', xy=(0, 1), \
xytext=(-15,5), ha='left', va='top', xycoords='axes fraction', \
textcoords='offset points', fontsize=20)
self.widgetSignal.canvas.axis1.set_title('Stem Graph')
self.widgetSignal.canvas.axis1.set_facecolor('lightblue')
self.widgetSignal.canvas.axis1.grid()
self.widgetSignal.canvas.draw()
self.show_fft(y,self.widgetFFTAbs, self.widgetFFTLog)
return y
def show_fft(self, h, qwidget1, qwidget2):
wc = float(self.leCutOff.text())
N = int(self.leFFTLength.text())
M = int(self.leSignalRange.text())
wc = wc*pi
# widgetFFTAbs
w,Hh = signal.freqz(h,1,whole=True, worN=N) # get entire frequency domain
wx = fft.fftfreq(len(w)) # shift to center for plotting
qwidget1.canvas.axis1.clear()
qwidget1.canvas.axis1.plot(w-pi,abs(fft.fftshift(Hh)),\
color='red', linewidth=3.0)
qwidget1.canvas.axis1.axis(xmax=pi/2,xmin=-pi/2)
qwidget1.canvas.axis1.vlines(\
[-1.1,1.1],0,1.2,color='g',lw=2.,linestyle='--',)
qwidget1.canvas.axis1.hlines(1,-pi,pi,color='g',lw=2.,linestyle='--',)
qwidget1.canvas.axis1.annotate(r'$\omega$', xy=(0.98, 0), \
ha='left', va='top', xycoords='axes fraction', fontsize=22)
qwidget1.canvas.axis1.set_ylabel(r"$|H(\omega)| $",fontsize=22)
qwidget1.canvas.axis1.set_title('Absolute FFT Graph')
qwidget1.canvas.axis1.set_facecolor('lightblue')
qwidget1.canvas.axis1.grid()
qwidget1.canvas.draw()
# widgetFFTLog
w,Hh = signal.freqz(h,1,whole=True, worN=N) # get entire frequency domain
wx = fft.fftfreq(len(w)) # shift to center for plotting
qwidget2.canvas.axis1.clear()
qwidget2.canvas.axis1.plot(w-pi,\
20*log10(abs(fft.fftshift(Hh))),color='red', linewidth=3.0)
qwidget2.canvas.axis1.axis(ymin=-40,xmax=pi/2,xmin=-pi/2)
qwidget2.canvas.axis1.vlines([-wc,wc],\
10,-40,color='g',lw=2.,linestyle='--',)
qwidget2.canvas.axis1.hlines(0,-pi,pi,color='g',lw=2.,linestyle='--',)
qwidget2.canvas.axis1.annotate(r'$\omega$', xy=(0.98, 0), \
ha='left', va='top', xycoords='axes fraction', fontsize=22)
qwidget2.canvas.axis1.set_ylabel(r"$20\log_{10}|H(\omega)| $",fontsize=18)
qwidget2.canvas.axis1.set_title('Log Absolute FFT Graph')
qwidget2.canvas.axis1.set_facecolor('lightblue')
qwidget2.canvas.axis1.grid()
qwidget2.canvas.draw()
def show_chirp(self):
global y
x_start = float(self.leXStart.text())
x_end = float(self.leXEnd.text())
f_start = float(self.leFStart.text())
f_end = float(self.leFEnd.text())
# widgetSignal
t = linspace(x_start, x_end, 5001)
w = chirp(t, f0=f_start, f1=f_end, t1=10, method='linear')
# Noise
if self.rbNoise.isChecked():
y = w + np.random.randn(len(w)) * 0.1
else:
y = w
self.widgetSignal.canvas.axis1.clear()
self.widgetSignal.canvas.axis1.plot(t,y,linewidth=3.0)
self.widgetSignal.canvas.axis1.annotate('$sec$', xy=(0.98, 0), \
ha='left', va='top', xycoords='axes fraction', fontsize=20)
self.widgetSignal.canvas.axis1.annotate('$h$', xy=(0, 1), \
xytext=(-15,5), ha='left', va='top', xycoords='axes fraction', \
textcoords='offset points', fontsize=20)
self.widgetSignal.canvas.axis1.set_title('Chirp Graph')
self.widgetSignal.canvas.axis1.set_facecolor('lightblue')
self.widgetSignal.canvas.axis1.grid()
self.widgetSignal.canvas.draw()
self.show_fft(y,self.widgetFFTAbs, self.widgetFFTLog)
return y
def show_sawtooth(self):
global y
x_start = float(self.leXStart.text())
x_end = float(self.leXEnd.text())
# widgetSignal
t = linspace(x_start, x_end, 5001)
w = signal.sawtooth(2 * np.pi * 5 * t)
# Noise
if self.rbNoise.isChecked():
y = w + np.random.randn(len(w)) * 0.1
else:
y = w
self.widgetSignal.canvas.axis1.clear()
self.widgetSignal.canvas.axis1.plot(t, y,linewidth=3.0)
self.widgetSignal.canvas.axis1.annotate('$sec$', xy=(0.98, 0), \
ha='left', va='top', xycoords='axes fraction', fontsize=20)
self.widgetSignal.canvas.axis1.annotate('$h$', xy=(0, 1), \
xytext=(-15,5), ha='left', va='top', xycoords='axes fraction', \
textcoords='offset points', fontsize=20)
self.widgetSignal.canvas.axis1.set_title('Chirp Graph')
self.widgetSignal.canvas.axis1.set_title('Sawtooth Graph')
self.widgetSignal.canvas.axis1.set_facecolor('lightblue')
self.widgetSignal.canvas.axis1.grid()
self.widgetSignal.canvas.draw()
self.show_fft(y,self.widgetFFTAbs, self.widgetFFTLog)
return y
def show_square(self):
global y
x_start = float(self.leXStart.text())
x_end = float(self.leXEnd.text())
# widgetSignal
t = linspace(x_start, x_end, 500, endpoint=False)
w = signal.square(2 * pi * 2 * t)
# Noise
if self.rbNoise.isChecked():
y = w + np.random.randn(len(w)) * 0.1
else:
y = w
self.widgetSignal.canvas.axis1.clear()
self.widgetSignal.canvas.axis1.plot(t, y, linewidth=3.0)
self.widgetSignal.canvas.axis1.annotate('$sec$', xy=(0.98, 0), \
ha='left', va='top', xycoords='axes fraction', \
fontsize=20)
self.widgetSignal.canvas.axis1.annotate('$h$', xy=(0, 1), \
xytext=(-15,5), ha='left', va='top', \
xycoords='axes fraction', textcoords='offset points', \
fontsize=20)
self.widgetSignal.canvas.axis1.set_title('Square Graph')
self.widgetSignal.canvas.axis1.set_facecolor('lightblue')
self.widgetSignal.canvas.axis1.grid()
self.widgetSignal.canvas.draw()
self.show_fft(y,self.widgetFFTAbs, self.widgetFFTLog)
return y
def show_sweep_poly(self):
global y
x_start = float(self.leXStart.text())
x_end = float(self.leXEnd.text())
# widgetSignal
p = np.poly1d([0.025, -0.36, 1.25, 2.0])
t = np.linspace(x_start, x_end, 5001)
y = signal.sweep_poly(t, p)
# Noise
if self.rbNoise.isChecked():
y = y + np.random.randn(len(y)) * 0.1
else:
y = y
self.widgetSignal.canvas.axis1.clear()
self.widgetSignal.canvas.axis1.plot(t, y, linewidth=3.0)
self.widgetSignal.canvas.axis1.annotate('$sec$', xy=(0.98, 0), \
ha='left', va='top', xycoords='axes fraction', \
fontsize=20)
self.widgetSignal.canvas.axis1.annotate('$h$', xy=(0, 1), \
xytext=(-15,5), ha='left', va='top', \
xycoords='axes fraction', textcoords='offset points', \
fontsize=20)
self.widgetSignal.canvas.axis1.set_title('Sweep Poly Graph')
self.widgetSignal.canvas.axis1.set_facecolor('lightblue')
self.widgetSignal.canvas.axis1.grid()
self.widgetSignal.canvas.draw()
self.show_fft(y,self.widgetFFTAbs, self.widgetFFTLog)
return y
def butter_filter(self, param):
global y
x_start = float(self.leXStart.text())
x_end = float(self.leXEnd.text())
t = linspace(x_start, x_end, len(y))
pass_band = float(self.lePassBand.text())
stop_band = float(self.leStopBand.text())
#Butterworth filtering
sos = signal.butter(stop_band, pass_band, param, fs=1000, output='sos')
filtered = signal.sosfilt(sos, y)
self.widgetOutput.canvas.axis1.clear()
self.widgetOutput.canvas.axis1.plot(t, filtered)
self.widgetOutput.canvas.axis1.set_ylabel("$h$",fontsize=22)
self.widgetOutput.canvas.axis1.set_xlabel("$sec$",fontsize=22)
self.widgetOutput.canvas.axis1.set_title('Butterworth Filtered Signal')
self.widgetOutput.canvas.axis1.set_facecolor('lightblue')
self.widgetOutput.canvas.axis1.grid()
self.widgetOutput.canvas.draw()
self.show_fft(filtered,self.widgetFFTAbsFiltered, \
self.widgetFFTLogFiltered)
def show_filtering(self):
strCB = self.cbFiltering.currentText()
if strCB == 'Butterworth Highpass':
self.butter_filter('hp')
if strCB == 'Butterworth Lowpass':
self.butter_filter('lp')
if strCB == 'Chebyshev Highpass':
self.cheby_filter('hp')
if strCB == 'Chebyshev Lowpass':
self.cheby_filter('lp')
if strCB == 'Elliptic Highpass':
self.ellip_filter('hp')
if strCB == 'Elliptic Lowpass':
self.ellip_filter('lp')
def cheby_filter(self, param):
global y
fsampling=1000
x_start = float(self.leXStart.text())
x_end = float(self.leXEnd.text())
t = linspace(x_start, x_end, len(y))
pass_band = float(self.lePassBand.text())
stop_band = float(self.leStopBand.text())
#Butterworth filtering
sos = signal.cheby1(stop_band, pass_band, 15, \
param, fs=fsampling, output='sos')
filtered = signal.sosfilt(sos, y)
self.widgetOutput.canvas.axis1.clear()
self.widgetOutput.canvas.axis1.plot(t, filtered)
self.widgetOutput.canvas.axis1.set_ylabel("$h$",fontsize=22)
self.widgetOutput.canvas.axis1.set_xlabel("$sec$",fontsize=22)
self.widgetOutput.canvas.axis1.set_title('Chebyshev Filtered Signal')
self.widgetOutput.canvas.axis1.set_facecolor('lightblue')
self.widgetOutput.canvas.axis1.grid()
self.widgetOutput.canvas.draw()
self.show_fft(filtered,self.widgetFFTAbsFiltered, \
self.widgetFFTLogFiltered)
def ellip_filter(self, param):
global y
fsampling=1000
x_start = float(self.leXStart.text())
x_end = float(self.leXEnd.text())
t = linspace(x_start, x_end, len(y))
pass_band = float(self.lePassBand.text())
stop_band = float(self.leStopBand.text())
#Butterworth filtering
sos = signal.ellip(8, 1, 100, stop_band, param, fs=1000, output='sos')
filtered = signal.sosfilt(sos, y)
self.widgetOutput.canvas.axis1.clear()
self.widgetOutput.canvas.axis1.plot(t, filtered)
self.widgetOutput.canvas.axis1.set_ylabel("$h$",fontsize=22)
self.widgetOutput.canvas.axis1.set_xlabel("$sec$",fontsize=22)
self.widgetOutput.canvas.axis1.set_title('Chebyshev Filtered Signal')
self.widgetOutput.canvas.axis1.set_facecolor('lightblue')
self.widgetOutput.canvas.axis1.grid()
self.widgetOutput.canvas.draw()
self.show_fft(filtered,self.widgetFFTAbsFiltered, \
self.widgetFFTLogFiltered)
def open_file(self):
global filename
filename = QFileDialog.getOpenFileName(self, 'OpenFile')
self.leFileName.setText(filename[0])
x = np.fromfile(open(filename[0]),np.int16)[24:]
print(len(x))
self.show_wav(x)
return filename
def show_wav(self, x):
global y
x_start = int(self.leXStartFile.text())
x_end = int(self.leXEndFile.text())
x=x[x_start:x_end]
# widgetSignal
t = linspace(x_start, x_end, len(x))
# Noise
if self.rbNoise.isChecked():
y = x + np.random.randn(len(x)) * 50
else :
y = x
self.widgetSignal.canvas.axis1.clear()
self.widgetSignal.canvas.axis1.plot(t, y)
self.widgetSignal.canvas.axis1.annotate('$n$', xy=(0.98, 0), \
ha='left', va='top', xycoords='axes fraction', fontsize=20)
self.widgetSignal.canvas.axis1.annotate('$h$', xy=(0, 1), \
xytext=(-15,5), ha='left', va='top', xycoords='axes fraction', \
textcoords='offset points', fontsize=20)
self.widgetSignal.canvas.axis1.set_title('Stem Graph')
self.widgetSignal.canvas.axis1.set_facecolor('lightblue')
self.widgetSignal.canvas.axis1.grid()
self.widgetSignal.canvas.draw()
self.show_fft(y,self.widgetFFTAbs, self.widgetFFTLog)
return y
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
ex = DemoGUIFFT()
ex.show()
sys.exit(app.exec_())



No comments:

Post a Comment