-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.py
More file actions
755 lines (638 loc) · 34.8 KB
/
mainwindow.py
File metadata and controls
755 lines (638 loc) · 34.8 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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
"""
filter_toolbox/mainwindow.py
============================
PyQt6 main window controller.
Loads the Designer .ui file, wires all signals/slots, manages plots
(pyqtgraph), and calls the student-implemented filter_design.py functions.
Students do NOT need to modify this file. All computation entry-points are
in filter_design.py.
"""
from __future__ import annotations
import traceback
from pathlib import Path
import numpy as np
import pyqtgraph as pg
from PyQt6 import uic
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QObject
from PyQt6.QtGui import QAction, QActionGroup, QColor, QPalette
from PyQt6.QtWidgets import (
QMainWindow, QApplication, QTableWidgetItem, QFileDialog,
QMessageBox, QHeaderView, QMenu, QStyledItemDelegate,
)
# ── backend ───────────────────────────────────────────────────────────────────
import filter_design as fd
from filter_design import (
FilterSpec, Approximation, FilterType, Topology, ESeries,
TransferFunction, ComponentValue, SimulationResult,
)
# ── themes & i18n ─────────────────────────────────────────────────────────────
from resources.styles import LIGHT_QSS, DARK_QSS
from resources.i18n import LANGUAGES, tr
UI_FILE = Path(__file__).parent / "mainwindow.ui"
ABOUT_FILE = Path(__file__).parent / "about_dialog.ui"
# ──────────────────────────────────────────────────────────────────────────────
# Delegate that visually greys out disabled combo-box items
# (QSS alone is not reliable across platforms for this)
# ──────────────────────────────────────────────────────────────────────────────
class DisabledItemDelegate(QStyledItemDelegate):
"""
Paints combo-box popup items in a muted colour when their
QStandardItem.isEnabled() flag is False, regardless of QSS theme.
"""
# Colours for the two themes — updated via set_dark()
_DISABLED_DARK = QColor("#4a5060")
_DISABLED_LIGHT = QColor("#b0b8c8")
_NORMAL_DARK = QColor("#d8dde8")
_NORMAL_LIGHT = QColor("#1e2230")
def __init__(self, parent=None, dark: bool = True):
super().__init__(parent)
self._dark = dark
def set_dark(self, dark: bool) -> None:
self._dark = dark
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
if not index.flags() & Qt.ItemFlag.ItemIsEnabled:
disabled_col = self._DISABLED_DARK if self._dark else self._DISABLED_LIGHT
option.palette.setColor(QPalette.ColorRole.Text, disabled_col)
option.palette.setColor(QPalette.ColorRole.HighlightedText, disabled_col)
# ──────────────────────────────────────────────────────────────────────────────
# Worker thread for SPICE simulation
# ──────────────────────────────────────────────────────────────────────────────
class SimWorker(QObject):
finished = pyqtSignal(SimulationResult)
error = pyqtSignal(str)
def __init__(self, netlist: str):
super().__init__()
self._netlist = netlist
def run(self) -> None:
try:
self.finished.emit(fd.run_spice_simulation(self._netlist))
except NotImplementedError:
self.error.emit("run_spice_simulation() is not yet implemented.")
except Exception:
self.error.emit(f"Simulation error:\n{traceback.format_exc()}")
# ──────────────────────────────────────────────────────────────────────────────
# Main Window
# ──────────────────────────────────────────────────────────────────────────────
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi(UI_FILE, self)
self._dark_mode : bool = True
self._lang : str = "en"
self._tf : TransferFunction | None = None
self._biquads : list[TransferFunction] = []
self._f_start : float = 1.0
self._f_stop : float = 1e6
self._components: list[ComponentValue] = []
self._sim_result: SimulationResult | None = None
self._sim_thread: QThread | None = None
self._sim_worker: SimWorker | None = None
self._spice_items: list = [] # track SPICE overlay items
self._setup_menu_bar()
self._setup_plots()
self._setup_plot_widgets()
self._connect_signals()
# Install delegates so disabled items render visibly greyed out
self._del_impl = DisabledItemDelegate(self.cbImplementation, dark=self._dark_mode)
self._del_icmodel = DisabledItemDelegate(self.cbIcModel, dark=self._dark_mode)
self.cbImplementation.setItemDelegate(self._del_impl)
self.cbIcModel.setItemDelegate(self._del_icmodel)
self._apply_theme()
self._retranslate()
self._update_spec_fields()
self._update_impl_fields()
# ── helpers ───────────────────────────────────────────────────────────────
def _(self, key: str, **kwargs) -> str:
return tr(key, self._lang, **kwargs)
# ── Menu bar ──────────────────────────────────────────────────────────────
def _setup_menu_bar(self) -> None:
mb = self.menuBar()
mb.setNativeMenuBar(False)
self._mFile = mb.addMenu("")
self.actionNew = QAction("", self)
self.actionOpen = QAction("", self)
self.actionSave = QAction("", self)
self.actionExportNetlist = QAction("", self)
self.actionExportReport = QAction("", self)
self.actionQuit = QAction("", self)
self.actionQuit.setShortcut("Ctrl+Q")
self._mFile.addAction(self.actionNew)
self._mFile.addAction(self.actionOpen)
self._mFile.addAction(self.actionSave)
self._mFile.addSeparator()
self._mFile.addAction(self.actionExportNetlist)
self._mFile.addAction(self.actionExportReport)
self._mFile.addSeparator()
self._mFile.addAction(self.actionQuit)
self._mView = mb.addMenu("")
self.actionToggleTheme = QAction("", self)
self.actionToggleLeftPanel = QAction("", self)
self._mView.addAction(self.actionToggleTheme)
self._mView.addAction(self.actionToggleLeftPanel)
# Language submenu with radio-style checkmarks
self._mLang = QMenu("", self)
self._mView.addSeparator()
self._mView.addMenu(self._mLang)
lang_group = QActionGroup(self)
lang_group.setExclusive(True)
self._lang_actions: dict[str, QAction] = {}
for display_name, code in LANGUAGES.items():
act = QAction(display_name, self, checkable=True)
act.setChecked(code == self._lang)
act.setData(code)
act.triggered.connect(self._on_language_changed)
lang_group.addAction(act)
self._mLang.addAction(act)
self._lang_actions[code] = act
self._mHelp = mb.addMenu("")
self.actionAbout = QAction("", self)
self._mHelp.addAction(self.actionAbout)
# ── Plot setup ────────────────────────────────────────────────────────────
def _setup_plots(self) -> None:
self._plot_mag = pg.PlotWidget()
self._plot_phase = pg.PlotWidget()
self._plot_gd = pg.PlotWidget()
self._plot_pz = pg.PlotWidget()
for pw in (self._plot_mag, self._plot_phase, self._plot_gd, self._plot_pz):
pw.setBackground(None)
pw.showGrid(x=True, y=True, alpha=0.3)
self._plot_mag.setLogMode(x=True, y=False)
self._plot_phase.setLogMode(x=True, y=False)
self._plot_gd.setLogMode(x=True, y=False)
self._plot_pz.setAspectLocked(True)
def _setup_plot_widgets(self) -> None:
def _replace(placeholder, new_widget):
layout = placeholder.parentWidget().layout()
idx = layout.indexOf(placeholder)
layout.removeWidget(placeholder)
placeholder.setParent(None)
layout.insertWidget(idx, new_widget)
_replace(self.wgtMagnitudePlot, self._plot_mag)
_replace(self.wgtPhasePlot, self._plot_phase)
_replace(self.wgtGroupDelayPlot, self._plot_gd)
_replace(self.wgtPoleZeroPlot, self._plot_pz)
# ── Signal wiring ─────────────────────────────────────────────────────────
def _connect_signals(self) -> None:
self.btnDesign.clicked.connect(self._on_design)
self.btnSimulate.clicked.connect(self._on_simulate)
self.btnExportNetlist.clicked.connect(self._on_export_netlist)
self.btnExportReport.clicked.connect(self._on_export_report)
self.btnToggleTheme.clicked.connect(self._on_toggle_theme)
self.actionNew.triggered.connect(self._on_new)
self.actionOpen.triggered.connect(self._on_open)
self.actionSave.triggered.connect(self._on_save)
self.actionExportNetlist.triggered.connect(self._on_export_netlist)
self.actionExportReport.triggered.connect(self._on_export_report)
self.actionQuit.triggered.connect(self.close)
self.actionToggleTheme.triggered.connect(self._on_toggle_theme)
self.actionToggleLeftPanel.triggered.connect(self._on_toggle_left_panel)
self.actionAbout.triggered.connect(self._on_about)
self.cbFilterType.currentIndexChanged.connect(self._update_spec_fields)
self.cbFilterType.currentIndexChanged.connect(self._update_impl_fields)
self.cbApproximation.currentIndexChanged.connect(self._update_spec_fields)
self.cbImplementation.currentIndexChanged.connect(self._update_impl_fields)
self.chkShowSOS.stateChanged.connect(self._on_sos_toggled)
self.btnResetZoom.clicked.connect(self._on_reset_zoom)
# ── i18n ─────────────────────────────────────────────────────────────────
def _retranslate(self) -> None:
t = self._
self.setWindowTitle(t("window_title"))
self.lblTitle.setText(t("app_title"))
self._mFile.setTitle(t("menu_file"))
self._mView.setTitle(t("menu_view"))
self._mHelp.setTitle(t("menu_help"))
self._mLang.setTitle(t("action_language"))
self.actionNew.setText(t("action_new"))
self.actionOpen.setText(t("action_open"))
self.actionSave.setText(t("action_save"))
self.actionExportNetlist.setText(t("action_export_netlist"))
self.actionExportReport.setText(t("action_export_report"))
self.actionQuit.setText(t("action_quit"))
self.actionToggleTheme.setText(t("action_toggle_theme"))
self.actionToggleLeftPanel.setText(t("action_toggle_panel"))
self.actionAbout.setText(t("action_about"))
self.btnDesign.setText(t("btn_design"))
self.btnSimulate.setText(t("btn_simulate"))
self.btnExportNetlist.setText(t("btn_export_netlist"))
self.btnExportReport.setText(t("btn_export_report"))
self.btnResetZoom.setText(t("btn_reset_zoom"))
self.btnToggleTheme.setText(t("btn_theme"))
self.chkShowSOS.setText(t("chk_show_sos"))
self.gbApprox.setTitle(t("gb_approx"))
self.gbSpecs.setTitle(t("gb_specs"))
self.gbImpl.setTitle(t("gb_impl"))
self.gbPassive.setTitle(t("gb_passive"))
self.gbComponents.setTitle(t("gb_components"))
self.lblApprox.setText(t("lbl_approx"))
self.lblType.setText(t("lbl_type"))
self.cbApproximation.setItemText(0, t("approx_butterworth"))
self.cbApproximation.setItemText(1, t("approx_cheby1"))
self.cbApproximation.setItemText(2, t("approx_cheby2"))
self.cbApproximation.setItemText(3, t("approx_elliptic"))
self.cbFilterType.setItemText(0, t("type_lp"))
self.cbFilterType.setItemText(1, t("type_hp"))
self.cbFilterType.setItemText(2, t("type_bp"))
self.cbFilterType.setItemText(3, t("type_bs"))
self.lblAp.setText(t("lbl_ap"))
self.lblAs.setText(t("lbl_as"))
self.lblOrderLabel.setText(t("lbl_order"))
self.lblImpl.setText(t("lbl_topology"))
self.lblIcModel.setText(t("lbl_ic_model"))
self.cbImplementation.setItemText(0, t("topo_sk"))
self.cbImplementation.setItemText(1, t("topo_tt"))
self.cbImplementation.setItemText(2, t("topo_del"))
self.lblRSeries.setText(t("lbl_r_series"))
self.lblCSeries.setText(t("lbl_c_series"))
self.lblRBase.setText(t("lbl_r_base"))
self.lblCBase.setText(t("lbl_c_base"))
self.tblComponents.setHorizontalHeaderLabels([
t("tbl_stage"), t("tbl_type"), t("tbl_component"),
t("tbl_ideal"), t("tbl_rounded"), t("tbl_error"),
])
self._plot_mag.setTitle(t("plot_mag_title"))
self._plot_mag.setLabel("bottom", t("plot_mag_x"), units="Hz")
self._plot_mag.setLabel("left", t("plot_mag_y"), units="dB")
self._plot_phase.setTitle(t("plot_phase_title"))
self._plot_phase.setLabel("bottom", t("plot_mag_x"), units="Hz")
self._plot_phase.setLabel("left", t("plot_phase_y"), units="°")
self._plot_gd.setTitle(t("plot_gd_title"))
self._plot_gd.setLabel("bottom", t("plot_mag_x"), units="Hz")
self._plot_gd.setLabel("left", t("plot_gd_y"), units="s")
self._plot_pz.setTitle(t("plot_pz_title"))
self._plot_pz.setLabel("bottom", t("plot_pz_x"))
self._plot_pz.setLabel("left", t("plot_pz_y"))
self.tabPlots.setTabText(0, t("tab_magnitude"))
self.tabPlots.setTabText(1, t("tab_phase"))
self.tabPlots.setTabText(2, t("tab_group_delay"))
self.tabPlots.setTabText(3, t("tab_pole_zero"))
self.tabPlots.setTabText(4, t("tab_schematic"))
self.lblSchematic.setText(t("schematic_placeholder"))
self._update_spec_fields()
self._update_impl_fields()
def _on_language_changed(self) -> None:
action = self.sender()
if action:
self._lang = action.data()
self._retranslate()
# ── Dynamic fields ────────────────────────────────────────────────────────
def _update_spec_fields(self) -> None:
ft = FilterType(self.cbFilterType.currentIndex())
is_two_band = ft in (FilterType.BANDPASS, FilterType.BANDSTOP)
for w in (self.sbFp2, self.sbFs2, self.lblFp2, self.lblFs2):
w.setEnabled(is_two_band)
w.setVisible(is_two_band)
if is_two_band:
self.lblFp.setText(self._("lbl_fp_lower"))
self.lblFs.setText(self._("lbl_fs_lower"))
self.lblFp2.setText(self._("lbl_fp2"))
self.lblFs2.setText(self._("lbl_fs2"))
else:
self.lblFp.setText(self._("lbl_fp"))
self.lblFs.setText(self._("lbl_fs"))
self.lblComputedOrder.setText("—")
def _update_impl_fields(self) -> None:
"""
Dynamically constrain topology and IC model dropdowns based on
the current filter type and topology selection.
Rules:
• High-pass filters cannot use Deliyannis-Friend (no HP topology exists).
• Tow-Thomas (UAF42) topology only works with the UAF42 IC model.
"""
ft = FilterType(self.cbFilterType.currentIndex())
topo_idx = self.cbImplementation.currentIndex()
# ── Rule 1: Deliyannis-Friend not available for High-pass ────────
is_highpass = ft == FilterType.HIGHPASS
deliy_item = self.cbImplementation.model().item(2) # index 2 = Deliyannis
if is_highpass:
deliy_item.setEnabled(False)
deliy_item.setToolTip(self._("topo_del_disabled_hp"))
# If Deliyannis is currently selected, fall back to Sallen-Key
if topo_idx == 2:
self.cbImplementation.setCurrentIndex(0)
else:
deliy_item.setEnabled(True)
deliy_item.setToolTip("")
# ── Rule 2: Tow-Thomas forces UAF42 IC model ─────────────────────
is_tow_thomas = self.cbImplementation.currentIndex() == 1
for i in range(self.cbIcModel.count()):
item = self.cbIcModel.model().item(i)
if is_tow_thomas:
# Only UAF42 is valid — disable everything else
is_uaf42 = "UAF42" in item.text()
item.setEnabled(is_uaf42)
if is_uaf42:
self.cbIcModel.setCurrentIndex(i)
else:
# Restore all models when switching away from Tow-Thomas
item.setEnabled(True)
# ── Theme ─────────────────────────────────────────────────────────────────
def _apply_theme(self) -> None:
QApplication.instance().setStyleSheet(
DARK_QSS if self._dark_mode else LIGHT_QSS)
bg = "#161926" if self._dark_mode else "#ffffff"
fg = "#d8dde8" if self._dark_mode else "#1e2230"
for pw in (self._plot_mag, self._plot_phase, self._plot_gd, self._plot_pz):
pw.setBackground(bg)
pw.getAxis("bottom").setPen(fg)
pw.getAxis("left").setPen(fg)
# Update legend styling if it exists
if pw.plotItem.legend:
pw.plotItem.legend.setLabelTextColor(
pg.mkColor("#ffffff") if self._dark_mode else pg.mkColor("#1e2230"))
brush = pg.mkBrush(30, 30, 40, 180) if self._dark_mode \
else pg.mkBrush(240, 243, 249, 200)
pw.plotItem.legend.setBrush(brush)
def _on_toggle_theme(self) -> None:
self._dark_mode = not self._dark_mode
self._del_impl.set_dark(self._dark_mode)
self._del_icmodel.set_dark(self._dark_mode)
self._apply_theme()
# ── Read spec ─────────────────────────────────────────────────────────────
def _read_spec(self) -> FilterSpec:
return FilterSpec(
approximation = Approximation(self.cbApproximation.currentIndex()),
filter_type = FilterType(self.cbFilterType.currentIndex()),
fp = self.sbFp.value(), fs = self.sbFs.value(),
fp2 = self.sbFp2.value(), fs2 = self.sbFs2.value(),
a_p = self.sbAp.value(), a_s = self.sbAs.value(),
)
def _read_eseries(self, combo) -> ESeries:
return {0: ESeries.E6, 1: ESeries.E12, 2: ESeries.E24,
3: ESeries.E48, 4: ESeries.E96, 5: ESeries.EXACT
}.get(combo.currentIndex(), ESeries.E24)
# ── Design ────────────────────────────────────────────────────────────────
def _on_design(self) -> None:
spec = self._read_spec()
self.lblStatus.setText(self._("status_computing"))
QApplication.processEvents()
try:
self._tf, computed_order = fd.compute_transfer_function(spec)
self.lblComputedOrder.setText(str(computed_order))
# Smart frequency range — bracket actual spec edges ±1 decade
ft = fd.FilterType(self.cbFilterType.currentIndex())
if ft in (fd.FilterType.BANDPASS, fd.FilterType.BANDSTOP):
f_lo = min(spec.fp, spec.fs, spec.fp2, spec.fs2)
f_hi = max(spec.fp, spec.fs, spec.fp2, spec.fs2)
else:
f_lo = min(spec.fp, spec.fs)
f_hi = max(spec.fp, spec.fs)
self._f_start = f_lo / 10.0
self._f_stop = f_hi * 10.0
freqs, mag_db, phase_deg, gd = fd.compute_frequency_response(
self._tf, f_start=self._f_start, f_stop=self._f_stop)
self._plot_theoretical(freqs, mag_db, phase_deg, gd)
# Store biquads so SOS checkbox can redraw without redesigning
self._biquads = fd.factored_biquads(self._tf)
self._sim_result = None # new design invalidates old simulation
self._spice_items.clear()
if self.chkShowSOS.isChecked():
self._plot_sos_responses(self._biquads, self._f_start, self._f_stop)
self.tabPlots.setCurrentIndex(0)
self._plot_pole_zero(self._tf)
topology = Topology(self.cbImplementation.currentIndex())
self._components = {
Topology.SALLEN_KEY: fd.synthesise_sallen_key,
Topology.TOW_THOMAS: fd.synthesise_tow_thomas,
Topology.DELIYANNIS: fd.synthesise_deliyannis,
}[topology](self._biquads, self.sbRBase.value(), self.sbCBase.value(),
self._read_eseries(self.cbRSeries),
self._read_eseries(self.cbCSeries))
self._populate_component_table(self._components)
self.lblStatus.setText(self._("status_design_done",
order=computed_order,
approx=self.cbApproximation.currentText(),
ftype=self.cbFilterType.currentText(),
fp=spec.fp, fs=spec.fs))
except NotImplementedError as nie:
self._show_not_implemented(str(nie))
except Exception:
self._show_error("Design", traceback.format_exc())
# ── Simulate ──────────────────────────────────────────────────────────────
def _on_simulate(self) -> None:
if not self._components:
QMessageBox.information(self,
self._("dlg_no_design_title"), self._("dlg_no_design_msg"))
return
try:
netlist = fd.generate_spice_netlist(
self._components,
Topology(self.cbImplementation.currentIndex()),
self.cbIcModel.currentText())
except NotImplementedError as nie:
self._show_not_implemented(str(nie)); return
self.lblStatus.setText(self._("status_simulating"))
self.btnSimulate.setEnabled(False)
QApplication.processEvents()
self._sim_thread = QThread()
self._sim_worker = SimWorker(netlist) # keep ref — prevents GC
self._sim_worker.moveToThread(self._sim_thread)
self._sim_thread.started.connect(self._sim_worker.run)
self._sim_worker.finished.connect(self._on_simulation_done)
self._sim_worker.error.connect(self._on_simulation_error)
self._sim_worker.finished.connect(self._sim_thread.quit)
self._sim_worker.error.connect(self._sim_thread.quit)
self._sim_thread.finished.connect(self._sim_thread.deleteLater)
self._sim_thread.start()
def _on_simulation_done(self, result: SimulationResult) -> None:
self._sim_result = result
self._sim_worker = None
self.btnSimulate.setEnabled(True)
self._plot_simulated(result)
self.lblStatus.setText(self._("status_sim_done"))
def _on_simulation_error(self, msg: str) -> None:
self._sim_worker = None
self.btnSimulate.setEnabled(True)
if "not yet implemented" in msg:
self._show_not_implemented(msg)
else:
self._show_error("Simulation error", msg)
# ── Plots ─────────────────────────────────────────────────────────────────
_THEORY_PEN = pg.mkPen("#4d94ff", width=2.5)
_SPICE_PEN = pg.mkPen("#ff5722", width=2.0, style=Qt.PenStyle.DashLine)
_POLE_BRUSH = pg.mkBrush("#ff4444")
_ZERO_BRUSH = pg.mkBrush("#44aaff")
def _plot_theoretical(self, freqs, mag, phase, gd) -> None:
for pw in (self._plot_mag, self._plot_phase, self._plot_gd):
pw.clear()
for level, color in ((-3, "#ffaa00"), (-20, "#888888"), (-40, "#555555")):
self._plot_mag.addItem(pg.InfiniteLine(
pos=level, angle=0,
pen=pg.mkPen(color, width=1, style=Qt.PenStyle.DashLine),
label=f"{level} dB", labelOpts={"color": color, "position": 0.02}))
name = self._("legend_theoretical")
self._plot_mag.plot(freqs, mag, pen=self._THEORY_PEN, name=name)
self._plot_phase.plot(freqs, phase, pen=self._THEORY_PEN, name=name)
self._plot_gd.plot(freqs, gd, pen=self._THEORY_PEN, name=name)
for pw in (self._plot_mag, self._plot_phase, self._plot_gd):
if not pw.plotItem.legend:
legend = pw.addLegend(
offset = (10, 10),
labelTextSize = "10pt",
)
legend.setLabelTextColor(pg.mkColor("#ffffff") if self._dark_mode
else pg.mkColor("#1e2230"))
# Semi-transparent dark/light background
brush = pg.mkBrush(30, 30, 40, 180) if self._dark_mode \
else pg.mkBrush(240, 243, 249, 200)
legend.setBrush(brush)
legend.setPen(pg.mkPen("#4d94ff", width=1))
def _plot_simulated(self, result: SimulationResult) -> None:
# Remove previous SPICE overlay curves before adding new ones
for item in self._spice_items:
try:
item.getViewBox().removeItem(item)
except Exception:
pass
self._spice_items.clear()
name = self._("legend_spice")
self._spice_items.append(
self._plot_mag.plot(result.frequencies, result.magnitude_db,
pen=self._SPICE_PEN, name=name)
)
self._spice_items.append(
self._plot_phase.plot(result.frequencies, result.phase_deg,
pen=self._SPICE_PEN, name=name)
)
def _plot_sos_responses(self, biquads, f_start: float, f_stop: float) -> None:
"""Overlay individual stage responses as thin solid lines with alpha."""
palette = [
"#a0c4ff", "#b9fbc0", "#ffd6a5", "#ffadad",
"#caffbf", "#fdffb6", "#c77dff", "#f4acb7",
]
for i, bq in enumerate(biquads):
try:
freqs, mag, _, _ = fd.compute_frequency_response(
bq, f_start=f_start, f_stop=f_stop)
color = pg.mkColor(palette[i % len(palette)])
color.setAlpha(180)
# Label as "Stage N [type]" — more informative than "SOS N"
label = f"Stage {i + 1} [{bq.section_type.value}]"
self._plot_mag.plot(freqs, mag,
pen=pg.mkPen(color, width=1.2),
name=label)
except Exception:
pass
def _on_sos_toggled(self) -> None:
"""Redraw magnitude plot when the SOS checkbox is toggled."""
if not self._tf:
return
try:
freqs, mag_db, phase_deg, gd = fd.compute_frequency_response(
self._tf, f_start=self._f_start, f_stop=self._f_stop)
self._plot_theoretical(freqs, mag_db, phase_deg, gd)
if self.chkShowSOS.isChecked() and self._biquads:
self._plot_sos_responses(self._biquads, self._f_start, self._f_stop)
if self._sim_result:
self._plot_simulated(self._sim_result)
except Exception:
pass
def _on_reset_zoom(self) -> None:
"""Reset all plot views to fit their current data."""
for pw in (self._plot_mag, self._plot_phase, self._plot_gd, self._plot_pz):
pw.autoRange()
def _plot_pole_zero(self, tf: TransferFunction) -> None:
self._plot_pz.clear()
if tf.poles.size:
self._plot_pz.plot(tf.poles.real, tf.poles.imag, pen=None,
symbol="x", symbolBrush=self._POLE_BRUSH,
symbolSize=12, name="Poles")
if tf.zeros.size:
self._plot_pz.plot(tf.zeros.real, tf.zeros.imag, pen=None,
symbol="o", symbolBrush=self._ZERO_BRUSH,
symbolSize=10, name="Zeros")
self._plot_pz.addLine(x=0, pen=pg.mkPen("#888888", width=1))
self._plot_pz.addLine(y=0, pen=pg.mkPen("#888888", width=1))
# ── Component table ───────────────────────────────────────────────────────
def _populate_component_table(self, components: list[ComponentValue]) -> None:
tbl = self.tblComponents
tbl.setRowCount(len(components))
for row, c in enumerate(components):
tbl.setItem(row, 0, QTableWidgetItem(str(c.stage)))
type_item = QTableWidgetItem(c.component_type.value)
type_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
tbl.setItem(row, 1, type_item)
tbl.setItem(row, 2, QTableWidgetItem(c.name))
tbl.setItem(row, 3, QTableWidgetItem(c.formatted_ideal()))
tbl.setItem(row, 4, QTableWidgetItem(c.formatted_rounded()))
err_item = QTableWidgetItem(f"{c.error_pct:+.2f} %")
if abs(c.error_pct) > 5.0:
err_item.setForeground(pg.mkColor("#ff6b6b"))
tbl.setItem(row, 5, err_item)
tbl.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
# ── Export ────────────────────────────────────────────────────────────────
def _on_export_netlist(self) -> None:
if not self._components:
QMessageBox.information(self,
self._("dlg_no_design_title"), self._("dlg_no_design_msg"))
return
path, _ = QFileDialog.getSaveFileName(
self, self._("dlg_netlist_title"), "filter.cir",
self._("dlg_netlist_filter"))
if not path:
return
try:
netlist = fd.generate_spice_netlist(
self._components,
Topology(self.cbImplementation.currentIndex()),
self.cbIcModel.currentText())
Path(path).write_text(netlist)
self.lblStatus.setText(self._("status_netlist_saved", path=path))
except NotImplementedError as nie:
self._show_not_implemented(str(nie))
except Exception:
self._show_error("Export", traceback.format_exc())
def _on_export_report(self) -> None:
QMessageBox.information(self,
self._("dlg_report_title"), self._("dlg_report_msg"))
# ── File menu ─────────────────────────────────────────────────────────────
def _on_new(self) -> None:
self._tf = None
self._biquads = []
self._f_start = 1.0
self._f_stop = 1e6
self._components = []
self._sim_result = None
self._spice_items.clear()
for pw in (self._plot_mag, self._plot_phase, self._plot_gd, self._plot_pz):
pw.clear()
self.tblComponents.setRowCount(0)
self.lblComputedOrder.setText("—")
self.lblStatus.setText(self._("status_new"))
def _on_open(self) -> None:
QMessageBox.information(self,
self._("dlg_open_title"), self._("dlg_open_msg"))
def _on_save(self) -> None:
QMessageBox.information(self,
self._("dlg_save_title"), self._("dlg_save_msg"))
# ── Misc ──────────────────────────────────────────────────────────────────
def _on_toggle_left_panel(self) -> None:
self.leftPanel.setVisible(not self.leftPanel.isVisible())
def _on_about(self) -> None:
dlg = uic.loadUi(ABOUT_FILE)
dlg.setStyleSheet(QApplication.instance().styleSheet())
t = self._
dlg.setWindowTitle(t("about_window_title"))
dlg.lblAppTitle.setText(t("about_app_title"))
dlg.lblCourse.setText(t("about_course"))
dlg.lblVersion.setText(t("about_version"))
dlg.gbStudents.setTitle(t("about_gb_students"))
dlg.gbInstructors.setTitle(t("about_gb_instructors"))
dlg.lblInstitution.setText(t("about_institution"))
dlg.lblYear.setText(t("about_year"))
dlg.btnClose.setText(t("about_close"))
dlg.exec()
# ── Error helpers ─────────────────────────────────────────────────────────
def _show_not_implemented(self, msg: str) -> None:
self.lblStatus.setText(self._("status_not_impl"))
QMessageBox.warning(self,
self._("dlg_not_impl_title"),
self._("dlg_not_impl_msg", msg=msg))
def _show_error(self, title: str, detail: str) -> None:
self.lblStatus.setText(self._("status_error", title=title))
dlg = QMessageBox(self)
dlg.setWindowTitle(title)
dlg.setText(self._("dlg_error_msg"))
dlg.setDetailedText(detail)
dlg.setIcon(QMessageBox.Icon.Critical)
dlg.exec()