-
Notifications
You must be signed in to change notification settings - Fork 1
/
Experimental_UI.py
1946 lines (1602 loc) · 99.6 KB
/
Experimental_UI.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
'''
Created on 13 Aug 2016
@author: apc
'''
import Tkinter as tk
import ttk
import tkMessageBox
import math
# import matlab.engine
import numpy as np
import copy
import re
import os
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import matplotlib.pyplot as plt
from Config import AbsorbtionImagingReader, PhotonProductionReader, ExperimentalAutomationReader
from ToolTip_UI import ToolTip
from PIL import Image, ImageTk
from DAQ import DaqPlayException
from ExperiementalRunner import PhotonProductionExperiment, AbsorbtionImagingExperiment, ExperimentalAutomationRunner
from _abcoll import Sequence
from atom.event import Event
from win32inetcon import STICKY_CACHE_ENTRY
from _hotshot import resolution
from instruments.pyicic.IC_ImagingControl import IC_ImagingControl
from instruments.WX218x.WX218x_awg import WX218x_awg, Channel
from instruments.WX218x.WX218x_DLL import WX218x_OutputMode, WX218x_OperationMode, WX218x_Waveform
from Tkinter import StringVar
from ScrolledText import ScrolledText
import threading
import Queue
import time
from msilib import init_database
import tkFileDialog
class Experimental_UI(tk.LabelFrame):
def __init__(self, parent, daq_ui, sequence_ui, photon_produciton_configuration_fname, absorbtion_imaging_config_fname,
ic_imaging_control=None, text="Experimental Actions", font=("Helvetica", 16), development_mode=False, **kwargs):
tk.LabelFrame.__init__(self, parent, text=text, font=font, **kwargs)
self.parent = parent
self.daq_ui = daq_ui
self.sequence_ui = sequence_ui
self.absorbtion_imaging_config = AbsorbtionImagingReader(absorbtion_imaging_config_fname).get_absorbtion_imaging_configuration()
self.photon_production_config = PhotonProductionReader(photon_produciton_configuration_fname).get_photon_production_configuration()
self.ic_ic = ic_imaging_control
'''Add buttons to set and run the experimental sequence'''
butt_opts = {'font': ("Helvetica", 12), 'height':25, 'width':150, 'compound': tk.LEFT}
grid_opts = {'padx':5, 'pady':2, 'sticky':tk.E+tk.W}
icon = Image.open("icons/graph_icon.png").resize((30,30))
icon = ImageTk.PhotoImage(icon)
self.set_seq_button = tk.Button(self, image=icon, text="Set sequence", command=self.openSeqWindow, background='green4', **butt_opts)
self.set_seq_button.image = icon # store the image as a variable in the widget to prevent garbage collection.
icon = Image.open("icons/play_icon.png").resize((30,30))
icon = ImageTk.PhotoImage(icon)
self.run_seq_button = tk.Button(self, image=icon, text="Run sequence", command=self.runSeq, background='green2', **butt_opts)
self.run_seq_button.image = icon # store the image as a variable in the widget to prevent garbage collection.
self.run_auto_exp_button = tk.Button(self, image=icon, text="Run automated exp.", command=self.runAutomatedExp, background='green1', **butt_opts)
self.run_auto_exp_button.image = icon # store the image as a variable in the widget to prevent garbage collection.
icon = Image.open("icons/config_icon.png").resize((30,30))
icon = ImageTk.PhotoImage(icon)
self.configure_photon_production_button = tk.Button(self, image=icon, width=25, height=25, command=self.photonProductionConfigButton, background='green2')
self.configure_photon_production_button.image = icon
self.total_iterations_frame = Frame_ExperimentalParam(self, 'Num. iterations', initVal=self.photon_production_config.iterations, dataType=int,
helpText='The number of times the experimental sequence will be run.',
action = lambda entry_value: self.photon_production_config.set_iterations(entry_value))
self.reload_time_frame = Frame_ExperimentalParam(self, 'MOT reload time (ms):', initVal = self.photon_production_config.mot_reload*10**-3, dataType=float,
helpText='The delay between sucsessive iterations.',
action = lambda entry_value: self.photon_production_config.set_mot_reload(entry_value*10**3))
icon = Image.open("icons/play_icon.png").resize((30,30))
icon = ImageTk.PhotoImage(icon)
self.run_abs_img_button = tk.Button(self, image=icon, text="Run abs. imaging", command=self.runAbsorbtionImaging, background='deep sky blue', **butt_opts)
self.test_bkg_button = tk.Button(self, image=icon, text="Test background", command=lambda: self.runAbsorbtionImaging(bkg_test=True), background='light sky blue', **butt_opts)
icon = Image.open("icons/config_icon.png").resize((30,30))
icon = ImageTk.PhotoImage(icon)
self.configure_abs_img_button = tk.Button(self, image=icon, width=25, height=25, command=self.absorbtionImagingConfigButton, background='deep sky blue')
self.configure_abs_img_button.image = icon
self.set_seq_button.grid(row=0,column=0,**grid_opts)
self.run_seq_button.grid(row=1,column=0,**grid_opts)
self.run_auto_exp_button.grid(row=2,column=0,**grid_opts)
self.configure_photon_production_button.grid(row=1,column=1,**grid_opts)
self.total_iterations_frame.grid(row=3,column=0,**grid_opts)
self.reload_time_frame.grid(row=4,column=0,**grid_opts)
self.test_bkg_button.grid(row=0,column=2, **grid_opts)
self.run_abs_img_button.grid(row=1,column=2, **grid_opts)
self.configure_abs_img_button.grid(row=1,column=3)
self.grid_columnconfigure(0, weight=1, uniform='button_col')
self.grid_columnconfigure(1, weight=1)
self.grid_columnconfigure(2, weight=1, uniform='button_col')
self.grid_columnconfigure(3, weight=1)
self.grid_columnconfigure(4, weight=1)
# self.test_abs_imaging_review_ui_button = tk.Button(self, text="Test abs img review", command=self.testAbsorbtionImagingReviewUI, background='deep sky blue')
# Create a placeholder to store an awg object for running run tones.
# self.run_tone_awg = None
# self.run_tone_freq = 75.25*10**6
# def set_run_tone_freq(freq):
# self.run_tone_freq=freq*10**6
# self.toggle_run_tone_button = tk.Button(self, text="Send run tone", command=self.toggleRunTone, background='red')
#
# self.run_tone_freq_frame = Frame_ExperimentalParam(self, 'Run tone freq (MHz)', initVal=self.run_tone_freq*10**-6, dataType=float,
# helpText='The run tone frequency in MHz.',
# action = lambda entry_value, f=set_run_tone_freq: f(entry_value))
#
#
# # self.test_abs_imaging_review_ui_button.grid(row=0,column=3, **grid_opts)
# self.toggle_run_tone_button.grid(row=1,column=4, **grid_opts)
# self.run_tone_freq_frame.grid(row=2,column=4, **grid_opts)
self.run_tones_frame = rtf = tk.LabelFrame(self,text="Run tones", font=("Helvetica", 12))
rtf_butt_opts = {'font': ("Helvetica", 12), 'height':25, 'width':150, 'compound': tk.LEFT}
rtf_grid_opts = {'padx':5, 'pady':2, 'sticky':tk.E+tk.W}
self.run_tone_awg = None
self.run_tone_freqs = [75.25*10**6, 106*10**6, 125.75*10**6, 75.25*10**6]
self.run_tone_output_states= [False, False, False, False]
self.run_tone_buttons = []
self.on_icon = ImageTk.PhotoImage(Image.open("icons/toggle_on_icon.png").resize((25,20)))
self.off_icon = ImageTk.PhotoImage(Image.open("icons/toggle_off_icon.png").resize((25,20)))
def set_run_tone_freq(ch, freq):
self.run_tone_freqs[ch]=freq*10**6
for i in range(4):
run_tone_freq_frame = Frame_ExperimentalParam(rtf, 'channel{0} freq(MHz)'.format(i+1), initVal=self.run_tone_freqs[i]*10**-6, dataType=float,
helpText='The run tone frequency in MHz.',
action = lambda entry_value, ch=i, f=set_run_tone_freq: f(ch, entry_value))
toggle_run_tone_button = tk.Button(rtf, image=self.off_icon, background='red', relief=tk.RAISED, width=28)
toggle_run_tone_button.config(command=lambda button=toggle_run_tone_button, i_ch=i: self.toggleRunTone(button, i_ch))
self.run_tone_buttons.append(toggle_run_tone_button)
run_tone_freq_frame.grid(row=i, column=0, **rtf_grid_opts)
toggle_run_tone_button.grid(row=i, column=1, **rtf_grid_opts)
rtf.grid_columnconfigure(0, weight=1)
rtf.grid_columnconfigure(1, weight=1)
rtf.grid(row=0, column=4, rowspan=3, **grid_opts)
def openSeqWindow(self):
if self.sequence_ui.configured_channel_labels != self.daq_ui.daq_controller.getChannelNumberNameDict(onlyVisable=False):
self.sequence_ui.configureForNewChannelLabels(self.daq_ui.daq_controller.getChannelNumberNameDict(onlyVisable=False))
if self.sequence_ui.configured_channel_calibrations != self.daq_ui.daq_controller.getChannelCalibrationDict():
self.sequence_ui.configureForNewChannelCalibrations(self.daq_ui.daq_controller.getChannelCalibrationDict())
self.sequence_ui.openWindow()
def runExperiment(self, photon_production_experiment, liveUI=True, autoCloseLiveUI=False):
'''
Run a photon production experiment. There is a some layered architecture here to be aware of if you
change code (threading can cause very confused computers if done wrong...). Basically we create two
objects:
1. PhotonProductionExperiment - this runner knows nothing about the UI, it simply configures the
instruments (.configure()), runs the experiment (.run()/.run_in_thread()), and tidies up after
itself (.close()). If we use .run() the program holds until the run() method returns (i.e. we
can not stop the experiment, poll it on-the-fly etc). run_in_thead runs the same code in a
separate thread, releasing the main thread (this one!) to keep going. In this case it is vital
we wait for the experimental thread to terminate before we try to close the experiment. This
is done with the <Thread object>.join() method.
2. Photon_produduction_live_UI - this is a top level window for on the fly control/analysis of
an experiment. It takes a PhotonProductionExperiment in order to either
- tell it to stop running / change the number of iterations to run
- poll it for new data, then use this to update the UI.
Note for completeness: to avoid timing issues between taking/saving the data, the PhotonProductionExperiment
spawns a new thread to save every iterations data to file.
'''
photon_production_experiment.configure()
if liveUI: experiment_live_ui = Photon_produduction_live_UI(self,
photon_produciton_experiment=photon_production_experiment,
auto_close=autoCloseLiveUI)
experiment_thread = photon_production_experiment.run_in_thread()
# Small delay to ensure the photon_production_experiment is flagged as live before the UI starts polling it.
# Otherwise the UI can think it's already over and not update!
time.sleep(0.1)
if liveUI:
experiment_live_ui.poll_live_data()
# Wait for the live window to close!
self.winfo_toplevel().wait_window(experiment_live_ui)
# Wait for the experimental thread to finish - though if the window is
# shut the photon_production_experiment really should be done!
experiment_thread.join()
# photon_production_experiment.close()
# experiment_live_ui.closeWindow()
def runSeq(self, liveUI=True, autoCloseLiveUI=False):
# If run tone is on, turn it off!
for state, button in zip(self.run_tone_output_states, self.run_tone_buttons):
if state:
button.invoke()
experiment = PhotonProductionExperiment(daq_controller=self.daq_ui.daq_controller,
sequence=self.sequence_ui.sequence,
photon_production_configuration=self.photon_production_config)
self.runExperiment(experiment, liveUI, autoCloseLiveUI)
def runAutomatedExp(self, liveUI=True):
fname = tkFileDialog.askopenfilename(master=self, title="Choose an Experimental Automation Configuration",
initialdir=os.path.join(os.getcwd(),"/configs/experimental automation"))
# Check for empty filenames (i.e. when the user cancelled the action)
if fname!= '':
experimental_automation_configuration = ExperimentalAutomationReader(fname).get_experimental_automation_configuration()
# Note we pass a copy of the photon production configuration so every different experiement can
# edit the parameters without effecting the top level settings.
automated_experiment = ExperimentalAutomationRunner(daq_controller=self.daq_ui.daq_controller,
experimental_automation_configuration=experimental_automation_configuration,
photon_production_configuration=copy.copy(self.photon_production_config))
start_automated_experiment = tkMessageBox.askyesno('Start automated experiment',\
'Please confirm whether you would like to start an automated experiment.\n' + \
'This will consist of {0} independent sequences and a total of {1} MOT throws'.\
format(automated_experiment.experiements_to_run,
automated_experiment.get_total_iterations()),
parent = self)
# Confirm the user wishes to run the automated experiment
if start_automated_experiment in (None, False):
return
elif start_automated_experiment:
# If run tone is on, turn it off!
if self.run_tone_awg:
self.toggle_run_tone_button()
automated_experiment.write_to_summary_file('\nStarting automated experiment at {0}\n\n'.format(time.strftime("%H-%M-%S")))
run_next_experiment = True
# Run all the queued experiements until we are done or one is manually stopped
while automated_experiment.has_next_experiment() and run_next_experiment:
# Get and run next experiment
experiment, seq_fname, modulation_frequencies = automated_experiment.get_next_experiment()
self.runExperiment(experiment, liveUI, autoCloseLiveUI=True)
run_next_experiment = not experiment.forced_stop
# Log experiment
automated_experiment.write_to_summary_file(
('Experiment {0}:\n' +
' time: {1}\n' +
' sequence: {2}\n' +
' iterations: {3}\n' +
' mot reload: {4}\n' +
' modulation frequencies: {5}\n').\
format(automated_experiment.experiements_iter,
experiment.data_saver.experiment_time,
seq_fname,
experiment.iterations,
experiment.mot_reload_time,
modulation_frequencies))
automated_experiment.close()
print 'Finished automated experiment.'
automated_experiment.write_to_summary_file('\nFinished automated experiment at {0}\n\n'.format(time.strftime("%H-%M-%S")))
def runAbsorbtionImaging(self, bkg_test=False):
experiment = AbsorbtionImagingExperiment(daq_controller = self.daq_ui.daq_controller,
sequence = self.sequence_ui.sequence,
absorbtion_imaging_configuration=self.absorbtion_imaging_config,
ic_imaging_control=self.ic_ic)
experiment.run(bkg_test=bkg_test)
if self.absorbtion_imaging_config.review_processed_images or bkg_test:
absorbtion_imaging_review_UI = Absorbtion_imaging_review_UI(self, experiment)
self.winfo_toplevel().wait_window(absorbtion_imaging_review_UI)
def testAbsorbtionImagingReviewUI(self):
import glob
import os
import re
dir = r'C:\Users\apc\Documents\Python Scripts\Cold Control Heavy\data\Absorbtion images\22-08-16\17-42-39'
# dir = r'C:\Users\apc\Documents\Python Scripts\Cold Control Heavy\data\Absorbtion images\26-08-16\15-12-27\raw'
img_arrs, bkg_arrs, img_labels, bkg_labels = [],[],[],[]
for filename in sorted(glob.glob(os.path.join(dir, '*.bmp')), key=lambda x: int(re.findall(r'\d+', x)[-1])):
img_labels.append(os.path.split(filename)[1])
# img_arrs.append(np.array(Image.open(filename)))
img_arrs.append(np.array(Image.open(filename).convert('L')))
for directory in sorted(glob.glob(os.path.join(dir, '*-backgrounds')), key=lambda x: int(re.findall(r'\d+', x)[-1])):
bkgs = []
bkg_labels.append(os.path.split(directory)[1])
for filename in glob.glob(os.path.join(directory, '*.bmp')):
# bkgs.append(np.array(Image.open(filename)))
bkgs.append(np.array(Image.open(filename).convert('L')))
bkg_arrs.append(bkgs)
bkg_aves = [sum([b.astype(np.float)/len(bkgs) for b in bkgs]) for bkgs in bkg_arrs]
unscaled_corr_imgs = [np.clip(np.round(bkg.astype(np.float) - img.astype(np.float)),0,255) for img, bkg in zip(img_arrs, bkg_aves)]
corr_imgs = [(arr * 255.0/arr.max()).astype(np.uint8) for arr in unscaled_corr_imgs]
class MockAbsImgExperiment(object):
def __init__(self, img_arrs, bkg_arrs, sequence_labels):
print 'Performed mock photon_production_experiment, genrating {0} images, each with dimensions {1}.'.format(len(img_arrs), img_arrs[0].shape)
self.img_arrs = img_arrs
self.bkg_arrs = bkg_arrs
self.sequence_labels = sequence_labels
self.results_ready = True
def getResults(self):
return self.img_arrs, self.bkg_arrs, self.sequence_labels
def saveProcessedImages(self, notes=None):
if notes:
print 'Save notes:', notes
print 'Saved processed images.'
mock = MockAbsImgExperiment(corr_imgs, bkg_aves, img_labels)
absorbtion_imaging_review_UI = Absorbtion_imaging_review_UI(self, mock)
self.winfo_toplevel().wait_window(absorbtion_imaging_review_UI)
def toggleRunTone(self, button, i_ch):
# No run_tone_awg configured, so make one and start the run tone
channel = Channel.values()[i_ch]
if self.run_tone_output_states[i_ch] == False:
if self.run_tone_awg == None:
self.run_tone_awg = awg = WX218x_awg()
awg.open(reset=False)
awg.configure_sample_rate(1.25*10**9)
awg.configure_output_mode(WX218x_OutputMode.FUNCTION)
else:
awg = self.run_tone_awg
freq = self.run_tone_freqs[i_ch]
print 'Sending run tone to {0} at {1}MHz'.format(channel, freq*10**-6)
awg.configure_standard_waveform(channel, WX218x_Waveform.SINE, frequency=freq, amplitude=2)
awg.configure_operation_mode(channel, WX218x_OperationMode.CONTINUOUS)
awg.enable_channel(channel)
self.run_tone_output_states[i_ch] = True
button.configure(bg='green', image=self.on_icon, relief=tk.SUNKEN)
else:
print 'Turning off run tone on {0}'.format(channel)
self.run_tone_awg.disable_channel(channel)
self.run_tone_output_states[i_ch] = False
if True not in self.run_tone_output_states:
# Reset the awg operation mode - this is required for sequences to run properly after using a run tone.
for channel in Channel.values():
self.run_tone_awg.configure_operation_mode(channel, WX218x_OperationMode.BURST)
self.run_tone_awg.close()
print 'Connection to AWG closed.'
self.run_tone_awg = None
button.configure(bg='red', image=self.off_icon, relief=tk.RAISED)
def photonProductionConfigButton(self):
config_UI = Photon_production_configuration_UI(self,
photon_production_configuration=self.photon_production_config
)
self.winfo_toplevel().wait_window(config_UI.top)
# If the user asked for their changes to be applied, set the absorbtion imaging config accordingly.
if config_UI.apply_changes:
self.photon_production_config = config_UI.photon_production_config
self.total_iterations_frame.entryWid.delete(0, tk.END)
self.total_iterations_frame.entryWid.insert(0, self.photon_production_config.iterations)
self.reload_time_frame.entryWid.delete(0, tk.END)
self.reload_time_frame.entryWid.insert(0, self.photon_production_config.mot_reload*10**-3)
def absorbtionImagingConfigButton(self):
config_UI = Absorbtion_imaging_configuration_UI(self,
absorbtion_imaging_configuration=self.absorbtion_imaging_config,
daq_controller=self.daq_ui.daq_controller,
sequence_length = self.sequence_ui.sequence.getLength(),
sequence_t_step = self.sequence_ui.sequence.t_step
)
self.winfo_toplevel().wait_window(config_UI.top)
# If the user asked for their changes to be applied, set the absorbtion imaging config accordingly.
if config_UI.apply_changes:
self.absorbtion_imaging_config = config_UI.config
# def openMotTempGUI(self):
# eng = matlab.engine.start_matlab()
# eng.addpath(eng.genpath(r'externals'), nargout=0)
# eng.motTempGUI()
# eng.quit()
class Frame_ExperimentalParam(tk.Frame):
'''
A sub-class of a Tkinter.Frame to create entry widgets and decorations for setting experimental numerical values.
label - The text to label the entry widget with
initVal - The initial value of the entry
dataType - The type expected by the entry (used for validation).
helpText - The info displayed when the user hovers the mouse.
action - A function called with the value of the widget as it's only arg, when a valid entry
is made. If no function is to be called, set action to None.
e.g. action = lambda entry_value: myAction(entry_value)
'''
def __init__(self, parent, label, initVal=1, dataType=int, helpText=None, action=None, state=tk.NORMAL, **kwargs):
tk.Frame.__init__(self, parent, **kwargs)
self.label = label
self.dataType = dataType
#
# if not self.dataType in [int, float, str]:
# raise Exception('Invalid number type specified.')
#
self.value = initVal
self.entryWid = tk.Entry(self, width=7)
self.entryWid.insert(0, self.value)
self.entryWid.configure(state=state)
self.labelWid = tk.Label(self, width=20, text=self.label, anchor='w')
self.entryWid.bind("<FocusOut>", self.validate)
self.entryWid.bind("<Return>", self.validate)
self.entryWid.bind("<Up>", self.arrowKey)
self.entryWid.bind("<Down>", self.arrowKey)
self.labelWid.grid(row=0,column=0)
self.entryWid.grid(row=0,column=1)
self.grid_columnconfigure(0, weight=0)
self.grid_columnconfigure(1, weight=1, pad=2)
if helpText != None:
self.tooltip = ToolTip(self, helpText)
self.action = action
def updateEntry(self, value):
entryState = self.entryWid.cget('state')
self.entryWid.configure(state=tk.NORMAL)
self.entryWid.delete(0, tk.END)
self.entryWid.insert(0, value)
self.entryWid.configure(state=entryState)
self.validate()
def validate(self, params=None):
'''
Ensure the widget value is in the right number form - if so update the frames value,
otherwise revert to the last valid entry and flash red to show an error.
'''
try:
self.value = self.dataType(self.entryWid.get())
self.flash('green')
# Call the action function if one is configured.
if self.action:
self.action(self.value)
except (ValueError, NameError):
self.entryWid.delete(0, tk.END)
self.entryWid.insert(0, self.value)
self.flash('red')
def flash(self, col, length=500):
'''
Flashes the background of the entry widget a colour (col) for a length of time (length) in ms.
Usually used during validation to indicate whether the new value entered is valid.
'''
self.entryWid.config(bg=col)
self.entryWid.after(length, lambda: self.entryWid.configure(bg='white'))
def arrowKey(self, event):
'''
Called when the Up or Down arrow key is pressed.
Increments the value on the DAQ channel accordingly.
'''
if self.dataType in (int, float):
# Count the number of places between the decimal place in the float and the cursor index
# to calculate the order of the incrementation, i.e 0.01,0.1,1,10,...ect.
# Try/Except to handle the case when there is no decimal point shown.
try:
decimalIndex = self.entryWid.get().index('.')
except ValueError:
decimalIndex = len(self.entryWid.get())
cursorIndex = self.entryWid.index(tk.INSERT)
incrementOrder = decimalIndex - cursorIndex
# If the increment order is -1 the cursor is on the decimal point so do nothing.
if incrementOrder != -1:
if incrementOrder < -1:
incrementOrder += 1
# Caculate the amount to change the value by. The sign is determined by the key pressed.
iterator = math.pow(10, incrementOrder) if event.keysym == "Up" \
else -1 * math.pow(10, incrementOrder)
currentValue = self.entryWid.get()
# We have to count the number of decimal points of the number and found the iterated
# value back to this level due to Python's imprecision with floats.
ndp = currentValue[::-1].find('.')
if ndp < 0: ndp=0
self.entryWid.delete(0, tk.END)
self.entryWid.insert(0, self.dataType(round(float(currentValue) + iterator, ndp)))
self.validate(event)
self.entryWid.icursor(cursorIndex)
class Photon_production_configuration_UI(object):
def __init__(self, parent, photon_production_configuration):
'''This object presents for editing the settings for photon production experiments. It takes and edits a
copy of the Photon Production Configuration. A flag then exists to indicate whether the user wants these
edits to be applied or not when the window is closed.'''
self
# A flag that denotes is the user confirms or cancels edits they make in this window when exiting.
self.apply_changes = False
self.photon_production_config = self.php_c = copy.copy(photon_production_configuration)
self.tdc_config = self.tdc_c = copy.copy(photon_production_configuration.tdc_configuration)
self.awg_config = self.awg_c = copy.copy(photon_production_configuration.awg_configuration)
self.top = self.configureWindow(parent)
self.top.wm_title("Photon production configuration")
self.top.grab_set()
# Changes the close button to call my close function.
self.top.protocol('WM_DELETE_WINDOW', self.closeWindow);
def configureWindow(self, parent):
'''
Build all the widget enteries for this UI.
'''
top = tk.Toplevel(parent)
frame = tk.Frame(top)
label_frame_font_opts = ("Helvetica", 12, "bold", "italic")
gen_frame = tk.LabelFrame(top, text="General", font=label_frame_font_opts)
awg_frame = tk.LabelFrame(top, text="AWG", font=label_frame_font_opts)
tdc_frame = tk.LabelFrame(top, text="TDC", font=label_frame_font_opts)
wfm_frame = tk.LabelFrame(top, text="Waveform", font=label_frame_font_opts)
gen_widgets, awg_widgets, tdc_widgets, wfm_widgets = [], [], [], []
##############################################################################
# GENERAL
##############################################################################
gen_widgets.append(Frame_ExperimentalParam(gen_frame,
label='Save location:',
initVal=self.php_c.save_location,
dataType=str,
helpText='Save location of experimental data.',
action=None,
state=tk.DISABLED))
gen_widgets.append(Frame_ExperimentalParam(gen_frame,
label='Iterations:',
initVal=self.php_c.iterations,
dataType=int,
helpText='Total number of iterations the experiment is run for.',
action= lambda entry_value: self.php_c.set_iterations(entry_value)))
gen_widgets.append(Frame_ExperimentalParam(gen_frame,
label='MOT reload (ms):',
initVal=self.php_c.mot_reload*10**-3,
dataType=float,
helpText='How long the MOT is loaded for.',
action= lambda entry_value: self.php_c.set_mot_reload(entry_value*10**3)))
##############################################################################
# AWG
##############################################################################
awg_widgets.append(Frame_ExperimentalParam(awg_frame,
label='Burst count:',
initVal=self.awg_c.burst_count,
dataType=int,
helpText='How many times the loaded waveform is output from the AWG per trigger pulse.',
action= lambda entry_value: self.awg_c.set_burst_count(entry_value)))
awg_widgets.append(Frame_ExperimentalParam(awg_frame,
label='Sample rate (GHz):',
initVal=self.awg_c.sample_rate*10**-9,
dataType=float,
helpText='The sample rate of the AWG. 1.25GHz is the maximum allowed.',
action= lambda entry_value: self.awg_c.set_sample_rate(entry_value*10**9)))
# TODO add waveform window
##############################################################################
# TDC
##############################################################################
# self.counter_channels = counter_channels
# self.marker_channel = marker_channel
tdc_widgets.append(Frame_ExperimentalParam(tdc_frame,
label='Counter channels:',
initVal=[x+1 for x in self.tdc_c.counter_channels],
dataType=lambda entry: map(int, list(eval(entry))),
helpText='Channels with SPCM\'s connected.\n' +\
'Channels 1-8 on box correspond to 0-7 in config files.\n' +\
'Please use the numbering convention 1-8 in this field.',
action= lambda entry_value: self.tdc_c.set_counter_channels([x-1 for x in entry_value])
))
tdc_widgets.append(Frame_ExperimentalParam(tdc_frame,
label='Marker channel:',
initVal=self.tdc_c.marker_channel,
dataType=int,
helpText='The channel into which a marker pulse for each photon generation pulse is input.\n' +\
'Channels 1-8 on box correspond to 0-7 in config files.\n' +\
'Please use the numbering convention 1-8 in this field.',
action= lambda entry_value: self.tdc_c.set_marker_channel(entry_value)
))
##############################################################################
# Waveforms
##############################################################################
wfm_widgets.append(Frame_ExperimentalParam(wfm_frame,
label='Waveform sequence:',
initVal=self.php_c.waveform_sequence,
dataType=list,
helpText='The order of waveforms through which the AWG will cycle.',
action=None,
state=tk.DISABLED
))
gen_widgets.append(Frame_ExperimentalParam(gen_frame,
label='Interleave waveforms:',
initVal=str(bool(self.php_c.interleave_waveforms)),
dataType=str,
helpText='Whether the waveforms are interleaved on alternate channels, one at a a time.',
action=None,
state=tk.DISABLED))
wfm_label_frame_font_opts = ("Helvetica", 10, "italic")
for i, wfm in [(i, self.php_c.waveforms[i]) for i in range(len(self.php_c.waveforms))]:
frame = tk.LabelFrame(wfm_frame, text="{0}".format(i), font=label_frame_font_opts)
wfm_fname_frame = tk.Frame(frame)
wfm_fname_wid = Frame_ExperimentalParam(wfm_fname_frame,
label='Waveform location:',
initVal=wfm.fname,
dataType=str,
helpText='Loaction of the waveform data',
action=None,
state=tk.DISABLED)
wfm_fname_wid.pack(side=tk.LEFT)
icon = Image.open("icons/folder_icon.png").resize((20,20))
icon = ImageTk.PhotoImage(icon)
load_wfm_button = tk.Button(wfm_fname_frame, image=icon,
command = lambda wfm=wfm, wid=wfm_fname_wid : self.loadWaveform(wfm, wid),
height=16, width=16)
load_wfm_button.image = icon # store the image as a variable in the widget to prevent garbage collection.
load_wfm_button.pack(side=tk.RIGHT)
wfm_mod_freq_wid = Frame_ExperimentalParam(frame,
label='Mod. frequency (MHz):',
initVal=wfm.get_mod_frequency()*10**-6,
dataType=float,
helpText='The frequency with which to modulate the waveform.',
action= lambda entry_value, wfm=wfm: wfm.set_mod_frequency(entry_value*10**6))
wfm_fname_frame.pack()
wfm_mod_freq_wid.pack()
wfm_widgets.append(frame)
for wid in gen_widgets + awg_widgets + tdc_widgets + wfm_widgets:
wid.pack()
button_frame = tk.Frame(top)
apply_button = tk.Button(button_frame, text='Apply', command=self.apply, width=15, bg='green')
cancel_button = tk.Button(button_frame, text='Cancel', command=self.cancel, width=15, bg='red')
apply_button.grid(row=0, column=0, sticky=tk.E)
cancel_button.grid(row=1, column=0, sticky=tk.E)
r=1
for frame in [gen_frame, awg_frame, wfm_frame, tdc_frame, button_frame]:
frame.grid(row=r, column=0, sticky=tk.E+tk.W)
r += 1
return top
def loadWaveform(self, wfm, wfm_fname_wid):
fname = tkFileDialog.askopenfilename(master=self.top, title="Load a sequence", initialdir="waveforms")
# Check for empty filenames (i.e. when the user cancelled the action)
if fname!= '':
wfm.set_fname(fname)
wfm_fname_wid.updateEntry(fname)
# Seems to be a tkinter bug that the parent is shown on top after a file dialog - so let's fix that
self.top.lift(self.top.master)
def displayWarning(self, message, delay=4000):
'''Create an unobtrusive warning label that disappears after a delay.'''
n_col, n_row = self.top.grid_size()
warningLabel = tk.Label(self.top, text=message, bg='yellow', height=1)
warningLabel.grid(row=n_row,column=0,columnspan=n_col, sticky=tk.N+tk.E+tk.W+tk.S)
self.top.after(delay, warningLabel.destroy)
def apply(self):
self.apply_changes = True
self.closeWindow(False)
def cancel(self):
self.apply_changes = False
self.closeWindow(False)
def closeWindow(self, ask_to_apply_changes = True):
"""Close the top window."""
if ask_to_apply_changes:
apply_on_exit = tkMessageBox.askyesnocancel('Confirm exit',\
'Would you like to apply your changes before you exit?',
parent = self.top)
if apply_on_exit == None:
return
elif apply_on_exit:
self.apply_changes = True
self.php_c.awg_configuration = self.awg_c
self.php_c.tdc_configuration = self.tdc_c
self.top.grab_release()
for wid in self.top.winfo_children():
wid.destroy()
self.top.destroy()
class Absorbtion_imaging_configuration_UI(object):
def __init__(self, parent, absorbtion_imaging_configuration, daq_controller, sequence_length, sequence_t_step):
'''This object presents for editing the settings for absorbtion imaging experiments. It takes and edits a
copy of the Absorbtion Imaging Configuration. A flag then exists to indicate whether the user wants these
edits to be applied or not when the window is closed.'''
# A flag that denotes is the user confirms or cancels edits they make in this window when exiting.
self.apply_changes = False
self.config = self.c = copy.copy(absorbtion_imaging_configuration)
self.daq_controller = daq_controller
self.sequence_length = sequence_length
self.sequence_t_step = sequence_t_step
self.top = self.configureWindow(parent)
self.top.wm_title("Absorbtion imaging configuration")
self.top.grab_set()
# Changes the close button to call my close function.
self.top.protocol('WM_DELETE_WINDOW', self.closeWindow);
def configureWindow(self, parent):
'''
Build all the widget enteries for this UI.
'''
top = tk.Toplevel(parent)
frame = tk.Frame(top)
labels, widgets, fns_to_bind = [], [], []
controller_channels = self.daq_controller.getChannels()
channel_opts_dict = dict(zip([self.getChannelDropdownLabel(ch.chNum, ch.chName) for ch in sorted(controller_channels, key=lambda x: x.chNum)],
[x.chNum for x in controller_channels]))
channel_opts = sorted(channel_opts_dict.keys(), key=channel_opts_dict.__getitem__)
labels.append('Camera trigger channel:')
self.c.camera_trig_ch_var = var = tk.StringVar()
var.set((key for key,value in channel_opts_dict.items() if value==self.c.camera_trig_ch).next())
camera_trig_ch_dropdown = tk.OptionMenu(frame, var, *channel_opts,
command=lambda x=var: self.update_camera_trig_ch(camera_trig_levs_wid,
n_bkg_wid,
(ch for ch in controller_channels if ch.chNum == channel_opts_dict[x]).next()))
widgets.append(camera_trig_ch_dropdown)
fns_to_bind.append(None)
labels.append('Imaging power channel:')
self.c.imag_power_ch_var = var = tk.StringVar()
var.set((key for key,value in channel_opts_dict.items() if value==self.c.imag_power_ch).next())
imag_power_ch_dropdown = tk.OptionMenu(frame, var, *channel_opts,
command=lambda x=var: self.update_imag_power_ch(imag_power_levs_wid,
n_bkg_wid,
(ch for ch in controller_channels if ch.chNum == channel_opts_dict[x]).next()))
widgets.append(imag_power_ch_dropdown)
fns_to_bind.append(None)
labels.append('Camera trigger levels:')
camera_trig_levs_wid = e = tk.Entry(frame)
camera_trig_levs_wid.insert(0, '{0}, {1}'.format(*self.c.camera_trig_levs))
widgets.append(camera_trig_levs_wid)
def update_cam_trigger_levs(new_levs):
self.c.camera_trig_levs = new_levs
fns_to_bind.append(lambda event: self.trig_levs_focus_out(event.widget, (ch for ch in controller_channels if ch.chNum == self.c.camera_trig_ch).next(),
lambda new_levs, f=update_cam_trigger_levs: f(new_levs)))
labels.append('Imaging power levels:')
imag_power_levs_wid = e = tk.Entry(frame)
imag_power_levs_wid.insert(0, '{0}, {1}'.format(*self.c.imag_power_levs))
widgets.append(imag_power_levs_wid)
def update_imag_power_levs(new_levs):
self.c.imag_power_levs = new_levs
fns_to_bind.append(lambda event: self.trig_levs_focus_out(event.widget, (ch for ch in controller_channels if ch.chNum == self.c.imag_power_ch).next(),
lambda new_levs, f=update_imag_power_levs: f(new_levs)))
labels.append(u'Camera pulse width (\u03bcs):')
camera_pulse_width_wid = e = tk.Entry(frame)
e.insert(0, self.c.camera_pulse_width)
widgets.append(e)
fns_to_bind.append(lambda event: self.camera_pulse_width_focus_out(event.widget))
labels.append(u'Imaging flash width (\u03bcs):')
imag_pulse_width_wid = e = tk.Entry(frame)
e.insert(0, self.c.imag_pulse_width)
widgets.append(e)
fns_to_bind.append(lambda event: self.imag_pulse_width_focus_out(event.widget))
labels.append(u't images (\u03bcs):')
t_imag_wid = e = tk.Entry(frame)
e.insert(0, self.c.t_imgs)
widgets.append(e)
fns_to_bind.append(lambda event: self.t_img_focus_out(event.widget))
labels.append(u'MOT reload time (ms):')
mot_reload_time_wid = e = tk.Entry(frame)
e.insert(0, self.c.mot_reload_time * 10**-3) # convert from us to ms
widgets.append(e)
fns_to_bind.append(lambda event: self.mot_reload_time_focus_out(event.widget))
labels.append('# backgrounds:')
n_bkg_wid = e = tk.Entry(frame)
e.insert(0, self.c.n_backgrounds)
widgets.append(e)
fns_to_bind.append(lambda event: self.n_backgrounds_focus_out(event.widget))
labels.append('Background off channels:')
bkg_off_channels_wid = e = tk.Entry(frame)
e.insert(0, self.c.bkg_off_channels)
widgets.append(e)
fns_to_bind.append(lambda event: self.bkg_off_channels_focus_out(event.widget))
labels.append('Save location:')
save_location_wid = e = tk.Label(frame, text=self.c.save_location)
widgets.append(e)
fns_to_bind.append(None)
labels.append('Auto-save options:')
save_options_wid = e = tk.Frame(frame)
check_frames = []
checkbuttons = []
check_vars = []
for check_label in ['Save raw images:', 'Save processed images:', 'Review processed images:']:
check_frame = tk.Frame(e)
lab = tk.Label(check_frame, text=check_label)
var = tk.IntVar()
checkbutton = tk.Checkbutton(check_frame, variable=var)
check_frames.append(check_frame)
checkbuttons.append(checkbutton)
check_vars.append(var)
lab.pack(side=tk.LEFT)
checkbutton.pack(side=tk.RIGHT)
# Bind methods to checkbuttons
checkbuttons[0].configure(command = lambda var=check_vars[0]: self.save_raw_checkbutton(var))
checkbuttons[1].configure(command = lambda var=check_vars[1]: self.save_processed_checkbutton(var))
checkbuttons[2].configure(command = lambda var=check_vars[2], save_var=check_vars[1], save_wid=checkbuttons[1]: self.review_imgs_checkbutton(var, save_var, save_wid))
# Set checkbuttons initial values and invoke bound methods (so the buttons are consistent, e.g. save_processed_images is disabled if review_processed images is selected).
for button, var, init_val in zip(checkbuttons, check_vars, [self.c.save_raw_images, self.c.save_processed_images, self.c.review_processed_images]):
var.set(init_val)
if check_vars[2].get():
self.review_imgs_checkbutton(check_vars[2], check_vars[1], checkbuttons[1])
for check_frame in check_frames:
check_frame.pack(side=tk.LEFT)
widgets.append(e)
fns_to_bind.append(None)
labels.append('Camera gain:')
cam_gain_frame = tk.Frame(frame)
cam_gain_entry_wid = e = tk.Entry(cam_gain_frame)
cam_gain_slider_wid = s = tk.Scale(cam_gain_frame, from_=self.c.cam_gain_lims[0], to=self.c.cam_gain_lims[1],
command = lambda value: self.cam_gain_slider_focus_out(value, cam_gain_entry_wid),
orient=tk.HORIZONTAL, showvalue=0)
e.bind("<FocusOut>", lambda event: self.cam_gain_entry_focus_out(event.widget, cam_gain_slider_wid))
e.bind("<Return>", lambda event: self.cam_gain_entry_focus_out(event.widget, cam_gain_slider_wid))
e.insert(0, self.c.cam_gain)
s.set(self.c.cam_gain)
e.grid(row=0,column=0)
s.grid(row=0,column=1, sticky=tk.E+tk.W)
cam_gain_frame.grid_columnconfigure(0, weight=0)
cam_gain_frame.grid_columnconfigure(1, weight=1, pad=5)
cam_gain_frame.grid(row=0,column=1,sticky=tk.N+tk.W+tk.E)
widgets.append(cam_gain_frame)
fns_to_bind.append(None)
labels.append('Camera exposure (s):')
cam_exposure_frame = tk.Frame(frame)
cam_exposure_entry_wid = e = tk.Entry(cam_exposure_frame)
cam_exposure_slider_wid = s = tk.Scale(cam_exposure_frame, from_=self.c.cam_exposure_lims[1], to=self.c.cam_exposure_lims[0],
command = lambda value: self.cam_exposure_slider_focus_out(value, cam_exposure_entry_wid),
orient=tk.HORIZONTAL, showvalue=0)
e.bind("<FocusOut>", lambda event: self.cam_exposure_entry_focus_out(event.widget, cam_exposure_slider_wid))
e.bind("<Return>", lambda event: self.cam_exposure_entry_focus_out(event.widget, cam_exposure_slider_wid))
e.insert(0, self.exposure_to_string(1/self.c.cam_exposure))
s.set(self.c.cam_exposure)
e.grid(row=0,column=0)
s.grid(row=0,column=1, sticky=tk.E+tk.W)
cam_exposure_frame.grid_columnconfigure(0, weight=0)
cam_exposure_frame.grid_columnconfigure(1, weight=1, pad=5)
cam_exposure_frame.grid(row=0,column=1,sticky=tk.N+tk.W+tk.E)
widgets.append(cam_exposure_frame)
fns_to_bind.append(None)
labels.append('Scan imaging freq:')
scan_img_freqs_var = tk.IntVar()
scan_img_freqs_var.set(self.c.scan_abs_img_freq)
scan_img_freqs_checkbutton = tk.Checkbutton(frame, variable=scan_img_freqs_var)
widgets.append(scan_img_freqs_checkbutton)
fns_to_bind.append(None)
labels.append('Imaging freq. channel:')
self.c.abs_img_freq_ch_var = var = tk.StringVar()
var.set((key for key,value in channel_opts_dict.items() if value==self.c.abs_img_freq_ch).next())
abs_img_freq_ch_dropdown = tk.OptionMenu(frame, var, *channel_opts,
command=lambda x=var: self.update_imaging_freq_ch(abs_img_freqs_entry_wid,
(ch for ch in controller_channels if ch.chNum == channel_opts_dict[x]).next()))
fns_to_bind.append(None)
widgets.append(abs_img_freq_ch_dropdown)
try:
calib_units,_,fromVFunc = self.daq_controller.getChannelCalibrationDict()[self.c.abs_img_freq_ch]
except KeyError:
calib_units,_,fromVFunc = 'V', None, lambda x: x
labels.append('Imaging freqs ({0}):'.format(calib_units))
abs_img_freqs_entry_wid = e = tk.Entry(frame)
e.insert(0, [fromVFunc(freq) for freq in self.c.abs_img_freqs])
widgets.append(e)
fns_to_bind.append(lambda event: self.imaging_freqs_focus_out(event.widget, (ch for ch in controller_channels if ch.chNum == self.c.abs_img_freq_ch).next()))
scan_img_freqs_checkbutton.configure(command = lambda var=scan_img_freqs_var: self.scan_imaging_freqs_checkbutton(var, [abs_img_freq_ch_dropdown, abs_img_freqs_entry_wid]))
if not self.c.scan_abs_img_freq:
abs_img_freq_ch_dropdown.configure(state=tk.DISABLED)
abs_img_freqs_entry_wid.configure(state=tk.DISABLED)
lab_grid_opts = {'sticky':tk.W}
wid_grid_opts = {'sticky':tk.E+tk.W}
lab_config = {'font':("Helvetica", 10, "bold"), 'padx':5}
r=0
for lab, wid, fn in zip(labels, widgets, fns_to_bind):
tk.Label(frame, text=lab, **lab_config).grid(row=r, column=0, **lab_grid_opts)
wid.grid(row=r, column=1, **wid_grid_opts)
if fn != None:
wid.bind("<FocusOut>", fn)
wid.bind("<Return>", fn)
r+=1
frame.grid_columnconfigure(0, weight=1)