forked from AFMD/sEQE-Setup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsEQE.py
1398 lines (1009 loc) · 53.2 KB
/
sEQE.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 28 11:59:40 2018
@author: jungbluth
"""
import io
import itertools
import math
import os
import re
import sys
import time
import logging
import warnings
import platform
import pathlib
import GUI_template
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import serial
import zhinst.utils
import zhinst.ziPython
# for the gui
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib import style
from numpy import *
from scipy.interpolate import interp1d
import codecs
from monochromator import Monochromator
from microscope.filterwheels.thorlabs import ThorlabsFilterWheel
from lockin import LockIn
from tkinter import Tk
from tkinter import filedialog
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
# Initialising ports, device names and save path
file = pathlib.Path('pathsNdevices_config.txt')
if file.exists():
pNpdata = file.read_text().split(',')
self.zurich_device = pNpdata[0]
self.filter_port = pNpdata[1]
self.mono_port = pNpdata[2]
self.save_path = pNpdata[3]
print(f'Found the following details for setup in pathsNdevices.txt: \n zurich instrument device name: {self.zurich_device} \n second filter wheel port: {self.filter_port} \n monochromator port: {self.mono_port} \n default path where data are saved: {self.save_path}')
for i in range(len(pNpdata)):
if pNpdata[i] == '':
print('Empty string in pathsNdevices.txt found. The current file will be deleted, please recreate the file')
file.unlink() # to delete file
else:
file.touch(exist_ok = False)
if platform.system() == 'Linux':
port_prefix = '/dev/ttyUSB'
elif platform.system() == 'Windows':
port_prefix = 'COM'
else:
self.logger.error('Operating System is not known - defaulting to Linux system')
port_prefix = '/dev/tty'
self.zurich_device = str(input('Which zurich instrument device is used ? - type device address string e.g. UHF-DEV2000. ')) #'hf2-dev838'
self.filter_port = port_prefix+str(input('Which port number is used by the second filter wheel ? - type a number '))# AFMD default 'COM4'
self.mono_port = port_prefix+str(input('Which port number is used by the monochromator ? - type a number '))# AFMD default 'COM1'
self.save_path = pathlib.Path(input('Where do you want to save your data ? - copy absolute path of folder '))# AFMD default 'C:\\Users\\Public\\Documents\\sEQE'
file.write_text(f'{self.zurich_device},{self.filter_port},{self.mono_port},{self.save_path}')
QtWidgets.QMainWindow.__init__(self)
warnings.filterwarnings("ignore")
self.logger = self.get_logger()
# Set up the user interface from Designer
self.ui = GUI_template.Ui_MainWindow()
self.ui.setupUi(self)
# Connections
self.mono_connected = False # Set the monochromator connection to False
self.lockin_connected = False # Set the Lock-in connection to False
self.filter_connected = False # Set the filterwheel connection to False
# Initialize Monochromator and Lock-In Amplifier
self.mono = Monochromator(self.mono_port)
self.lockin = LockIn(self.zurich_device)
# General Setup
self.channel = 1
self.c = str(self.channel-1)
self.c6 = str(6)
self.do_plot = True
self.complete_scan = False
# these can not be defined here, due to empty text boxes at start up
# self.userName = self.ui.user.text()
# self.experimentName = self.ui.experiment.text()
# self.path =f'{self.save_path}/{self.userName}/{self.experimentName}'
self.filter_addition = 'None' ####################################################################################
# Handle Monochromator Buttons
self.ui.connectButton_Mono.clicked.connect(self.connectToMono) # Connect only to Monochromator
self.ui.monoGotoButton.clicked.connect(self.MonoHandleWavelengthButton) # Go to specific wavelength
self.ui.monoSpeedButton.clicked.connect(self.MonoHandleSpeedButton) # Set scan speed
self.ui.monoGratingButton.clicked.connect(self.MonoHandleGratingButtons) # Change grating
self.ui.monoFilterButton.clicked.connect(self.MonoHandleFilterButton) # Change filter
self.ui.monoFilterInitButton.clicked.connect(self.MonoHandleFilterInitButton) # Initialize filter
# Handle Lock-in Buttons
self.ui.connectButton_Lockin.clicked.connect(self.connectToLockin) # Connect only to Lock-in
self.ui.lockinParameterButton.clicked.connect(self.LockinHandleParameterButton) # Set Lock-in parameters
# Handle Filterwheel Buttons
self.ui.connectButton_Filter.clicked.connect(self.connectToFilter) # Connect only to Filterwheel
# Handle Combined Buttons
self.ui.connectButton.clicked.connect(self.connectToEquipment)
self.ui.completeScanButton_start.clicked.connect(self.MonoHandleCompleteScanButton) #########################################################################################
self.ui.completeScanButton_stop.clicked.connect(self.HandleStopCompleteScanButton) #########################################################################################
# Save and Import data from files or naming from path
self.ui.save_to_file.clicked.connect(self.save_mono_parameter) # Save measurement parameter to file
self.ui.import_from_file.clicked.connect(self.load_mono_parameter)
self.ui.importNamingButton.clicked.connect(self.load_naming)
# Import photodiode calibration files
Si_file = pd.ExcelFile("FDS100-CAL.xlsx") # The files are in the sEQE Analysis folder
# print(Si_file.sheet_names)
self.Si_cal = Si_file.parse('Sheet1')
# print(self.Si_cal)
InGaAs_file = pd.ExcelFile("FGA21-CAL.xlsx")
self.InGaAs_cal = InGaAs_file.parse('Sheet1')
# Close connection to Monochromator and Thorlabs filter wheel when window is closed
def __del__(self):
try:
self.thorfilterwheel.close()
with serial.Serial(self.mono_port, 9600, timeout=0) as self.p:
self.p.close()
except:
pass
# -----------------------------------------------------------------------------------------------------------
#### Functions to import data into GUI
# -----------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------
#### Functions to connect to Monochromator and Lock-in
# -----------------------------------------------------------------------------------------------------------
# Establish serial connection to Monochromator
def connectToMono(self):
"""Function to establish connection to monochromator.
Returns
-------
None
"""
try:
self.mono_connected = self.mono.connect()
if self.mono_connected:
self.logger.info('Connection to Monochromator Established')
self.ui.imageConnect_mono.setPixmap(QtGui.QPixmap("Button_on.png"))
except Exception as err:
self.logger.exception("Unexpected error during execution of connectToMono function:")
# Establish connection to LOCKIN
def connectToLockin(self):
"""Function to establish connection to Lockin.
Returns
-------
list
Zurich Instruments localhost name and device details
"""
try:
self.daq, self.device, self.lockin_connected = self.lockin.connect()
self.ui.imageConnect_lockin.setPixmap(QtGui.QPixmap("Button_on.png"))
return self.daq, self.device
except Exception as err:
self.logger.exception("Unexpected error during execution of connectToLockin function:")
# Establish connection to Filterwheel
def connectToFilter(self):
"""Function to establish connection to filter wheel.
Returns
-------
None
"""
try:
self.thorfilterwheel = ThorlabsFilterWheel(com=self.filter_port) # Initialize here = GUI openable without equipment physically connected
if self.thorfilterwheel.position == 0:
self.filter_connected = True
self.logger.info("Connection to Thorlabs filter wheel established")
self.ui.imageConnect_filter.setPixmap(QtGui.QPixmap("Button_on.png"))
else:
self.logger.exception('Could not find the Thorlabs filter wheel in position 1, i.e. in open position. Please check current filter wheel position manually.')
self.filter_connected = False
except Exception as err:
self.logger.exception("Unexpected error during execution of connectToFilter function:")
# -----------------------------------------------------------------------------------------------------------
# Establish connection to all equipment
def connectToEquipment(self):
"""Function to establish connection to monochromator, Lockin & filter wheel.
Returns
-------
None
"""
try:
self.connectToLockin()
self.connectToMono()
self.connectToFilter()
self.ui.imageConnect.setPixmap(QtGui.QPixmap("Button_on.png"))
except Exception as err:
self.logger.exception("Unexpected error during execution of connectToEquipment function:")
# -----------------------------------------------------------------------------------------------------------
#### Functions to handle parameter buttons for Monochromator and Lock-in
# -----------------------------------------------------------------------------------------------------------
## Monochromator Functions
# Set and GOTO wavelength
def MonoHandleWavelengthButton(self): # Function sets desired wavelength and calls chooseWavelength function
"""Function to read wavelength value from GUI.
Returns
-------
None
"""
wavelength = self.ui.pickNM.value()
self.mono.chooseWavelength(wavelength)
# Update the scan speed
def MonoHandleSpeedButton(self): # Function sets desired scan speed and calls chooseScanSpeed function
"""Function to read monochromator speed from GUI.
Returns
-------
None
"""
speed = self.ui.pickScanSpeed.value()
self.mono.chooseScanSpeed(speed)
# Set and move to grating
def MonoHandleGratingButtons(self): # Function sets desired grating number and calls chooseGrating function
"""Function to read grating number from monochromator.
Returns
-------
None
"""
if self.ui.Blaze_300.isChecked():
gratingNo = 1
elif self.ui.Blaze_750.isChecked():
gratingNo = 2
elif self.ui.Blaze_1600.isChecked():
gratingNo = 3
self.mono.chooseGrating(gratingNo)
# Update filter number
def MonoHandleFilterButton(self):
"""Function to read filter position from GUI.
Returns
-------
None
"""
filterNo = int(self.ui.pickFilter.value())
self.mono.chooseFilter(filterNo)
# Initialize filter
def MonoHandleFilterInitButton(self):
"""Function to read filter initialization position from GUI.
Returns
-------
None
"""
filterStart = self.ui.pickFilterInitStart.value()
filterDiff = int(8-filterStart)
self.mono.initializeFilter(filterDiff)
self.ui.imageInit_filterwheel.setPixmap(QtGui.QPixmap("Button_on.png"))
self.logger.info('Monochromator Filter Wheel initialized')
# -----------------------------------------------------------------------------------------------------------
## Lock-in Functions
# Define and set Lock-in parameters
def LockinHandleParameterButton(self):
"""Function to read Lockin amplification value from GUI.
Returns
-------
None
"""
try:
if self.lockin_connected:
self.amplification = self.ui.pickAmp.value()
self.LockinUpdateParameters(self.amplification)
else:
self.logger.info('Lock-In not connected')
except Exception as err:
self.logger.exception("Unexpected error during execution of LockinHandleParametersButton function:")
def LockinUpdateParameters(self,amplification): # Function sets desired Lock-in parameters and calls setParameter function
"""Function to update Lockin parameters.
Parameters
----------
amplification int, required
amplification value of the LockIn signal
Returns
-------
None
Raises
------
LoggerError
Raises error if Lockin not connected or Exception handling
"""
try:
if self.lockin_connected:
self.c_2 = str(self.channel) # Channel 2, with value 1, for the reference input
self.tc = self.ui.pickTC.value() # Import value for time constant
self.rate = self.ui.pickDTR.value() # Import value for data transfer rate
self.lowpass = self.ui.pickLPFO.value() # Import value for low pass filter order
self.range = 2 # This sets the default voltage range to 2
self.ac = 0 # AC off
self.imp50 = 0 # 50 Ohm off
self.imp50_2 = 1 # Turn on 50 Ohm on channel 2 to attenuate signal from chopper controller as reference signal
self.diff = 1 # Diff off
self.diff_2 = 0 #diff for channel 2 off
# if self.ui.acButton.isChecked(): # AC on if button is checked
# self.ac = 1
# if self.ui.imp50Button.isChecked(): # 50 Ohm on if button is checked
# self.imp50 = 1
# if self.ui.diffButton.isChecked(): # Diff on if button is checked
# self.diff = 1
# self.frequency = self.ui.pickFreq.value() # For manual frequency control. The frequency tab is currently not implemented in the GUI
self.lockin.setParameters(self.diff_2, self.diff, self.imp50, self.imp50_2, self.ac, self.range, self.lowpass, self.rate, self.tc, self.c_2, amplification)
self.logger.info('Updating Lock-In Settings')
else:
self.logger.error("Lock-In not connected")
except Exception as err:
self.logger.exception("Unexpected error during execution of LockinUpdateParameters function:")
# -----------------------------------------------------------------------------------------------------------
#### Functions to handle filter and grating changes
# -----------------------------------------------------------------------------------------------------------
def monoCheckFilter(self, wavelength): # Filter switching points from GUI
"""
Function to update position of first filter wheel from GUI defaults.
Parameters
----------
wavelength: float, required
Current wavelength position of monochromator
Returns
-------
None
Raises
------
LoggerError
Raises error if filter wheel commands are invalid or monochromator not connected
"""
filterNo = self.mono.checkFilter()
startNM_F2 = int(self.ui.startNM_F2.value())
stopNM_F2 = int(self.ui.stopNM_F2.value())
startNM_F3 = int(self.ui.startNM_F3.value())
stopNM_F3 = int(self.ui.stopNM_F3.value())
startNM_F4 = int(self.ui.startNM_F4.value())
stopNM_F4 = int(self.ui.stopNM_F4.value())
startNM_F5 = int(self.ui.startNM_F5.value())
stopNM_F5 = int(self.ui.stopNM_F5.value())
if startNM_F2 <= wavelength < stopNM_F2: # Filter 3 [FESH0700]: from 350 - 649 -- including start, excluing end
shouldbeFilterNo = 2
elif startNM_F3 <= wavelength < stopNM_F3: # Filter 3 [FESH0700]: from 350 - 649 -- including start, excluing end
shouldbeFilterNo = 3
elif startNM_F4 <= wavelength < stopNM_F4: # Filter 4 [FESH1000]: from 650 - 984 -- including start, excluding end
shouldbeFilterNo = 4
elif startNM_F5 <= wavelength <= stopNM_F5: # Filter 5 [FELH0950]: from 985 - 1800 -- including start, including end
shouldbeFilterNo = 5
else:
self.logger.error('Error: Filter Out Of Range')
if shouldbeFilterNo != filterNo:
self.mono.chooseFilter(shouldbeFilterNo)
# Take data and discard it, this is required to avoid kinks
# Poll data for 5 time constants, second parameter is poll timeout in [ms] (recomended value is 500ms)
dataDict = self.daq.poll(5*self.tc,500)
# Dictionary with ['timestamp']['x']['y']['frequency']['phase']['dio']['trigger']['auxin0']['auxin1']['time']
else:
pass
def monoCheckGrating(self, wavelength): # Grating switching points from GUI
"""Function to update monochromator grating position from GUI defaults.
Parameters
----------
wavelength: float, required
Current wavelength position of monochromator
Returns
--------
None
Raises
------
LoggerError
Raises error if grating commands are invalid or monochromator not connected
"""
gratingNo = self.mono.checkGrating()
startNM_G1 = int(self.ui.startNM_G1.value())
stopNM_G1 = int(self.ui.stopNM_G1.value())
startNM_G2 = int(self.ui.startNM_G2.value())
stopNM_G2 = int(self.ui.stopNM_G2.value())
startNM_G3 = int(self.ui.startNM_G3.value())
stopNM_G3 = int(self.ui.stopNM_G3.value())
if startNM_G1 <= wavelength < stopNM_G1: # Grating 1: from 350 - 549 -- including start, excluding end
shouldbeGratingNo = 1
elif startNM_G2 <= wavelength < stopNM_G2: # Grating 2: from 550 - 1299 -- including start, excluding end
shouldbeGratingNo = 2
elif startNM_G3 <= wavelength <= stopNM_G3: # Grating 3: from 1300 - 1800 -- including start, including end
shouldbeGratingNo = 3
else: # Do I need this?
self.logger.error('Error: Grating Out Of Range')
if shouldbeGratingNo != gratingNo:
self.mono.chooseGrating(shouldbeGratingNo)
# Take data and discard it, this is required to avoid kinks
# Poll data for 5 time constants, second parameter is poll timeout in [ms] (recomended value is 500ms)
dataDict = self.daq.poll(5*self.tc,500)
# Dictionary with ['timestamp']['x']['y']['frequency']['phase']['dio']['trigger']['auxin0']['auxin1']['time']
else:
pass
# -----------------------------------------------------------------------------------------------------------
#### Function to handle filter changes of Thorlabs filter wheel
# -----------------------------------------------------------------------------------------------------------
def thorChangeFilter(self, pos):
"""Function to update position of second filter wheel.
Parameters
----------
pos: int, required
Target filter position, between 1-6
Returns
-------
bool
True if connection to second filter wheel is successful, False otherwise
Raises
------
LoggerError
Raises error if second filter wheel not connected
"""
try:
if not self.filter_connected:
self.logger.exception("External Filter Wheel Not Connected")
return False
self.thorfilterwheel._do_set_position(pos-1) # -1 due to microscope.thorfilterwheel code accepting only 0-5
self.logger.info(f'Thorlabs filterwheel moved to {pos}. position')
return True
except Exception as err:
self.logger.exception("Unexpected error during execution of thorChangeFilter function:")
# -----------------------------------------------------------------------------------------------------------
#### Functions to handle measurement parameter and measurment itself
# -----------------------------------------------------------------------------------------------------------
def MonoHandleCompleteScanButton(self):
"""Function to measure samples with different filters.
Returns
-------
None
"""
try:
self.complete_scan = True
self.ui.imageCompleteScan_start.setPixmap(QtGui.QPixmap("Button_on.png"))
measurement_values = {}
if self.ui.scan_noFilter.isChecked():
self.thorChangeFilter(1)
if self.thorChangeFilter(1):
self.filter_addition = 'no'
self.logger.info('Moving to Open Filter Position')
start_f1 = self.ui.scan_startNM_1.value()
stop_f1 = self.ui.scan_stopNM_1.value()
step_f1 = self.ui.scan_stepNM_1.value()
amp_f1 = self.ui.scan_pickAmp_1.value()
measurement_values['f1']=[start_f1,stop_f1,step_f1,amp_f1]
self.amplification = amp_f1
self.LockinUpdateParameters(self.amplification)
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_f1, stop_f1, step_f1)
self.HandleMeasurement(scan_list, start_f1, stop_f1, step_f1, amp_f1, 3)
if self.ui.scan_Filter2.isChecked():
self.thorChangeFilter(2)
if self.thorChangeFilter(2):
self.filter_addition = str(int(self.ui.cuton_filter_2.value()))
self.logger.info('Moving to %s nm Filter' % self.filter_addition)
start_f2 = self.ui.scan_startNM_2.value()
stop_f2 = self.ui.scan_stopNM_2.value()
step_f2 = self.ui.scan_stepNM_2.value()
amp_f2 = self.ui.scan_pickAmp_2.value()
measurement_values['f2']=[start_f2,stop_f2,step_f2,amp_f2]
self.amplification = amp_f2
self.LockinUpdateParameters(self.amplification)
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_f2, stop_f2, step_f2)
self.HandleMeasurement(scan_list, start_f2, stop_f2, step_f2, amp_f2, 3)
if self.ui.scan_Filter3.isChecked():
self.thorChangeFilter(3)
if self.thorChangeFilter(3):
self.filter_addition = str(int(self.ui.cuton_filter_3.value()))
self.logger.info('Moving to %s nm Filter' % self.filter_addition)
start_f3 = self.ui.scan_startNM_3.value()
stop_f3 = self.ui.scan_stopNM_3.value()
step_f3 = self.ui.scan_stepNM_3.value()
amp_f3 = self.ui.scan_pickAmp_3.value()
measurement_values['f3']=[start_f3,stop_f3,step_f3,amp_f3]
self.amplification = amp_f3
self.LockinUpdateParameters(self.amplification)
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_f3, stop_f3, step_f3)
self.HandleMeasurement(scan_list, start_f3, stop_f3, step_f3, amp_f3, 3)
if self.ui.scan_Filter4.isChecked():
self.thorChangeFilter(4)
if self.thorChangeFilter(4):
self.filter_addition = str(int(self.ui.cuton_filter_4.value()))
self.logger.info('Moving to %s nm Filter' % self.filter_addition)
start_f4 = self.ui.scan_startNM_4.value()
stop_f4 = self.ui.scan_stopNM_4.value()
step_f4 = self.ui.scan_stepNM_4.value()
amp_f4 = self.ui.scan_pickAmp_4.value()
measurement_values['f4']=[start_f4,stop_f4,step_f4,amp_f4]
self.amplification = amp_f4
self.LockinUpdateParameters(self.amplification)
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_f4, stop_f4, step_f4)
self.HandleMeasurement(scan_list, start_f4, stop_f4, step_f4, amp_f4, 3)
if self.ui.scan_Filter5.isChecked():
self.thorChangeFilter(5)
if self.thorChangeFilter(5):
self.filter_addition = str(int(self.ui.cuton_filter_5.value()))
self.logger.info('Moving to %s nm Filter' % self.filter_addition)
start_f5 = self.ui.scan_startNM_5.value()
stop_f5 = self.ui.scan_stopNM_5.value()
step_f5 = self.ui.scan_stepNM_5.value()
amp_f5 = self.ui.scan_pickAmp_5.value()
measurement_values['f5']=[start_f5,stop_f5,step_f5,amp_f5]
self.amplification = amp_f5
self.LockinUpdateParameters(self.amplification)
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_f5, stop_f5, step_f5)
self.HandleMeasurement(scan_list, start_f5, stop_f5, step_f5, amp_f5, 3)
if self.ui.scan_Filter6.isChecked():
self.thorChangeFilter(6)
if self.thorChangeFilter(6):
self.filter_addition = str(int(self.ui.cuton_filter_6.value()))
self.logger.info('Moving to %s nm Filter' % self.filter_addition)
start_f6 = self.ui.scan_startNM_6.value()
stop_f6 = self.ui.scan_stopNM_6.value()
step_f6 = self.ui.scan_stepNM_6.value()
amp_f6 = self.ui.scan_pickAmp_6.value()
measurement_values['f6']=[start_f6,stop_f6,step_f6,amp_f6]
self.amplification = amp_f6
self.LockinUpdateParameters(self.amplification)
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_f6, stop_f6, step_f6)
self.HandleMeasurement(scan_list, start_f6, stop_f6, step_f6, amp_f6, 3)
self.thorChangeFilter(1)
self.logger.info('Moving to open filter')
self.mono.chooseFilter(1)
self.complete_scan = False
self.ui.imageCompleteScan_start.setPixmap(QtGui.QPixmap("Button_off.png"))
self.ui.imageCompleteScan_stop.setPixmap(QtGui.QPixmap("Button_off.png"))
self.logger.info('Finished Measurement')
measurement_parameter = pd.DataFrame.from_dict(measurement_values)
#self.save(measurement_values)
except Exception as err:
self.logger.exception("Unexpected error during execution of MonoHandleCompleteScanButton function:")
def load_naming(self):
"""Function to load naming from directory path
Parameters
----------
None
Returns
-------
None
"""
try:
root = Tk() # Creates master window for tkinters filedialog window
root.withdraw() # Hides master window
filepath = filedialog.askdirectory() # Creates pop-up window to ask for file save
names = filepath.split("/")
self.ui.user.setText(names[5])
self.ui.experiment.setText(names[6])
except Exception as err:
self.logger.exception("Unexpected error during execution of load_naming function:")
def save_mono_parameter(self):
"""Function to save monochromator measurement parameters to file
Parameters
----------
None
Returns
-------
None
Raises
------
LoggerWarning
Raises warning if tkinter saving dialog was closed without entering filename
Notes
-----
Reads the spinbox values and saves them into a file selected via tkinter dialog
"""
try:
measurement_values = {}
if self.ui.scan_noFilter.isChecked():
start_f1 = self.ui.scan_startNM_1.value()
stop_f1 = self.ui.scan_stopNM_1.value()
step_f1 = self.ui.scan_stepNM_1.value()
amp_f1 = self.ui.scan_pickAmp_1.value()
measurement_values['f1']=[start_f1,stop_f1,step_f1,amp_f1]
if self.ui.scan_Filter2.isChecked():
start_f2 = self.ui.scan_startNM_2.value()
stop_f2 = self.ui.scan_stopNM_2.value()
step_f2 = self.ui.scan_stepNM_2.value()
amp_f2 = self.ui.scan_pickAmp_2.value()
measurement_values['f2']=[start_f2,stop_f2,step_f2,amp_f2]
if self.ui.scan_Filter3.isChecked():
start_f3 = self.ui.scan_startNM_3.value()
stop_f3 = self.ui.scan_stopNM_3.value()
step_f3 = self.ui.scan_stepNM_3.value()
amp_f3 = self.ui.scan_pickAmp_3.value()
measurement_values['f3']=[start_f3,stop_f3,step_f3,amp_f3]
if self.ui.scan_Filter4.isChecked():
start_f4 = self.ui.scan_startNM_4.value()
stop_f4 = self.ui.scan_stopNM_4.value()
step_f4 = self.ui.scan_stepNM_4.value()
amp_f4 = self.ui.scan_pickAmp_4.value()
measurement_values['f4']=[start_f4,stop_f4,step_f4,amp_f4]
if self.ui.scan_Filter5.isChecked():
start_f5 = self.ui.scan_startNM_5.value()
stop_f5 = self.ui.scan_stopNM_5.value()
step_f5 = self.ui.scan_stepNM_5.value()
amp_f5 = self.ui.scan_pickAmp_5.value()
measurement_values['f5']=[start_f5,stop_f5,step_f5,amp_f5]
if self.ui.scan_Filter6.isChecked():
start_f6 = self.ui.scan_startNM_6.value()
stop_f6 = self.ui.scan_stopNM_6.value()
step_f6 = self.ui.scan_stepNM_6.value()
amp_f6 = self.ui.scan_pickAmp_6.value()
measurement_values['f6']=[start_f6,stop_f6,step_f6,amp_f6]
measurement_parameter = pd.DataFrame.from_dict(measurement_values)
root = Tk() # Creates master window for tkinters filedialog window
root.withdraw() # Hides master window
filepath = filedialog.asksaveasfilename() # Creates pop-up window to ask for file save
# This somehow destroys the Qt event manager, error message:
# "QCoreApplication::exec: The event loop is already running"
# self.filename = str(input('What is the name of this measurement routine ?: '))
# if self.path.exists() not:
# os.
measurement_parameter.to_csv(filepath, index= False)
self.logger.info('Saved measurement parameter into: '+ filepath)
except FileNotFoundError:
self.logger.warning('No parameters were safed due to missing filename')
except Exception as err:
self.logger.exception("Unexpected error during execution of save_mono_parameter function:")
def load_mono_parameter(self):
"""Function to load monochromator measurement parameters from file.
Parameters
----------
None
Returns
-------
None
Notes
-----
Selects a file via tkinter dialog, reads the values and sets measurement parameters
"""
try:
root = Tk() # Creates master window for tkinters filedialog window
root.withdraw() # Hides master window
filepath = filedialog.askopenfilename() # Creates pop-up window to ask for file save
measurement_parameters = pd.read_csv(filepath)
if self.ui.scan_noFilter.isChecked():
self.ui.scan_startNM_1.setValue(measurement_parameters['f1'][0])
self.ui.scan_stopNM_1.setValue(measurement_parameters['f1'][1])
self.ui.scan_stepNM_1.setValue(measurement_parameters['f1'][2])
self.ui.scan_pickAmp_1.setValue(measurement_parameters['f1'][3])
if self.ui.scan_Filter2.isChecked():
self.ui.scan_startNM_2.setValue(measurement_parameters['f2'][0])
self.ui.scan_stopNM_2.setValue(measurement_parameters['f2'][1])
self.ui.scan_stepNM_2.setValue(measurement_parameters['f2'][2])
self.ui.scan_pickAmp_2.setValue(measurement_parameters['f2'][3])
if self.ui.scan_Filter3.isChecked():
self.ui.scan_startNM_3.setValue(measurement_parameters['f3'][0])
self.ui.scan_stopNM_3.setValue(measurement_parameters['f3'][1])
self.ui.scan_stepNM_3.setValue(measurement_parameters['f3'][2])
self.ui.scan_pickAmp_3.setValue(measurement_parameters['f3'][3])
if self.ui.scan_Filter4.isChecked():
self.ui.scan_startNM_4.setValue(measurement_parameters['f4'][0])
self.ui.scan_stopNM_4.setValue(measurement_parameters['f4'][1])
self.ui.scan_stepNM_4.setValue(measurement_parameters['f4'][2])
self.ui.scan_pickAmp_4.setValue(measurement_parameters['f4'][3])
if self.ui.scan_Filter5.isChecked():
self.ui.scan_startNM_5.setValue(measurement_parameters['f5'][0])
self.ui.scan_stopNM_5.setValue(measurement_parameters['f5'][1])
self.ui.scan_stepNM_5.setValue(measurement_parameters['f5'][2])
self.ui.scan_pickAmp_5.setValue(measurement_parameters['f5'][3])
if self.ui.scan_Filter6.isChecked():
self.ui.scan_startNM_6.setValue(measurement_parameters['f6'][0])
self.ui.scan_stopNM_6.setValue(measurement_parameters['f6'][1])
self.ui.scan_stepNM_6.setValue(measurement_parameters['f6'][2])
self.ui.scan_pickAmp_6.setValue(measurement_parameters['f6'][3])
except Exception as err:
self.logger.exception("Unexpected error during execution of load_mono_parameter function:")
# General function to create scanning list
def createScanJob(self, start, stop, step):
"""Function to compile scan parameters.
Parameters
----------
start: float, required
Wavelength start value
stop: float, required
Wavelength stop value
step: float, required
Wavelength step value
Returns
-------
List
List of integer wavelength values
"""
scan_list = []
number = int((stop-start)/step)
for n in range(-1, number + 1):
# -1 to start from before the beginning, +1 to include the last iteration of 'number', [and +2 to go above stop (this can
# be changed later])
wavelength = start + n*step
scan_list.append(wavelength)
return scan_list
# -----------------------------------------------------------------------------------------------------------
#### Functions to handle measurement
# -----------------------------------------------------------------------------------------------------------
# Measure LOCKIN response
def HandleMeasurement(self, scan_list, start, stop, step, amp, number):
"""Function to prepare sample measurement.
Parameters
----------
scan_list: list of ints, required
List of wavelength values to scan
start: float, required
Wavelength start value
stop: float, required
Wavelength stop value
step: float, required
Wavelength step value
amp: float, required
Pre-amplifier amplification value
number: int, required
Specifier to decide if power value is calculated (1) or not (0)