-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcallMainWin.py
More file actions
424 lines (369 loc) · 17.3 KB
/
callMainWin.py
File metadata and controls
424 lines (369 loc) · 17.3 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
# -*- coding: utf-8 -*-
"""
Module implementing MainWindow.
"""
import time
from datetime import datetime
import numpy as np
import pandas as pd
from PyQt5.QtCore import pyqtSlot, QThread, pyqtSignal, QTimer
from PyQt5.QtGui import QIntValidator, QStandardItem, QStandardItemModel, QFont
from PyQt5.QtWidgets import QMainWindow, QApplication, QHeaderView, QAbstractItemView, QFileDialog, QMessageBox
from manWin import Ui_MainWindow # 主界面
from specModel import SpecSVRModel, SpecLRModel
from specctrl import SpecCtrl
from specDatabase import SpecDataBase
import serial.tools.list_ports as sp
# 用于线程之间交流的全局变量
global wave_len, spec_value, int_time, avg_time
global spectrometer
global measure_mode, reading_status, isMeasuring
isMeasuring, measure = False, "DARK"
spectrometer = SpecCtrl(timeout=2)
global database
global model_selection, isTraining, isPredicting
database = SpecDataBase()
class MainWindow(QMainWindow, Ui_MainWindow):
"""
Class documentation goes here.
"""
def __init__(self, parent=None):
"""
Constructor
@param parent reference to the parent widget
@type QWidget
"""
super(MainWindow, self).__init__(parent)
self.setupUi(self)
# my code here
self.switch_connect_status(False)
self.config_lineEdit()
self.model_SVR = SpecSVRModel()
self.model_LR = SpecLRModel()
self.matplotlibWidget_spec.setVisible(False)
self.checkBox_continuous.stateChanged.connect(
self.measure_mode_changed)
self.model_data = QStandardItemModel(0, 3)
self.model_data.setHorizontalHeaderLabels(['采集时间', '水分', 'DON'])
self.tableView_data.setModel(self.model_data)
self.tableView_data.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.tableView_data.horizontalHeader().setStretchLastSection(True)
self.tableView_data.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.tableView_data.clicked.connect(self.fresh_plot)
self.measure_thread = MeasureThread()
self.measure_thread.start()
self.measure_thread.trigger.connect(self.measure_finished)
self.continuous_timer = QTimer(self)
self.continuous_timer.timeout.connect(self.update_timer)
self.label_don.setFont(QFont("SimSun", 14))
self.label_don_level.setFont(QFont("SimSun", 14))
self.label_mosi.setFont(QFont("SimSun", 14))
port_list = list(sp.comports())
if len(port_list) <= 0:
print('No port Found')
else:
port_list = [port.device for port in port_list]
self.comboBox_com.addItems(port_list)
@pyqtSlot()
def on_pushButton_connect_clicked(self):
if spectrometer.status:
spectrometer.disconnect()
self.switch_connect_status(False, 'spec')
self.matplotlibWidget_spec.setVisible(False)
self.comboBox_com.setEnabled(True)
else:
dev = self.comboBox_com.currentText()
spectrometer.connect(dev)
if spectrometer.status:
self.lineEdit_int_time.setEnabled(True)
self.lineEdit_avg_time.setEnabled(True)
self.pushButton_dark_ref.setEnabled(True)
self.switch_connect_status(True, 'data')
self.comboBox_com.setEnabled(False)
# self.pushButton_white_ref.setEnabled(True)
@pyqtSlot()
def on_pushButton_dark_ref_clicked(self):
global int_time, avg_time, measure_mode, isMeasuring
int_time = self.lineEdit_int_time.text()
avg_time = self.lineEdit_avg_time.text()
int_time = 50 if int_time == "" else int(int_time)
avg_time = 1 if avg_time == "" else int(avg_time)
measure_mode = 'DARK'
# 开始测量,等结束了唤醒measure finished
# self.measure_thread.start()
isMeasuring = True
self.pushButton_sample.setEnabled(False)
self.pushButton_white_ref.setEnabled(False)
self.pushButton_dark_ref.setEnabled(False)
@pyqtSlot()
def on_pushButton_white_ref_clicked(self):
global int_time, avg_time, measure_mode, isMeasuring
int_time = self.lineEdit_int_time.text()
avg_time = self.lineEdit_avg_time.text()
int_time = 50 if int_time == "" else int(int_time)
avg_time = 1 if avg_time == "" else int(avg_time)
measure_mode = 'LIGHT'
# 开始测量,等结束了唤醒measure finished
# self.measure_thread.start()
isMeasuring = True
self.pushButton_sample.setEnabled(False)
self.pushButton_white_ref.setEnabled(False)
self.pushButton_dark_ref.setEnabled(False)
@pyqtSlot()
def on_pushButton_sample_clicked(self):
"""
Slot documentation goes here.
"""
global int_time, avg_time, measure_mode, isMeasuring
if self.checkBox_continuous.isChecked():
measure_interval = self.lineEdit_param_interval.text()
measure_interval = 0 if measure_interval == "" else int(
measure_interval)
measure_mode = 'REFER'
self.continuous_timer.start(measure_interval * 1000)
else:
int_time = self.lineEdit_int_time.text()
avg_time = self.lineEdit_avg_time.text()
int_time = 50 if int_time == "" else int(int_time)
avg_time = 1 if avg_time == "" else int(avg_time)
measure_mode = 'REFER'
isMeasuring = True
self.pushButton_sample.setEnabled(False)
self.pushButton_white_ref.setEnabled(False)
self.pushButton_dark_ref.setEnabled(False)
@pyqtSlot()
def on_pushButton_add_label_clicked(self):
if self.tableView_data.currentIndex().isValid() == False:
return
index = self.tableView_data.currentIndex().row()
mosi = np.nan if self.lineEdit_mosi.text() is "" else float(self.lineEdit_mosi.text())
don = np.nan if self.lineEdit_don.text() is "" else float(self.lineEdit_don.text())
database.set_label(index, mosi, don)
self.model_data.setItem(index, 1, QStandardItem(str(mosi)))
self.model_data.setItem(index, 2, QStandardItem(str(don)))
@pyqtSlot()
def on_pushButton_del_label_clicked(self):
if self.tableView_data.currentIndex().isValid() == False:
return
index = self.tableView_data.currentIndex().row()
mosi = np.nan
don = np.nan
database.remove_label(index)
self.model_data.setItem(index, 1, QStandardItem(str(mosi)))
self.model_data.setItem(index, 2, QStandardItem(str(don)))
@pyqtSlot()
def on_pushButton_del_data_clicked(self):
if self.tableView_data.currentIndex().isValid() == False:
return
index = self.tableView_data.currentIndex().row()
database.remove(index=index)
self.model_data.removeRow(index)
@pyqtSlot()
def on_pushButton_save_data_clicked(self):
if database.shape[0] == 0:
return
fname, _ = QFileDialog.getSaveFileName(self, "Save File", filter="EXCEL Files (*.xlsx)")
if fname is not '':
database.save(fname, header=[wave_len[i] for i in range(wave_len.shape[0])])
@pyqtSlot()
def on_pushButton_load_data_clicked(self):
global wave_len
fname, _ = QFileDialog.getOpenFileName(self, "Save File", filter="EXCEL Files (*.xlsx)")
if fname is "":
return
self.model_data.clear()
self.model_data.setHorizontalHeaderLabels(['采集时间', '水分', 'DON'])
wave_len = database.load(file_path=fname, is_append=True)
for row_idx in range(database.shape[0]):
temp = database.get_row(row_idx)
content = [QStandardItem(str(temp["time"])), QStandardItem(str(temp["mosi"])),
QStandardItem(str(temp["don"]))]
self.model_data.appendRow(content)
self.tableView_data.resizeColumnsToContents()
@pyqtSlot()
def on_pushButton_save_model_clicked(self):
model = {"线性回归": self.model_LR, "支持向量回归": self.model_SVR}[self.comboBox_model_selection.currentText()]
fname, _ = QFileDialog.getSaveFileName(self, "Save Model", filter="Model File (*.model)")
if fname is not '':
model.save(fname)
@pyqtSlot()
def on_pushButton_load_model_clicked(self):
model = {"线性回归": self.model_LR, "支持向量回归": self.model_SVR}[self.comboBox_model_selection.currentText()]
fname, _ = QFileDialog.getOpenFileName(self, "Load Model", filter="Model File (*.model)")
if fname is not '':
model.load(fname)
self.checkBox_pred.setEnabled(True)
@pyqtSlot()
def on_pushButton_train_model_clicked(self):
model = {"线性回归": self.model_LR, "支持向量回归": self.model_SVR}[self.comboBox_model_selection.currentText()]
self.pushButton_train_model.setEnabled(False)
self.pushButton_load_model.setEnabled(False)
self.pushButton_save_model.setEnabled(False)
QApplication.processEvents()
if database.shape[0] is not 0:
model.fit(database)
QMessageBox.information(self, "训练完毕", '训练完毕')
self.pushButton_train_model.setEnabled(True)
self.pushButton_load_model.setEnabled(True)
self.pushButton_save_model.setEnabled(True)
self.checkBox_pred.setEnabled(True)
def switch_connect_status(self, status=True, set_range='all'):
assert set_range in ["all", 'spec', 'data']
if (set_range is "spec") or (set_range is "all"):
self.lineEdit_int_time.setEnabled(status)
self.lineEdit_avg_time.setEnabled(status)
self.lineEdit_param_interval.setEnabled(status)
self.pushButton_dark_ref.setEnabled(status)
self.pushButton_white_ref.setEnabled(status)
self.pushButton_sample.setEnabled(status)
self.checkBox_continuous.setEnabled(status)
self.checkBox_continuous.setChecked(False)
self.checkBox_pred.setEnabled(status)
if (set_range is "data") or (set_range is "all"):
self.lineEdit_mosi.setEnabled(status)
self.lineEdit_don.setEnabled(status)
self.pushButton_add_label.setEnabled(status)
self.pushButton_save_data.setEnabled(status)
self.pushButton_save_model.setEnabled(status)
self.pushButton_train_model.setEnabled(status)
self.pushButton_del_label.setEnabled(status)
self.pushButton_del_data.setEnabled(status)
self.comboBox_model_selection.setEnabled(status)
self.tableView_data.setEnabled(status)
def config_lineEdit(self):
int_time_validator = QIntValidator(self)
avg_time_validator = QIntValidator(self)
param_interval_validator = QIntValidator(self)
int_time_validator.setRange(2, 40000)
avg_time_validator.setRange(1, 500)
param_interval_validator.setRange(0, 6000)
self.lineEdit_int_time.setValidator(int_time_validator)
self.lineEdit_avg_time.setValidator(avg_time_validator)
self.lineEdit_param_interval.setValidator(param_interval_validator)
# mosi_validator = QDoubleValidator(self)
# don_validator = QDoubleValidator(self)
# mosi_validator.setRange(0, 100)
# don_validator.setRange(0, 1000000)
# self.lineEdit_mosi.setValidator(mosi_validator)
# self.lineEdit_don.setValidator(don_validator)
def measure_mode_changed(self):
print('measure mode changed')
if self.checkBox_continuous.isChecked():
self.lineEdit_param_interval.setEnabled(True)
else:
self.lineEdit_param_interval.setEnabled(False)
self.continuous_timer.stop()
def clear_all(self):
self.matplotlibWidget_spec.mpl.axes.cla()
def measure_finished(self):
if self.checkBox_continuous.isChecked():
if reading_status:
measure_interval = self.lineEdit_param_interval.text()
measure_interval = 0 if measure_interval == "" else int(
measure_interval)
if self.checkBox_pred.isChecked():
model = {"线性回归": self.model_LR, "支持向量回归": self.model_SVR}[self.comboBox_model_selection.currentText()]
mosi, don = model.predict(spec_value.reshape(1, -1))
self.label_mosi.setText(str(mosi[0]))
self.label_don.setText(str(don[0]))
self.label_don_level.setText(str("超标" if don[0] > 1 else "合格"))
self.matplotlibWidget_spec.setVisible(True)
self.matplotlibWidget_spec.mpl.draw_spec(wave_len, spec_value)
self.add_spec()
print('get wave_length shape: {}, spec shape: {}'.format(
wave_len.shape, spec_value.shape))
self.continuous_timer.start(measure_interval * 1000)
else:
print('read failed')
else:
if reading_status:
if self.checkBox_pred.isChecked() and measure_mode is "REFER":
model = {"线性回归": self.model_LR, "支持向量回归":
self.model_SVR}[self.comboBox_model_selection.currentText()]
mosi, don = model.predict(spec_value.reshape(1, -1))
self.label_mosi.setText(str(mosi[0]))
self.label_don.setText(str(don[0]))
self.label_don_level.setText(str("超标" if don[0] > 1 else "合格"))
self.matplotlibWidget_spec.setVisible(True)
self.matplotlibWidget_spec.mpl.draw_spec(wave_len, spec_value)
self.pushButton_white_ref.setEnabled(True)
self.add_spec()
print('get wave_length shape: {}, spec shape: {}'.format(
wave_len.shape, spec_value.shape))
if measure_mode is "DARK":
self.pushButton_dark_ref.setEnabled(True)
self.pushButton_white_ref.setEnabled(True)
else:
self.pushButton_sample.setEnabled(True)
self.pushButton_white_ref.setEnabled(True)
self.pushButton_dark_ref.setEnabled(True)
self.checkBox_continuous.setEnabled(True)
self.checkBox_continuous.setChecked(False)
else:
print('read failed')
def update_timer(self):
global isMeasuring
while isMeasuring:
pass
isMeasuring = True
self.continuous_timer.stop()
def add_spec(self):
now_str = datetime.now().strftime("%H:%M:%S")
mosi = np.nan if self.lineEdit_mosi.text() is "" else float(self.lineEdit_mosi.text())
don = np.nan if self.lineEdit_don.text() is "" else float(self.lineEdit_don.text())
row_list = [QStandardItem(now_str), QStandardItem(
str(mosi)), QStandardItem(str(don))]
self.model_data.appendRow(row_list)
database.add(spec=spec_value, meas_time=now_str, mosi=mosi, don=don)
def fresh_plot(self):
global wave_len, spec_value
idx = self.tableView_data.currentIndex().row()
temp = database.get_row(idx)
spec_value = temp["spec"]
self.lineEdit_don.setText(str(temp["don"]))
self.lineEdit_mosi.setText(str(temp['mosi']))
self.matplotlibWidget_spec.mpl.draw_spec(wave_len=wave_len, spec_val=spec_value)
self.matplotlibWidget_spec.setVisible(True)
if self.checkBox_pred.isChecked():
model = {"线性回归": self.model_LR, "支持向量回归": self.model_SVR}[self.comboBox_model_selection.currentText()]
model.predict(spec_value.reshape(1, -1))
class MeasureThread(QThread):
trigger = pyqtSignal()
def __int__(self):
super(MeasureThread, self).__init__()
def run(self):
while True:
global isMeasuring
if isMeasuring:
global measure_mode, int_time, avg_time, wave_len, spec_value
try:
print("spectrometer status : {}".format(spectrometer.status))
wave_len, spec_value = spectrometer.measure(mode=measure_mode, inter_time=int_time,
avg_scan=avg_time,
transmission_wait=0.001)
# self.checkBox_pred.setEnabled(True)
global reading_status
reading_status = True
except:
reading_status = False
print("Get problem when reading the spectrometer")
spectrometer.disconnect()
isMeasuring = False
# 循环完毕后发出信号
self.trigger.emit()
time.sleep(0.05)
class ModelThread(QThread):
trigger = pyqtSignal()
def __init__(self):
super(ModelThread, self).__init__()
self.model_SVR = SpecSVRModel()
self.model_LR = SpecLRModel()
def run(self):
while True:
global isModeling
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
ui = MainWindow()
ui.show()
sys.exit(app.exec_())