-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSettlementPro.py
More file actions
3467 lines (3077 loc) · 150 KB
/
SettlementPro.py
File metadata and controls
3467 lines (3077 loc) · 150 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 time
import io
import copy
import os
import json
import urllib.request
import urllib.error
import tempfile
import numpy as np
from datetime import datetime, timedelta
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QTableWidget, QTableWidgetItem, QPushButton,
QLabel, QLineEdit, QHeaderView, QMessageBox, QGroupBox, QTextEdit,
QFileDialog, QCheckBox, QSplashScreen, QComboBox, QColorDialog, QDialog, QGridLayout, QDoubleSpinBox, QDateEdit, QInputDialog, QScrollArea, QToolButton, QFrame)
from PyQt6.QtGui import QPixmap, QPainter, QColor, QFont, QIcon, QPen
from PyQt6.QtCore import Qt, QDate
import matplotlib.dates as mdates
# 尝试导入可选依赖库
try:
from openpyxl import Workbook
HAS_OPENPYXL = True
except ImportError:
HAS_OPENPYXL = False
try:
from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
HAS_DOCX = True
except ImportError:
HAS_DOCX = False
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
# 设置中文字体,防止绘图乱码
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'Arial']
plt.rcParams['axes.unicode_minus'] = False
# --- 暗黑模式样式表 ---
DARK_STYLESHEET = """
QMainWindow, QWidget {
background-color: #2b2b2b;
color: #ffffff;
}
QGroupBox {
border: 1px solid #555;
border-radius: 5px;
margin-top: 10px;
font-weight: bold;
}
QGroupBox::title {
subcontrol-origin: margin;
subcontrol-position: top center;
padding: 0 5px;
color: #ffffff;
}
QTableWidget {
background-color: #3c3f41;
color: #ffffff;
gridline-color: #555;
selection-background-color: #4b6eaf;
}
QHeaderView::section {
background-color: #3c3f41;
color: #ffffff;
border: 1px solid #555;
}
QLineEdit, QTextEdit {
background-color: #3c3f41;
color: #ffffff;
border: 1px solid #555;
border-radius: 3px;
}
QPushButton {
background-color: #3c3f41;
color: #ffffff;
border: 1px solid #555;
padding: 6px;
border-radius: 4px;
}
QPushButton:hover {
background-color: #4c5052;
}
QPushButton:pressed {
background-color: #2c2f31;
}
QCheckBox {
color: #ffffff;
}
QLabel {
color: #ffffff;
}
"""
class GreyModelGM11:
"""
GM(1,1) 灰色预测模型核心算法类
"""
def __init__(self):
self.a = None # 发展系数
self.b = None # 灰作用量
self.x0 = None # 原始序列
self.x1 = None # 累加序列
self.fitted = False
def fit(self, data):
"""训练模型"""
try:
self.x0 = np.array(data, dtype=float)
n = len(self.x0)
if n < 4:
return False, "数据量太少,至少需要4期数据"
# 1. 一次累加生成 (1-AGO)
self.x1 = np.cumsum(self.x0)
# 2. 构造数据矩阵 B 和数据向量 Y
B = []
Y = []
for i in range(1, n):
# 紧邻均值生成
z = 0.5 * (self.x1[i] + self.x1[i-1])
B.append([-z, 1])
Y.append(self.x0[i])
B = np.array(B)
Y = np.array(Y).reshape(-1, 1)
# 3. 最小二乘法求解
# (B^T * B)^-1 * B^T * Y
bt_b = np.dot(B.T, B)
if np.linalg.det(bt_b) == 0:
return False, "矩阵奇异,无法求解"
bt_b_inv = np.linalg.inv(bt_b)
params = np.dot(np.dot(bt_b_inv, B.T), Y)
self.a = params[0][0]
self.b = params[1][0]
self.fitted = True
return True, "模型构建成功"
except Exception as e:
return False, str(e)
def predict(self, k_times):
"""预测未来 k_times 期 (包含已有的期数)"""
if not self.fitted:
return None
predict_x1 = []
predict_x0 = []
# 响应方程
x0_1 = self.x0[0]
term1 = x0_1 - self.b / self.a
for k in range(k_times):
if k == 0:
val = x0_1
predict_x1.append(val)
predict_x0.append(val)
else:
# 计算累加预测值
val = term1 * np.exp(-self.a * k) + self.b / self.a
predict_x1.append(val)
# 累减还原得到原始预测值
predict_x0.append(val - predict_x1[-2])
return np.array(predict_x0)
def get_accuracy(self, predicted_vals):
"""计算残差和相对误差"""
n = len(self.x0)
residuals = self.x0 - predicted_vals[:n]
relative_error = np.abs(residuals) / self.x0 * 100
return residuals, relative_error
def residual_check(self, relative_errors, threshold=10.0):
"""
残差检验 (精度等级评定)
:param relative_errors: 相对误差百分比数组
:param threshold: 合格阈值 (默认 10%)
:return: (bool 是否合格, str 评价信息)
"""
avg_err = np.mean(relative_errors)
if avg_err < 1.0: grade = "一级 (优)"
elif avg_err < 5.0: grade = "二级 (合格)"
elif avg_err < 10.0: grade = "三级 (勉强)"
else: grade = "四级 (不合格)"
msg = f"精度评级: {grade}\n平均相对误差: {avg_err:.2f}%"
return avg_err <= threshold, msg
def posterior_variance_check(self, residuals):
"""
后验差检验 (C值/P值) - 更严格的精度评定
:param residuals: 残差数组
:return: (bool 是否合格, str 评价信息, float C, float P)
"""
n = len(residuals)
if n < 1: return False, "数据不足", 0.0, 0.0
# S1: 原始数据标准差
s1 = np.std(self.x0)
# S2: 残差标准差
s2 = np.std(residuals)
# C值: 后验差比值 (越小越好)
C = s2 / s1 if s1 != 0 else 0.0
# P值: 小误差概率 p = P{|e(k)-e_bar| < 0.6745*S1} (越大越好)
res_mean = np.mean(residuals)
threshold = 0.6745 * s1
p_count = np.sum(np.abs(residuals - res_mean) < threshold)
P = p_count / n
# 评级标准 (参照工程测量规范)
if P > 0.95 and C < 0.35: grade = "一级 (好)"; qualified = True
elif P > 0.80 and C < 0.50: grade = "二级 (合格)"; qualified = True
elif P > 0.70 and C < 0.65: grade = "三级 (勉强)"; qualified = True
else: grade = "四级 (不合格)"; qualified = False
msg = f"精度评级: {grade}\n后验差比值 C = {C:.4f}\n小误差概率 P = {P:.4f}"
return qualified, msg, C, P
def rolling_predict_check(self, data, min_len=4):
"""
滚动预测检验:模拟每增加一期数据就重新建模预测下一期
:param data: 实测数据序列
:param min_len: 起始建模的最少数据量 (默认4)
:return: 滚动预测值序列 (与 data 等长, 前 min_len 个为原始值)
"""
n = len(data)
# 初始化结果数组,默认填充原始值(因为前几期无法滚动预测)
rolling_results = np.array(data, dtype=float)
# 从第 min_len 期开始 (索引 min_len),预测该期
# 例如 min_len=4,我们有 0,1,2,3 四个数,第一次预测索引 4 的数
for i in range(min_len, n):
# 使用 [0, i-1] 的数据 (共 i 个点) 来预测第 i 个点
history = data[:i]
temp_model = GreyModelGM11()
success, _ = temp_model.fit(history)
if success:
# 预测 i+1 期 (即包含当前点 i)
# predict 返回长度为 len(history)+1 的数组,最后一个即为预测值
preds = temp_model.predict(len(history) + 1)
rolling_results[i] = preds[-1]
else:
rolling_results[i] = np.nan # 建模失败标记
return rolling_results
class SimpleKalmanFilter:
"""
简易一维卡尔曼滤波器
用于平滑沉降观测数据,去除随机噪声,提取真实趋势
"""
def __init__(self, Q=0.01, R=1.0):
self.Q = Q # 过程噪声协方差 (Process Noise) - 假设系统状态变化的波动
self.R = R # 观测噪声协方差 (Measurement Noise) - 仪器的测量误差
self.x_hat = None # 后验估计值 (最佳估计)
self.P = 1.0 # 后验误差协方差
def filter(self, data):
results = []
for z in data:
if self.x_hat is None:
self.x_hat = z
results.append(z)
continue
# 1. 预测 (Time Update): 假设静态或缓变过程 x(k) = x(k-1)
x_pred = self.x_hat
P_pred = self.P + self.Q
# 2. 更新 (Measurement Update)
K = P_pred / (P_pred + self.R) # 卡尔曼增益
self.x_hat = x_pred + K * (z - x_pred)
self.P = (1 - K) * P_pred
results.append(self.x_hat)
return np.array(results)
class MovingAverageFilter:
"""
移动平均滤波器 (Moving Average Filter)
通过计算滑动窗口内的平均值来平滑数据,消除短期波动
"""
def __init__(self, window_size=3):
self.window_size = window_size
def filter(self, data):
data = np.array(data)
result = []
for i in range(len(data)):
# 窗口范围:从 i-window_size+1 到 i (包含 i)
start_idx = max(0, i - self.window_size + 1)
window = data[start_idx : i + 1]
result.append(np.mean(window))
return np.array(result)
class ExponentialMovingAverageFilter:
"""
指数移动平均滤波器 (EMA)
给予近期数据更高权重,对趋势变化反应更灵敏
"""
def __init__(self, alpha=0.3):
self.alpha = alpha # 平滑系数 (0 < alpha < 1),值越大越接近实测值
def filter(self, data):
data = np.array(data)
if len(data) == 0: return np.array([])
result = [data[0]] # 第一项直接作为初始值
for i in range(1, len(data)):
# EMA_today = alpha * value_today + (1-alpha) * EMA_yesterday
val = self.alpha * data[i] + (1 - self.alpha) * result[-1]
result.append(val)
return np.array(result)
class StyleConfigDialog(QDialog):
"""图表样式配置对话框"""
def __init__(self, current_styles, parent=None):
super().__init__(parent)
self.setWindowTitle("图表样式配置")
self.resize(400, 300)
# 深拷贝当前样式,避免直接修改
self.temp_styles = copy.deepcopy(current_styles)
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
grid = QGridLayout()
headers = ["图层名称", "颜色", "线型", "线宽"]
for col, h in enumerate(headers):
grid.addWidget(QLabel(h), 0, col)
# 映射内部键名到显示名称
self.names_map = {
'observed': '实测值',
'predicted': '预测值',
'poly': '多项式拟合',
'rolling': '滚动预测',
'kalman': '卡尔曼滤波',
'ma': '移动平均',
'ema': '指数平滑',
'conf_int': '置信区间 (填充)'
}
row = 1
for key, name in self.names_map.items():
style = self.temp_styles[key]
grid.addWidget(QLabel(name), row, 0)
# 颜色按钮
btn_color = QPushButton()
btn_color.setFixedSize(50, 25)
self.set_btn_color(btn_color, style['color'])
# 使用 lambda 捕获变量
btn_color.clicked.connect(lambda checked, k=key, b=btn_color: self.choose_color(k, b))
grid.addWidget(btn_color, row, 1)
# 线型下拉框
combo_style = QComboBox()
combo_style.addItems(['-', '--', '-.', ':'])
combo_style.setCurrentText(style['style'])
combo_style.currentTextChanged.connect(lambda t, k=key: self.update_style(k, 'style', t))
grid.addWidget(combo_style, row, 2)
# 线宽微调框
spin_width = QDoubleSpinBox()
spin_width.setRange(0.5, 10.0)
spin_width.setSingleStep(0.5)
spin_width.setValue(style['width'])
spin_width.valueChanged.connect(lambda v, k=key: self.update_style(k, 'width', v))
grid.addWidget(spin_width, row, 3)
row += 1
layout.addLayout(grid)
btn_box = QHBoxLayout()
btn_ok = QPushButton("确定")
btn_ok.clicked.connect(self.accept)
btn_cancel = QPushButton("取消")
btn_cancel.clicked.connect(self.reject)
btn_box.addWidget(btn_ok)
btn_box.addWidget(btn_cancel)
layout.addLayout(btn_box)
self.setLayout(layout)
def set_btn_color(self, btn, color_str):
btn.setStyleSheet(f"background-color: {color_str}; border: 1px solid #555;")
def choose_color(self, key, btn):
c = QColorDialog.getColor(QColor(self.temp_styles[key]['color']), self, "选择颜色")
if c.isValid():
hex_c = c.name()
self.temp_styles[key]['color'] = hex_c
self.set_btn_color(btn, hex_c)
def update_style(self, key, field, value):
self.temp_styles[key][field] = value
def get_styles(self):
return self.temp_styles
class ApiSettingsDialog(QDialog):
"""API 设置对话框"""
def __init__(self, settings, parent=None):
super().__init__(parent)
self.setWindowTitle("API 设置")
self.resize(420, 220)
self.settings = settings
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
form = QGridLayout()
form.addWidget(QLabel("API 地址:"), 0, 0)
self.input_endpoint = QLineEdit(self.settings.get("endpoint", ""))
form.addWidget(self.input_endpoint, 0, 1)
form.addWidget(QLabel("模型名:"), 1, 0)
self.input_model = QLineEdit(self.settings.get("model", ""))
form.addWidget(self.input_model, 1, 1)
form.addWidget(QLabel("API Key:"), 2, 0)
self.input_key = QLineEdit(self.settings.get("api_key", ""))
self.input_key.setEchoMode(QLineEdit.EchoMode.Password)
form.addWidget(self.input_key, 2, 1)
layout.addLayout(form)
btn_layout = QHBoxLayout()
btn_ok = QPushButton("保存")
btn_cancel = QPushButton("取消")
btn_ok.clicked.connect(self.accept)
btn_cancel.clicked.connect(self.reject)
btn_layout.addWidget(btn_ok)
btn_layout.addWidget(btn_cancel)
layout.addLayout(btn_layout)
self.setLayout(layout)
def get_settings(self):
return {
"endpoint": self.input_endpoint.text().strip(),
"model": self.input_model.text().strip(),
"api_key": self.input_key.text().strip()
}
class MplCanvas(FigureCanvas):
"""Matplotlib 绘图画布"""
def __init__(self, parent=None, width=5, height=4, dpi=100):
self.fig = Figure(figsize=(width, height), dpi=dpi)
# --- 修改:创建两个子图 (上图显示沉降,下图显示速率) ---
gs = self.fig.add_gridspec(2, 1, height_ratios=[3, 1], hspace=0.08)
self.ax1 = self.fig.add_subplot(gs[0]) # 主图
self.ax2 = self.fig.add_subplot(gs[1], sharex=self.ax1) # 子图 (共享X轴)
super(MplCanvas, self).__init__(self.fig)
class CollapsibleBox(QWidget):
"""简易可折叠面板"""
def __init__(self, title="", parent=None):
super().__init__(parent)
self.toggle_button = QToolButton(text=title, checkable=True, checked=True)
self.toggle_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
self.toggle_button.setArrowType(Qt.ArrowType.DownArrow)
self.toggle_button.setStyleSheet("QToolButton { border: none; font-weight: bold; }")
self.toggle_button.toggled.connect(self.on_toggled)
header_layout = QHBoxLayout()
header_layout.setContentsMargins(4, 4, 4, 0)
header_layout.addWidget(self.toggle_button)
header_layout.addStretch()
self.content_area = QFrame()
self.content_area.setFrameShape(QFrame.Shape.StyledPanel)
self.content_area.setFrameShadow(QFrame.Shadow.Plain)
self.content_layout = QVBoxLayout()
self.content_layout.setContentsMargins(8, 6, 8, 8)
self.content_area.setLayout(self.content_layout)
main_layout = QVBoxLayout(self)
main_layout.setContentsMargins(2, 2, 2, 2)
main_layout.addLayout(header_layout)
main_layout.addWidget(self.content_area)
def setContentLayout(self, layout):
while self.content_layout.count():
item = self.content_layout.takeAt(0)
widget = item.widget()
if widget:
widget.setParent(None)
self.content_layout.addLayout(layout)
def on_toggled(self, checked):
self.content_area.setVisible(checked)
self.toggle_button.setArrowType(Qt.ArrowType.DownArrow if checked else Qt.ArrowType.RightArrow)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("沉降监测与变形预测系统 - 测绘工程课设")
self.resize(1100, 700)
self.gm_model = GreyModelGM11()
self.is_dark_mode = False # 记录当前主题状态
self.points_data = {}
self.points_stage = {}
self.point_positions = {}
self.current_point = None
self.is_loading_point = False
self.last_raw_data = None
self.last_predicted = None
self.last_residuals = None
self.last_rel_errors = None
self.last_model_name = None
self.last_model_params = None
self.last_model_rmse = None
self.last_model_mae = None
self.multi_ref_points = []
self.last_ref_stability_text = None
self.last_change_index = None
self.last_stage_stats = None
self.last_stage_segments = None
self.last_outlier_indices = []
self.last_risk_text = None
self.last_stability_text = None
self.last_unstable_refs = []
self.last_corrected = False
self.point_results = {}
self.last_deform_grades = None
self.last_stage_deep = None
self.multi_point_analysis = None
self.api_endpoint = "https://api.deepseek.com/chat/completions"
self.api_model = "deepseek-chat"
self.api_key = ""
self.load_api_settings()
# --- 初始化图表样式配置 ---
self.plot_styles = {
'observed': {'color': '#0000FF', 'style': '-', 'width': 1.5, 'marker': 'o'},
'predicted': {'color': '#FF0000', 'style': '--', 'width': 1.5, 'marker': '*'},
'poly': {'color': '#008000', 'style': '--', 'width': 1.5, 'marker': '^'},
'rolling': {'color': '#FF00FF', 'style': '-.', 'width': 1.5, 'marker': '.'},
'kalman': {'color': '#00FFFF', 'style': '-', 'width': 2.0, 'marker': None},
'ma': {'color': '#FFA500', 'style': '-', 'width': 1.5, 'marker': '.'},
'ema': {'color': '#9C27B0', 'style': '-', 'width': 2.0, 'marker': None},
'conf_int': {'color': '#FF0000', 'style': '-', 'width': 1.0, 'marker': None}
}
# 初始化界面布局
self.init_ui()
# 预填一些演示数据
self.init_points()
def init_ui(self):
self.set_app_icon() # 设置程序图标
# --- 菜单栏 ---
menubar = self.menuBar()
settings_menu = menubar.addMenu("设置")
self.act_style = settings_menu.addAction("图表样式设置")
self.act_style.triggered.connect(self.open_style_config)
self.act_theme = settings_menu.addAction("切换暗黑模式")
self.act_theme.triggered.connect(self.toggle_theme)
self.act_api = settings_menu.addAction("API 设置")
self.act_api.triggered.connect(self.open_api_settings)
help_menu = menubar.addMenu("帮助")
about_act = help_menu.addAction("关于")
about_act.triggered.connect(self.show_about)
self.lbl_github = QLabel(
'本项目已在GitHub开源 <a href="https://github.com/ForestSun2023/SettlementPro">'
'https://github.com/ForestSun2023/SettlementPro</a>'
)
self.lbl_github.setTextFormat(Qt.TextFormat.RichText)
self.lbl_github.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
self.lbl_github.setOpenExternalLinks(True)
self.lbl_github.setStyleSheet("margin-right: 50px; margin-top: 10px;")
menubar.setCornerWidget(self.lbl_github, Qt.Corner.TopRightCorner)
main_widget = QWidget()
self.setCentralWidget(main_widget)
main_layout = QHBoxLayout(main_widget)
# --- 左侧面板:数据输入与控制 ---
left_panel = QVBoxLayout()
# 1. 数据表格区域
data_group = CollapsibleBox("监测数据录入")
data_layout = QVBoxLayout()
self.table = QTableWidget()
self.table.setColumnCount(3)
self.table.setHorizontalHeaderLabels(["期数 (t)", "累积沉降量 (mm)", "施工阶段"])
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
self.table.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
self.table.setMinimumHeight(220)
self.table.itemChanged.connect(self.on_table_changed)
data_layout.addWidget(self.table)
# 表格操作按钮
btn_layout = QHBoxLayout()
self.btn_add_row = QPushButton("添加行")
self.btn_add_row.clicked.connect(self.add_row)
self.btn_del_row = QPushButton("删除行")
self.btn_del_row.clicked.connect(self.del_row)
self.btn_clear = QPushButton("清空数据")
self.btn_clear.clicked.connect(self.clear_data)
self.btn_import = QPushButton("导入 CSV")
self.btn_import.clicked.connect(self.import_csv)
self.btn_save = QPushButton("保存数据")
self.btn_save.clicked.connect(self.save_data)
btn_layout.addWidget(self.btn_add_row)
btn_layout.addWidget(self.btn_del_row)
btn_layout.addWidget(self.btn_clear)
btn_layout.addWidget(self.btn_import)
btn_layout.addWidget(self.btn_save)
data_layout.addLayout(btn_layout)
data_group.setContentLayout(data_layout)
# 1.5 测点管理区域
point_group = CollapsibleBox("测点管理")
point_layout = QVBoxLayout()
point_select_layout = QHBoxLayout()
point_select_layout.addWidget(QLabel("当前测点:"))
self.combo_point = QComboBox()
self.combo_point.currentTextChanged.connect(self.on_point_changed)
point_select_layout.addWidget(self.combo_point)
point_layout.addLayout(point_select_layout)
point_btn_layout = QHBoxLayout()
self.btn_add_point = QPushButton("新增测点")
self.btn_add_point.clicked.connect(self.add_point)
self.btn_rename_point = QPushButton("重命名")
self.btn_rename_point.clicked.connect(self.rename_point)
self.btn_del_point = QPushButton("删除测点")
self.btn_del_point.clicked.connect(self.delete_point)
point_btn_layout.addWidget(self.btn_add_point)
point_btn_layout.addWidget(self.btn_rename_point)
point_btn_layout.addWidget(self.btn_del_point)
point_layout.addLayout(point_btn_layout)
base_btn_layout = QHBoxLayout()
self.btn_multi_ref = QPushButton("多基准设置")
self.btn_multi_ref.clicked.connect(self.open_multi_ref_dialog)
self.chk_apply_ref = QCheckBox("启用基准漂移修正")
base_btn_layout.addWidget(self.btn_multi_ref)
base_btn_layout.addWidget(self.chk_apply_ref)
point_layout.addLayout(base_btn_layout)
self.lbl_multi_ref = QLabel("多基准:未选择")
point_layout.addWidget(self.lbl_multi_ref)
pos_layout = QHBoxLayout()
pos_layout.addWidget(QLabel("里程/位置 (m):"))
self.input_point_pos = QDoubleSpinBox()
self.input_point_pos.setRange(-100000.0, 100000.0)
self.input_point_pos.setDecimals(3)
self.input_point_pos.setValue(0.0)
self.input_point_pos.valueChanged.connect(self.update_point_position)
pos_layout.addWidget(self.input_point_pos)
point_layout.addLayout(pos_layout)
ref_layout = QHBoxLayout()
ref_layout.addWidget(QLabel("参考点:"))
self.combo_ref_point = QComboBox()
self.combo_ref_point.currentTextChanged.connect(self.update_multi_point_metrics)
ref_layout.addWidget(self.combo_ref_point)
point_layout.addLayout(ref_layout)
self.chk_show_ref = QCheckBox("显示参考点曲线")
self.chk_show_ref.setChecked(True)
point_layout.addWidget(self.chk_show_ref)
point_group.setContentLayout(point_layout)
# 2. 预测控制区域
control_group = CollapsibleBox("模型计算与预测")
control_layout = QVBoxLayout()
h_layout = QHBoxLayout()
h_layout.addWidget(QLabel("预测未来期数:"))
self.input_future = QLineEdit("3")
h_layout.addWidget(self.input_future)
control_layout.addLayout(h_layout)
model_layout = QHBoxLayout()
model_layout.addWidget(QLabel("主模型:"))
self.combo_model = QComboBox()
self.combo_model.addItems(["自动选型", "GM(1,1)", "对数模型", "幂函数模型", "指数模型", "双曲线模型"])
self.combo_model.setCurrentText("自动选型")
model_layout.addWidget(self.combo_model)
control_layout.addLayout(model_layout)
self.lbl_model_select = QLabel("自动选型结果:--")
self.lbl_model_rmse = QLabel("RMSE:--")
self.lbl_model_mae = QLabel("MAE:--")
self.lbl_model_note = QLabel("参数说明:--")
control_layout.addWidget(self.lbl_model_select)
control_layout.addWidget(self.lbl_model_rmse)
control_layout.addWidget(self.lbl_model_mae)
control_layout.addWidget(self.lbl_model_note)
h_layout_thresh = QHBoxLayout()
h_layout_thresh.addWidget(QLabel("速率阈值 (mm):"))
self.input_rate_threshold = QLineEdit("2.0")
h_layout_thresh.addWidget(self.input_rate_threshold)
control_layout.addLayout(h_layout_thresh)
self.chk_rolling = QCheckBox("启用滚动预测检验")
control_layout.addWidget(self.chk_rolling)
self.chk_kalman = QCheckBox("显示卡尔曼滤波 (去噪)")
control_layout.addWidget(self.chk_kalman)
# -- 修改:将移动平均复选框与窗口大小输入框组合 --
ma_layout = QHBoxLayout()
self.chk_moving_avg = QCheckBox("移动平均 (窗口):")
self.input_ma_window = QLineEdit("3")
self.input_ma_window.setFixedWidth(60) # 设置一个合适的宽度
ma_layout.addWidget(self.chk_moving_avg)
ma_layout.addWidget(self.input_ma_window)
control_layout.addLayout(ma_layout)
self.chk_ema = QCheckBox("显示指数平滑 (EMA)")
control_layout.addWidget(self.chk_ema)
# -- 新增:多项式拟合阶数选择 --
poly_layout = QHBoxLayout()
self.chk_poly = QCheckBox("显示多项式拟合 (阶数):")
self.chk_poly.setChecked(True) # 默认开启
self.combo_poly_order = QComboBox()
self.combo_poly_order.addItems(["1", "2", "3", "4", "5"])
self.combo_poly_order.setCurrentText("2") # 默认 2 阶
self.combo_poly_order.setFixedWidth(60)
poly_layout.addWidget(self.chk_poly)
poly_layout.addWidget(self.combo_poly_order)
control_layout.addLayout(poly_layout)
self.chk_conf_int = QCheckBox("显示 95% 置信区间")
self.chk_conf_int.setChecked(True)
control_layout.addWidget(self.chk_conf_int)
# -- 新增:异常值检测 --
self.chk_detect_outliers = QCheckBox("启用异常值检测")
self.chk_detect_outliers.setChecked(True)
control_layout.addWidget(self.chk_detect_outliers)
outlier_layout = QHBoxLayout()
outlier_layout.addWidget(QLabel("检测方法:"))
self.combo_outlier_method = QComboBox()
self.combo_outlier_method.addItems(["IQR", "3σ", "Grubbs"])
outlier_layout.addWidget(self.combo_outlier_method)
outlier_layout.addWidget(QLabel("α:"))
self.combo_grubbs_alpha = QComboBox()
self.combo_grubbs_alpha.addItems(["0.05", "0.01"])
self.combo_grubbs_alpha.setCurrentText("0.05")
outlier_layout.addWidget(self.combo_grubbs_alpha)
control_layout.addLayout(outlier_layout)
outlier_handle_layout = QHBoxLayout()
outlier_handle_layout.addWidget(QLabel("异常处理:"))
self.combo_outlier_handle = QComboBox()
self.combo_outlier_handle.addItems(["不处理", "剔除", "线性插值", "邻点均值"])
outlier_handle_layout.addWidget(self.combo_outlier_handle)
control_layout.addLayout(outlier_handle_layout)
change_layout = QHBoxLayout()
self.chk_change_detect = QCheckBox("工况识别 (CUSUM)")
self.chk_change_detect.setChecked(True)
change_layout.addWidget(self.chk_change_detect)
change_layout.addWidget(QLabel("阈值:"))
self.input_cusum_threshold = QLineEdit("3.0")
self.input_cusum_threshold.setFixedWidth(60)
change_layout.addWidget(self.input_cusum_threshold)
control_layout.addLayout(change_layout)
# -- 新增:日期设置 --
date_layout = QHBoxLayout()
date_layout.addWidget(QLabel("起始日期:"))
self.input_start_date = QDateEdit()
self.input_start_date.setDate(QDate.currentDate()) # 默认为今天
self.input_start_date.setCalendarPopup(True) # 启用日历弹窗
date_layout.addWidget(self.input_start_date)
date_layout.addWidget(QLabel("间隔(天):"))
self.input_interval = QLineEdit("7") # 默认7天一期
self.input_interval.setFixedWidth(40)
date_layout.addWidget(self.input_interval)
control_layout.addLayout(date_layout)
self.btn_calculate = QPushButton("执行计算与预测")
self.btn_calculate.setStyleSheet("background-color: #4CAF50; color: white; font-weight: bold; padding: 8px;")
self.btn_calculate.clicked.connect(self.run_prediction)
control_layout.addWidget(self.btn_calculate)
self.btn_export_excel = QPushButton("导出 Excel")
self.btn_export_excel.clicked.connect(self.export_to_excel)
export_layout = QHBoxLayout()
export_layout.addWidget(self.btn_export_excel)
self.btn_export_word = QPushButton("生成 Word 报告")
self.btn_export_word.clicked.connect(self.export_word_report)
export_layout.addWidget(self.btn_export_word)
self.btn_export = QPushButton("导出分析图表")
self.btn_export.clicked.connect(self.export_image)
export_layout.addWidget(self.btn_export)
control_layout.addLayout(export_layout)
control_group.setContentLayout(control_layout)
# 2.5 多点评价参数
eval_group = CollapsibleBox("多点评价参数")
eval_layout = QGridLayout()
eval_layout.addWidget(QLabel("稳定判定窗口 N:"), 0, 0)
self.input_stable_window = QLineEdit("3")
self.input_stable_window.setFixedWidth(60)
eval_layout.addWidget(self.input_stable_window, 0, 1)
eval_layout.addWidget(QLabel("稳定速率阈值 (mm/期):"), 0, 2)
self.input_stable_threshold = QLineEdit("0.5")
self.input_stable_threshold.setFixedWidth(60)
eval_layout.addWidget(self.input_stable_threshold, 0, 3)
eval_layout.addWidget(QLabel("累计沉降限值 (mm):"), 1, 0)
self.input_total_limit = QLineEdit("30")
self.input_total_limit.setFixedWidth(60)
eval_layout.addWidget(self.input_total_limit, 1, 1)
eval_layout.addWidget(QLabel("差异沉降限值 (mm):"), 1, 2)
self.input_diff_limit = QLineEdit("15")
self.input_diff_limit.setFixedWidth(60)
eval_layout.addWidget(self.input_diff_limit, 1, 3)
eval_layout.addWidget(QLabel("倾斜率限值 (mm/m):"), 2, 0)
self.input_tilt_limit = QLineEdit("2.0")
self.input_tilt_limit.setFixedWidth(60)
eval_layout.addWidget(self.input_tilt_limit, 2, 1)
eval_layout.addWidget(QLabel("基准漂移阈值 (mm):"), 2, 2)
self.input_ref_drift_limit = QLineEdit("2.0")
self.input_ref_drift_limit.setFixedWidth(60)
eval_layout.addWidget(self.input_ref_drift_limit, 2, 3)
eval_layout.addWidget(QLabel("角变形限值 (1/):"), 3, 0)
self.input_ang_limit = QLineEdit("500")
self.input_ang_limit.setFixedWidth(60)
eval_layout.addWidget(self.input_ang_limit, 3, 1)
eval_group.setContentLayout(eval_layout)
# 2.55 观测精度评定
acc_group = CollapsibleBox("观测精度评定")
acc_layout = QGridLayout()
acc_layout.addWidget(QLabel("仪器精度 (mm):"), 0, 0)
self.input_inst_precision = QLineEdit("1.0")
self.input_inst_precision.setFixedWidth(60)
acc_layout.addWidget(self.input_inst_precision, 0, 1)
acc_layout.addWidget(QLabel("测回数:"), 0, 2)
self.input_rounds = QLineEdit("2")
self.input_rounds.setFixedWidth(60)
acc_layout.addWidget(self.input_rounds, 0, 3)
acc_layout.addWidget(QLabel("观测标准差 (mm):"), 1, 0)
self.input_obs_std = QLineEdit("1.0")
self.input_obs_std.setFixedWidth(60)
acc_layout.addWidget(self.input_obs_std, 1, 1)
self.lbl_acc_eval = QLabel("评定:--")
acc_layout.addWidget(self.lbl_acc_eval, 1, 2, 1, 2)
acc_group.setContentLayout(acc_layout)
# 2.6 变形指标展示
metric_group = CollapsibleBox("多点变形指标")
metric_layout = QVBoxLayout()
self.lbl_diff_settlement = QLabel("差异沉降:-- mm")
self.lbl_tilt = QLabel("倾斜率:-- mm/m")
self.lbl_ang_distortion = QLabel("角变形:--")
self.lbl_grade_diff = QLabel("差异沉降等级:--")
self.lbl_grade_tilt = QLabel("倾斜等级:--")
self.lbl_grade_ang = QLabel("角变形等级:--")
self.lbl_stability = QLabel("稳定性:--")
self.lbl_risk = QLabel("风险等级:--")
metric_layout.addWidget(self.lbl_diff_settlement)
metric_layout.addWidget(self.lbl_tilt)
metric_layout.addWidget(self.lbl_ang_distortion)
metric_layout.addWidget(self.lbl_grade_diff)
metric_layout.addWidget(self.lbl_grade_tilt)
metric_layout.addWidget(self.lbl_grade_ang)
metric_layout.addWidget(self.lbl_stability)
metric_layout.addWidget(self.lbl_risk)
metric_group.setContentLayout(metric_layout)
# 2.65 复测频率建议
resurvey_group = CollapsibleBox("复测频率建议")
resurvey_layout = QVBoxLayout()
self.table_resurvey = QTableWidget()
self.table_resurvey.setColumnCount(3)
self.table_resurvey.setHorizontalHeaderLabels(["测点", "最近间距(m)", "建议频率"])
self.table_resurvey.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
self.table_resurvey.setMinimumHeight(120)
resurvey_layout.addWidget(self.table_resurvey)
resurvey_group.setContentLayout(resurvey_layout)
# 2.7 协同分析
coop_group = CollapsibleBox("多测点协同分析")
coop_layout = QVBoxLayout()
self.lbl_mean_curve = QLabel("群点平均曲线:--")
self.lbl_max_diff = QLabel("最大差异点:--")
self.lbl_outlier_spread = QLabel("异常传播:--")
coop_layout.addWidget(self.lbl_mean_curve)
coop_layout.addWidget(self.lbl_max_diff)
coop_layout.addWidget(self.lbl_outlier_spread)
coop_group.setContentLayout(coop_layout)
# 3. 结果日志区域
log_group = CollapsibleBox("计算报告")
log_layout = QVBoxLayout()
self.log_text = QTextEdit()
self.log_text.setReadOnly(True)
self.log_text.setMinimumHeight(240)
log_layout.addWidget(self.log_text)
log_group.setContentLayout(log_layout)
# 添加到左侧面板
left_panel.addWidget(data_group, stretch=4)
left_panel.addWidget(point_group, stretch=1)
left_panel.addWidget(control_group, stretch=1)
left_panel.addWidget(eval_group, stretch=1)
left_panel.addWidget(metric_group, stretch=1)
left_panel.addWidget(acc_group, stretch=1)
left_panel.addWidget(resurvey_group, stretch=1)
left_panel.addWidget(coop_group, stretch=1)
left_panel.addWidget(log_group, stretch=3)
# --- 右侧面板:绘图区域 ---
right_panel = QVBoxLayout()
plot_group = QGroupBox("沉降曲线可视化")
plot_layout = QVBoxLayout()
self.canvas = MplCanvas(self, width=5, height=4, dpi=100)
plot_layout.addWidget(self.canvas)
plot_group.setLayout(plot_layout)
right_panel.addWidget(plot_group)
# --- 组合主布局 ---
left_container = QWidget()
left_container.setLayout(left_panel)
left_scroll = QScrollArea()
left_scroll.setWidgetResizable(True)
left_scroll.setWidget(left_container)
left_scroll.setMinimumWidth(430)
main_layout.addWidget(left_scroll, stretch=1)
main_layout.addLayout(right_panel, stretch=2)
def set_app_icon(self):
"""设置应用程序图标 (动态生成,无需外部文件)"""
# 创建一个 64x64 的画布
pixmap = QPixmap(64, 64)
pixmap.fill(QColor(0, 0, 0, 0)) # 透明背景
painter = QPainter(pixmap)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
# 1. 绘制背景 (深青色圆角矩形)
painter.setBrush(QColor("#00838F"))
painter.setPen(Qt.PenStyle.NoPen)
painter.drawRoundedRect(4, 4, 56, 56, 12, 12)
# 2. 绘制折线图符号 (白色)
pen = QPen(QColor("white"))
pen.setWidth(5)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
painter.setPen(pen)
# 绘制简单的趋势线
painter.drawLine(15, 48, 30, 32)
painter.drawLine(30, 32, 42, 40)
painter.drawLine(42, 40, 52, 16)