-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmmc.py
More file actions
4303 lines (3617 loc) · 186 KB
/
mmc.py
File metadata and controls
4303 lines (3617 loc) · 186 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
#
# @file mmc.py
# @author Mit Bailey (mitbailey@outlook.com)
# @brief The MMC GUI and program.
# @version See Git tags for version information.
# @date 2022.08.03
#
# @copyright Copyright (c) 2022
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
#
""" TODO
- Verify that running n scans, deleting <n-1 but >1 scans, where none of the scans are scan 0 or scan n, then saving all scans works without issue on the RESULTS tab.
- 'Unsafe' mode with memory - remembers the position we were last at and loads in from there.
- Likely, we should just always do this.
- We should also have a "you must home this axis" prior to use warning / requirement.
- The 'unsafe' mode will simply disable this requirement.
- Maybe a "Has been homed at least once this session" flag on every axis
- If the flag is "false", then a popup message appears
- User can ignore warning and run once, ignore this and all home warnings, cancel action.
- If the setup is different it will nuke the saved positions.
"""
"""
UI Element Naming Scheme
------------------------
All UI elements should be named in the following format:
UIE_[window code]_[subsection code]_[Chosen Name]_[Q-type]
Device Manager Window dmw_
Main GUI Window mgw_
Machine Config. Window mcw_
Main Drive md_
Filter Wheel fw_
Sample Movement sm_
Detector Rotation dr_
Data Table dt_
Q-Types: Capital letters of the type;
ex:
QMainWindow _qmw
QPushButton _qpb
EXCEPTIONS:
QCheckBox = qckbx
QProgressBar = qpbar
"""
from middleware import MotionController # , list_all_devices
from PyQt5 import QtCore
import signal
from utilities import version
from middleware import Detector
from utilities import log
from utilities import motion_controller_list as mcl
from instruments.mcpherson import McPherson
from utilities_qt import connect_devices
from utilities_qt import update_position_displays
from utilities_qt import scan
from utilities_qt.datatable import DataTableWidget
from PyQt5.QtWidgets import QGraphicsView
import webbrowser
from utilities.config import load_config_devman, save_config_devman, load_config, save_config, reset_config
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT
import matplotlib
import copy
from functools import partial
import datetime as dt
import numpy as np
import weakref
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import (QMainWindow, QDoubleSpinBox, QApplication, QComboBox, QDialog, QFileDialog, QHBoxLayout, QLabel, QMessageBox, QPushButton, QRadioButton, QSizePolicy,
QStyle, QVBoxLayout, QHBoxLayout, QWidget, QLineEdit, QTabWidget, QTableWidgetItem, QFrame, QProgressBar, QCheckBox, QSpinBox, QStatusBar, QAction, QSpacerItem, QGroupBox)
from PyQt5.QtGui import QColor, QFontDatabase, QFont
from PyQt5.QtCore import (pyqtSignal, QFileInfo, QEvent,
QFile, QIODevice, QTimer, QPropertyAnimation, QEasingCurve)
from PyQt5 import uic
import sys
import traceback as tb
import os
import hashlib
import faulthandler
import math
import typing
import subprocess
from typing import Callable
from typing_extensions import Self
faulthandler.enable()
# Obtains the executable directory (as exeDir) and the application directory (as appDir) for future use.
try:
exeDir = sys._MEIPASS
except Exception:
exeDir = os.getcwd()
if getattr(sys, 'frozen', False):
appDir = os.path.dirname(sys.executable)
elif __file__:
appDir = os.path.dirname(__file__)
matplotlib.use('Qt5Agg')
try:
import middleware as mw
except Exception as e:
log.error(str(e))
raise e
QtWidgets.QApplication.setAttribute(
QtCore.Qt.AA_EnableHighDpiScaling, True) # enable highdpi scaling
QtWidgets.QApplication.setAttribute(
QtCore.Qt.AA_UseHighDpiPixmaps, True) # use highdpi icons
# Setup signal.
signal.signal(signal.SIGINT, signal.SIG_DFL)
# Setup fonts variables.
digital_7_italic_22 = None
digital_7_16 = None
# Determines which enabler files exist - these will enable certain experimental or advanced sections of the program.
SHOW_FILTER_WHEEL = os.path.isfile('enable.exp')
# SHOW_SAMPLE_MOVEMENT = os.path.isfile('enable.adv')
SHOW_SAMPLE_MOVEMENT = True
# SHOW_DETECTOR_ROTATION = os.path.isfile('enable.adv')
SHOW_DETECTOR_ROTATION = True
ALLOW_DUMMY_MODE = os.path.isfile('enable.dev')
# Classes.
# Sets up the navigation toolbar for the graph.
class NavigationToolbar(NavigationToolbar2QT):
def edit_parameters(self):
super(NavigationToolbar, self).edit_parameters()
# Sets up the canvas for the graph.
class MplCanvas(FigureCanvasQTAgg):
def __init__(self:Self, parent=None, width:float=5, height:float=4, dpi:int=100, xlabel:str='Position (nm or deg)', ylabel:str='Magnitude (pA or V)'):
fig = Figure(figsize=(width, height), dpi=dpi, tight_layout=True)
self._parent = parent
self.axes = fig.add_subplot(111)
self.xlabel = xlabel
self.ylabel = ylabel
self.axes.set_xlabel(self.xlabel)
self.axes.set_ylabel(self.ylabel)
self.axes.grid()
self.lines = dict()
self.colors = ['b', 'r', 'k', 'c', 'g', 'm', 'tab:orange']
self._tableClearCb = None
super(MplCanvas, self).__init__(fig)
def get_toolbar(self:Self) -> NavigationToolbar:
self.toolbar = NavigationToolbar(self, self._parent)
return self.toolbar
def set_table_clear_cb(self:Self, fcn:Callable[[object], None]) -> None:
self._tableClearCb = fcn
def clear_plot_fcn(self:Self, det_idx:int):
if not self._parent.scanRunning:
self.axes.cla()
self.axes.set_xlabel(self.xlabel)
self.axes.set_ylabel(self.ylabel)
self.axes.grid()
self.draw()
if self._tableClearCb is not None:
self._tableClearCb()
return
def update_plots(self:Self, data: list):
self.axes.cla()
self.axes.set_xlabel(self.xlabel)
self.axes.set_ylabel(self.ylabel)
for row in data:
c = self.colors[row[-1] % len(self.colors)]
log.debug(f"Plotting: {row[0]} ; {row[1]}")
if len(row[0]) != len(row[1]):
log.error('X and Y data lengths do not match!')
continue
self.lines[row[-1]
], = self.axes.plot(row[0], row[1], label=row[2], color=c)
self.axes.legend()
self.axes.grid()
self.draw()
return
def append_plot(self, idx, xdata, ydata):
if idx not in self.lines.keys():
c = self.colors[idx % len(self.colors)]
self.lines[idx], = self.axes.plot(
xdata, ydata, label='Scan #%d' % (idx), color=c)
else:
self.lines[idx].set_data(xdata, ydata)
self.draw()
# The main MMC program and GUI class.
class MMC_Main(QMainWindow):
# STARTUP PROCEDURE
# Begins by starting the Device Manager window.
# Once devices are selected and connected, the Main GUI window is launched.
# MMC_Main.__init__() --> show_window_device_manager() >>> emits device_manager_ready_signal
# --> autoconnect_devices() >>> emits devices_auto_connected_signal
# --> devices_auto_connected()
# IF devices connected --> _show_main_gui()
# ELSE allow user to interact w/ device manager
SIGNAL_device_manager_ready = pyqtSignal()
SIGNAL_devices_connection_check = pyqtSignal(bool, list, list)
EXIT_CODE_FINISHED = 0
EXIT_CODE_REBOOT = 1
# Destructor
def __del__(self):
if self.motion_controllers is not None:
del self.motion_controllers
if self.mtn_ctrls is not None:
del self.mtn_ctrls
if self.detectors is not None:
del self.detectors
if self.dev_finder is not None:
self.dev_finder.done = True
del self.dev_finder
# Constructor
def __init__(self, application, uiresource=None):
self.global_scan_id = 0
self.scan_start_delay = 0.0
self.detection_delay = 0.0
self.per_detection_averages = 1
try:
self.git_hash = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('ascii').strip()
except Exception as e:
log.error('Not a Git repo: Unable to get git hash: %s' % (str(e)))
log.warn('Not a Git repo: Did you download the source code from GitHub as a zip file?')
log.warn('Not a Git repo: To maintain the proper version hash, please use `git clone [URL]` instead.')
self.git_hash = 'R'
self.selected_config_save_path = os.path.expanduser(
'~/Documents') + '/mcpherson_mmc/s_d.csv'
# Handles the initial showing of the UI.
self.mtn_ctrls = []
self.detectors = []
self.connect_devices_thread = connect_devices.ConnectDevices(
weakref.proxy(self))
self.connecting_devices = False
self.update_position_displays_thread = update_position_displays.UpdatePositionDisplays(
weakref.proxy(self))
self.queue_executor_thread = scan.QueueExecutor(weakref.proxy(self))
self.autosave_next_scan = False
self.application: QApplication = application
self._startup_args = self.application.arguments()
super(MMC_Main, self).__init__()
uic.loadUi(uiresource, self)
self.setWindowIcon(QtGui.QIcon(exeDir + '/res/faviconV2.png'))
self.SIGNAL_device_manager_ready.connect(self.connect_devices)
self.SIGNAL_devices_connection_check.connect(
self.devices_connection_check)
self.dev_man_win_enabled = False
self.main_gui_booted = False
self.dmw = None
self.show_window_device_manager()
self.dev_finder = None
self.scan_queue = None
self.autosave_next_dir = None
self.motion_controllers = mcl.MotionControllerList()
# Load Configuration File
self.moving = False
self.movement_sensitive_buttons_disabled = False
# Default measurement sign.
self.mes_sign = 1
# Default grating equation values.
self.max_pos = 600.0
self.min_pos = -40.0
self.model_index = 0
self.grating_density = 1200.0 # grooves/mm
self.zero_ofst = 37.8461 # nm
self.fw_offset = 0.0
self.st_offset = 0.0
self.sr_offset = 0.0
self.sa_offset = 0.0
self.dr_offset = 0.0
# Other settings' default values.
self.main_axis_index = 0
self.filter_axis_index = 0
self.rsamp_axis_index = 0
self.asamp_axis_index = 0
self.tsamp_axis_index = 0
self.detector_axis_index = 0
self.main_axis_dev_name = 'none'
self.filter_axis_dev_name = 'none'
self.rsamp_axis_dev_name = 'none'
self.asamp_axis_dev_name = 'none'
self.tsamp_axis_dev_name = 'none'
self.detector_axis_dev_name = 'none'
self.num_axes_at_time_of_save = 0
self.fw_max_pos = 9999
self.fw_min_pos = -9999
self.smr_max_pos = 9999
self.smr_min_pos = -9999
self.sma_max_pos = 9999
self.sma_min_pos = -9999
self.smt_max_pos = 9999
self.smt_min_pos = -9999
self.dr_max_pos = 9999
self.dr_min_pos = -9999
self.md_sp = 0.0
self.fw_sp = 0.0
self.sr_sp = 0.0
self.sa_sp = 0.0
self.st_sp = 0.0
self.dr_sp = 0.0
self.movement_mults_load_success = False
self.home_mults = []
self.move_mults = []
self.load_config(appDir, False)
self.manual_position = 0 # 0 nm
self.startpos = 0
self.stoppos = 0
self.steppos = 0.1
self.reference_operation = 0
self.reference_order_meas_ref = True
def eventFilter(self, source, event):
if event.type() == QEvent.Wheel:
return True
return super().eventFilter(source, event)
# Screen shown during startup to disable premature user interaction as well as handle device-not-found issues.
def show_window_device_manager(self):
self.device_timer = None
if self.dmw is None:
ui_file_name = exeDir + '/ui/device_manager.ui'
ui_file = QFile(ui_file_name)
if not ui_file.open(QIODevice.ReadOnly):
log.fatal(
f"Cannot open {ui_file_name}: {ui_file.errorString()}")
raise RuntimeError('Could not load grating input UI file')
self.dmw = QDialog(self) # pass parent window
uic.loadUi(ui_file, self.dmw)
self.dmw.setWindowTitle('%s (%s-%s)'%(version.__long_name__, version.__version__, self.git_hash))
self.dmw_list = ''
self.UIEL_dmw_detector_qhbl = []
self.UIEL_dmw_detector_qhbl.append(
self.dmw.findChild(QHBoxLayout, "detector_combo_sublayout"))
self.UIEL_dmw_mtn_ctrl_qhbl = []
self.UIEL_dmw_mtn_ctrl_qhbl.append(
self.dmw.findChild(QHBoxLayout, "mtn_ctrl_combo_sublayout"))
self.UIEL_dmw_detector_qcb = []
self.UIEL_dmw_detector_qcb.append(
self.dmw.findChild(QComboBox, "samp_combo"))
self.UIEL_dmw_detector_qcb[0].addItem("NO DEVICE SELECTED")
self.UIEL_dmw_detector_model_qcb = []
self.UIEL_dmw_detector_model_qcb.append(
self.dmw.findChild(QComboBox, "samp_model_combo"))
for device in Detector.SupportedDevices:
self.UIEL_dmw_detector_model_qcb[0].addItem(device)
self.UIEL_dmw_mtn_ctrl_qcb = []
self.UIEL_dmw_mtn_ctrl_qcb.append(
self.dmw.findChild(QComboBox, "mtn_combo"))
self.UIEL_dmw_mtn_ctrl_qcb[0].addItem("NO DEVICE SELECTED")
self.UIEL_dmw_mtn_ctrl_model_qcb = []
self.UIEL_dmw_mtn_ctrl_model_qcb.append(
self.dmw.findChild(QComboBox, "mtn_model_combo"))
for device in MotionController.SupportedDevices:
self.UIEL_dmw_mtn_ctrl_model_qcb[0].addItem(device)
self.UIE_dmw_accept_qpb: QPushButton = self.dmw.findChild(
QPushButton, "acc_button")
self.UIE_dmw_accept_qpb.clicked.connect(self.connect_devices)
self.UIE_dmw_cancel_qpb: QPushButton = self.dmw.findChild(
QPushButton, "cancel_button")
self.UIE_dmw_cancel_qpb.clicked.connect(
self.cancel_connect_devices)
self.UIE_dmw_cancel_qpb.setEnabled(False)
self.UIE_dmw_dummy_qckbx: QCheckBox = self.dmw.findChild(
QCheckBox, "dum_checkbox")
self.UIE_dmw_dummy_qckbx.setChecked(len(self._startup_args) == 2)
if not ALLOW_DUMMY_MODE:
self.UIE_dmw_dummy_qckbx.hide()
self.UIE_dmw_loading_status_ql: QLabel = self.dmw.findChild(
QLabel, 'current_loading_status')
self.UIE_dmw_num_detectors_qsb: QSpinBox = self.dmw.findChild(
QSpinBox, "num_detectors")
self.UIE_dmw_num_detectors_qsb.valueChanged.connect(
self.update_num_detectors_ui)
self.num_detectors = 1
self.UIE_dmw_mc_add_qpb: QPushButton = self.dmw.findChild(
QPushButton, "mc_add")
self.UIE_dmw_mc_add_qpb.clicked.connect(self.mc_add_fn)
self.UIE_dmw_mc_sub_qpb: QPushButton = self.dmw.findChild(
QPushButton, "mc_sub")
self.UIE_dmw_mc_sub_qpb.clicked.connect(self.mc_sub_fn)
self.UIE_dmw_d_add_qpb: QPushButton = self.dmw.findChild(
QPushButton, "d_add")
self.UIE_dmw_d_add_qpb.clicked.connect(self.d_add_fn)
self.UIE_dmw_d_sub_qpb: QPushButton = self.dmw.findChild(
QPushButton, "d_sub")
self.UIE_dmw_d_sub_qpb.clicked.connect(self.d_sub_fn)
self.UIE_dmw_num_motion_controllers_qsb: QSpinBox = self.dmw.findChild(
QSpinBox, "num_motion_controllers")
self.UIE_dmw_num_motion_controllers_qsb.valueChanged.connect(
self.update_num_motion_controllers_ui)
self.num_motion_controllers = 1
self.UIE_dmw_detector_combo_qvbl: QVBoxLayout = self.dmw.findChild(
QVBoxLayout, "detector_combo_layout")
self.UIE_dmw_mtn_ctrl_combo_qvbl: QVBoxLayout = self.dmw.findChild(
QVBoxLayout, "mtn_ctrl_combo_layout")
self.UIE_dmw_load_bar_qpb: QProgressBar = self.dmw.findChild(
QProgressBar, "loading_bar")
self.UIE_dmw_load_spinner_ql: QLabel = self.dmw.findChild(
QLabel, "load_spinner")
self.devman_list_devices(True)
self.dmw.show()
self.anim_dmw_load_spinner = QtGui.QMovie(exeDir + '/res/131.gif')
self.UIE_dmw_load_spinner_ql.setMovie(self.anim_dmw_load_spinner)
self.application.processEvents()
if not self.dev_man_win_enabled:
self.dev_man_win_enabled = True
self.device_timer = QTimer()
self.device_timer.timeout.connect(self.devman_list_devices)
# Devices are checked for every this many milliseconds.
# This does not seem to be the source of the lag when connecting a KST201. Unknown why that occurs. Likely best to avoid that device.
self.device_timer.start(10000)
if log.logging_to_file():
log.info('Log file is active.')
else:
log.warn('Log file is not active.')
self.QMessageBoxCritical(
'Log File Error', 'The software was unable to create the log file. This is likely due to a lack of permissions. Try running the program as an Administrator or no error logs will be produced.')
# Called when the main GUI window is closed.
def closeEvent(self, event):
answer = self.QMessageBoxYNC(
'Exit Confirmation', "Do you want to save all current settings and values?")
event.ignore()
if answer == 0:
log.info('Exiting program and saving current configuration.')
self.save_config(appDir + '/config.ini')
event.accept()
elif answer == 1:
log.info('Exiting program without saving current configuration.')
event.accept()
else:
log.info('Canceling program exit.')
def d_add_fn(self):
self.UIE_dmw_num_detectors_qsb.setValue(
self.UIE_dmw_num_detectors_qsb.value() + 1)
pass
def d_sub_fn(self):
self.UIE_dmw_num_detectors_qsb.setValue(
self.UIE_dmw_num_detectors_qsb.value() - 1)
pass
def mc_add_fn(self):
self.UIE_dmw_num_motion_controllers_qsb.setValue(
self.UIE_dmw_num_motion_controllers_qsb.value() + 1)
pass
def mc_sub_fn(self):
self.UIE_dmw_num_motion_controllers_qsb.setValue(
self.UIE_dmw_num_motion_controllers_qsb.value() - 1)
pass
def update_num_detectors_ui(self, force: bool = False):
if (self.num_detectors != self.UIE_dmw_num_detectors_qsb.value()) or (force):
self.num_detectors = self.UIE_dmw_num_detectors_qsb.value()
for widget in self.UIEL_dmw_detector_qcb:
widget.setParent(None)
for widget in self.UIEL_dmw_detector_model_qcb:
widget.setParent(None)
for layout in self.UIEL_dmw_detector_qhbl:
self.UIE_dmw_detector_combo_qvbl.removeItem(layout)
self.UIEL_dmw_detector_qcb = []
self.UIEL_dmw_detector_model_qcb = []
self.UIEL_dmw_detector_qhbl = []
for i in range(self.num_detectors):
s_combo = QComboBox()
s_combo.addItem("NO DEVICE SELECTED")
for dev in self.dev_list:
s_combo.addItem('%s' % (dev))
m_combo = QComboBox()
for device in Detector.SupportedDevices:
m_combo.addItem(device)
layout = QHBoxLayout()
layout.addWidget(s_combo)
layout.addWidget(m_combo)
layout.setStretch(0, 4)
layout.setStretch(1, 1)
self.UIE_dmw_detector_combo_qvbl.addLayout(layout)
self.UIEL_dmw_detector_qcb.append(s_combo)
self.UIEL_dmw_detector_model_qcb.append(m_combo)
self.UIEL_dmw_detector_qhbl.append(layout)
log.debug('new detectors combo list len: %d' %
(len(self.UIEL_dmw_detector_qcb)))
def update_num_motion_controllers_ui(self, force: bool = True):
if (self.num_motion_controllers != self.UIE_dmw_num_motion_controllers_qsb.value()) or (force):
self.num_motion_controllers = self.UIE_dmw_num_motion_controllers_qsb.value()
for widget in self.UIEL_dmw_mtn_ctrl_qcb:
widget.setParent(None)
for widget in self.UIEL_dmw_mtn_ctrl_model_qcb:
widget.setParent(None)
for layout in self.UIEL_dmw_mtn_ctrl_qhbl:
self.UIE_dmw_mtn_ctrl_combo_qvbl.removeItem(layout)
# Very important - must reset the combos list.
self.UIEL_dmw_mtn_ctrl_qcb = []
self.UIEL_dmw_mtn_ctrl_model_qcb = []
self.UIEL_dmw_mtn_ctrl_qhbl = []
for i in range(self.num_motion_controllers):
s_combo = QComboBox()
s_combo.addItem("NO DEVICE SELECTED")
for dev in self.dev_list:
s_combo.addItem('%s' % (dev))
m_combo = QComboBox()
for device in MotionController.SupportedDevices:
m_combo.addItem(device)
layout = QHBoxLayout()
layout.addWidget(s_combo)
layout.addWidget(m_combo)
layout.setStretch(0, 4)
layout.setStretch(1, 1)
self.UIE_dmw_mtn_ctrl_combo_qvbl.addLayout(layout)
self.UIEL_dmw_mtn_ctrl_qcb.append(s_combo)
self.UIEL_dmw_mtn_ctrl_model_qcb.append(m_combo)
self.UIEL_dmw_mtn_ctrl_qhbl.append(layout)
log.debug('new mtn ctrls combo list len: %d' %
(len(self.UIEL_dmw_mtn_ctrl_qcb)))
def connect_devices(self):
# Save the current states of the devman immediately when Accept is pressed.
""" Parameters we want to save.
- Number of detectors.
- Spinbox index
"""
self.UIE_dmw_load_spinner_ql.show()
self.anim_dmw_load_spinner.start()
if self.num_detectors == 1 and self.UIEL_dmw_detector_qcb[0].currentIndex() == 0:
self.QMessageBoxInformation(
'No Detectors Selected', 'No detectors selected: will run without a detector.')
self.detectors = [] # This should allow for loops to auto-skip.
self.num_detectors = 0
else:
try:
for i in range(self.num_detectors):
if self.UIEL_dmw_detector_qcb[i].currentIndex() == 0:
self.QMessageBoxInformation(
'Connection Failure', 'No detector was selected for entry #%d.' % (i))
self.anim_dmw_load_spinner.stop()
self.UIE_dmw_load_spinner_ql.hide()
return
except Exception as e:
log.error(str(e))
self.QMessageBoxCritical(
'Connection Failure', 'An error occurred while attempting to connect to the detector.\n%s' % (str(e)))
self.anim_dmw_load_spinner.stop()
self.UIE_dmw_load_spinner_ql.hide()
return
for i in range(self.num_motion_controllers):
try:
if self.UIEL_dmw_mtn_ctrl_qcb[i].currentIndex() == 0:
self.QMessageBoxInformation(
'Connection Failure', 'No motion controller was selected for entry #%d.' % (i))
self.anim_dmw_load_spinner.stop()
self.UIE_dmw_load_spinner_ql.hide()
return
except Exception as e:
log.error(str(e))
self.QMessageBoxCritical(
'Connection Failure', 'An error occurred while attempting to connect to the motion controller.\n%s' % (str(e)))
self.anim_dmw_load_spinner.stop()
self.UIE_dmw_load_spinner_ql.hide()
return
# Save config here.
self.save_config_devman(appDir + '/devman.ini')
if not self.connecting_devices:
self.connect_devices = True
self.UIE_dmw_cancel_qpb.setEnabled(True)
self.UIE_dmw_accept_qpb.setEnabled(False)
self.application.processEvents()
self.dummy = self.UIE_dmw_dummy_qckbx.isChecked()
self.connect_devices_thread.start()
def cancel_connect_devices(self):
# TODO: Implement device connection cancelation.
log.warn('Cancelling device connections is not yet implemented.')
def _connect_devices(self, detectors_connected, mtn_ctrls_connected):
self.connecting_devices = False
self.UIE_dmw_cancel_qpb.setEnabled(False)
self.UIE_dmw_accept_qpb.setEnabled(True)
self.SIGNAL_devices_connection_check.emit(
self.dummy, detectors_connected, mtn_ctrls_connected)
def _connect_devices_failure_cleanup(self):
self._connect_devices_progress_anim(0)
self.connecting_devices = False
self.UIE_dmw_cancel_qpb.setEnabled(False)
self.UIE_dmw_accept_qpb.setEnabled(True)
self.anim_dmw_load_spinner.stop()
self.UIE_dmw_load_spinner_ql.hide()
def _connect_devices_status(self, message):
self.UIE_dmw_loading_status_ql.setText(message)
def _connect_devices_progress_anim(self, value):
self.anim = QPropertyAnimation(
targetObject=self.UIE_dmw_load_bar_qpb, propertyName=b"value")
self.anim.setEasingCurve(QEasingCurve.Type.OutCubic)
self.anim.setStartValue(self.UIE_dmw_load_bar_qpb.value())
self.anim.setEndValue(value)
self.anim.setDuration(5000)
self.anim.start()
# If things are connected, boot main GUI.
# If somethings wrong, enable advanced dev man functions.
def devices_connection_check(self, dummy: bool, detectors: list, mtn_ctrls: list):
connected = True
for status in detectors:
if not status:
connected = False
break
if connected:
for status in mtn_ctrls:
if not status:
connected = False
break
if connected:
if self.device_timer is not None:
log.warn('STOPPING DEVICE TIMER!')
self.device_timer.stop()
self._show_main_gui(dummy)
return
# If we are here, then we have not automatically connected to all required devices. We must now enable the device manager.
self.QMessageBoxWarning(
'Connection Failure', 'Connection attempt has failed!\n%s' % (mtn_ctrls))
def _show_main_gui(self, dummy: bool):
# Set this via the QMenu QAction Edit->Change Auto-log Directory
self.data_save_directory = os.path.expanduser('~/Documents')
self.data_save_directory += '/mcpherson_mmc/%s/' % (
dt.datetime.now().strftime('%Y%m%d'))
if not os.path.exists(self.data_save_directory):
os.makedirs(self.data_save_directory)
self.num_scans = 0
self.previous_position = -9999
self.immobile_count = 0
# The data we are using as a reference post-operation (if applicable).
# e.g., the result of sample_scan/ref_scan
self.operated_ref_data = None
self.reference_active = False
self.is_advanced_ref = False
self.autosave_data_bool = False
self.pop_out_table = False
self.pop_out_plot = False
self.mda_moving = False
self.fwa_moving = False
self.sra_moving = False
self.saa_moving = False
self.sta_moving = False
self.dra_moving = False
self.scanRunning = False
self.machine_conf_win: QDialog = None
self.grating_conf_win: QDialog = None
self.spectral_ops_win: QDialog = None
self.grating_density_in: QDoubleSpinBox = None
self.UIE_mcw_max_pos_in_qdsb: QDoubleSpinBox = None
self.UIE_mcw_min_pos_in_qdsb: QDoubleSpinBox = None
self.UIE_mcw_zero_ofst_in_qdsb: QDoubleSpinBox = None
self.UIE_mcw_machine_conf_qpb: QPushButton = None
self.UIE_mcw_steps_per_nm_qdsb: QDoubleSpinBox = None
if ALLOW_DUMMY_MODE:
if dummy:
self.setWindowTitle('%s (%s-%s-DB)'%(version.__long_name__, version.__version__, self.git_hash))
else:
self.setWindowTitle('%s (%s-%s-HW)'%(version.__long_name__, version.__version__, self.git_hash))
else:
self.setWindowTitle('%s (%s-%s)'%(version.__long_name__, version.__version__, self.git_hash))
self.is_conv_set = False # Use this flag to set conversion
# GUI initialization, gets the UI elements from the .ui file.
self.UIE_mgw_scan_qpb: QPushButton = self.findChild(QPushButton, "begin_scan_button") # Scanning Control 'Begin Scan' Button
self.UIE_mgw_scan_top_qpb: QPushButton = self.findChild(QPushButton, "begin_scan_top")
self.UIE_mgw_stop_scan_qpb: QPushButton = self.findChild(QPushButton, "stop_scan_button")
self.UIE_mgw_stop_scan_qpb.setEnabled(False)
self.UIE_mgw_save_data_qckbx: QCheckBox = self.findChild(
QCheckBox, "save_data_checkbox") # Scanning Control 'Save Data' Checkbox
self.UIE_mgw_dir_box_qle = self.findChild(
QLineEdit, "save_dir_lineedit")
self.UIE_mgw_start_qdsb = self.findChild(
QDoubleSpinBox, "start_set_spinbox")
self.UIE_mgw_stop_qdsb = self.findChild(
QDoubleSpinBox, "end_set_spinbox")
if dummy:
self.UIE_mgw_stop_qdsb.setValue(10.0)
# self.UIE_mgw_mca_pos_ql = self.findChild(QLabel, "mca_pos")
self.UIE_mgw_fwa_pos_ql = self.findChild(QLabel, "fwa_pos")
self.UIE_mgw_sra_pos_ql = self.findChild(QLabel, "sra_pos")
self.UIE_mgw_saa_pos_ql = self.findChild(QLabel, "saa_pos")
self.UIE_mgw_sta_pos_ql = self.findChild(QLabel, "sta_pos")
self.UIE_mgw_dra_pos_ql = self.findChild(QLabel, "dra_pos")
self.UIE_mgw_step_qdsb = self.findChild(
QDoubleSpinBox, "step_set_spinbox")
self.UIE_mgw_currpos_nm_disp_ql = self.findChild(QLabel, "currpos_nm")
self.UIE_mgw_scan_status_ql = self.findChild(QLabel, "status_label")
self.UIE_mgw_scan_qpbar = self.findChild(QProgressBar, "progressbar")
self.UIE_mgw_scan_time_ql = self.findChild(QLabel, "scan_time")
self.scan_remaining_timer = QtCore.QTimer(self)
self.scan_time_left = 0.0
self.UIE_mgw_save_config_qpb: QPushButton = self.findChild(
QPushButton, 'save_config_button')
self.UIE_mgw_spectral_ops_qpb: QPushButton = self.findChild(
QPushButton, 'spectral_math')
self.UIE_mgw_spectral_ops_qpb.clicked.connect(
self.show_window_spectral_ops)
self.UIE_mgw_spectral_ops_qpb.hide()
self.UIE_mgw_pos_qdsb: QDoubleSpinBox = self.findChild(
QDoubleSpinBox, "pos_set_spinbox") # Manual Control 'Position:' Spin Box
self.UIE_mgw_move_to_position_qpb: QPushButton = self.findChild(
QPushButton, "move_pos_button")
self.UIE_mgw_xmin_in_qle: QLineEdit = self.findChild(
QLineEdit, "xmin_in")
self.UIE_mgw_ymin_in_qle: QLineEdit = self.findChild(
QLineEdit, "ymin_in")
self.UIE_mgw_xmax_in_qle: QLineEdit = self.findChild(
QLineEdit, "xmax_in")
self.UIE_mgw_ymax_in_qle: QLineEdit = self.findChild(
QLineEdit, "ymax_in")
self.UIE_mgw_plot_clear_plots_qpb: QPushButton = self.findChild(
QPushButton, "clear_plots_button")
self.UIE_mgw_machine_conf_qa: QAction = self.findChild(
QAction, "machine_configuration")
self.UIE_mgw_invert_mes_qa: QAction = self.findChild(
QAction, "invert_mes")
self.UIE_mgw_autosave_data_qa: QAction = self.findChild(
QAction, "autosave_data")
self.UIE_mgw_autosave_dir_qa: QAction = self.findChild(
QAction, "autosave_dir_prompt")
self.UIE_mgw_preferences_qa: QAction = self.findChild(
QAction, "preferences")
self.UIE_mgw_pop_out_table_qa: QAction = self.findChild(
QAction, "pop_out_table")
self.UIE_mgw_pop_out_plot_qa: QAction = self.findChild(
QAction, "pop_out_plot")
self.UIE_mgw_about_source_qa: QAction = self.findChild(
QAction, "actionSource_Code")
self.UIE_mgw_about_licensing_qa: QAction = self.findChild(
QAction, "actionLicensing")
self.UIE_mgw_about_manual_qa: QAction = self.findChild(
QAction, "actionManual_2")
self.UIE_mgw_import_qa: QAction = self.findChild(
QAction, "actionImport_Config")
self.UIE_mgw_export_qa: QAction = self.findChild(
QAction, "actionExport_Config")
self.UIE_mgw_save_current_config_qa: QAction = self.findChild(
QAction, "actionSave_Current_Config")
self.UIE_mgw_import_qa.triggered.connect(self.config_import)
self.UIE_mgw_export_qa.triggered.connect(self.config_export)
self.UIE_mgw_save_current_config_qa.triggered.connect(self.config_save)
self.UIE_mgw_save_data_qpb: QPushButton = self.findChild(
QPushButton, 'save_data_button')
self.UIE_mgw_save_data_qpb.clicked.connect(self.save_data_cb)
self.UIE_mgw_delete_data_qpb: QPushButton = self.findChild(
QPushButton, 'delete_data_button')
self.UIE_mgw_delete_data_qpb.clicked.connect(self.delete_data_cb)
self.UIE_mgw_ref_det_qcb: QComboBox = self.findChild(
QComboBox, 'ref_det')
self.UIE_mgw_sample_det_qcb: QComboBox = self.findChild(
QComboBox, 'sample_det')
for i in range(self.num_detectors):
self.UIE_mgw_ref_det_qcb.addItem('Det %d' % (i+1))
for i in range(self.num_detectors):
self.UIE_mgw_sample_det_qcb.addItem('Det %d' % (i+1))
self.UIE_mgw_setref_qpb: QPushButton = self.findChild(
QPushButton, 'fir_order_ref_set')
self.UIE_mgw_setop_qcb: QComboBox = self.findChild(
QComboBox, 'fir_order_ref_op')
self.UIE_mgw_setr1_qpb: QPushButton = self.findChild(
QPushButton, 'sec_order_ref_setr1')
# self.UIE_mgw_setop1_qcb: QComboBox = self.findChild(QComboBox, 'sec_order_ref_op1')
self.UIE_mgw_setr2_qpb: QPushButton = self.findChild(
QPushButton, 'sec_order_ref_setr2')
# self.UIE_mgw_setop2_qcb: QComboBox = self.findChild(QComboBox, 'sec_order_ref_op2')
self.UIE_mgw_ref_collap_qpb: QPushButton = self.findChild(
QPushButton, 'ref_collap')
self.ref_collapsed = False
self.UIE_mgw_ref_area_qw: QWidget = self.findChild(QWidget, 'ref_area')
self.UIE_mgw_ref_reset_qpb: QPushButton = self.findChild(
QPushButton, 'ref_reset')
self.UIE_mgw_ref_enact_qpb: QPushButton = self.findChild(
QPushButton, 'ref_enact')
self.UIE_mgw_ref_simple_qrb: QRadioButton = self.findChild(
QRadioButton, 'ref_simple')
self.UIE_mgw_ref_advanced_qrb: QRadioButton = self.findChild(
QRadioButton, 'ref_advanced')
self.UIE_mgw_simple_opbox_qgb: QGroupBox = self.findChild(
QGroupBox, 'simple_opbox')
self.UIE_mgw_advanced_opbox_qgb: QGroupBox = self.findChild(
QGroupBox, 'advanced_opbox')
self.UIE_mgw_advanced_opbox_qgb.hide()
self.ref_collapsed = True
self.UIE_mgw_ref_area_qw.setVisible(False)
self.UIE_mgw_ref_collap_qpb.setText('∑ ⮜')
self.ref0_data = None
self.ref1_data = None
self.ref2_data = None
self.ref_det_idx = 0
self.sample_det_idx = 0
self.UIE_mgw_setref_qpb.clicked.connect(self.set_ref)
self.UIE_mgw_setr1_qpb.clicked.connect(self.set_ref1)
self.UIE_mgw_setr2_qpb.clicked.connect(self.set_ref2)
self.UIE_mgw_ref_collap_qpb.clicked.connect(self.collapse_ref)
self.UIE_mgw_ref_reset_qpb.clicked.connect(self.reset_ref)
self.UIE_mgw_ref_enact_qpb.clicked.connect(self.enact_ref)
self.UIE_mgw_ref_reset_qpb.setDisabled(True)
self.UIE_mgw_ref_advanced_qrb.toggled.connect(self.toggle_ref)
self.UIE_mgw_open_queue_file_qpb: QPushButton = self.findChild(
QPushButton, 'open_queue_file_button')
self.UIE_mgw_open_queue_file_qpb.clicked.connect(self.load_queue_file)
self.UIE_mgw_begin_queue_qpb: QPushButton = self.findChild(
QPushButton, 'begin_queue_button')
self.UIE_mgw_begin_queue_qpb.clicked.connect(self.begin_queue)
self.UIE_mgw_table_qtw: QTabWidget = self.findChild(
QTabWidget, "table_tabs")
self.UIE_mgw_mda_load_spinner_ql: QLabel = self.findChild(
QLabel, "mda_load_spinner")
self.anim_mgw_mda_load_spinner = QtGui.QMovie(
exeDir + '/res/Thin stripes.gif')
self.UIE_mgw_mda_load_spinner_ql.setMovie(
self.anim_mgw_mda_load_spinner)
self.anim_mgw_mda_load_spinner_running = False
self.UIE_mgw_fwa_load_spinner_ql: QLabel = self.findChild(
QLabel, "fwa_load_spinner")
self.anim_mgw_fwa_load_spinner = QtGui.QMovie(
exeDir + '/res/Thin stripes.gif')
self.UIE_mgw_fwa_load_spinner_ql.setMovie(
self.anim_mgw_fwa_load_spinner)
self.anim_mgw_fwa_load_spinner_running = False
self.UIE_mgw_sra_load_spinner_ql: QLabel = self.findChild(
QLabel, "sra_load_spinner")
self.anim_mgw_sra_load_spinner = QtGui.QMovie(
exeDir + '/res/Thin stripes.gif')
self.UIE_mgw_sra_load_spinner_ql.setMovie(
self.anim_mgw_sra_load_spinner)
self.anim_mgw_sra_load_spinner_running = False
self.UIE_mgw_saa_load_spinner_ql: QLabel = self.findChild(
QLabel, "saa_load_spinner")
self.anim_mgw_saa_load_spinner = QtGui.QMovie(
exeDir + '/res/Thin stripes.gif')
self.UIE_mgw_saa_load_spinner_ql.setMovie(
self.anim_mgw_saa_load_spinner)
self.anim_mgw_saa_load_spinner_running = False
self.UIE_mgw_sta_load_spinner_ql: QLabel = self.findChild(
QLabel, "sta_load_spinner")
self.anim_mgw_sta_load_spinner = QtGui.QMovie(
exeDir + '/res/Thin stripes.gif')
self.UIE_mgw_sta_load_spinner_ql.setMovie(
self.anim_mgw_sta_load_spinner)
self.anim_mgw_sta_load_spinner_running = False
self.UIE_mgw_dra_load_spinner_ql: QLabel = self.findChild(
QLabel, "dra_load_spinner")
self.anim_mgw_dra_load_spinner = QtGui.QMovie(
exeDir + '/res/Thin stripes.gif')
self.UIE_mgw_dra_load_spinner_ql.setMovie(
self.anim_mgw_dra_load_spinner)
self.anim_mgw_dra_load_spinner_running = False
# Setup the first (result) table tab.
table = DataTableWidget(self)
VLayout = QVBoxLayout()
VLayout.addWidget(table)
self.UIE_mgw_table_qtw.widget(0).setLayout(VLayout)
self.table_result = table
self.table_result.is_result = True
self.UIE_mgw_table_result_tab = self.UIE_mgw_table_qtw.widget(0)