-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
259 lines (214 loc) · 9.61 KB
/
main.py
File metadata and controls
259 lines (214 loc) · 9.61 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
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
from PyQt6 import QtWidgets, uic, QtGui
from PyQt6.QtGui import QPen, QColor, QIcon
from PyQt6.QtCore import QTimer
import numpy as np
import pyqtgraph as pg
import qdarkstyle
import sys
from scipy.signal import freqz, zpk2tf, lfilter
import os
from scipy.io import wavfile
import csv
from Signal import Signal
from scipy.fft import fft
from PaddingArea import PaddingArea
from PyQt6.QtCore import Qt, QElapsedTimer
from PhaseCorrectionWindow import PhaseCorrectionWindow
from UnitCircle import UnitCircle
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.init_ui()
self.setWindowIcon(QIcon("Icons\pngwing.com.png"))
# self.plot_magnitude_and_phase()
self.zPlane = self.ui.zPlane
self.magPlot = self.ui.magPlot
self.ui.magPlot.setBackground("transparent")
self.ui.phasePlot.setBackground("transparent")
self.inputSignal.setBackground("transparent")
self.outputSignal.setBackground("transparent")
self.input_mode = None
self.point_per_second = 1 # Initial filter speed
self.idx = 0
self.signal = Signal()
self.all_phase_correction_filters = [
0.99, 0.345, 0.732, 0.456]
self.checked_phase_correction_filters = []
self.zeros_all_pass = np.array([], dtype=complex)
self.poles_all_pass = np.array([], dtype=complex)
self.zeros = np.array([], dtype=complex)
self.poles = np.array([], dtype=complex)
def init_ui(self):
self.ui = uic.loadUi('Mainwindow.ui', self)
self.setWindowTitle("Digital Filter Designer")
# Plot the magnitude response
self.inputSignal.plotItem.showGrid(True, True)
self.inputSignal.clear()
self.inputSignal.setLabel('left', 'Magnitude')
self.inputSignal.setLabel('bottom', 'Time')
# Plot the magnitude response
self.outputSignal.plotItem.showGrid(True, True)
self.outputSignal.clear()
self.outputSignal.setLabel('left', 'Magnitude')
self.outputSignal.setLabel('bottom', 'Time')
# Plot the magnitude response
self.magPlot.plotItem.showGrid(True, True)
self.magPlot.setLabel('left', 'Magnitude')
self.magPlot.setLabel('bottom', 'W (radian/sample)')
# Plot the phase response
self.phasePlot.plotItem.showGrid(True, True)
self.phasePlot.setLabel('left', 'Phase (radian)')
self.phasePlot.setLabel('bottom', 'W (radian/sample)')
self.ui.correctPhase.clicked.connect(self.open_phase_correction_window)
self.ui.correctPhase.setIcon(QIcon("Icons\correction.png"))
self.ui.importSignal.clicked.disconnect()
self.ui.importSignal.clicked.connect(self.on_importSignal_clicked)
self.ui.customSignal.clicked.connect(self.on_customSignal_clicked)
self.ui.importSignal.setIcon(
QIcon('Icons\\upload-square-svgrepo-com.png'))
self.ui.customSignal.setIcon(QIcon('Icons\custom.png'))
self.Speed.setMinimum(1)
self.Speed.setMaximum(100)
self.Speed.setValue(1) # Initial value
self.Speed.valueChanged.connect(self.update_filter_speed)
self.padding_area = PaddingArea(self)
self.circle_object = UnitCircle(self)
self.area.layout().addWidget(self.padding_area)
def compose_complex(self, list_of_points):
complex_points = list()
for point in list_of_points:
real_part = round(point.x(), 3)
imaginary_part = round(point.y(), 3)
new_complex_number = complex(real_part, imaginary_part)
complex_points.append(new_complex_number)
return np.array(complex_points, dtype=complex)
def update_zeros_poles(self):
self.zeros = self.compose_complex(self.circle_object.Zeros)
self.poles = self.compose_complex(self.circle_object.Poles)
print(f"Current zeros values :{self.zeros}")
print(f"Current Poles values :{self.poles}")
def update_filter_speed(self, value):
self.point_per_second = value
self.numOfPoints.setText(f"{self.point_per_second} points/sec")
def update_filter(self):
if self.idx < len(self.signal.output_signal_after_filter):
self.idx += self.point_per_second
# Plot updated output signal
self.inputSignal.plot(
self.signal.time[:self.idx], self.signal.data[:self.idx], pen=pg.mkPen(
color=(0, 0, 255), width=2))
self.outputSignal.plot(self.signal.time[:self.idx],
self.signal.output_signal_after_filter[:self.idx], pen=pg.mkPen(
color=(255, 0, 0), width=2))
def on_importSignal_clicked(self):
self.input_mode = "import"
self.idx = 0
self.browse()
def on_customSignal_clicked(self):
if self.input_mode == "custom":
self.input_mode = None
self.padding_area.first_time_enter = True
else:
self.input_mode = "custom"
self.idx = 0
self.signal = Signal()
# Set button color based on the current input_mode
if self.input_mode == "custom":
self.sender().setStyleSheet(
"background-color: red; border: 1px solid gray; padding: 9px; border-radius: 6px; font-size: 14px;")
else:
self.sender().setStyleSheet(
"background-color: #000; border: 1px solid gray; padding: 9px; border-radius: 6px;font-size: 14px;")
def browse(self):
self.idx = 0
file_filter = "Raw Data (*.csv *.wav)"
file_path, _ = QtWidgets.QFileDialog.getOpenFileName(
None, 'Open Signal File', './', filter=file_filter)
if file_path:
file_name = os.path.basename(file_path)
self.open_file(file_path, file_name)
def open_file(self, path: str, file_name: str):
# Lists to store time and data
time = [] # List to store time values
data = [] # List to store data values
frequency = 0
# Extract the file extension (last 3 characters) from the path
filetype = path[-3:]
if filetype == "wav":
# Read the WAV file
sample_rate, data = wavfile.read(path)
time = np.linspace(0, data.shape[0] / sample_rate, data.shape[0])
# Check if the file type is CSV, text (txt), or Excel (xls)
if filetype in ["csv", "txt", "xls"]:
# Open the data file for reading ('r' mode)
with open(path, 'r') as data_file:
# Create a CSV reader object with a comma as the delimiter
data_reader = csv.reader(data_file, delimiter=',')
next(data_reader)
# Iterate through each row (line) in the data file
for row in data_reader:
# Extract the time value from the first column (index 0)
time_value = float(row[0])
# Extract the amplitude value from the second column (index 1)
amplitude_value = float(row[1])
# Append the time and amplitude values to respective lists
time.append(time_value)
data.append(amplitude_value)
# Create a Signal object with the file name without the extension
self.signal.data = data
self.signal.time = time
self.outputSignal.clear()
self.inputSignal.clear()
self.plot_input_and_output_signal()
def plot_magnitude_and_phase(self): # need to be modified
self.points_on_the_circle = self.calculate_points_on_circle()
w, mag, phase = self.get_the_mag_and_phase(self.zeros, self.poles)
pen_color = QColor(255, 255, 255)
line_width = 2
self.magPlot.clear()
self.magPlot.plot(w, mag, pen=pg.mkPen(
color=pen_color, width=line_width))
self.phasePlot.clear()
self.phasePlot.plot(w, phase, pen=pg.mkPen(
color=pen_color, width=line_width))
def plot_input_and_output_signal(self):
numerator, denominator = zpk2tf(self.zeros, self.poles, 1)
self.signal.output_signal_after_filter = np.real(
lfilter(numerator, denominator, self.signal.data))
# Timer to update filter
self.timer = pg.QtCore.QTimer()
self.timer.timeout.connect(self.update_filter)
self.timer.start(1000) # Update every 10 milliseconds
def calculate_points_on_circle(self):
theta_for_half_circle = np.linspace(0, np.pi, 100)
x_upper = np.cos(theta_for_half_circle)
y_upper = np.sin(theta_for_half_circle)
return x_upper + (y_upper * 1j)
def open_phase_correction_window(self):
# Open a new window
new_window = PhaseCorrectionWindow(self)
new_window.show()
def show_error_message(self, message):
msg_box = QtWidgets.QMessageBox()
msg_box.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msg_box.setWindowTitle("Error")
msg_box.setText(message)
msg_box.exec()
def closeEvent(self, event):
self.setEnabled(True)
super(MainWindow, self).closeEvent(event)
def get_the_mag_and_phase(self, zeros, poles):
# Calculate frequency response
w, h = freqz(np.poly(zeros), np.poly(poles))
frequencies = w
mag_response = abs(h)
phase_response = np.angle(h)
return frequencies, mag_response, phase_response
def main():
app = QtWidgets.QApplication([])
app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt6())
main_window = MainWindow()
main_window.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()