-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui_main.py
More file actions
2659 lines (2271 loc) · 108 KB
/
Copy pathgui_main.py
File metadata and controls
2659 lines (2271 loc) · 108 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
"""
气体传感器实验数据分析 - 图形界面版本。
使用 PySide6 构建 GUI,集成 Matplotlib 绘图。
"""
import sys
import io
from pathlib import Path
from typing import Optional, Tuple, List
import numpy as np
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side, numbers
from openpyxl.utils import get_column_letter
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QTableWidget, QTableWidgetItem, QPushButton, QFileDialog,
QDialog, QFormLayout, QSpinBox, QDoubleSpinBox, QCheckBox,
QDialogButtonBox, QMessageBox, QHeaderView, QLabel, QGroupBox,
QSplitter, QSizePolicy, QFrame, QComboBox, QColorDialog,
QLineEdit, QProgressDialog
)
from PySide6.QtCore import Qt, QMimeData
from PySide6.QtGui import QAction, QIcon, QClipboard, QFont, QColor
import matplotlib
matplotlib.use('QtAgg')
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.lines import Line2D
from settings_manager import SettingsManager, AppSettings, AnalysisSettings
from analyze_core import run_analysis, AnalysisResult, OvershootInfo
from language_manager import LanguageManager
# Windows console UTF-8 output
if sys.platform == 'win32':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# 蓝白配色扁平化样式表
FLAT_STYLE = """
QMainWindow, QDialog {
background-color: #f5f7fa;
}
QWidget {
font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
font-size: 11px;
}
QGroupBox {
background-color: white;
border: 1px solid #d0d7de;
border-radius: 6px;
margin-top: 10px;
padding-top: 15px;
font-weight: bold;
color: #24292f;
}
QGroupBox::title {
subcontrol-origin: margin;
left: 10px;
padding: 0 5px;
}
QPushButton {
background-color: #0969da;
color: white;
border: none;
border-radius: 6px;
padding: 8px 16px;
font-weight: bold;
min-width: 80px;
}
QPushButton:hover {
background-color: #0860ca;
}
QPushButton:pressed {
background-color: #0757b5;
}
QPushButton:disabled {
background-color: #8c959f;
}
QTableWidget {
background-color: white;
border: 1px solid #d0d7de;
border-radius: 6px;
gridline-color: #e1e4e8;
selection-background-color: #ddf4ff;
selection-color: #24292f;
}
QTableWidget::item {
padding: 5px;
}
QHeaderView::section {
background-color: #f6f8fa;
border: none;
border-bottom: 2px solid #0969da;
padding: 8px;
font-weight: bold;
color: #24292f;
}
QCheckBox {
spacing: 8px;
color: #24292f;
}
QCheckBox::indicator {
width: 18px;
height: 18px;
border: 2px solid #d0d7de;
border-radius: 4px;
background-color: white;
}
QCheckBox::indicator:checked {
background-color: #0969da;
border-color: #0969da;
}
QCheckBox::indicator:disabled {
background-color: #f6f8fa;
border-color: #e1e4e8;
}
QRadioButton {
spacing: 8px;
color: #24292f;
}
QRadioButton::indicator {
width: 18px;
height: 18px;
border: 2px solid #d0d7de;
border-radius: 9px;
background-color: white;
}
QRadioButton::indicator:checked {
background-color: #0969da;
border-color: #0969da;
}
QComboBox {
border: 1px solid #d0d7de;
border-radius: 6px;
padding: 5px 10px;
background-color: white;
color: #24292f;
}
QComboBox:hover {
border-color: #0969da;
}
QComboBox::drop-down {
border: none;
}
QLabel {
color: #24292f;
}
QLineEdit {
border: 1px solid #d0d7de;
border-radius: 4px;
padding: 5px 8px;
background-color: white;
}
QLineEdit:hover {
border-color: #0969da;
}
QMenuBar {
background-color: white;
border-bottom: 1px solid #d0d7de;
}
QMenuBar::item:selected {
background-color: #ddf4ff;
}
QMenu {
background-color: white;
border: 1px solid #d0d7de;
}
QMenu::item:selected {
background-color: #ddf4ff;
}
QStatusBar {
background-color: #f6f8fa;
border-top: 1px solid #d0d7de;
}
QSplitter::handle {
background-color: #d0d7de;
}
QSpinBox, QDoubleSpinBox {
border: 1px solid #d0d7de;
border-radius: 4px;
padding: 4px;
background-color: white;
}
QSpinBox:hover, QDoubleSpinBox:hover {
border-color: #0969da;
}
QSpinBox::up-button, QDoubleSpinBox::up-button {
subcontrol-origin: border;
subcontrol-position: top right;
border-left: 1px solid #d0d7de;
border-bottom: 1px solid #d0d7de;
border-top-right-radius: 4px;
background-color: #f6f8fa;
width: 20px;
}
QSpinBox::up-button:hover, QDoubleSpinBox::up-button:hover {
background-color: #ddf4ff;
}
QSpinBox::down-button, QDoubleSpinBox::down-button {
subcontrol-origin: border;
subcontrol-position: bottom right;
border-left: 1px solid #d0d7de;
border-top: 1px solid #d0d7de;
border-bottom-right-radius: 4px;
background-color: #f6f8fa;
width: 20px;
}
QSpinBox::down-button:hover, QDoubleSpinBox::down-button:hover {
background-color: #ddf4ff;
}
QSpinBox::up-arrow, QDoubleSpinBox::up-arrow {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 7px solid #24292f;
}
QSpinBox::down-arrow, QDoubleSpinBox::down-arrow {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 7px solid #24292f;
}
QProgressDialog {
background-color: white;
}
"""
def get_current_unit_and_scale(max_val: float) -> Tuple[str, float]:
"""
根据电流最大值自动选择合适的单位和缩放因子。
返回 (单位字符串, 缩放因子)。
规则:当最大值 > 5000X 时,升级到下一个单位。
"""
abs_max = abs(max_val)
if abs_max == 0:
return 'A', 1.0
if abs_max < 1e-9:
return 'pA', 1e12
elif abs_max < 1e-6:
return 'nA', 1e9
elif abs_max < 1e-3:
return 'μA', 1e6
elif abs_max < 1.0:
return 'mA', 1e3
else:
return 'A', 1.0
def get_voltage_unit_and_scale(max_val: float) -> Tuple[str, float]:
"""
根据电压最大值自动选择合适的单位和缩放因子。
返回 (单位字符串, 缩放因子)。
阈值:< 1.0 → mV, < 5000 → V, 否则 → kV。
"""
abs_max = abs(max_val)
if abs_max == 0:
return 'V', 1.0
if abs_max < 1.0:
return 'mV', 1e3
elif abs_max < 5000:
return 'V', 1.0
else:
return 'kV', 1e-3
def get_resistance_unit_and_scale(max_val: float) -> Tuple[str, float]:
"""
根据电阻最大值自动选择合适的单位和缩放因子。
返回 (单位字符串, 缩放因子)。
"""
abs_max = abs(max_val)
if abs_max == 0:
return 'Ω', 1.0
if abs_max < 1e3:
return 'Ω', 1.0
elif abs_max < 1e6:
return 'kΩ', 1e-3
elif abs_max < 1e9:
return 'MΩ', 1e-6
else:
return 'GΩ', 1e-9
def _get_manual_current_scale(unit: str) -> float:
"""返回手动选择的电流单位对应的缩放因子。"""
return {'pA': 1e12, 'nA': 1e9, 'μA': 1e6, 'mA': 1e3, 'A': 1.0}[unit]
def _get_manual_voltage_scale(unit: str) -> float:
"""返回手动选择的电压单位对应的缩放因子。"""
return {'μV': 1e6, 'mV': 1e3, 'V': 1.0}[unit]
def _get_manual_resistance_scale(unit: str) -> float:
"""返回手动选择的电阻单位对应的缩放因子。"""
return {'Ω': 1.0, 'kΩ': 1e-3, 'MΩ': 1e-6, 'GΩ': 1e-9, 'TΩ': 1e-12}[unit]
CURRENT_UNITS = ["nA", "μA", "mA", "A"]
VOLTAGE_UNITS = ["μV", "mV", "V"]
RESISTANCE_UNITS = ["Ω", "kΩ", "MΩ", "GΩ", "TΩ"]
def _column_unit_scale(values: List[float], unit_func) -> Tuple[str, float]:
"""根据一列中的有效值确定该列的单位和缩放因子。"""
valid = [v for v in values if v is not None and np.isfinite(v) and v > 0]
if not valid:
return unit_func(0)[0], 1.0
return unit_func(max(valid))
def _make_form_group(title: str, rows: list, extra_widget=None):
"""创建表单分组。rows >= 2 时使用双列布局。"""
group = QGroupBox(title)
if len(rows) < 2:
form = QFormLayout()
for label_text, widget in rows:
form.addRow(label_text, widget)
if extra_widget:
form.addRow("", extra_widget)
group.setLayout(form)
else:
outer = QHBoxLayout()
mid = (len(rows) + 1) // 2
for col_idx, col_start in enumerate((0, mid)):
form = QFormLayout()
for i in range(col_start, min(col_start + mid, len(rows))):
label_text, widget = rows[i]
form.addRow(label_text, widget)
if extra_widget and col_idx == 1:
form.addRow("", extra_widget)
outer.addLayout(form)
group.setLayout(outer)
return group
def _compute_figsize_and_scale(aspect_ratio: str) -> tuple:
"""
根据用户输入的宽高比字符串计算 figsize 和缩放因子。
输入:"16:9", "4:3", "5:4", "" (空字符串表示使用默认值)
返回:(figsize, scale_factor)
缩放算法:保持宽度固定为 12 英寸,高度 = 12 / (w/h)。
缩放因子 = 新高度 / 参考高度(6),应用于所有字体和线宽,
保证视觉元素与图形高度的比例恒定。
"""
REF_WIDTH = 12.0
REF_HEIGHT = 6.0
DEFAULT = ((REF_WIDTH, REF_HEIGHT), 1.0)
if not aspect_ratio or not aspect_ratio.strip():
return DEFAULT
ar = aspect_ratio.strip()
parts = ar.split(':')
if len(parts) != 2:
return DEFAULT
try:
w = float(parts[0].strip())
h = float(parts[1].strip())
if w <= 0 or h <= 0:
return DEFAULT
except ValueError:
return DEFAULT
new_height = REF_WIDTH * (h / w)
scale_factor = new_height / REF_HEIGHT
return (REF_WIDTH, new_height), scale_factor
class ColorButton(QPushButton):
"""点击弹出颜色选择对话框的小按钮"""
def __init__(self, hex_color: str, parent=None):
super().__init__(parent)
self._color = hex_color
self.setFixedSize(36, 22)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.clicked.connect(self._pick)
self._update_style()
def _update_style(self):
self.setStyleSheet(
f"QPushButton{{background-color:{self._color}; border:1px solid #b0b7c0; "
f"border-radius:3px; min-width:36px; min-height:22px;}}"
f"QPushButton:hover{{border-color:#0969da;}}"
)
def _pick(self):
color = QColorDialog.getColor(QColor(self._color), self)
if color.isValid():
self._color = color.name()
self._update_style()
def color(self) -> str:
return self._color
class SystemSettingsDialog(QDialog):
"""系统首选项对话框:分析参数、峰值检测、界面缩放、语言"""
def __init__(self, settings: AppSettings, lang: LanguageManager, parent=None):
super().__init__(parent)
self.settings = settings
self.lang = lang
self.setWindowTitle(self.lang.get("dialog_system_settings"))
self.setMinimumWidth(400)
self._setup_ui()
def _tr(self, key: str, **kwargs) -> str:
return self.lang.get(key, **kwargs)
def _setup_ui(self):
layout = QVBoxLayout(self)
self.rise_lower = QDoubleSpinBox()
self.rise_lower.setRange(0.1, 99.9)
self.rise_lower.setValue(self.settings.analysis.rise_lower_percent)
self.rise_lower.setSuffix(" %")
self.rise_upper = QDoubleSpinBox()
self.rise_upper.setRange(0.1, 99.9)
self.rise_upper.setValue(self.settings.analysis.rise_upper_percent)
self.rise_upper.setSuffix(" %")
self.fall_upper = QDoubleSpinBox()
self.fall_upper.setRange(0.1, 99.9)
self.fall_upper.setValue(self.settings.analysis.fall_upper_percent)
self.fall_upper.setSuffix(" %")
self.fall_lower = QDoubleSpinBox()
self.fall_lower.setRange(0.1, 99.9)
self.fall_lower.setValue(self.settings.analysis.fall_lower_percent)
self.fall_lower.setSuffix(" %")
analysis_rows = [
(self._tr("label_rise_lower"), self.rise_lower),
(self._tr("label_rise_upper"), self.rise_upper),
(self._tr("label_fall_upper"), self.fall_upper),
(self._tr("label_fall_lower"), self.fall_lower),
]
layout.addWidget(_make_form_group(self._tr("group_analysis"), analysis_rows))
self.prominence = QDoubleSpinBox()
self.prominence.setRange(0.01, 5.0)
self.prominence.setValue(self.settings.analysis.prominence)
self.prominence.setSingleStep(0.05)
self.prominence.setDecimals(2)
self.distance = QSpinBox()
self.distance.setRange(10, 1000)
self.distance.setValue(self.settings.analysis.distance)
self.distance.setSuffix(" pts")
self.baseline_fraction = QDoubleSpinBox()
self.baseline_fraction.setRange(0.001, 0.5)
self.baseline_fraction.setValue(self.settings.analysis.baseline_fraction)
self.baseline_fraction.setSingleStep(0.005)
self.baseline_fraction.setDecimals(3)
self.peak_threshold = QDoubleSpinBox()
self.peak_threshold.setRange(1e-12, 1e-3)
self.peak_threshold.setValue(self.settings.analysis.peak_threshold)
self.peak_threshold.setSingleStep(1e-8)
self.peak_threshold.setDecimals(10)
self.peak_threshold.setSuffix(" A")
reset_btn = QPushButton(self._tr("btn_reset"))
reset_btn.setStyleSheet("""
QPushButton {
background-color: #6e7781;
min-width: 120px;
}
QPushButton:hover {
background-color: #57606a;
}
""")
reset_btn.clicked.connect(self._reset_detection)
detection_rows = [
(self._tr("label_prominence"), self.prominence),
(self._tr("label_distance"), self.distance),
(self._tr("label_baseline"), self.baseline_fraction),
(self._tr("label_peak_thresh"), self.peak_threshold),
]
layout.addWidget(_make_form_group(self._tr("group_detection"), detection_rows, reset_btn))
self.gui_scale = QDoubleSpinBox()
self.gui_scale.setRange(0.5, 3.0)
self.gui_scale.setValue(self.settings.gui_scale)
self.gui_scale.setSingleStep(0.1)
self.gui_scale.setSuffix(" x")
scale_rows = [(self._tr("label_gui_scale"), self.gui_scale)]
layout.addWidget(_make_form_group(self._tr("group_gui_scale"), scale_rows))
self.combo_language = QComboBox()
for code in self.lang.get_available_languages():
self.combo_language.addItem(self.lang.get_language_name(code), code)
current_idx = self.lang.get_available_languages().index(self.lang.language)
self.combo_language.setCurrentIndex(current_idx)
lang_rows = [(self._tr("label_language"), self.combo_language)]
layout.addWidget(_make_form_group(self._tr("group_language"), lang_rows))
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
def _reset_detection(self):
"""重置峰值检测参数为默认值"""
defaults = AnalysisSettings()
self.prominence.setValue(defaults.prominence)
self.distance.setValue(defaults.distance)
self.baseline_fraction.setValue(defaults.baseline_fraction)
self.peak_threshold.setValue(defaults.peak_threshold)
def get_settings(self) -> dict:
return {
'analysis': {
'rise_lower_percent': self.rise_lower.value(),
'rise_upper_percent': self.rise_upper.value(),
'fall_upper_percent': self.fall_upper.value(),
'fall_lower_percent': self.fall_lower.value(),
'prominence': self.prominence.value(),
'distance': self.distance.value(),
'baseline_fraction': self.baseline_fraction.value(),
'peak_threshold': self.peak_threshold.value(),
},
'gui_scale': self.gui_scale.value(),
'language': self.combo_language.currentData(),
}
def get_analysis_changed(self) -> bool:
return (
self.rise_lower.value() != self.settings.analysis.rise_lower_percent or
self.rise_upper.value() != self.settings.analysis.rise_upper_percent or
self.fall_upper.value() != self.settings.analysis.fall_upper_percent or
self.fall_lower.value() != self.settings.analysis.fall_lower_percent or
self.prominence.value() != self.settings.analysis.prominence or
self.distance.value() != self.settings.analysis.distance or
self.baseline_fraction.value() != self.settings.analysis.baseline_fraction or
self.peak_threshold.value() != self.settings.analysis.peak_threshold
)
# 可用的 matplotlib 标记形状列表
MARKER_SHAPES = ['*', 'o', 's', '^', 'v', 'D', 'd', 'p', 'P', 'X', 'h', 'H', '+', 'x', '|', '_']
class PlotSettingsDialog(QDialog):
"""绘图首选项对话框:字体、曲线样式、标记样式、通道B设置"""
def __init__(self, settings: AppSettings, lang: LanguageManager, parent=None):
super().__init__(parent)
self.settings = settings
self.lang = lang
self.setWindowTitle(self.lang.get("dialog_plot_settings"))
self.setMinimumWidth(520)
self._setup_ui()
def _tr(self, key: str, **kwargs) -> str:
return self.lang.get(key, **kwargs)
def _setup_ui(self):
layout = QVBoxLayout(self)
ps = self.settings.plot
# ── 字体与文本 ──────────────────────────────────────────
self.title_size = QSpinBox(); self.title_size.setRange(8, 36); self.title_size.setValue(ps.font_size_title)
self.title_bold = QCheckBox(); self.title_bold.setChecked(ps.title_bold)
self.axis_label_size = QSpinBox(); self.axis_label_size.setRange(8, 24); self.axis_label_size.setValue(ps.font_size_axis_label)
self.axis_label_bold = QCheckBox(); self.axis_label_bold.setChecked(ps.axis_label_bold)
self.tick_size = QSpinBox(); self.tick_size.setRange(6, 18); self.tick_size.setValue(ps.font_size_tick)
self.legend_size = QSpinBox(); self.legend_size.setRange(6, 18); self.legend_size.setValue(ps.font_size_legend)
self.annotation_size = QSpinBox(); self.annotation_size.setRange(6, 16); self.annotation_size.setValue(ps.font_size_annotation)
font_rows = [
(self._tr("label_title_size"), self.title_size),
(self._tr("label_title_bold"), self.title_bold),
(self._tr("label_axis_size"), self.axis_label_size),
(self._tr("label_axis_bold"), self.axis_label_bold),
(self._tr("label_tick_size"), self.tick_size),
(self._tr("label_legend_size"), self.legend_size),
(self._tr("label_annot_size"), self.annotation_size),
]
layout.addWidget(_make_form_group(self._tr("group_font_text"), font_rows))
# ── 通道A(电流)曲线样式 ───────────────────────────────
group_ch_a = QGroupBox(self._tr("group_ch_a_curve"))
outer = QHBoxLayout(group_ch_a)
# 左列:线宽 + 对应颜色
left_form = QFormLayout()
lw_raw_row = QHBoxLayout()
self.line_width_raw = QDoubleSpinBox(); self.line_width_raw.setRange(0.1, 5.0); self.line_width_raw.setValue(ps.line_width_raw); self.line_width_raw.setSingleStep(0.1); self.line_width_raw.setDecimals(1)
self.btn_color_raw = ColorButton(ps.color_raw)
lw_raw_row.addWidget(self.line_width_raw); lw_raw_row.addWidget(self.btn_color_raw)
left_form.addRow(self._tr("label_line_width_raw"), lw_raw_row)
lw_smooth_row = QHBoxLayout()
self.line_width_smooth = QDoubleSpinBox(); self.line_width_smooth.setRange(0.1, 5.0); self.line_width_smooth.setValue(ps.line_width_smooth); self.line_width_smooth.setSingleStep(0.1); self.line_width_smooth.setDecimals(1)
self.btn_color_smooth = ColorButton(ps.color_smooth)
lw_smooth_row.addWidget(self.line_width_smooth); lw_smooth_row.addWidget(self.btn_color_smooth)
left_form.addRow(self._tr("label_line_width_smooth"), lw_smooth_row)
self.line_width_edge = QDoubleSpinBox(); self.line_width_edge.setRange(0.5, 8.0); self.line_width_edge.setValue(ps.line_width_edge); self.line_width_edge.setSingleStep(0.5); self.line_width_edge.setDecimals(1)
left_form.addRow(self._tr("label_line_width_edge"), self.line_width_edge)
outer.addLayout(left_form)
# 右列:颜色
right_form = QFormLayout()
self.btn_color_rise = ColorButton(ps.color_rise)
right_form.addRow(self._tr("label_color_rise"), self.btn_color_rise)
self.btn_color_fall = ColorButton(ps.color_fall)
right_form.addRow(self._tr("label_color_fall"), self.btn_color_fall)
self.btn_color_peak = ColorButton(ps.color_peak)
right_form.addRow(self._tr("label_color_peak"), self.btn_color_peak)
self.btn_color_rise_marker = ColorButton(ps.color_rise_marker)
right_form.addRow(self._tr("label_color_rise_marker"), self.btn_color_rise_marker)
self.btn_color_fall_marker = ColorButton(ps.color_fall_marker)
right_form.addRow(self._tr("label_color_fall_marker"), self.btn_color_fall_marker)
outer.addLayout(right_form)
layout.addWidget(group_ch_a)
# ── 通道A 标记样式 ──────────────────────────────────────
group_marker = QGroupBox(self._tr("group_marker_style"))
marker_outer = QHBoxLayout(group_marker)
marker_left = QFormLayout()
self.combo_peak_shape = QComboBox()
self.combo_peak_shape.addItems(MARKER_SHAPES)
self.combo_peak_shape.setCurrentText(ps.marker_peak_shape)
marker_left.addRow(self._tr("label_marker_peak_shape"), self.combo_peak_shape)
self.marker_peak_size = QSpinBox(); self.marker_peak_size.setRange(4, 30); self.marker_peak_size.setValue(ps.marker_peak_size)
marker_left.addRow(self._tr("label_marker_peak_size"), self.marker_peak_size)
self.combo_crossing_a = QComboBox()
self.combo_crossing_a.addItems(MARKER_SHAPES)
self.combo_crossing_a.setCurrentText(ps.marker_crossing_a_shape)
marker_left.addRow(self._tr("label_marker_crossing_a"), self.combo_crossing_a)
self.combo_crossing_b = QComboBox()
self.combo_crossing_b.addItems(MARKER_SHAPES)
self.combo_crossing_b.setCurrentText(ps.marker_crossing_b_shape)
marker_left.addRow(self._tr("label_marker_crossing_b"), self.combo_crossing_b)
self.marker_edge_size = QSpinBox(); self.marker_edge_size.setRange(2, 15); self.marker_edge_size.setValue(ps.marker_edge_size)
marker_left.addRow(self._tr("label_marker_edge_size"), self.marker_edge_size)
marker_outer.addLayout(marker_left)
marker_outer.addStretch()
layout.addWidget(group_marker)
# ── 通道B 绘图设置 ──────────────────────────────────────
group_ch_b = QGroupBox(self._tr("group_ch_b_plot"))
ch_b_outer = QHBoxLayout(group_ch_b)
ch_b_left = QFormLayout()
self.line_width_b_channel = QDoubleSpinBox(); self.line_width_b_channel.setRange(0.1, 5.0); self.line_width_b_channel.setValue(ps.b_channel_line_width); self.line_width_b_channel.setSingleStep(0.1); self.line_width_b_channel.setDecimals(1)
ch_b_left.addRow(self._tr("label_b_channel_lw"), self.line_width_b_channel)
ch_b_right = QFormLayout()
self.btn_color_voltage = ColorButton(ps.color_voltage)
ch_b_right.addRow(self._tr("label_color_voltage"), self.btn_color_voltage)
self.btn_color_resistance = ColorButton(ps.color_resistance)
ch_b_right.addRow(self._tr("label_color_resistance"), self.btn_color_resistance)
ch_b_outer.addLayout(ch_b_left)
ch_b_outer.addLayout(ch_b_right)
layout.addWidget(group_ch_b)
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
def get_settings(self) -> dict:
return {
'plot': {
'font_size_title': self.title_size.value(),
'title_bold': self.title_bold.isChecked(),
'font_size_axis_label': self.axis_label_size.value(),
'axis_label_bold': self.axis_label_bold.isChecked(),
'font_size_tick': self.tick_size.value(),
'font_size_legend': self.legend_size.value(),
'font_size_annotation': self.annotation_size.value(),
'line_width_raw': self.line_width_raw.value(),
'line_width_smooth': self.line_width_smooth.value(),
'line_width_edge': self.line_width_edge.value(),
'color_raw': self.btn_color_raw.color(),
'color_smooth': self.btn_color_smooth.color(),
'color_rise': self.btn_color_rise.color(),
'color_fall': self.btn_color_fall.color(),
'color_peak': self.btn_color_peak.color(),
'color_rise_marker': self.btn_color_rise_marker.color(),
'color_fall_marker': self.btn_color_fall_marker.color(),
'color_voltage': self.btn_color_voltage.color(),
'color_resistance': self.btn_color_resistance.color(),
'b_channel_line_width': self.line_width_b_channel.value(),
'marker_peak_shape': self.combo_peak_shape.currentText(),
'marker_peak_size': self.marker_peak_size.value(),
'marker_crossing_a_shape': self.combo_crossing_a.currentText(),
'marker_crossing_b_shape': self.combo_crossing_b.currentText(),
'marker_edge_size': self.marker_edge_size.value(),
},
}
class BatchConfirmDialog(QDialog):
"""批量处理确认对话框:显示当前分析设置摘要"""
def __init__(self, settings: AppSettings, file_count: int,
lang: LanguageManager, parent=None):
super().__init__(parent)
self.settings = settings
self.file_count = file_count
self.lang = lang
self.setWindowTitle(self._tr("dlg_batch_confirm_title"))
self.setMinimumWidth(400)
self._setup_ui()
def _tr(self, key: str, **kwargs) -> str:
return self.lang.get(key, **kwargs)
def _setup_ui(self):
layout = QVBoxLayout(self)
# 摘要文本
summary = QLabel(
self._tr("msg_batch_summary", n=self.file_count)
)
summary.setWordWrap(True)
summary.setStyleSheet("font-size: 12px; font-weight: bold; margin-bottom: 10px;")
layout.addWidget(summary)
a = self.settings.analysis
# 通道A 设置摘要
ch_a_rows = [
(self._tr("label_rise_lower"), QLabel(f"{a.rise_lower_percent:.1f} %")),
(self._tr("label_rise_upper"), QLabel(f"{a.rise_upper_percent:.1f} %")),
(self._tr("label_fall_upper"), QLabel(f"{a.fall_upper_percent:.1f} %")),
(self._tr("label_fall_lower"), QLabel(f"{a.fall_lower_percent:.1f} %")),
(self._tr("label_prominence"), QLabel(f"{a.prominence:.2f}")),
(self._tr("label_distance"), QLabel(f"{a.distance} pts")),
(self._tr("label_baseline"), QLabel(f"{a.baseline_fraction:.3f}")),
(self._tr("label_peak_thresh"), QLabel(f"{a.peak_threshold:.2e} A")),
]
layout.addWidget(_make_form_group(
self._tr("group_ch_a_summary"), ch_a_rows
))
# 通道B 设置摘要
b_name = self.settings.b_channel
if b_name == "resistance":
b_display = self._tr("opt_b_resistance")
elif b_name == "voltage":
b_display = self._tr("opt_b_voltage")
else:
b_display = self._tr("opt_b_none")
ch_b_rows = [(self._tr("label_channel_b"), QLabel(b_display))]
layout.addWidget(_make_form_group(
self._tr("group_ch_b_summary"), ch_b_rows
))
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
class BatchOutputDialog(QDialog):
"""批量输出设置对话框:Excel名称、图像类型、输出目录、图像选项"""
def __init__(self, lang: LanguageManager, parent=None):
super().__init__(parent)
self.lang = lang
self.setWindowTitle(self._tr("dlg_batch_output_title"))
self.setMinimumWidth(480)
self._setup_ui()
def _tr(self, key: str, **kwargs) -> str:
return self.lang.get(key, **kwargs)
def _setup_ui(self):
layout = QVBoxLayout(self)
# 汇总表名称
excel_group = QGroupBox(self._tr("group_excel_name"))
excel_layout = QVBoxLayout(excel_group)
self.edit_excel_name = QLineEdit("batch_results.xlsx")
excel_layout.addWidget(self.edit_excel_name)
layout.addWidget(excel_group)
# 图像相关设置
img_group = QGroupBox(self._tr("group_image_settings"))
img_layout = QVBoxLayout(img_group)
# 图像类型
types_layout = QHBoxLayout()
self.chk_svg = QCheckBox(self._tr("chk_svg"))
self.chk_svg.setChecked(True)
types_layout.addWidget(self.chk_svg)
self.chk_png = QCheckBox(self._tr("chk_png"))
self.chk_png.setChecked(True)
types_layout.addWidget(self.chk_png)
types_layout.addStretch()
img_layout.addLayout(types_layout)
# 宽高比
ar_layout = QHBoxLayout()
ar_label = QLabel(self._tr("label_aspect_ratio"))
self.edit_aspect_ratio = QLineEdit("")
self.edit_aspect_ratio.setPlaceholderText("e.g. 16:9, 4:3, 5:4")
self.edit_aspect_ratio.setMaximumWidth(120)
ar_layout.addWidget(ar_label)
ar_layout.addWidget(self.edit_aspect_ratio)
ar_layout.addStretch()
img_layout.addLayout(ar_layout)
# 数据底图
self.chk_base_plot = QCheckBox(self._tr("chk_base_plot"))
self.chk_base_plot.setChecked(False)
img_layout.addWidget(self.chk_base_plot)
layout.addWidget(img_group)
# 输出目录
dir_group = QGroupBox(self._tr("group_output_dir"))
dir_layout = QHBoxLayout(dir_group)
self.edit_output_dir = QLineEdit(str(Path.home() / "Desktop"))
dir_layout.addWidget(self.edit_output_dir)
btn_select = QPushButton(self._tr("btn_select_dir"))
btn_select.clicked.connect(self._select_dir)
dir_layout.addWidget(btn_select)
layout.addWidget(dir_group)
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
def _select_dir(self):
d = QFileDialog.getExistingDirectory(
self, self._tr("dlg_select_dir_title"), self.edit_output_dir.text()
)
if d:
self.edit_output_dir.setText(d)
def get_excel_name(self) -> str:
return self.edit_excel_name.text().strip()
def get_output_dir(self) -> str:
return self.edit_output_dir.text().strip()
def get_svg_enabled(self) -> bool:
return self.chk_svg.isChecked()
def get_png_enabled(self) -> bool:
return self.chk_png.isChecked()
def get_aspect_ratio(self) -> str:
return self.edit_aspect_ratio.text().strip()
def get_base_plot_enabled(self) -> bool:
return self.chk_base_plot.isChecked()
def _build_figure(result: AnalysisResult, settings: AppSettings,
b_channel: str = "",
left_scale: str = 'linear', right_scale: str = 'linear',
figsize: tuple = (12, 6), dpi: int = 100,
base_plot: bool = False, fig: Figure = None,
ch_a_unit_override: tuple = None,
ch_b_unit_override: tuple = None,
x_range: tuple = None,
y1_range: tuple = None,
y2_range: tuple = None,
x_ruler_offset: float = None,
x_label_override: str = None) -> Figure:
"""构建 Matplotlib Figure。fig 参数允许复用已有 Figure(供 PlotCanvas 使用)。"""
if fig is None:
fig = Figure(figsize=figsize, dpi=dpi)
else:
fig.clear()
times = result.times
currents = result.currents
voltages = result.voltages
resistances = result.resistances
currents_smooth = result.currents_smooth
rounds = result.rounds
plot_settings = settings.plot
analysis_settings = settings.analysis
if x_ruler_offset is not None and x_ruler_offset != 0:
times = times - x_ruler_offset
if x_range is not None:
x_range = (x_range[0] - x_ruler_offset, x_range[1] - x_ruler_offset)
if ch_a_unit_override:
current_unit, current_scale = ch_a_unit_override
else:
current_unit, current_scale = get_current_unit_and_scale(np.max(currents))
font_family = 'Times New Roman'
currents_scaled = currents * current_scale
currents_smooth_scaled = currents_smooth * current_scale
ax = fig.add_subplot(111)
ax.plot(
times, currents_scaled,
color=plot_settings.color_raw, linewidth=plot_settings.line_width_raw, alpha=0.4,
label='Raw data'
)
ax.plot(
times, currents_smooth_scaled,
color=plot_settings.color_smooth, linewidth=plot_settings.line_width_smooth, alpha=0.7,
label='Smoothed'
)
marker_a = plot_settings.marker_crossing_a_shape
marker_b = plot_settings.marker_crossing_b_shape
edge_ms = plot_settings.marker_edge_size
for r in rounds:
start, peak, end = r.start_idx, r.peak_idx, r.end_idx
ax.plot(
times[start:peak + 1], currents_smooth_scaled[start:peak + 1],
color=plot_settings.color_rise, linewidth=plot_settings.line_width_edge,
)
ax.plot(
times[peak:end + 1], currents_smooth_scaled[peak:end + 1],
color=plot_settings.color_fall, linewidth=plot_settings.line_width_edge,
)
ax.plot(times[peak], currents_smooth_scaled[peak],
plot_settings.marker_peak_shape,
color=plot_settings.color_peak,
markersize=plot_settings.marker_peak_size)
if not base_plot:
ax.annotate(
f'#{r.round_num}',
xy=(times[peak], currents_smooth_scaled[peak]),
xytext=(5, 10), textcoords='offset points',
fontsize=plot_settings.font_size_annotation,
color='darkred', fontfamily=font_family,
)
if r.rise:
for key, marker in [('t_lower', marker_a), ('t_upper', marker_b)]:
t_val = getattr(r.rise, key)
t_plot = t_val - x_ruler_offset if x_ruler_offset else t_val
idx = np.argmin(np.abs(times - t_plot))
ax.plot(t_plot, currents_smooth_scaled[idx], marker,
color=plot_settings.color_rise_marker, markersize=edge_ms)
if r.fall:
for key, marker in [('t_upper', marker_a), ('t_lower', marker_b)]:
t_val = getattr(r.fall, key)
t_plot = t_val - x_ruler_offset if x_ruler_offset else t_val
idx = np.argmin(np.abs(times - t_plot))
ax.plot(t_plot, currents_smooth_scaled[idx], marker,
color=plot_settings.color_fall_marker, markersize=edge_ms)
if r.is_overshoot and r.overshoot_info:
rapid_t = r.overshoot_info.rapid_descent_start_time
if x_ruler_offset:
rapid_t = rapid_t - x_ruler_offset
ax.axvline(x=rapid_t, color='orange', linestyle='--',
alpha=0.6, linewidth=1)
if not base_plot:
ax.set_ylabel(
f'Current ({current_unit})',
fontsize=plot_settings.font_size_axis_label,
fontweight='bold' if plot_settings.axis_label_bold else 'normal',
fontfamily=font_family,
)
ax.set_xlabel(