-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbqdesign.py
376 lines (308 loc) · 12.6 KB
/
bqdesign.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
374
375
376
#!/usr/bin/env python3
import logging
import sys
import os
from PySide2 import QtWidgets
import numpy as np
from pyqtgraph.parametertree import Parameter, ParameterTree, ParameterItem, registerParameterType
import pyqtgraph.parametertree.parameterTypes as pTypes
import pyqtgraph
from pyqtgraph.Qt import QtCore, QtGui
from scipy import signal
from data_curve_widget import DataCurveListWidget
from biquad_design import BIQUAD_DESIGN_LIBRARY
SAMPLERATE = 48000
NPOINTS = 8192
class FilterParameter(pTypes.GroupParameter):
coefficients_changed = QtCore.Signal()
def __init__(self, **opts):
super().__init__(**opts)
class InductanceFilterParameter(FilterParameter):
def __init__(self, **opts):
opts['type'] = 'bool'
opts['value'] = True
super().__init__(**opts)
self.addChild(
{
'name': 'R',
'type': 'float',
'value': 1.0,
'suffix': 'Ohm',
'siPrefix': False,
})
self.addChild(
{
'name': 'L',
'type': 'float',
'value': 0.0,
'suffix': 'H',
'siPrefix': False,
})
self.addChild(
{
'name': 'Rleak',
'type': 'float',
'value': 20,
'suffix': 'Ohm',
'siPrefix': False,
})
self.R = self.param('R')
self.L = self.param('L')
self.Rleak = self.param('Rleak')
self.R.sigValueChanged.connect(self.design_filter)
self.L.sigValueChanged.connect(self.design_filter)
self.Rleak.sigValueChanged.connect(self.design_filter)
def design_filter(self):
R = self.R.value()
Rleak = self.Rleak.value()
L = self.L.value()
Zs = signal.lti([(R + Rleak) * L, R * Rleak], [L, Rleak])
Zd = Zs.to_discrete(1 / SAMPLERATE)
self.b = Zd.num
self.a = Zd.den
self.sos = signal.tf2sos(self.b, self.a)
self.coefficients_changed.emit()
class DigitalFilterParameter(FilterParameter):
def __init__(self, **opts):
opts['type'] = 'bool'
opts['value'] = True
super().__init__(**opts)
self.addChild(
{
'name': 'numerator',
'type': 'text',
'value': '1.0, 0.0, 0.0',
'siPrefix': False,
})
self.addChild(
{
'name': 'denominator',
'type': 'text',
'value': '1.0, 0.0, 0.0',
'siPrefix': False
})
self.numerator = self.param('numerator')
self.denominator = self.param('denominator')
self.numerator.sigValueChanged.connect(self.design_filter)
self.denominator.sigValueChanged.connect(self.design_filter)
def design_filter(self):
self.a = np.fromstring(self.denominator.value(), dtype=np.float64)
self.b = np.fromstring(self.numerator.value(), dtype=np.float64)
self.sos = signal.tf2sos(self.b, self.a)
self.coefficients_changed.emit()
class BiquadParameter(FilterParameter):
def __init__(self, **opts):
opts['type'] = 'bool'
opts['value'] = True
super().__init__(**opts)
self.addChild(
{
'name': 'type',
'type': 'list',
'value': 'parametric eq',
'siPrefix': True,
'limits': BIQUAD_DESIGN_LIBRARY.keys()
})
self.addChild(
{
'name': 'Q',
'type': 'float',
'value': np.sqrt(2) / 2,
'siPrefix': True
})
self.addChild(
{
'name': 'fc',
'type': 'float',
'value': 100,
'suffix': 'Hz',
'siPrefix': True
})
self.addChild(
{
'name': 'gain',
'type': 'float',
'value': 0,
'suffix': 'dB',
'siPrefix': True
})
self.addChild(
{
'name': 'linear gain',
'type': 'float',
'value': 1.0,
'min': 0.0,
'siPrefix': False,
})
self.filter_type = self.param('type')
self.Q = self.param('Q')
self.fc = self.param('fc')
self.gain = self.param('gain')
self.linear_gain = self.param('linear gain')
self.filter_type.sigValueChanged.connect(self.design_filter)
self.Q.sigValueChanged.connect(self.design_filter)
self.fc.sigValueChanged.connect(self.design_filter)
self.gain.sigValueChanged.connect(self.on_gain_changed)
self.linear_gain.sigValueChanged.connect(self.on_linear_gain_changed)
self.linear_gain.sigValueChanged.connect(self.design_filter)
self.b = np.array([1.0, 0, 0])
self.a = np.array([1.0, 0, 0])
self.design_filter()
def on_linear_gain_changed(self):
self.gain.setValue(20 * np.log10(self.linear_gain.value()))
def on_gain_changed(self):
self.linear_gain.setValue(10**(self.gain.value()/20.0))
def design_filter(self):
"""
This filter is used to design Biquad Filters
This creates the A and B coefficients for Biquad IIR filters as used in CSPL
"""
f0 = self.fc.value()
Q = self.Q.value()
gain = self.linear_gain.value()
biquadType = self.filter_type.value()
design_function = BIQUAD_DESIGN_LIBRARY[biquadType]
b_coefficients, a_coefficients = design_function(
gain, f0, Q, SAMPLERATE)
# if the filter design results in a numerator and denominator that are equal, then just implement the passthrough filter
if np.array_equal(b_coefficients, a_coefficients):
b_coefficients = np.array([1., 0., 0.])
a_coefficients = np.array([1., 0., 0.])
self.a = np.array(a_coefficients) / a_coefficients[0]
self.b = np.array(b_coefficients) / a_coefficients[0]
assert len(self.a) == 3
assert len(self.b) == 3
self.sos = signal.tf2sos(self.b, self.a)
self.coefficients_changed.emit()
class FilterCascadeParameter(FilterParameter):
def __init__(self, **opts):
opts['type'] = 'group'
opts['addText'] = "Add"
self.filter_types = {
"Biquad": BiquadParameter,
"Inductance": InductanceFilterParameter,
# "Custom": DigitalFilterParameter,
}
opts['addList'] = list(self.filter_types.keys())
super().__init__(**opts)
for child in self.children():
if isinstance(child, FilterParameter):
child.coefficients_changed.connect(self.update_fiter)
def addNew(self, filter_type="Biquad"):
filter_type_cls = self.filter_types[filter_type]
child = self.addChild(filter_type_cls(name="%s %d" % (filter_type,
len(self.childs)+1), removable=True, renamable=True))
if isinstance(child, FilterParameter):
child.coefficients_changed.connect(self.update_fiter)
def update_fiter(self):
self.coefficients_changed.emit()
class BiquadDesigner(QtGui.QMainWindow):
def __init__(self):
super().__init__()
self._colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728',
'#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
self._color_index = 0
self.last_folder = os.getcwd()
self.filter_parameters = FilterCascadeParameter(name='Filter Cascade', children=[
BiquadParameter(name="Biquad 1", removable=True, renamable=True)])
self.parameter_tree = ParameterTree()
self.parameter_tree.setParameters(self.filter_parameters, showTop=True)
self.plot_widget = pyqtgraph.PlotWidget()
self.plot = self.plot_widget.getPlotItem()
self.plot.setTitle("Magnitude response")
self.plot.setLabel("bottom", "Frequency", "Hz")
self.plot.setXRange(20, SAMPLERATE/2)
self.plot.showGrid(x=True, y=True)
self.plot.addLegend()
self.normalized_frequencies = np.linspace(1/NPOINTS, 0.5, NPOINTS)
magnitude = np.ones(self.normalized_frequencies.shape)
self.total_response_magnitude = self.plot.plot(
x=self.normalized_frequencies*SAMPLERATE, y=magnitude, name="Total", pen=self.get_next_pen())
toolbar = self.get_main_toolbar()
self.addToolBar(toolbar)
parameters_dock = QtWidgets.QDockWidget("Parameters", parent=self)
parameters_dock.setFeatures(
QtWidgets.QDockWidget.DockWidgetMovable | QtWidgets.QDockWidget.DockWidgetFloatable)
parameters_dock.setWidget(self.parameter_tree)
self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, parameters_dock)
curve_widget = DataCurveListWidget(self.plot)
curve_dock = QtGui.QDockWidget("Curves", parent=self)
curve_dock.setFeatures(
QtWidgets.QDockWidget.DockWidgetMovable | QtWidgets.QDockWidget.DockWidgetFloatable)
curve_dock.setWidget(curve_widget)
self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, curve_dock)
self.setCentralWidget(self.plot_widget)
self.update_frequency_response()
self.resize(800, 800)
self.show()
self.filter_parameters.coefficients_changed.connect(
self.update_frequency_response)
def get_main_toolbar(self):
toolbar = QtWidgets.QToolBar("Main toolbar")
open_button = QtWidgets.QAction("Open", self)
open_button.triggered.connect(self.reload_state)
toolbar.addAction(open_button)
save_button = QtWidgets.QAction("Save", self)
save_button.triggered.connect(self.save_state)
toolbar.addAction(save_button)
save_button = QtWidgets.QAction("Save SOS", self)
save_button.triggered.connect(self.save_sos_coefficients)
toolbar.addAction(save_button)
refresh_button = QtWidgets.QAction("Refresh", self)
refresh_button.triggered.connect(self.update_frequency_response)
toolbar.addAction(refresh_button)
return toolbar
def get_next_pen(self):
c = self._colors[self._color_index]
self._color_index = (self._color_index + 1) % len(self._colors)
return pyqtgraph.mkPen(c)
def update_frequency_response(self):
self.sos = self.get_second_order_sections()
w, h = signal.sosfreqz(
self.sos, self.normalized_frequencies * np.pi * 2)
magnitude = np.abs(h)
self.total_response_magnitude.setData(
x=self.normalized_frequencies * SAMPLERATE, y=magnitude)
def get_second_order_sections(self):
sos = []
for f in self.filter_parameters:
if hasattr(f, "sos"):
sos.append(f.sos)
if len(sos) == 0:
sos = [[1, 0, 0, 1, 0, 0]]
return np.vstack(sos)
def update_last_folder(self, filename):
self.last_folder = os.path.dirname(filename)
def save_sos_coefficients(self):
def textproto_sos_save(filename, data):
if data.shape[1] != 6:
raise TypeError("All sections should be 6 coefficients")
with open(filename, "w") as fid:
for section in data:
fid.write(
"biquad: {{b0: {0:.6e} b1: {1:.6e} b2: {2:.6e} a1: {4:.6e} a2: {5:.6e} }}\n".format(*section))
filters = {
"Data files (*.txt)": lambda filename, data: np.savetxt(filename, data,
header="# Second order secions coefficients"),
"Textproto (*.textproto)": textproto_sos_save,
}
sos_filename, file_type = QtWidgets.QFileDialog.getSaveFileName(self, 'Save SOS',
self.last_folder, ';;'.join(filters.keys()))
self.update_last_folder(sos_filename)
if sos_filename == "":
return
sos = self.get_second_order_sections()
save_method = filters[file_type]
save_method(sos_filename, sos)
def save_state(self):
logging.warning('Not yet implemented')
def reload_state(self):
logging.warning('Not yet implemented')
if __name__ == '__main__':
logging.basicConfig()
app = QtGui.QApplication(sys.argv)
ex = BiquadDesigner()
sys.exit(app.exec_())
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()