-
Notifications
You must be signed in to change notification settings - Fork 0
/
scnr2.py
1141 lines (952 loc) · 41.3 KB
/
scnr2.py
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 os
import numpy as np
import time
#os.environ["QT_API"] = "pyside"
from qtpy import QtCore,QtWidgets,QtGui
import pyqtgraph as pg
from skimage import exposure
from skimage import io
# from PyQt5 import uic
# Ui_MainWindow = uic.loadUiType("gui/main.ui")[0]
# from qtpy import uic
# Ui_MainWindow = uic.loadUiType("gui/main.ui")[0]
from gui.main import Ui_MainWindow
# Device Control imports
import PIStage
# import AndorSpectrometer
import spectrometer_client
# Helper Classes imports
import spectrum
import settings
import camerathread
import gamepadthread
import numpymodel
import dialogs
from custom_pyqtgraph_classes import movableCrosshair, xmovableCrosshair
from gui.main import Ui_MainWindow
# for debugging
init_pad = True
init_cam = True
init_stage = True
init_spectrometer = True
class SCNR(QtWidgets.QMainWindow):
_window_title = "SCNR2"
_heartbeat = 100 # ms delay at which the plot/gui is refreshed, and the gamepad moves the stage
stage = None
cam = None
padthread = None
spectrometer = None
labels = None
cam_reference_image = None
background_image = None
last_image = None
savedir = "./Spectra/"
path = "./"
def __init__(self, options,parent=None):
super(SCNR, self).__init__(parent)
self.ui = Ui_MainWindow()
#setup, stage_ok, cam_ok, ok = dialogs.StartUp_Dialog.getOptions()
setup, stage_ok, cam_ok = options
#print(setup)
if ok:
init_cam = cam_ok
init_stage = stage_ok
if setup == 'Nikon' :
self.settings = settings.Settings('config_nikon.ini')
elif setup == 'Zeiss':
self.settings = settings.Settings('config_zeiss.ini')
elif setup == 'Freespace': #Freespace Setup
self.settings = settings.Settings('config_freespace.ini')
else:
raise RuntimeError("Setup not specified!")
#print("Setup not specified, quitting.")
super(SCNR, self).close()
else:
super(SCNR, self).close()
self.ui.setupUi(self)
# init settings
self.ui.search_correct_checkBox.setChecked(False)
self.ui.slitwidth_spin.setValue(self.settings.slit_width)
self.ui.centre_wavelength_spin.setValue(self.settings.centre_wavelength)
self.ui.rasterdim_spin.setValue(self.settings.rasterdim)
self.ui.rasterwidth_spin.setValue(self.settings.rasterwidth)
self.ui.search_int_time_spin.setValue(self.settings.search_integration_time)
self.ui.sigma_spin.setValue(self.settings.sigma)
self.ui.search_zmult_spin.setValue(self.settings.zmult)
self.ui.exposure_time_spin.setValue(self.settings.cam_exposure_time)
self.ui.label_stepsize.setText(str(self.settings.stepsize))
self.ui.zscan_centre_spinbox.setValue(self.settings.zscan_centre)
self.ui.zscan_width_spinbox.setValue(self.settings.zscan_width)
if self.settings.autofocus_mode == 'gauss':
self.ui.autofocus_combobox.setCurrentIndex(0)
elif self.settings.autofocus_mode == 'gaussexport':
self.ui.autofocus_combobox.setCurrentIndex(1)
elif self.settings.autofocus_mode == 'maximum':
self.ui.autofocus_combobox.setCurrentIndex(2)
elif self.settings.autofocus_mode == 'brightfield':
self.ui.autofocus_combobox.setCurrentIndex(3)
elif self.settings.autofocus_mode == 'zscan':
self.ui.autofocus_combobox.setCurrentIndex(4)
self.pw = pg.PlotWidget()
# vb = CustomViewBox()
# self.pw = pg.PlotWidget(viewBox=vb, enableMenu=False)
self.plot = self.pw.plot()
l1 = QtWidgets.QVBoxLayout(self.ui.specwidget)
l1.addWidget(self.pw)
self.pw.setLabel('left', 'Intensity [a.u.]')
self.pw.setLabel('bottom', 'Wavelength [nm]')
gv = pg.GraphicsView()
vb = pg.ViewBox()
self.detector_img = pg.ImageItem()
vb.addItem(self.detector_img)
self.slitmarker = xmovableCrosshair(pos=[self.settings.slitmarker_x, self.settings.slitmarker_y], size=15)
vb.addItem(self.slitmarker)
gv.setCentralWidget(vb)
l = QtWidgets.QGridLayout(self.ui.detectorwidget)
l.setSpacing(0)
l.addWidget(gv, 0, 0)
w = pg.HistogramLUTWidget()
l.addWidget(w, 0, 1)
w.setImageItem(self.detector_img)
# self.pw.setLabel('left', 'y', units='px')
# self.pw.setLabel('bottom', 'x', units='px')
# init Spectrometer
if init_spectrometer:
self.spectrometer = spectrometer_client.SpectrometerClient()
# print('Initializing Spectrometer')
# self.spectrometer = AndorSpectrometer.Spectrometer(start_cooler=start_cooler,init_shutter=True,verbosity=1)
# self.spectrometer.SetExposureTime(self.settings.integration_time / 1000)
self.setSpectrumMode()
self.spectrometer.SetExposureTime(self.settings.integration_time)
# print('Spectrometer initialized')
self.spectrometer.SetMinVertReadout(1)
# init detector mode combobox
self.ui.mode_combobox.addItem("Spectrum")
self.ui.mode_combobox.addItem("Image of Slit")
self.ui.mode_combobox.addItem("Full Image")
# init camera stuff
if init_cam:
gv2 = pg.GraphicsView()
vb2 = pg.ViewBox()
self.img = pg.ImageItem()
vb2.addItem(self.img)
self.cammarker = movableCrosshair(pos=[self.settings.cammarker_x, self.settings.cammarker_y], size=25)
vb2.addItem(self.cammarker)
gv2.setCentralWidget(vb2)
l2 = QtWidgets.QGridLayout(self.ui.camwidget)
l2.setSpacing(0)
l2.addWidget(gv2, 0, 0)
w = pg.HistogramLUTWidget()
l2.addWidget(w, 0, 1)
w.setImageItem(self.img)
try:
if setup == 'Nikon':
self.cam = camerathread.CameraThread(xflip=True,yflip=False)
elif setup == 'Zeiss': # Microscope Setup
self.cam = camerathread.CameraThread(xflip=True,yflip=True)
elif setup == 'Freespace': # Freespace Setup
self.cam = camerathread.CameraThread(xflip=False,yflip=True)
img = self.cam.get_image()
print(img.shape)
except:
print("Error initializing Camera")
if self.cam.isinitialized:
self.cam.set_exposure(self.settings.cam_exposure_time * 1000)
self.cam.ImageReadySignal.connect(self.update_camera)
self.cam.start()
self.ui.cam_tab.setDisabled(False)
else:
self.cam = None
# self.ui.left_tab.setEnabled(False)
print("Could not initialize Camera")
QtWidgets.QMessageBox.critical(self, 'Error', "Could not initialize Camera.", QtWidgets.QMessageBox.Ok)
#self.ui.left_tab.removeTab(1)
self.ui.cam_tab.setDisabled(True)
else:
#self.ui.left_tab.removeTab(1)
self.cam = None
self.ui.cam_tab.setDisabled(True)
# init stage
if init_stage:
try:
self.stage = PIStage.E545(self.settings.stage_ip, self.settings.stage_port, coordinate_mapping = self.settings.coord_mapping)
# self.stage = PIStage.E545('127.0.0.1', self.settings.stage_port)
except Exception as e:
print(e)
self.stage = None
# self.stage = PIStage.Dummy()
# print("Could not initialize PIStage, using Dummy instead")
if self.stage is not None:
if self.stage.is_initialized:
self.ui.addpos_button.setEnabled(True)
self.ui.scanning_tab.setEnabled(True)
self.ui.searchmax_button.setEnabled(True)
self.ui.autofocus_button.setEnabled(True)
self.ui.stage_frame.setEnabled(True)
self.ui.search_checkBox.setEnabled(True)
self.ui.lockin_button.setEnabled(True)
self.ui.lockin_checkBox.setEnabled(True)
else:
self.stage = None
QtWidgets.QMessageBox.critical(self, 'Error', "Could not initialize PI Stage.", QtWidgets.QMessageBox.Ok)
# for testing:
else:
self.ui.scanning_tab.setEnabled(True)
# init Gamepad
if not self.stage is None:
if init_pad:
try:
self.padthread = gamepadthread.GamepadThread()
except:
print("Error initializing Gamepad")
if self.padthread.isinitialized:
self.padthread.BSignal.connect(self.on_search_clicked)
self.padthread.XSignal.connect(self.on_addpos_clicked)
self.padthread.YSignal.connect(self.on_stepup_clicked)
self.padthread.ASignal.connect(self.on_stepdown_clicked)
self.padthread.xaxisSignal.connect(self.on_xaxis)
self.xaxis = 0.0
self.padthread.yaxisSignal.connect(self.on_yaxis)
self.yaxis = 0.0
self.padthread.rxaxisSignal.connect(self.on_rxaxis)
self.rxaxis = 0.0
self.padthread.ryaxisSignal.connect(self.on_ryaxis)
self.ryaxis = 0.0
self.padthread.start()
self.gamepad_timer = QtCore.QTimer(self)
self.gamepad_timer.timeout.connect(self.check_pad_analog)
self.gamepad_timer.start(100)
self.pad_active = True
else:
self.pad_active = False
self.padthread = None
print("Could not initialize Gamepad")
QtWidgets.QMessageBox.critical(self, 'Error', "Could not initialize Gamepad.", QtWidgets.QMessageBox.Ok)
# init spectrum stuff
self.spectrum = spectrum.Spectrum(self.spectrometer, self.stage, self.settings)
self.spectrum.updateStatus.connect(self.on_updateStatus)
self.spectrum.updateProgress.connect(self.on_updateProgress)
self.spectrum.updatePositions.connect(self.on_updatePositions)
self.spectrum.disableButtons.connect(self.on_disableButtons)
self.spectrum.enableButtons.connect(self.on_enableButtons)
self.spectrum.specSignal.connect(self.on_update_spectrum)
self.spectrum.set_searchmax_ontarget.connect(self.set_searchmax_ontarget)
self.spectrum.set_autofocus_ontarget.connect(self.set_autofocus_ontarget)
# init setting tab values
self.ui.integration_time_spin.setValue(self.settings.integration_time)
self.ui.number_of_samples_spin.setValue(self.settings.number_of_samples)
if init_spectrometer:
# init grating combobox
gratings = self.spectrometer.GetGratingInfo()
for i in range(len(gratings)):
self.ui.grating_combobox.addItem(str(round(gratings[i + 1])) + ' lines/mm')
active_grating = self.spectrometer.GetGrating()
self.ui.grating_combobox.setCurrentIndex(active_grating - 1)
# init Position Table
self.positions = np.matrix([[10.0, 10.0], [15.0, 15.0]])
self.posModel = numpymodel.NumpyModel(self.positions)
self.ui.posTable.setModel(self.posModel)
self.vh = self.ui.posTable.verticalHeader()
self.vh.setVisible(False)
self.hh = self.ui.posTable.horizontalHeader()
self.hh.setVisible(True)
self.on_temp_clicked()
self.show_pos()
def closeEvent(self, event):
self.on_savesettings_clicked()
super(SCNR, self).closeEvent(event)
def close(self):
self.on_savesettings_clicked()
super(SCNR, self).close()
def show_pos(self):
if not self.stage is None:
pos = self.stage.last_pos()
self.ui.label_x.setText("x: {0:+6.3f}".format(pos[0]))
self.ui.label_y.setText("y: {0:+6.3f}".format(pos[1]))
self.ui.label_z.setText("z: {0:+6.3f}".format(pos[2]))
# ----- Slot for Detector Mode
@QtCore.Slot(int)
def on_mode_changed(self, index):
if init_spectrometer:
self.spectrometer.AbortAcquisition()
time.sleep(0.5)
if index == 0:
self.setSpectrumMode()
elif index == 1:
self.setImageMode()
elif index == 2:
self.setFullImageMode()
def setSpectrumMode(self):
self.ui.dark_button.setEnabled(True)
self.ui.bg_button.setEnabled(True)
self.ui.ref_button.setEnabled(True)
self.ui.mean_button.setEnabled(True)
self.ui.series_button.setEnabled(True)
self.ui.searchmax_button.setEnabled(True)
self.ui.lockin_button.setEnabled(True)
if self.settings.centre_wavelength > 0:
self.spectrometer.SetCentreWavelength(self.settings.centre_wavelength)
else:
self.spectrometer.SetCentreWavelength(700)
self.ui.centre_wavelength_spin.setValue(self.settings.centre_wavelength)
self.spectrometer.SetSlitWidth(self.settings.slit_width)
self.ui.slitwidth_spin.setValue(self.settings.slit_width)
self.spectrometer.SetSingleTrack()
def setImageMode(self):
self.ui.dark_button.setDisabled(True)
self.ui.bg_button.setDisabled(True)
self.ui.ref_button.setDisabled(True)
#self.ui.mean_button.setDisabled(True)
self.ui.series_button.setDisabled(True)
self.ui.searchmax_button.setDisabled(True)
self.ui.lockin_button.setDisabled(True)
self.spectrometer.SetSlitWidth(2500)
self.ui.slitwidth_spin.setValue(2500)
self.spectrometer.SetImageofSlit()
self.ui.centre_wavelength_spin.setValue(0)
def setFullImageMode(self):
self.ui.dark_button.setDisabled(True)
self.ui.bg_button.setDisabled(True)
self.ui.ref_button.setDisabled(True)
#self.ui.mean_button.setDisabled(True)
self.ui.series_button.setDisabled(True)
self.ui.searchmax_button.setDisabled(True)
self.ui.lockin_button.setDisabled(True)
self.spectrometer.SetFullImage()
# ----- END Slot for Detektor Mode
# ----- Slots for Camera Stuff
@QtCore.Slot(np.ndarray)
def update_camera(self, img):
self.cam.disable()
autolevels = False
if self.cam_reference_image is not None:
img -= self.cam_reference_image
#img = img / self.cam_reference_image
img -= np.min(img)
#img *= 1000
if self.ui.autocontrast_checkBox.isChecked():
plow, phigh = np.percentile(img, (1, 99))
img = exposure.rescale_intensity(img, in_range=(plow, phigh))
#img = exposure.equalize_adapthist(img, clip_limit=0.03)
autolevels = True
self.img.setImage(img,autoLevels=autolevels,autoDownsample = True)
self.cam.enable()
@QtCore.Slot()
def on_camreference_clicked(self):
self.cam_reference_image = self.cam.get_image()
@QtCore.Slot()
def on_clear_reference_clicked(self):
self.cam_reference_image = None
@QtCore.Slot()
def on_save_cam_image_clicked(self):
img = self.img.image
save_as = QtWidgets.QFileDialog.getSaveFileName(self, "Save currently shown Spectrum as", './spectra/',
'CSV Files (*.csv)')
save_as = save_as[0]
if not save_as[-4:] == '.csv':
save_as += ".csv"
try:
np.savetxt(save_as, img)
except:
print("Error Saving file " + save_as)
QtWidgets.QMessageBox.warning(self, 'Error', "Error Saving file " + save_as, QtWidgets.QMessageBox.Ok)
@QtCore.Slot(int)
def on_lefttab_changed(self, index):
if init_cam:
if index == 1:
self.cam.enable()
else:
self.cam.disable()
# ----- END Slots for Camera Stuff
# ----- Slots for Spectrum Stuff
def correct_spec(self, spec):
if self.ui.correct_checkBox.isChecked():
return self.spectrum.correct_spectrum(spec)
return spec
def correct_image(self, image):
if self.ui.correct_image_checkBox.isChecked():
if self.background_image is not None:
if self.background_image.shape == image.shape:
image = np.subtract(image,self.background_image)
else:
QtWidgets.QMessageBox.warning(self, 'Error', "Image shapes not compatible, could not subtract background" ,
QtWidgets.QMessageBox.Ok)
if not self.spectrum.dark is None and not self.spectrum.lamp is None:
image = np.array(image,dtype=np.float32)
print('correct_image '+ str(image.shape))
for i in range(image.shape[1]):
image[:,i] = image[:,i] / (self.spectrum.lamp - self.spectrum.dark)
image = image - image.min()
image = image / image.max()
image = image * 10000
image = np.array(image,dtype=np.int)
print('correct_image finished')
return image
@QtCore.Slot(np.ndarray)
def on_update_spectrum(self, spec):
if spec is not None:
if self.spectrometer.mode == "imageofslit" or self.spectrometer.mode == "fullimage":
self.last_image = spec
print('on_update_spectrum '+str(spec.shape))
# img = self.correct_image(self.last_image)
# self.detector_img.setImage(img,autoLevels=False)
self.detector_img.setImage(self.correct_image(self.last_image), autoLevels=False)
elif self.spectrometer.mode == 'singletrack':
self.plot.setData(self.spectrometer.GetWavelength(), self.correct_spec(spec))
else:
QtWidgets.QMessageBox.warning(self, 'Error', "Communication with Spectrometer out of sync, please try again.", QtWidgets.QMessageBox.Ok)
@QtCore.Slot(str)
def on_updateStatus(self, status):
self.ui.status.setText(status)
@QtCore.Slot(float)
def on_updateProgress(self, progress):
self.ui.progressBar.setValue(int(progress))
@QtCore.Slot(np.ndarray)
def on_updatePositions(self, pos):
self.posModel.addData(pos)
@QtCore.Slot()
def on_disableButtons(self):
self.ui.right_tab.setDisabled(True)
self.ui.stage_frame.setDisabled(True)
self.ui.searchmax_button.setDisabled(True)
self.ui.autofocus_button.setDisabled(True)
self.ui.stepup_button.setDisabled(True)
self.ui.stepdown_button.setDisabled(True)
self.ui.temp_button.setDisabled(True)
self.ui.lockin_button.setDisabled(True)
self.ui.lockin_checkBox.setDisabled(True)
self.ui.stop_button.setDisabled(False)
@QtCore.Slot()
def on_enableButtons(self):
self.ui.right_tab.setDisabled(False)
self.ui.temp_button.setDisabled(False)
if not self.stage is None:
self.ui.stage_frame.setDisabled(False)
self.ui.searchmax_button.setDisabled(False)
self.ui.autofocus_button.setDisabled(False)
self.ui.stepup_button.setDisabled(False)
self.ui.stepdown_button.setDisabled(False)
self.ui.addpos_button.setDisabled(False)
self.ui.lockin_button.setDisabled(False)
self.ui.lockin_checkBox.setDisabled(False)
self.ui.stop_button.setDisabled(True)
#self.pad_active = True
# ----- END Slots for Spectrum Stuff
# ----- Slots for Gamepad
@QtCore.Slot(float)
def on_xaxis(self, x):
self.xaxis = x
@QtCore.Slot(float)
def on_yaxis(self, y):
self.yaxis = -y
@QtCore.Slot(float)
def on_rxaxis(self, x):
print(x)
self.rxaxis = x
@QtCore.Slot(float)
def on_ryaxis(self, y):
print(y)
self.ryaxis = -y
@QtCore.Slot()
def check_pad_analog(self):
if self.pad_active:
x_step = self.xaxis
if abs(x_step) > 0.001:
x_step = x_step * self.settings.stepsize
else:
x_step = 0.0
y_step = self.yaxis
if abs(y_step) > 0.001:
y_step = y_step * self.settings.stepsize
else:
y_step = 0.0
z_step = self.ryaxis
if abs(z_step) > 0.001:
z_step = z_step * self.settings.stepsize
else:
z_step = 0.0
if abs(x_step) > 0.001:
if abs(y_step) > 0.001:
self.set_searchmax_ontarget(False)
self.stage.moverel(dx=x_step, dy=y_step)
else:
self.set_searchmax_ontarget(False)
self.stage.moverel(dx=x_step)
elif abs(y_step) > 0.001:
self.set_searchmax_ontarget(False)
self.stage.moverel(dy=y_step)
if abs(z_step) > 0.0001:
self.stage.moverel(dz=z_step)
self.set_autofocus_ontarget(False)
self.show_pos()
# ----- END Slots for Gamepad
# ----- Slots for Buttons
@QtCore.Slot()
def on_start_scan_clicked(self):
prefix, ok = QtWidgets.QInputDialog.getText(self, 'Save Folder',
'Enter Folder to save spectra to:')
if ok:
try:
# os.path.exists(prefix)
os.mkdir(self.savedir + prefix)
except:
# print("Error creating directory ."+path.sep + prefix)
print("Error creating directory ./" + prefix)
QtWidgets.QMessageBox.warning(self, 'Error', "Error creating directory ./" + prefix + "", QtWidgets.QMessageBox.Ok)
# path = self.savedir + prefix + path.sep
path = self.savedir + prefix + "/"
self.ui.status.setText("Scanning ...")
# self.spectrum.make_scan(self.scan_store, path, self.button_searchonoff.get_active(), self.button_lockinonoff.get_active())
self.on_disableButtons()
self.spectrum.take_scan(self.posModel.getMatrix(), self.labels, path, self.ui.lockin_checkBox.isChecked(),
self.ui.search_checkBox.isChecked(),self.ui.autofocus_checkBox.isChecked())
@QtCore.Slot()
def on_scan3d_clicked(self):
prefix, ok = QtWidgets.QInputDialog.getText(self, 'Save Folder',
'Enter Folder to save spectra to:')
if ok:
try:
os.mkdir(self.savedir + prefix)
except:
print("Error creating directory ./" + prefix)
QtWidgets.QMessageBox.warning(self, 'Error', "Error creating directory ./" + prefix + "", QtWidgets.QMessageBox.Ok)
path = self.savedir + prefix + "/"
file = path + "cube.csv"
self.stage.query_pos()
x,y,z = self.stage.last_pos()
x = np.linspace(x - self.ui.cube_width_spin.value() / 2, x + self.ui.cube_width_spin.value() / 2,
self.ui.cube_steps_spin.value())
y = np.linspace(y - self.ui.cube_width_spin.value() / 2, y + self.ui.cube_width_spin.value() / 2,
self.ui.cube_steps_spin.value())
z = np.linspace(z - self.ui.cube_width_spin.value()*self.settings.zmult / 2, z + self.ui.cube_width_spin.value()*self.settings.zmult / 2,
self.ui.cube_steps_spin.value()*self.settings.zmult)
xx,yy,zz = np.meshgrid(x,y,z)
xx = xx.ravel()
yy = yy.ravel()
zz = zz.ravel()
pos = np.vstack((xx,yy,zz))
pos = pos.transpose()
self.ui.status.setText("Scanning ...")
self.on_disableButtons()
self.spectrum.take_scan3d(pos, file)
@QtCore.Slot()
def on_stop_clicked(self):
self.ui.status.setText('Stopped')
self.spectrum.stop_process()
@QtCore.Slot()
def on_reset_clicked(self):
self.spectrum.reset()
@QtCore.Slot()
def on_lockin_clicked(self):
self.on_disableButtons()
self.ui.status.setText('Acquiring ...')
self.spectrum.take_lockin()
# @QtCore.Slot()
# def on_direction_clicked(self):
# self.direction_dialog.rundialog()
@QtCore.Slot()
def on_live_clicked(self):
self.on_disableButtons()
self.ui.status.setText('Liveview')
if self.spectrometer.mode == 'singletrack':
self.spectrum.take_live()
elif self.spectrometer.mode == 'imageofslit':
self.spectrum.take_live_image()
elif self.spectrometer.mode == 'fullimage':
self.spectrum.take_live_fullimage()
@QtCore.Slot()
def on_single_clicked(self):
self.on_disableButtons()
self.ui.status.setText('Single')
if self.spectrometer.mode == 'singletrack':
self.spectrum.take_live(single=True)
elif self.spectrometer.mode == 'imageofslit':
self.spectrum.take_live_image(single=True)
elif self.spectrometer.mode == 'fullimage':
self.spectrum.take_live_fullimage(single=True)
@QtCore.Slot()
def on_searchgrid_clicked(self):
self.set_searchmax_ontarget(False)
self.on_disableButtons()
self.ui.status.setText("Searching Max.")
self.spectrum.scan_search_max(self.posModel.getMatrix(), self.labels)
@QtCore.Slot()
def on_search_clicked(self):
if self.spectrometer.mode == 'singletrack':
self.set_searchmax_ontarget(False)
self.on_disableButtons()
# self.spectrometer.SetCentreWavelength(0.0)
# self.spectrometer.SetSlitWidth(500)
# self.spectrum.start_autofocus()
self.ui.status.setText("Searching Max ...")
self.spectrum.search_max()
else:
QtWidgets.QMessageBox.warning(self, 'Error', 'Search only possible in Spectrum Mode' ,QtWidgets.QMessageBox.Ok)
@QtCore.Slot()
def on_autofocus_clicked(self):
if self.spectrometer.mode == 'singletrack':
self.set_autofocus_ontarget(False)
self.on_disableButtons()
self.ui.status.setText("Focussing ...")
self.spectrum.start_autofocus()
else:
QtWidgets.QMessageBox.warning(self, 'Error', 'Autofocus only possible in Spectrum Mode' ,QtWidgets.QMessageBox.Ok)
@QtCore.Slot()
def on_save_clicked(self):
self.ui.status.setText("Saving Data ...")
prefix, ok = QtWidgets.QInputDialog.getText(self, 'Save Folder',
'Enter Folder to save spectra to:')
if ok:
try:
# os.path.exists(prefix)
os.mkdir(self.savedir + prefix)
except:
# print("Error creating directory ."+path.sep + prefix)
print("Error creating directory ./" + prefix)
QtWidgets.QMessageBox.warning(self, 'Error', "Error creating directory ./" + prefix + "", QtWidgets.QMessageBox.Ok)
# path = self.savedir + prefix + path.sep
path = self.savedir + prefix + "/"
self.spectrum.save_data(path)
@QtCore.Slot()
def on_saveas_clicked(self):
self.ui.status.setText("Saving Data ...")
save_as = QtWidgets.QFileDialog.getSaveFileName(self, "Save currently shown Spectrum as", './spectra/',
'CSV Files (*.csv)')
#print(save_as[0])
save_as = save_as[0]
if not save_as[-4:] == '.csv':
save_as += ".csv"
# prefix, ok = QtWidgets.QInputDialog.getText(self, 'Save Folder', 'Enter Folder to save spectra to:')
if not self.spectrum.mean is None:
try:
self.spectrum.save_spectrum(self.spectrum.mean, save_as, None, False, True)
except:
print("Error Saving file " + save_as)
QtWidgets.QMessageBox.warning(self, 'Error', "Error Saving file " + save_as, QtWidgets.QMessageBox.Ok)
@QtCore.Slot()
def on_dark_clicked(self):
self.on_disableButtons()
self.ui.status.setText('Taking Dark Spectrum')
self.spectrum.take_dark()
@QtCore.Slot()
def on_lamp_clicked(self):
self.on_disableButtons()
self.ui.status.setText('Taking Ref Spectrum')
self.spectrum.take_lamp()
@QtCore.Slot()
def on_mean_clicked(self):
self.on_disableButtons()
self.ui.status.setText('Taking Mean Spectrum')
if self.spectrometer.mode == 'singletrack':
self.spectrum.take_mean()
elif self.spectrometer.mode == 'imageofslit':
self.spectrum.take_mean_image()
elif self.spectrometer.mode == 'fullimage':
self.spectrum.take_mean_fullimage()
@QtCore.Slot()
def on_bg_clicked(self):
self.on_disableButtons()
self.ui.status.setText('Taking Background Spectrum')
self.spectrum.take_bg()
@QtCore.Slot()
def on_series_clicked(self):
prefix, ok = QtWidgets.QInputDialog.getText(self, 'Save Folder',
'Enter Folder to save spectra to:')
if ok:
try:
# os.path.exists(prefix)
os.mkdir(self.savedir + prefix)
except:
# print("Error creating directory ."+path.sep + prefix)
print("Error creating directory ./" + prefix)
QtWidgets.QMessageBox.warning(self, 'Error', "Error creating directory ./" + prefix + "", QtWidgets.QMessageBox.Ok)
# path = self.savedir + prefix + path.sep
path = self.savedir + prefix + "/"
self.ui.status.setText("Time Series ...")
# self.spectrum.make_scan(self.scan_store, path, self.button_searchonoff.get_active(), self.button_lockinonoff.get_active())
self.on_disableButtons()
self.spectrum.take_series(path)
@QtCore.Slot()
def on_loaddark_clicked(self):
buf = self._load_spectrum_from_file()
if not buf is None:
self.spectrum.dark = buf
@QtCore.Slot()
def on_loadlamp_clicked(self):
buf = self._load_spectrum_from_file()
if not buf is None:
self.spectrum.lamp = buf
@QtCore.Slot()
def on_loadbg_clicked(self):
buf = self._load_spectrum_from_file()
if not buf is None:
self.spectrum.bg = buf
@QtCore.Slot()
def on_xup_clicked(self):
self.stage.moverel(dx=self.settings.stepsize)
self.show_pos()
self.set_searchmax_ontarget(False)
@QtCore.Slot()
def on_xdown_clicked(self):
self.stage.moverel(dx=-self.settings.stepsize)
self.show_pos()
self.set_searchmax_ontarget(False)
@QtCore.Slot()
def on_yup_clicked(self):
self.stage.moverel(dy=self.settings.stepsize)
self.show_pos()
self.set_searchmax_ontarget(False)
@QtCore.Slot()
def on_ydown_clicked(self):
self.stage.moverel(dy=-self.settings.stepsize)
self.show_pos()
self.set_searchmax_ontarget(False)
@QtCore.Slot()
def on_zup_clicked(self):
self.stage.moverel(dz=self.settings.stepsize)
self.show_pos()
self.set_autofocus_ontarget(False)
@QtCore.Slot()
def on_zdown_clicked(self):
self.stage.moverel(dz=-self.settings.stepsize)
self.show_pos()
self.set_autofocus_ontarget(False)
@QtCore.Slot()
def on_stepup_clicked(self):
self.settings.stepsize *= 10
if self.settings.stepsize > 10:
self.settings.stepsize = 10.0
self.ui.label_stepsize.setText(str(self.settings.stepsize))
self.settings.save()
@QtCore.Slot()
def on_stepdown_clicked(self):
self.settings.stepsize /= 10
if self.settings.stepsize < 0.001:
self.settings.stepsize = 0.001
self.ui.label_stepsize.setText(str(self.settings.stepsize))
self.settings.save()
@QtCore.Slot()
def on_temp_clicked(self):
self.ui.label_temp.setText('Detector Temperature: ' + str(round(self.spectrometer.GetTemperature(), 1)) + ' °C')
@QtCore.Slot()
def on_use_image_background_clicked(self):
self.background_image = self.last_image
@QtCore.Slot()
def on_save_detectorimage_clicked(self):
img = self.last_image#self.correct_image(self.last_image)
save_as = QtWidgets.QFileDialog.getSaveFileName(self, "Save currently shown Spectrum as", './spectra/',
'CSV Files (*.csv)')
save_as = save_as[0]
if not save_as[-4:] == '.csv':
save_as += ".csv"
try:
if self.ui.mode_combobox.currentIndex() == 2:
img = np.vstack((img.T,self.spectrometer.GetWavelength()))
np.savetxt(save_as,img)
elif self.ui.mode_combobox.currentIndex() == 1:
np.savetxt(save_as,img)
except:
print("Error Saving file " + save_as)
QtWidgets.QMessageBox.warning(self, 'Error', "Error Saving file " + save_as, QtWidgets.QMessageBox.Ok)
@QtCore.Slot()
def on_offset_clicked(self):
detector_offset, grating_offset, ok = dialogs.Offset_Dialog.get_Offsets(self.spectrometer)
if ok:
print("1 ")
self.spectrometer.SetGratingOffset(grating_offset)
print("2 ")
self.spectrometer.SetDetectorOffset(detector_offset)
print("3 ")
# ----- END Slots for Buttons
# ----- Scanning Listview Slots
@QtCore.Slot()
def on_addpos_clicked(self):
self.stage.query_pos()
x, y, z = self.stage.last_pos()
positions = np.matrix([x, y])
self.posModel.addData(positions)
@QtCore.Slot()
def on_spangrid_clicked(self):
positions = self.posModel.getMatrix()
grid, self.labels, ok = dialogs.SpanGrid_Dialog.getXY(positions)
if ok:
self.posModel.clear()
self.posModel.addData(grid)
@QtCore.Slot()
def on_scan_add(self):
positions = np.matrix([0.0, 0.0])
self.posModel.addData(positions)
@QtCore.Slot()
def on_scan_remove(self):
indices = self.ui.posTable.selectionModel().selectedIndexes()
rows = np.array([], dtype=int)
for index in indices:
rows = np.append(rows, index.row())
self.posModel.removeRows(rows)
@QtCore.Slot()
def on_scan_clear(self):
self.posModel.clear()
# ----- END Scanning Listview Slots
# ----- Slots for Settings
@QtCore.Slot()
def on_int_time_edited(self):
self.settings.integration_time = self.ui.integration_time_spin.value()
self.spectrometer.SetExposureTime(self.ui.integration_time_spin.value())
@QtCore.Slot()
def on_number_of_samples_edited(self):
self.settings.number_of_samples = self.ui.number_of_samples_spin.value()
@QtCore.Slot()
def on_slit_width_edited(self):
self.settings.slit_width = self.ui.slitwidth_spin.value()
self.spectrometer.SetSlitWidth(self.ui.slitwidth_spin.value())
time.sleep(0.5)
@QtCore.Slot()
def on_centre_wavelength_edited(self):
self.settings.centre_wavelength = self.ui.centre_wavelength_spin.value()
self.spectrometer.SetCentreWavelength(self.ui.centre_wavelength_spin.value())
@QtCore.Slot(int)
def on_grating_changed(self, index):
self.spectrometer.SetGrating(index + 1)
@QtCore.Slot()
@QtCore.Slot()
def on_exposure_time_edited(self):
self.settings.cam_exposure_time = self.ui.exposure_time_spin.value()
self.cam.set_exposure(self.settings.cam_exposure_time * 1000)
@QtCore.Slot()
def on_search_int_time_edited(self):
self.settings.search_integration_time = self.ui.search_int_time_spin.value()
@QtCore.Slot()
def on_rasterdim_edited(self):
self.settings.rasterdim = self.ui.rasterdim_spin.value()
@QtCore.Slot()
def on_rasterwidth_edited(self):
self.settings.rasterwidth = self.ui.rasterwidth_spin.value()
@QtCore.Slot()
def on_sigma_edited(self):
self.settings.sigma = self.ui.sigma_spin.value()
@QtCore.Slot()
def on_search_zmult_edited(self):
self.settings.zmult = self.ui.search_zmult_spin.value()
@QtCore.Slot()
def on_detector_temp_edited(self):
self.spectrometer.SetTemperature(self.ui.detector_temp_spinbox.value())