-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathafg_gui.py
More file actions
1640 lines (1420 loc) · 66.7 KB
/
afg_gui.py
File metadata and controls
1640 lines (1420 loc) · 66.7 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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import math
import os
from dataclasses import dataclass
from typing import List, Optional, Tuple
import numpy as np
import sympy as sp
from PySide6 import QtCore, QtWidgets
def _is_truthy_env(name: str) -> bool:
value = (os.environ.get(name, "") or "").strip()
return value in {"1", "true", "True", "yes", "YES"}
def _try_get_web_engine_view_class():
if _is_truthy_env("AFG_DISABLE_WEBENGINE"):
return None
try:
from PySide6.QtWebEngineWidgets import QWebEngineView # type: ignore
return QWebEngineView
except Exception:
return None
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg
from matplotlib.figure import Figure
DEFAULT_N_SAMPLES = 8192
@dataclass
class Waveform:
x: np.ndarray
y: np.ndarray
class MplCanvas(FigureCanvasQTAgg):
def __init__(self, parent: Optional[QtWidgets.QWidget] = None):
fig = Figure(figsize=(7, 4), dpi=100)
self.ax = fig.add_subplot(111)
super().__init__(fig)
self.setParent(parent)
self.ax.set_title("Arbitrary Function")
self.ax.set_xlabel("x")
self.ax.set_ylabel("y")
self.ax.set_xlim(0.0, 1.0)
self.ax.set_ylim(-1.2, 1.2)
self.ax.grid(True, alpha=0.3)
(self._line,) = self.ax.plot([], [], lw=2)
self._draw_points: List[Tuple[float, float]] = []
self._drawing = False
self._eps_x = 1e-6
self.mpl_connect("button_press_event", self._on_press)
self.mpl_connect("button_release_event", self._on_release)
self.mpl_connect("motion_notify_event", self._on_move)
def clear(self) -> None:
self._draw_points = []
self._line.set_data([], [])
self.ax.set_ylim(-1.2, 1.2)
self.draw_idle()
def set_waveform(self, wf: Waveform) -> None:
self._draw_points = []
self._line.set_data(wf.x, wf.y)
self.draw_idle()
def set_ylim(self, ymin: float, ymax: float) -> None:
self.ax.set_ylim(ymin, ymax)
self.draw_idle()
def get_drawn_points(self) -> List[Tuple[float, float]]:
return list(self._draw_points)
def _on_press(self, event) -> None:
if event.inaxes != self.ax:
return
if event.button != 1:
return
self._drawing = True
self._append_point(event.xdata, event.ydata)
def _on_release(self, event) -> None:
if event.button == 1:
self._drawing = False
def _on_move(self, event) -> None:
if not self._drawing:
return
if event.inaxes != self.ax:
return
self._append_point(event.xdata, event.ydata)
def _append_point(self, x: Optional[float], y: Optional[float]) -> None:
if x is None or y is None:
return
x = float(np.clip(x, 0.0, 1.0))
y = float(np.clip(y, -1.0, 1.0))
if self._draw_points:
last_x, _last_y = self._draw_points[-1]
if x < (last_x - self._eps_x):
return
if abs(x - last_x) <= self._eps_x:
self._draw_points[-1] = (last_x, y)
else:
self._draw_points.append((x, y))
else:
self._draw_points.append((x, y))
xs = [p[0] for p in self._draw_points]
ys = [p[1] for p in self._draw_points]
self._line.set_data(xs, ys)
self.draw_idle()
class PreviewCanvas(FigureCanvasQTAgg):
def __init__(self, parent: Optional[QtWidgets.QWidget] = None):
fig = Figure(figsize=(3, 2), dpi=100)
self.ax = fig.add_subplot(111)
super().__init__(fig)
self.setParent(parent)
self.ax.set_xlim(0.0, 1.0)
self.ax.set_ylim(-1.2, 1.2)
self.ax.grid(True, alpha=0.25)
self.ax.set_xticks([])
self.ax.set_yticks([])
(self._line,) = self.ax.plot([], [], lw=1.5)
def set_waveform(self, wf: Optional[Waveform]) -> None:
if wf is None:
self._line.set_data([], [])
else:
self._line.set_data(wf.x, wf.y)
self.draw_idle()
def set_ylim(self, ymin: float, ymax: float) -> None:
self.ax.set_ylim(ymin, ymax)
self.draw_idle()
class MainWindow(QtWidgets.QMainWindow):
def __init__(self) -> None:
super().__init__()
self.setWindowTitle("Arbitrary Function Generator")
central = QtWidgets.QWidget(self)
self.setCentralWidget(central)
self.canvas = MplCanvas(self)
self.preview_a = PreviewCanvas(self)
self.preview_b = PreviewCanvas(self)
self.add_a_btn = QtWidgets.QPushButton("Adicionar A", self)
self.add_b_btn = QtWidgets.QPushButton("Adicionar B", self)
self.concat_a_btn = QtWidgets.QPushButton("Concatenar -> A", self)
self.concat_b_btn = QtWidgets.QPushButton("Concatenar -> B", self)
self.sum_btn = QtWidgets.QPushButton("Somar A + B", self)
self.sub_btn = QtWidgets.QPushButton("Subtrair A - B", self)
self.mul_btn = QtWidgets.QPushButton("Multiplicar A * B", self)
self.div_btn = QtWidgets.QPushButton("Dividir A / B", self)
self.preset_combo = QtWidgets.QComboBox(self)
self._preset_defs = []
self._init_presets()
self.preset_invert_check = QtWidgets.QCheckBox("Inverter sinal (preset)", self)
self.preset_invert_check.setChecked(False)
self.sinever_reverse_sweep_check = QtWidgets.QCheckBox("Inverter varredura (SineVer)", self)
self.sinever_reverse_sweep_check.setChecked(False)
self.sine_fraction_combo = QtWidgets.QComboBox(self)
self.sine_fraction_combo.addItem("Ciclo completo (1/1)", "1")
self.sine_fraction_combo.addItem("1/2", "1/2")
self.sine_fraction_combo.addItem("1/3", "1/3")
self.sine_fraction_combo.addItem("1/4", "1/4")
self.sine_fraction_combo.addItem("1/5", "1/5")
self.sine_fraction_combo.addItem("1/6", "1/6")
self.sine_fraction_combo.addItem("1/7", "1/7")
self.sine_fraction_combo.addItem("1/8", "1/8")
self.sine_fraction_combo.addItem("1/9", "1/9")
self.sine_fraction_combo.addItem("1/10", "1/10")
self.triangle_opening_angle_spin = QtWidgets.QDoubleSpinBox(self)
self.triangle_opening_angle_spin.setRange(1.0, 179.0)
self.triangle_opening_angle_spin.setDecimals(1)
self.triangle_opening_angle_spin.setSingleStep(1.0)
self.triangle_opening_angle_spin.setValue(60.0)
self.heartbeat_cycles_spin = QtWidgets.QSpinBox(self)
self.heartbeat_cycles_spin.setRange(1, 128)
self.heartbeat_cycles_spin.setValue(5)
self.heartbeat_type_combo = QtWidgets.QComboBox(self)
self.heartbeat_type_combo.addItem("Normal", "normal")
self.heartbeat_type_combo.addItem("Taquicardia", "tachy")
self.heartbeat_type_combo.addItem("Bradicardia", "brady")
self.heartbeat_type_combo.addItem("PVC (extra-sístole ventricular)", "pvc")
self.heartbeat_type_combo.addItem("Fibrilação atrial (simplificada)", "afib")
self.bell_width_spin = QtWidgets.QDoubleSpinBox(self)
self.bell_width_spin.setRange(0.01, 0.50)
self.bell_width_spin.setDecimals(3)
self.bell_width_spin.setSingleStep(0.005)
self.bell_width_spin.setValue(0.12)
self.bell_rise_smooth_spin = QtWidgets.QDoubleSpinBox(self)
self.bell_rise_smooth_spin.setRange(0.20, 5.00)
self.bell_rise_smooth_spin.setDecimals(2)
self.bell_rise_smooth_spin.setSingleStep(0.05)
self.bell_rise_smooth_spin.setValue(1.00)
self.bell_fall_smooth_spin = QtWidgets.QDoubleSpinBox(self)
self.bell_fall_smooth_spin.setRange(0.20, 5.00)
self.bell_fall_smooth_spin.setDecimals(2)
self.bell_fall_smooth_spin.setSingleStep(0.05)
self.bell_fall_smooth_spin.setValue(1.00)
self.square_duty_spin = QtWidgets.QDoubleSpinBox(self)
self.square_duty_spin.setRange(0.1, 99.9)
self.square_duty_spin.setDecimals(1)
self.square_duty_spin.setSingleStep(1.0)
self.square_duty_spin.setValue(50.0)
self.square_bounce_rise_check = QtWidgets.QCheckBox("Recochetear na subida", self)
self.square_bounce_rise_check.setChecked(False)
self.square_bounce_fall_check = QtWidgets.QCheckBox("Recochetear na descida", self)
self.square_bounce_fall_check.setChecked(False)
self.square_bounce_amp_spin = QtWidgets.QDoubleSpinBox(self)
self.square_bounce_amp_spin.setRange(0.0, 1.0)
self.square_bounce_amp_spin.setDecimals(3)
self.square_bounce_amp_spin.setSingleStep(0.02)
self.square_bounce_amp_spin.setValue(0.15)
self.square_bounce_duration_spin = QtWidgets.QDoubleSpinBox(self)
self.square_bounce_duration_spin.setRange(0.0, 0.5)
self.square_bounce_duration_spin.setDecimals(4)
self.square_bounce_duration_spin.setSingleStep(0.005)
self.square_bounce_duration_spin.setValue(0.03)
self.square_rise_time_spin = QtWidgets.QDoubleSpinBox(self)
self.square_rise_time_spin.setRange(0.0, 0.25)
self.square_rise_time_spin.setDecimals(4)
self.square_rise_time_spin.setSingleStep(0.002)
self.square_rise_time_spin.setValue(0.0)
self.square_fall_time_spin = QtWidgets.QDoubleSpinBox(self)
self.square_fall_time_spin.setRange(0.0, 0.25)
self.square_fall_time_spin.setDecimals(4)
self.square_fall_time_spin.setSingleStep(0.002)
self.square_fall_time_spin.setValue(0.0)
self.square_bounce_decay_type_combo = QtWidgets.QComboBox(self)
self.square_bounce_decay_type_combo.addItem("Exponencial (direto)", "exp")
self.square_bounce_decay_type_combo.addItem("Ln (direto)", "ln")
self.square_bounce_decay_spin = QtWidgets.QDoubleSpinBox(self)
self.square_bounce_decay_spin.setRange(0.01, 50.0)
self.square_bounce_decay_spin.setDecimals(3)
self.square_bounce_decay_spin.setSingleStep(0.25)
self.square_bounce_decay_spin.setValue(8.0)
self.exp_log_smooth_spin = QtWidgets.QDoubleSpinBox(self)
self.exp_log_smooth_spin.setRange(0.10, 50.0)
self.exp_log_smooth_spin.setDecimals(2)
self.exp_log_smooth_spin.setSingleStep(0.25)
self.exp_log_smooth_spin.setValue(5.0)
self.formula_edit = QtWidgets.QLineEdit(self)
self.formula_edit.setPlaceholderText("Ex: sin(2*pi*x/256) + 0.2*sin(2*pi*x/1024) (x = 0..N-1)")
self.apply_formula_btn = QtWidgets.QPushButton("Aplicar fórmula", self)
self.clear_btn = QtWidgets.QPushButton("Limpar desenho", self)
self.save_btn = QtWidgets.QPushButton("Salvar .txt", self)
self.load_btn = QtWidgets.QPushButton("Carregar .txt", self)
self.sample_count_spin = QtWidgets.QSpinBox(self)
self.sample_count_spin.setRange(16, 262144)
self.sample_count_spin.setSingleStep(256)
self.sample_count_spin.setValue(DEFAULT_N_SAMPLES)
self.cycles_spin = QtWidgets.QSpinBox(self)
self.cycles_spin.setRange(1, 64)
self.cycles_spin.setSingleStep(1)
self.cycles_spin.setValue(1)
self.amp_spin = QtWidgets.QDoubleSpinBox(self)
self.amp_spin.setRange(0.0, 10.0)
self.amp_spin.setDecimals(4)
self.amp_spin.setSingleStep(0.1)
self.amp_spin.setValue(1.0)
self.phase_spin = QtWidgets.QDoubleSpinBox(self)
self.phase_spin.setRange(-360.0, 360.0)
self.phase_spin.setDecimals(2)
self.phase_spin.setSingleStep(5.0)
self.phase_spin.setValue(0.0)
self.offset_spin = QtWidgets.QDoubleSpinBox(self)
self.offset_spin.setRange(-10.0, 10.0)
self.offset_spin.setDecimals(4)
self.offset_spin.setSingleStep(0.05)
self.offset_spin.setValue(0.0)
self.status = QtWidgets.QLabel("", self)
self.status.setWordWrap(True)
self.web_view = None
web_engine_view_class = _try_get_web_engine_view_class()
if web_engine_view_class is not None:
try:
self.web_view = web_engine_view_class(self)
self.web_view.setMinimumHeight(120)
except Exception:
self.web_view = None
if self.web_view is None:
placeholder = QtWidgets.QLabel(
"QtWebEngine está desabilitado/indisponível. A fórmula será plotada, mas não renderizada via MathJax.",
self,
)
placeholder.setWordWrap(True)
self.web_view = placeholder # type: ignore
controls = QtWidgets.QVBoxLayout()
controls.addWidget(QtWidgets.QLabel("Presets:", self))
controls.addWidget(self.preset_combo)
preset_checks_row = QtWidgets.QHBoxLayout()
preset_checks_row.addWidget(self.preset_invert_check)
preset_checks_row.addWidget(self.sinever_reverse_sweep_check)
controls.addLayout(preset_checks_row)
self.sine_controls = QtWidgets.QGroupBox("Seno/Cosseno", self)
sine_form = QtWidgets.QFormLayout(self.sine_controls)
sine_form.addRow("Trecho do ciclo:", self.sine_fraction_combo)
controls.addWidget(self.sine_controls)
self.exp_log_controls = QtWidgets.QGroupBox("Exponencial/Logaritmo", self)
exp_log_form = QtWidgets.QFormLayout(self.exp_log_controls)
exp_log_form.addRow("Suavidade:", self.exp_log_smooth_spin)
controls.addWidget(self.exp_log_controls)
self.triangle_controls = QtWidgets.QGroupBox("Triangular", self)
tri_form = QtWidgets.QFormLayout(self.triangle_controls)
tri_form.addRow("Ângulo de abertura (graus):", self.triangle_opening_angle_spin)
controls.addWidget(self.triangle_controls)
self.bell_controls = QtWidgets.QGroupBox("Sino (Gaussiana)", self)
bell_form = QtWidgets.QFormLayout(self.bell_controls)
bell_form.addRow("Abertura (largura):", self.bell_width_spin)
bell_form.addRow("Suavidade de subida:", self.bell_rise_smooth_spin)
bell_form.addRow("Suavidade de descida:", self.bell_fall_smooth_spin)
controls.addWidget(self.bell_controls)
self.square_controls = QtWidgets.QGroupBox("Quadrada", self)
square_form = QtWidgets.QFormLayout(self.square_controls)
square_form.addRow("Duty Cycle (%):", self.square_duty_spin)
square_form.addRow("Subida (fração do ciclo):", self.square_rise_time_spin)
square_form.addRow("Descida (fração do ciclo):", self.square_fall_time_spin)
square_form.addRow(self.square_bounce_rise_check)
square_form.addRow(self.square_bounce_fall_check)
square_form.addRow("Amplitude do recochete:", self.square_bounce_amp_spin)
square_form.addRow("Duração (fração do ciclo):", self.square_bounce_duration_spin)
square_form.addRow("Decaimento:", self.square_bounce_decay_type_combo)
square_form.addRow("Intensidade:", self.square_bounce_decay_spin)
controls.addWidget(self.square_controls)
self.heartbeat_controls = QtWidgets.QGroupBox("Heartbeat", self)
hb_form = QtWidgets.QFormLayout(self.heartbeat_controls)
hb_form.addRow("Ciclos no buffer (bat/s):", self.heartbeat_cycles_spin)
hb_form.addRow("Tipo:", self.heartbeat_type_combo)
controls.addWidget(self.heartbeat_controls)
controls.addWidget(QtWidgets.QLabel("Fórmula:", self))
controls.addWidget(self.formula_edit)
controls.addWidget(self.apply_formula_btn)
controls.addSpacing(8)
controls.addWidget(QtWidgets.QLabel("Render (MathJax):", self))
controls.addWidget(self.web_view) # type: ignore[arg-type]
controls.addSpacing(8)
controls.addWidget(QtWidgets.QLabel("Amplitude:", self))
controls.addWidget(self.amp_spin)
controls.addWidget(QtWidgets.QLabel("Defasagem (graus):", self))
controls.addWidget(self.phase_spin)
controls.addWidget(QtWidgets.QLabel("Offset:", self))
controls.addWidget(self.offset_spin)
controls.addSpacing(8)
controls.addWidget(QtWidgets.QLabel("Amostras:", self))
controls.addWidget(self.sample_count_spin)
controls.addWidget(QtWidgets.QLabel("Ciclos:", self))
controls.addWidget(self.cycles_spin)
controls.addSpacing(8)
controls.addWidget(self.load_btn)
controls.addWidget(self.save_btn)
controls.addStretch(1)
controls.addWidget(self.status)
left_panel = QtWidgets.QVBoxLayout()
left_panel.addWidget(QtWidgets.QLabel("Slot A", self))
left_panel.addWidget(self.preview_a)
slot_a_btns = QtWidgets.QHBoxLayout()
slot_a_btns.addWidget(self.add_a_btn)
slot_a_btns.addWidget(self.concat_a_btn)
left_panel.addLayout(slot_a_btns)
left_panel.addSpacing(10)
left_panel.addWidget(self.sum_btn)
left_panel.addWidget(self.sub_btn)
left_panel.addWidget(self.mul_btn)
left_panel.addWidget(self.div_btn)
left_panel.addSpacing(10)
left_panel.addWidget(QtWidgets.QLabel("Slot B", self))
left_panel.addWidget(self.preview_b)
slot_b_btns = QtWidgets.QHBoxLayout()
slot_b_btns.addWidget(self.add_b_btn)
slot_b_btns.addWidget(self.concat_b_btn)
left_panel.addLayout(slot_b_btns)
left_panel.addStretch(1)
center_panel = QtWidgets.QVBoxLayout()
center_panel.addWidget(self.canvas)
center_panel.addWidget(self.clear_btn)
main = QtWidgets.QHBoxLayout(central)
main.addLayout(left_panel, stretch=1)
main.addLayout(center_panel, stretch=3)
main.addLayout(controls, stretch=2)
self.apply_formula_btn.clicked.connect(self._on_apply_formula)
self.clear_btn.clicked.connect(self._on_clear)
self.load_btn.clicked.connect(self._on_load)
self.save_btn.clicked.connect(self._on_save)
self.formula_edit.textChanged.connect(self._on_formula_changed)
self.preset_combo.currentIndexChanged.connect(self._on_preset_changed)
self.preset_invert_check.stateChanged.connect(self._on_preset_invert_changed)
self.sinever_reverse_sweep_check.stateChanged.connect(self._on_preset_params_changed)
self.sine_fraction_combo.currentIndexChanged.connect(self._on_sine_fraction_changed)
self.triangle_opening_angle_spin.valueChanged.connect(self._on_preset_params_changed)
self.bell_width_spin.valueChanged.connect(self._on_preset_params_changed)
self.bell_rise_smooth_spin.valueChanged.connect(self._on_preset_params_changed)
self.bell_fall_smooth_spin.valueChanged.connect(self._on_preset_params_changed)
self.square_duty_spin.valueChanged.connect(self._on_preset_params_changed)
self.square_rise_time_spin.valueChanged.connect(self._on_preset_params_changed)
self.square_fall_time_spin.valueChanged.connect(self._on_preset_params_changed)
self.square_bounce_rise_check.stateChanged.connect(self._on_preset_params_changed)
self.square_bounce_fall_check.stateChanged.connect(self._on_preset_params_changed)
self.square_bounce_amp_spin.valueChanged.connect(self._on_preset_params_changed)
self.square_bounce_duration_spin.valueChanged.connect(self._on_preset_params_changed)
self.square_bounce_decay_type_combo.currentIndexChanged.connect(self._on_preset_params_changed)
self.square_bounce_decay_spin.valueChanged.connect(self._on_preset_params_changed)
self.exp_log_smooth_spin.valueChanged.connect(self._on_exp_log_smooth_changed)
self.heartbeat_cycles_spin.valueChanged.connect(self._on_heartbeat_params_changed)
self.heartbeat_type_combo.currentIndexChanged.connect(self._on_heartbeat_params_changed)
self.sample_count_spin.valueChanged.connect(self._on_sample_count_changed)
self.cycles_spin.valueChanged.connect(self._on_transform_changed)
self.amp_spin.valueChanged.connect(self._on_transform_changed)
self.phase_spin.valueChanged.connect(self._on_transform_changed)
self.offset_spin.valueChanged.connect(self._on_transform_changed)
self.add_a_btn.clicked.connect(self._on_add_a)
self.add_b_btn.clicked.connect(self._on_add_b)
self.sum_btn.clicked.connect(self._on_sum)
self.sub_btn.clicked.connect(self._on_sub)
self.mul_btn.clicked.connect(self._on_mul)
self.div_btn.clicked.connect(self._on_div)
self.concat_a_btn.clicked.connect(self._on_concat_a)
self.concat_b_btn.clicked.connect(self._on_concat_b)
self._current_waveform_base: Optional[Waveform] = None
self._slot_a_base: Optional[Waveform] = None
self._slot_b_base: Optional[Waveform] = None
self._slot_a_cycles: List[Waveform] = []
self._slot_b_cycles: List[Waveform] = []
self._suppress_custom_switch = False
self.preview_a.set_waveform(None)
self.preview_b.set_waveform(None)
self._on_formula_changed(self.formula_edit.text())
self._update_heartbeat_controls()
self._update_preset_invert_control()
self._update_sinever_reverse_sweep_control()
self._update_sine_controls()
self._update_exp_log_controls()
self._update_triangle_controls()
self._update_bell_controls()
self._update_square_controls()
self._update_save_label()
def _init_presets(self) -> None:
# kind: 'expr' usa SymPy; kind: 'gen' gera diretamente 8192 amostras
self.preset_combo.clear()
self.preset_combo.addItem("Custom", {"kind": "custom"})
self.preset_combo.addItem("AbsSine", {"kind": "gen", "gen": "abs_sine"})
self.preset_combo.addItem("AmpALT", {"kind": "gen", "gen": "amp_alt"})
self.preset_combo.addItem("AttALT", {"kind": "gen", "gen": "att_alt"})
self.preset_combo.addItem("Seno (sin)", {"kind": "expr", "expr_id": "sin", "expr": "sin(2*pi*x/8191)"})
self.preset_combo.addItem("Cosseno (cos)", {"kind": "expr", "expr_id": "cos", "expr": "cos(2*pi*x/8191)"})
self.preset_combo.addItem("CosH", {"kind": "gen", "gen": "cosh"})
self.preset_combo.addItem("Exponencial (exp)", {"kind": "expr", "expr_id": "exp", "expr": "(exp(5*(x/8191)) - 1) / (exp(5) - 1)"})
self.preset_combo.addItem(
"Logaritmo natural (ln)",
{"kind": "expr", "expr_id": "log", "expr": "log(1 + 9*(x/8191)) / log(10)"},
)
self.preset_combo.addItem("LogNormal", {"kind": "gen", "gen": "lognormal"})
self.preset_combo.addItem("Log2_up", {"kind": "gen", "gen": "log2_up"})
self.preset_combo.addItem("Log2_down", {"kind": "gen", "gen": "log2_down"})
self.preset_combo.addItem("Quadrada", {"kind": "gen", "gen": "square"})
self.preset_combo.addItem("Dente de serra", {"kind": "expr", "expr": "x/8191"})
self.preset_combo.addItem("Triangular", {"kind": "gen", "gen": "triangular"})
self.preset_combo.addItem("tri_up", {"kind": "gen", "gen": "tri_up"})
self.preset_combo.addItem("tri_down", {"kind": "gen", "gen": "tri_down"})
self.preset_combo.addItem("Trapezia", {"kind": "gen", "gen": "trapezia"})
self.preset_combo.addItem("StairUD", {"kind": "gen", "gen": "stair_ud"})
self.preset_combo.addItem("StepResp", {"kind": "gen", "gen": "step_resp"})
self.preset_combo.addItem("Sinc", {"kind": "gen", "gen": "sinc"})
self.preset_combo.addItem("Lorentz", {"kind": "gen", "gen": "lorentz"})
self.preset_combo.addItem("GaussianMonopulse", {"kind": "gen", "gen": "gaussian_monopulse"})
self.preset_combo.addItem("GaussPulse", {"kind": "gen", "gen": "gauss_pulse"})
self.preset_combo.addItem("Radar", {"kind": "gen", "gen": "radar"})
self.preset_combo.addItem("Sino comum (Gaussiana)", {"kind": "gen", "gen": "gaussian_bell"})
self.preset_combo.addItem("Sino invertido", {"kind": "gen", "gen": "gaussian_bell_inverted"})
self.preset_combo.addItem("Ruído branco", {"kind": "gen", "gen": "white_noise"})
self.preset_combo.addItem("Ruído rosa", {"kind": "gen", "gen": "pink_noise"})
self.preset_combo.addItem("Cardiac", {"kind": "gen", "gen": "heartbeat"})
self.preset_combo.addItem("Pulseogram", {"kind": "gen", "gen": "pulseogram"})
self.preset_combo.addItem("EEG", {"kind": "gen", "gen": "eeg"})
self.preset_combo.addItem("EOG", {"kind": "gen", "gen": "eog"})
self.preset_combo.addItem("TV", {"kind": "gen", "gen": "tv"})
self.preset_combo.addItem("VOICE", {"kind": "gen", "gen": "voice"})
self.preset_combo.addItem("SineVer", {"kind": "gen", "gen": "sine_ver"})
def _update_heartbeat_controls(self) -> None:
data = self.preset_combo.currentData()
enabled = bool(isinstance(data, dict) and data.get("kind") == "gen" and data.get("gen") == "heartbeat")
self.heartbeat_controls.setVisible(enabled)
def _update_preset_invert_control(self) -> None:
data = self.preset_combo.currentData()
enabled = bool(isinstance(data, dict) and data.get("kind") in {"expr", "gen"})
self.preset_invert_check.setEnabled(enabled)
def _update_sinever_reverse_sweep_control(self) -> None:
data = self.preset_combo.currentData()
enabled = bool(isinstance(data, dict) and data.get("kind") == "gen" and data.get("gen") == "sine_ver")
self.sinever_reverse_sweep_check.setEnabled(enabled)
def _update_sine_controls(self) -> None:
data = self.preset_combo.currentData()
enabled = bool(
isinstance(data, dict)
and data.get("kind") == "expr"
and data.get("expr_id") in {"sin", "cos"}
)
self.sine_controls.setVisible(enabled)
def _update_exp_log_controls(self) -> None:
data = self.preset_combo.currentData()
enabled = bool(
isinstance(data, dict)
and data.get("kind") == "expr"
and data.get("expr_id") in {"exp", "log"}
)
self.exp_log_controls.setVisible(enabled)
def _update_triangle_controls(self) -> None:
data = self.preset_combo.currentData()
enabled = bool(isinstance(data, dict) and data.get("kind") == "gen" and data.get("gen") == "triangular")
self.triangle_controls.setVisible(enabled)
def _update_bell_controls(self) -> None:
data = self.preset_combo.currentData()
enabled = bool(
isinstance(data, dict)
and data.get("kind") == "gen"
and data.get("gen") in {"gaussian_bell", "gaussian_bell_inverted"}
)
self.bell_controls.setVisible(enabled)
def _update_square_controls(self) -> None:
data = self.preset_combo.currentData()
enabled = bool(isinstance(data, dict) and data.get("kind") == "gen" and data.get("gen") == "square")
self.square_controls.setVisible(enabled)
def _on_sine_fraction_changed(self, _index: int) -> None:
# Atualiza o campo de fórmula somente se o preset atual for seno/cosseno.
data = self.preset_combo.currentData()
if not (isinstance(data, dict) and data.get("kind") == "expr" and data.get("expr_id") in {"sin", "cos"}):
return
expr_id = str(data.get("expr_id"))
fraction = str(self.sine_fraction_combo.currentData() or "1")
denom = self._get_sample_denom()
self._set_formula_text_programmatically(f"{expr_id}(2*pi*(x/{denom})*({fraction}))")
def _on_exp_log_smooth_changed(self) -> None:
data = self.preset_combo.currentData()
if not (isinstance(data, dict) and data.get("kind") == "expr" and data.get("expr_id") in {"exp", "log"}):
return
self._update_exp_log_formula()
def _update_exp_log_formula(self) -> None:
data = self.preset_combo.currentData()
if not (isinstance(data, dict) and data.get("kind") == "expr" and data.get("expr_id") in {"exp", "log"}):
return
expr_id = str(data.get("expr_id"))
k = float(self.exp_log_smooth_spin.value())
denom = self._get_sample_denom()
if expr_id == "exp":
self._set_formula_text_programmatically(f"(exp({k}*(x/{denom})) - 1) / (exp({k}) - 1)")
else:
self._set_formula_text_programmatically(f"log(1 + {k}*(x/{denom})) / log(1 + {k})")
def _on_preset_invert_changed(self) -> None:
# Inversão é aplicada ao clicar em Aplicar.
pass
def _on_preset_params_changed(self) -> None:
# Mantém UI responsiva; geração só ocorre ao clicar em Aplicar.
pass
def _on_heartbeat_params_changed(self) -> None:
# Mantém UI responsiva; geração só ocorre ao clicar em Aplicar.
pass
def _on_preset_changed(self, _index: int) -> None:
data = self.preset_combo.currentData()
if not isinstance(data, dict):
return
if data.get("kind") == "expr":
expr = str(data.get("expr", ""))
if expr:
self._set_formula_text_programmatically(expr)
self._update_heartbeat_controls()
self._update_preset_invert_control()
self._update_sinever_reverse_sweep_control()
self._update_sine_controls()
self._update_exp_log_controls()
self._update_triangle_controls()
self._update_bell_controls()
self._update_square_controls()
if data.get("kind") == "expr" and data.get("expr_id") in {"sin", "cos"}:
self._on_sine_fraction_changed(self.sine_fraction_combo.currentIndex())
if data.get("kind") == "expr" and data.get("expr_id") in {"exp", "log"}:
self._update_exp_log_formula()
def _gauss(self, t: np.ndarray, mu: float, sigma: float) -> np.ndarray:
return np.exp(-0.5 * ((t - mu) / sigma) ** 2)
def _get_sample_count(self) -> int:
return int(self.sample_count_spin.value())
def _get_sample_denom(self) -> int:
# Evita divisão por zero em expressões do tipo x/(N-1)
return max(1, self._get_sample_count() - 1)
def _get_cycles(self) -> int:
return int(max(1, self.cycles_spin.value()))
def _update_save_label(self) -> None:
n = self._get_sample_count()
self.save_btn.setText(f"Salvar .txt ({n} amostras)")
def _resample_waveform(self, wf: Waveform, n_new: int) -> Waveform:
grid_new = np.linspace(0.0, 1.0, n_new, endpoint=False)
y_new = np.interp(grid_new, wf.x, wf.y)
return Waveform(x=grid_new, y=y_new)
def _compose_equal_cycles(self, cycles: List[Waveform], n_target: int) -> Optional[Waveform]:
if not cycles:
return None
m = int(len(cycles))
n_target = int(max(2, n_target))
base_len = n_target // m
rem = n_target - (base_len * m)
if base_len <= 0:
base_len = 1
rem = 0
y_out = np.zeros(n_target, dtype=float)
idx = 0
for i, wf in enumerate(cycles):
seg_len = base_len + (1 if i < rem else 0)
if seg_len <= 0:
continue
wf_seg = self._resample_waveform(wf, seg_len) if wf.y.size != seg_len else wf
y_out[idx : idx + seg_len] = wf_seg.y[:seg_len]
idx += seg_len
grid = np.linspace(0.0, 1.0, n_target, endpoint=False)
return Waveform(x=grid, y=y_out)
def _on_sample_count_changed(self) -> None:
n = self._get_sample_count()
if self._current_waveform_base is not None and self._current_waveform_base.y.size != n:
self._current_waveform_base = self._resample_waveform(self._current_waveform_base, n)
if self._slot_a_cycles:
self._slot_a_cycles = [self._resample_waveform(w, n) for w in self._slot_a_cycles]
self._slot_a_base = self._compose_equal_cycles(self._slot_a_cycles, n)
elif self._slot_a_base is not None and self._slot_a_base.y.size != n:
self._slot_a_base = self._resample_waveform(self._slot_a_base, n)
if self._slot_b_cycles:
self._slot_b_cycles = [self._resample_waveform(w, n) for w in self._slot_b_cycles]
self._slot_b_base = self._compose_equal_cycles(self._slot_b_cycles, n)
elif self._slot_b_base is not None and self._slot_b_base.y.size != n:
self._slot_b_base = self._resample_waveform(self._slot_b_base, n)
self._update_save_label()
self._refresh_previews()
if self._current_waveform_base is not None:
self._refresh_main_plot()
def _set_formula_text_programmatically(self, text: str) -> None:
self._suppress_custom_switch = True
try:
self.formula_edit.setText(text)
finally:
self._suppress_custom_switch = False
def _heartbeat_template(self, n: int, kind: str) -> np.ndarray:
# Template simples de um ciclo PQRST, baseado em literatura de simulação por morfologia
# (ex.: abordagem por picos gaussianos e/ou ecgsyn). Aqui é propositalmente simplificado.
t = np.linspace(0.0, 1.0, n, endpoint=False)
# (mu, sigma, amp)
P = (0.18, 0.03, 0.12)
Q = (0.36, 0.010, -0.18)
R = (0.40, 0.012, 1.00)
S = (0.43, 0.012, -0.35)
T = (0.62, 0.050, 0.30)
if kind == "tachy":
# QRS levemente mais estreito e T um pouco menor
Q = (Q[0], Q[1] * 0.85, Q[2])
R = (R[0], R[1] * 0.85, R[2])
S = (S[0], S[1] * 0.85, S[2])
T = (T[0], T[1], T[2] * 0.85)
elif kind == "brady":
# T um pouco mais largo
T = (T[0], T[1] * 1.15, T[2])
elif kind == "pvc":
# PVC simplificado: sem onda P, QRS mais largo e T invertida
P = (P[0], P[1], 0.0)
Q = (0.35, 0.020, -0.25)
R = (0.40, 0.030, 1.10)
S = (0.46, 0.025, -0.55)
T = (0.70, 0.070, -0.25)
elif kind == "afib":
# AFib simplificado: remove P e adiciona baseline fibrilatória
P = (P[0], P[1], 0.0)
y = (
P[2] * self._gauss(t, P[0], P[1])
+ Q[2] * self._gauss(t, Q[0], Q[1])
+ R[2] * self._gauss(t, R[0], R[1])
+ S[2] * self._gauss(t, S[0], S[1])
+ T[2] * self._gauss(t, T[0], T[1])
)
if kind == "afib":
y = y + 0.03 * np.sin(2 * np.pi * (6.0 * t)) + 0.02 * np.sin(2 * np.pi * (9.0 * t + 0.2))
# Normaliza para [-1, 1]
y = y - np.mean(y)
y = y / (np.max(np.abs(y)) + 1e-12)
return y
def _generate_heartbeat(self, cycles: int, kind: str, n_samples: int) -> np.ndarray:
# Interpreta o buffer como 1 segundo: cycles = batimentos por segundo no buffer.
cycles = int(max(1, cycles))
if kind == "tachy":
cycles = max(cycles, 8)
elif kind == "brady":
cycles = min(cycles, 2)
# Gera intervalos RR em amostras (soma = n_samples)
if kind == "afib":
rr = np.random.uniform(0.6, 1.4, size=cycles)
rr = rr / rr.sum() * n_samples
rr = np.maximum(16.0, rr)
rr = rr / rr.sum() * n_samples
rr_int = np.floor(rr).astype(int)
rr_int[-1] += n_samples - int(rr_int.sum())
elif kind == "pvc":
# Uma extra-sístole a cada 4 batimentos: curto + compensatório.
base = n_samples / cycles
rr_int = np.full(cycles, int(round(base)), dtype=int)
if cycles >= 4:
i = cycles // 2
short = max(16, int(round(base * 0.65)))
long = max(16, int(round(base * 1.35)))
rr_int[i] = short
rr_int[min(i + 1, cycles - 1)] = long
rr_int[-1] += n_samples - int(rr_int.sum())
else:
rr_int = np.full(cycles, n_samples // cycles, dtype=int)
rr_int[-1] += n_samples - int(rr_int.sum())
y = np.zeros(n_samples, dtype=float)
idx = 0
for b in range(cycles):
n = int(rr_int[b])
if n <= 0:
continue
beat_kind = kind
if kind == "pvc" and cycles >= 4 and b == cycles // 2:
beat_kind = "pvc"
tmpl = self._heartbeat_template(n, beat_kind)
y[idx : idx + n] = tmpl[:n]
idx += n
y = np.nan_to_num(y, nan=0.0, posinf=0.0, neginf=0.0)
y = y / (np.max(np.abs(y)) + 1e-12) * 0.9
return y
def _generate_preset(self, gen_name: str) -> Waveform:
n = self._get_sample_count()
grid = np.linspace(0.0, 1.0, n, endpoint=False)
x = np.arange(n, dtype=float)
do_clip = True
if gen_name == "white_noise":
y = np.random.normal(0.0, 0.35, size=n)
elif gen_name == "abs_sine":
y = np.abs(np.sin(2.0 * np.pi * grid))
y = y / (np.max(np.abs(y)) + 1e-12) * 0.9
elif gen_name == "amp_alt":
s = np.sin(2.0 * np.pi * grid)
a = np.where(grid < 0.5, 1.0, 0.35)
y = s * a
y = y / (np.max(np.abs(y)) + 1e-12) * 0.9
elif gen_name == "att_alt":
s = np.sin(2.0 * np.pi * grid)
k = 6.0
env1 = np.exp(-k * (grid / 0.5))
env2 = np.exp(-k * ((grid - 0.5) / 0.5))
env = np.where(grid < 0.5, env1, env2)
y = s * env
y = y / (np.max(np.abs(y)) + 1e-12) * 0.9
elif gen_name == "square":
do_clip = False
duty = float(self.square_duty_spin.value()) / 100.0
duty = float(np.clip(duty, 1e-6, 1.0 - 1e-6))
rise_w_ui = float(self.square_rise_time_spin.value())
fall_w_ui = float(self.square_fall_time_spin.value())
max_edge_w = 0.25
rise_w_ui = float(np.clip(rise_w_ui, 0.0, max_edge_w))
fall_w_ui = float(np.clip(fall_w_ui, 0.0, max_edge_w))
inv_log_k = 60.0
inv_log_k = float(max(1e-6, inv_log_k))
def inv_log_width(w: float) -> float:
u = float(np.clip(w, 0.0, max_edge_w))
if max_edge_w <= 0.0:
return 0.0
un = u / max_edge_w
return max_edge_w * (1.0 - (np.log1p(inv_log_k * (1.0 - un)) / np.log1p(inv_log_k)))
rise_w = inv_log_width(rise_w_ui)
fall_w = inv_log_width(fall_w_ui)
bounce_amp = float(self.square_bounce_amp_spin.value())
bounce_duration = float(self.square_bounce_duration_spin.value())
bounce_duration = float(np.clip(bounce_duration, 0.0, 0.5))
decay_k = float(self.square_bounce_decay_spin.value())
decay_kind = str(self.square_bounce_decay_type_combo.currentData() or "exp")
rise_on = bool(self.square_bounce_rise_check.isChecked())
fall_on = bool(self.square_bounce_fall_check.isChecked())
t = grid
def sigmoid(z: np.ndarray) -> np.ndarray:
return 0.5 * (1.0 + np.tanh(z))
def step(t0: np.ndarray, edge: float) -> np.ndarray:
return (t0 >= edge).astype(float)
def wrapped_dist(t0: np.ndarray, center: float) -> np.ndarray:
# intervalo [-0.5, 0.5)
return ((t0 - center + 0.5) % 1.0) - 0.5
# Transição de subida em t=0 (circular) e de descida em t=duty.
if rise_w <= 0.0:
r = step(t, 0.0)
else:
r = sigmoid(wrapped_dist(t, 0.0) / max(1e-12, rise_w))
if fall_w <= 0.0:
f = step(t, duty)
else:
f = sigmoid((t - duty) / max(1e-12, fall_w))
base = r * (1.0 - f)
y = base.copy()
if bounce_amp > 0.0 and bounce_duration > 0.0 and (rise_on or fall_on):
def decay(u: np.ndarray) -> np.ndarray:
u = np.clip(u, 0.0, 1.0)
if decay_kind == "exp":
return np.exp(-decay_k * u)
if decay_kind == "ln":
return 1.0 - (np.log1p(decay_k * u) / np.log1p(decay_k))
return np.exp(-decay_k * u)
# Oscilação fixa dentro da janela: 6 ciclos na duração escolhida
edge_freq = 6.0
def add_bounce(edge_t: float, direction: float) -> None:
dt = (t - edge_t) % 1.0
mask = dt < bounce_duration
if not np.any(mask):
return
u = dt[mask] / max(1e-12, bounce_duration)
# cos() inicia em 1.0: gera overshoot imediato (subida acima, descida abaixo)
ring = np.cos(2.0 * np.pi * edge_freq * u) * decay(u)
y[mask] = y[mask] + direction * bounce_amp * ring
# Subida em t=0 (início do ciclo)
if rise_on:
add_bounce(edge_t=(0.0 + rise_w) % 1.0, direction=+1.0)
# Descida em t=duty
if fall_on:
add_bounce(edge_t=(duty + fall_w) % 1.0, direction=-1.0)
y = np.nan_to_num(y, nan=0.0, posinf=0.0, neginf=0.0)
elif gen_name == "tri_up":
y = grid * 2.0 - 1.0
y = np.clip(y, -1.0, 1.0)
elif gen_name == "tri_down":
y = 1.0 - (grid * 2.0)
y = np.clip(y, -1.0, 1.0)
elif gen_name == "trapezia":
rise = 0.15
high = 0.35
fall = 0.15
low = 1.0 - (rise + high + fall)
t = grid
y = np.empty_like(t)
a0 = rise
a1 = rise + high
a2 = rise + high + fall
y[t < a0] = (t[t < a0] / max(1e-12, rise))
y[(t >= a0) & (t < a1)] = 1.0
y[(t >= a1) & (t < a2)] = 1.0 - ((t[(t >= a1) & (t < a2)] - a1) / max(1e-12, fall))
y[t >= a2] = 0.0
y = y * 2.0 - 1.0
y = np.clip(y, -1.0, 1.0)
elif gen_name == "stair_ud":
steps = 8
half = n // 2
y = np.zeros(n, dtype=float)
for i in range(half):
y[i] = np.floor((i / max(1, half - 1)) * steps) / max(1, steps - 1)
for i in range(half, n):
j = i - half
y[i] = 1.0 - (np.floor((j / max(1, n - half - 1)) * steps) / max(1, steps - 1))
y = y * 2.0 - 1.0
y = np.clip(y, -1.0, 1.0)
elif gen_name == "step_resp":
k = 10.0
t = grid
y = 1.0 - np.exp(-k * t)
y = y * 2.0 - 1.0
y = y / (np.max(np.abs(y)) + 1e-12) * 0.9
elif gen_name == "cosh":
t = (grid - 0.5) * 6.0
y = np.cosh(t)
y = y - np.mean(y)
y = y / (np.max(np.abs(y)) + 1e-12) * 0.9
elif gen_name == "gauss_pulse":
t = grid
sigma = 0.06
y = np.exp(-0.5 * ((t - 0.5) / max(1e-6, sigma)) ** 2)
y = y - np.mean(y)
y = y / (np.max(np.abs(y)) + 1e-12) * 0.9