-
Notifications
You must be signed in to change notification settings - Fork 1
/
ExperiementalRunner.py
1786 lines (1459 loc) · 84.1 KB
/
ExperiementalRunner.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
'''
This module is intended to hold the top profiles for running assorted experiments from
configuration through to data acquisition.
Created on 13 Aug 2016
@author: Tom Barrett
'''
from time import sleep
import copy
import os
import time
import numpy as np
import threading
from PIL import Image
import csv
import glob
import re
from DAQ import DAQ_controller, DaqPlayException
from instruments.WX218x.WX218x_awg import WX218x_awg, Channel
from instruments.WX218x.WX218x_DLL import WX218x_MarkerSource, WX218x_OutputMode, WX218x_OperationMode, WX218x_SequenceAdvanceMode, WX218x_TraceMode, WX218x_TriggerImpedance, WX218x_TriggerMode, WX218x_TriggerSlope, WX218x_Waveform
from instruments.quTAU.TDC_quTAU import TDC_quTAU
from instruments.quTAU.TDC_BaseDLL import TDC_SimType, TDC_DevType, TDC_SignalCond
from instruments.pyicic.IC_ImagingControl import IC_ImagingControl
from instruments.pyicic.IC_Exception import IC_Exception
from instruments.TF930 import TF930
from Sequence import IntervalStyle
from sympy.physics.units import frequency
from serial.serialutil import SerialException
import collections
import _tkinter
class ExperimentalRunner(object):
'''
classdocs
'''
def __init__(self, daq_controller):
'''
Constructor
'''
# Save the initial values on the DAQ channels so we can return to them later
self.daq_controller = daq_controller
self.configure()
def configure(self):
raise NotImplementedError()
def run(self):
raise NotImplementedError()
def close(self):
raise NotImplementedError()
class PhotonProductionExperiment(ExperimentalRunner):
def __init__(self, daq_controller, sequence, photon_production_configuration):
self.daq_controller = daq_controller
self.sequence = sequence
self.photon_production_config = c = photon_production_configuration
self.tdc_config = self.photon_production_config.tdc_configuration
self.awg_config = self.photon_production_config.awg_configuration
self.iterations = c.iterations
self.mot_reload_time = c.mot_reload*10**-6
print 'MOT reload time (s)', self.mot_reload_time
self.is_live = False # Experiment is not running yet
self.forced_stop = False # Flag for if the experiment is forcibly stopped early.
self.data_queue = None # Queue to push data into
def configure(self):
self.__configure_DAQ_cards()
# Configure the awg and record the length of the waveform loaded onto it (in seconds)
self.awg, self.waveform_length = self.__configure_awg()
self.tdc = self.__configure_tdc()
# try:
# self.counter = TF930.TF930(port='COM5')
# except SerialException:
# print 'Cannot find counter. Ignoring and carrying on.'
# self.counter = None
self.counter = None
# Get tdc timebase in ps - do i once now, rather than every time we poll
# the tdc for data (just for performance reasons).
self.tdc_timebase = self.tdc.get_timebase()*10**12
self.data_saver = PhotonProductionDataSaver(self.tdc_timebase,
self.tdc_config.marker_channel,
self.photon_production_config.save_location,
data_queue = self.data_queue,
create_log=False)
def configure_data_queue(self, data_queue):
self.data_queue = data_queue
try:
self.data_saver.data_queue = self.data_queue
except AttributeError:
pass
def run(self):
self.tdc.enable_tdc_input(True)
self.tdc.freeze_buffers(True)
self.tdc.clear_buffer()
time.sleep(1)
self.is_live = True
i = 1
tdc_read_thread = None
self.daq_controller.load(self.sequence.getArray())
while i <= self.iterations and self.is_live:
print 'iter: {0}'.format(i)
sleep(self.mot_reload_time)
if tdc_read_thread: tdc_read_thread.join(timeout=5000)
# self.daq_controller.load(self.sequence.getArray()) # TODO: can we load only once at start?
print 'unfreeze'
self.tdc.freeze_buffers(False)
# sleep(1)
print 'play'
self.daq_controller.play(float(self.sequence.t_step), clearCards=False)
print 'freeze'
tdc_read_thread = threading.Thread(name='PhotonProductionExperiment_read TDC buffer and start save thread',
target=self.__save_throw_data,
args=(i,))
tdc_read_thread.start()
# self.__save_throw_data(throw_number=i)
#
# if (i%100 == 0 or i==1) and self.counter != None:
# self.data_saver.log_in_thread(['Repump offset VCO is at ', self.counter.query_frequency],
# throw_number=i)
self.daq_controller.writeChannelValues()
i+=1
self.daq_controller.clearCards()
self.is_live = False
if tdc_read_thread: tdc_read_thread.join(timeout=5000)
self.tdc.enable_tdc_input(False)
def run_in_thread(self, start_thread=True):
'''
Run the experiment with the experimental loop in a separate thread.
'''
def run_and_close():
self.run()
self.close()
thread = threading.Thread(name='PhotonProductionExperiment_run',
target=run_and_close)
if start_thread:
thread.start()
return thread
def close(self):
print "Closing connection to AWG...",
self.awg.disable_channel(Channel.CHANNEL_1)
self.awg.disable_channel(Channel.CHANNEL_2)
self.awg.disable_channel(Channel.CHANNEL_3)
self.awg.disable_channel(Channel.CHANNEL_4)
self.awg.close()
print "...closed"
print "Closing connection to TDC...",
self.tdc.close()
print "...closed"
if self.counter!=None:
print 'Closing connection to TF930'
self.counter.close()
if self.isDaqContinuousOutput:
print "Returning to free running DAQ values."
self.daq_controller.writeChannelValues()
else:
print "Reverting DAQ output to off."
self.daq_controller.toggleContinuousOutput()
self.daq_controller.writeChannelValues()
print 'Consolidating experimental data...',
self.data_saver.combine_saves()
print 'done.'
def __save_throw_data(self, throw_number):
t=time.time()
sleep( 200*10**-3 )
self.tdc.freeze_buffers(True)
print 'reading tdc'
timestamps, channels, valid = self.tdc.get_timestamps(True)
print 'throw {0}: counts on tdc={1}, tdc read time={2}ms'.format(throw_number,valid,(time.time()-t)*10**3)
self.data_saver.save_in_thread(timestamps, channels, valid, throw_number)
# save_thread.join(timeout=5000)
# fname = r'C:/Users/apc/Desktop/test/'
# f = open(os.path.join(fname, '{0}.txt'.format(throw_number)), 'w')
# print 'writing to:', os.path.join(fname, '/{0}.txt'.format(throw_number))
# for line in zip(timestamps[:valid], channels[:valid]):
# f.write('{0},{1}\n'.format(*line))
# f.close()
def __configure_DAQ_cards(self):
self.isDaqContinuousOutput = self.daq_controller.continuousOutput
if not self.isDaqContinuousOutput:
print "DAQ output must be on to run a sequence - turning it on."
self.daq_controller.toggleContinuousOutput()
self.daq_controller.load(self.sequence.getArray())
# def __configure_awg_old(self):
# print 'Connecting to AWG...'
# awg = WX218x_awg()
# awg.open(reset=False)
# print '...connected'
# awg.clear_arbitrary_sequence()
# awg.clear_arbitrary_waveform()
# awg.configure_sample_rate(self.awg_config.sample_rate)
# awg.configure_burst_count(self.awg_config.waveform_output_channel, self.awg_config.burst_count)
# awg.configure_operation_mode(self.awg_config.waveform_output_channel, WX218x_OperationMode.TRIGGER)
# time.sleep(1)
# awg.configure_output_mode(WX218x_OutputMode.ARBITRARY)
# awg.configure_trigger_source(self.awg_config.waveform_output_channel, WX218x_TriggerMode.EXTERNAL)
# awg.configure_trigger_level(self.awg_config.waveform_output_channel, 2)
# awg.configure_trigger_slope(self.awg_config.waveform_output_channel, WX218x_TriggerSlope.POSITIVE)
#
# waveform_data = []
# marker_data = []
#
# marker_levs = self.photon_production_config.marker_levels
# marker_wid = int(self.photon_production_config.marker_width*10**-6 * self.photon_production_config.awg_configuration.sample_rate)
# sample_rate = self.awg_config.sample_rate
#
# def get_waveform_calib_fnc(calib_fname, max_eff=0.9):
# calib_data = np.genfromtxt(calib_fname,skip_header=1)
# calib_data[:,1] /= 100. # convert % as saved to decimal efficiencies
# calib_data = calib_data[(calib_data[:,1]<=max_eff)] # remove all elements with greater than the maximum efficiency
# calib_data[:,1] /= max(calib_data[:,1]) # rescale effiencies
#
# return lambda x: np.interp(np.abs(x),
# calib_data[:,1],
# calib_data[:,0])
#
# waveform_aom_calibs = {}
# print os.path.join(self.photon_production_config.waveform_aom_calibrations_location, '*MHz.txt')
# for filename in glob.glob(os.path.join(self.photon_production_config.waveform_aom_calibrations_location, '*MHz.txt')):
# try:
# waveform_aom_calibs[float(re.match(r'\d+\.*\d*', os.path.split(filename)[1]).group(0))] = get_waveform_calib_fnc(filename)
# except AttributeError:
# pass
#
# waveforms = [self.photon_production_config.waveforms[i] for i in self.photon_production_config.waveform_sequence]
#
# marker_offset = np.rint(self.photon_production_config.marker_delay*10**-6 * self.photon_production_config.awg_configuration.sample_rate)
# print "Marker offset is", marker_offset
# queud_markers = []
#
# for waveform, delay in zip(waveforms, self.photon_production_config.waveform_stitch_delays):
#
# if not waveform_aom_calibs:
# calib_fun = lambda x: x
# else:
# calib_fun = waveform_aom_calibs[min(waveform_aom_calibs,
# key=lambda calib_freq: np.abs(calib_freq - waveform.get_mod_frequency()*10**-6))]
# print 'For waveform with freq {0}MHz, using calib for {1}MHz'.format(waveform.get_mod_frequency()*10**-6,
# min(waveform_aom_calibs, key=lambda calib_freq: np.abs(calib_freq - waveform.get_mod_frequency()*10**-6)))
#
#
# marker_pos = []
# for i in range(len(queud_markers)):
# if queud_markers[i] < waveform.get_n_samples():
# marker_pos.append(queud_markers.pop(i))
# if marker_offset <= waveform.get_n_samples():
# marker_pos.append(marker_offset)
# else:
# queud_markers.append(marker_offset)
#
# print 'Writing markers at', marker_pos
# waveform_data += waveform.get(sample_rate=sample_rate, calibration_function=calib_fun) + [0]*delay
# marker_data += waveform.get_marker_data(marker_positions=marker_pos, marker_levels=marker_levs, marker_width=marker_wid) + [marker_levs[0]]*delay
# # marker_data += waveform.get(sample_rate=sample_rate) + [0]*delay
# queud_markers = [x-(waveform.get_n_samples()+delay) for x in queud_markers]
#
# '''
# Wrap any makers still queued into the first waveforms markers (presuming we are looping through this sequence multiple times).
# '''
# if queud_markers != []:
# marker_index = 0
# for waveform in waveforms:
# # queud_markers = [x-(waveforms[-1].get_n_samples()+self.photon_production_config.waveform_stitch_delays[-1]) for x in queud_markers]
# if len([x for x in queud_markers if x>=0])>0:
# print 'Still in queue:', [x for x in queud_markers if x>=0]
# markers_in_waveform = [x for x in queud_markers if marker_index <= x <= marker_index+waveform.get_n_samples()]
# print 'Can wrap from queue:',markers_in_waveform
# wrapped_marker_data = waveform.get_marker_data(marker_positions=markers_in_waveform,
# marker_levels=marker_levs,
# marker_width=marker_wid) + [marker_levs[0]]*delay
# print 'hit', marker_index, marker_index+len(wrapped_marker_data)
# marker_data[marker_index:marker_index+len(wrapped_marker_data)] = \
# [marker_levs[1] if (a==marker_levs[1] or b==marker_levs[1]) else marker_levs[0] if (a==marker_levs[0] and b==marker_levs[0]) else a+b
# for a,b in zip(marker_data[:len(wrapped_marker_data)], wrapped_marker_data)]
# marker_index+=len(wrapped_marker_data)
# queud_markers = [x-waveform.get_n_samples() for x in queud_markers]
#
# # Convert the marker offset (used to account for lags in writing the AWG waveform and the STIRAP pulse being sent through the cavity)
# # from us to AWG units. Ensure the total amount added to the waveform is 16*n samples.
# # marker_offset_2 = (np.floor(marker_offset_1/16) + 1) * 16 - marker_offset_1 if marker_offset_1%16 != 0 else 0
# #
# # print marker_offset_1
# # print marker_offset_2
# #
# # waveform_data = [0]*marker_offset_2 + waveform_data + [0]*marker_offset_1
# # marker_data = [marker_levs[0]]*marker_offset_1 + marker_data + [marker_levs[0]]*marker_offset_2
# #
# # # This is a big fix. If the first element of the sequence is 1 (i.e. max high level)
# # # then the channel remains high at the end of the sequence. Don't know why...
# # if marker_data[0]==1: marker_data[0]=0
# # if marker_data[-1]==1: marker_data[-1]=0
#
#
# '''Previously we wrote marker data onto channel2 - we now try to use the marker channels. However, the
# above work to produce a waveform-ready set of marker data is kept as it is quick and allows us to easily
# revert back to our previous methods (simply uncomment the following line).'''
# wave_handle, marker_handle = awg.create_custom_adv(waveform_data, marker_data)
#
# for channel in next(x for x in [(Channel.CHANNEL_1, Channel.CHANNEL_2),
# (Channel.CHANNEL_3, Channel.CHANNEL_4)]
# if self.awg_config.waveform_output_channel in x):
# awg.enable_channel(channel)
# awg.configure_arb_gain(channel, 2)
#
# marker_starts = [x[0] for x in enumerate(zip([0]+marker_data[:-1],marker_data)) if x[1][0]==0 and x[1][1]>0]
#
# if len(marker_starts) > 2:
# print 'ERROR: There are more markers required than can be set currently using the marker channels!'
# marker_starts = marker_starts[:2]
#
# print 'Writing markers to marker channels at {0}'.format(marker_starts)
# marker_channel_index = 1
# for marker_pos in marker_starts:
# awg.configure_marker(self.awg_config.waveform_output_channel,
# index = marker_channel_index,
# position = marker_pos - marker_wid/4,
# width = marker_wid/2)
# marker_channel_index += 1
#
# return awg, len(waveform_data)/sample_rate
#
def __configure_awg(self):
print 'Connecting to AWG...'
awg = WX218x_awg()
awg.open(reset=False)
print '...connected'
awg.clear_arbitrary_sequence()
awg.clear_arbitrary_waveform()
awg.configure_sample_rate(self.awg_config.sample_rate)
awg_chs = self.awg_config.waveform_output_channels
awg.configure_output_mode(WX218x_OutputMode.ARBITRARY)
awg.configure_couple_enabled(True)
for ch in [awg_chs[x] for x in range(len(awg_chs)) if x%2==0]:
print 'Configuring trigger options for', ch
awg.configure_burst_count(ch, self.awg_config.burst_count)
awg.configure_operation_mode(ch, WX218x_OperationMode.TRIGGER)
time.sleep(1)
awg.configure_trigger_source(ch, WX218x_TriggerMode.EXTERNAL)
awg.configure_trigger_level(ch, 2)
awg.configure_trigger_slope(ch, WX218x_TriggerSlope.POSITIVE)
channel_absolute_offsets = [np.rint(x*10**-6 * self.awg_config.sample_rate) for x in self.awg_config.waveform_output_channel_lags]
channel_relative_offsets = list(map(lambda x, m=max(channel_absolute_offsets): int(m-x), channel_absolute_offsets))
print "Channel relative lags (in awg steps are)", channel_relative_offsets
print "Channel absolute offsets (in awg steps are)", channel_absolute_offsets
marker_levs, marker_waveform_levs = (0,1.2), (0,1)
marker_wid = int(self.awg_config.marker_width*10**-6 * self.awg_config.sample_rate)
def get_waveform_calib_fnc(calib_fname, max_eff=0.9):
calib_data = np.genfromtxt(calib_fname,skip_header=1)
calib_data[:,1] /= 100. # convert % as saved to decimal efficiencies
calib_data = calib_data[(calib_data[:,1]<=max_eff)] # remove all elements with greater than the maximum efficiency
calib_data[:,1] /= max(calib_data[:,1]) # rescale effiencies
return lambda x: np.interp(np.abs(x),
calib_data[:,1],
calib_data[:,0])
seq_waveforms = [[self.photon_production_config.waveforms[i] for i in ch_waveforms]
for ch_waveforms in self.photon_production_config.waveform_sequence]
queud_markers = []
seq_waveform_data, seq_marker_data = [[] for _ in xrange(len(awg_chs))], []
# Note we deep copy the config stitch delays so that updating them below doesn't change the configuration settings.
seq_waveforms_stitch_delays = copy.deepcopy(self.photon_production_config.waveform_stitch_delays)
if self.photon_production_config.interleave_waveforms:
# '''Add a delay to the front of the i-th channel to wait for the 0,1...,i-1 channels
# first waveforms to finish'''
# for i in range(1, len(seq_waveform_data)):
# seq_waveform_data[i] += [0]*(len(seq_waveform_data[i-1]) + seq_waveforms[i-1][0].get_n_samples())
#
# '''For other channels/waveforms, add the length of the interleaved waveform from
# the opposite channel to the stich delay'''
# for i in range(0, len(seq_waveforms)):
# for j in range(0, len(seq_waveforms[i])):
# for k in [l for l in range(len(seq_waveforms)) if l!=i]:
# if j!=len(seq_waveforms[i])-1 or k>i:
# # print i,j,k
# seq_waveforms_stitch_delays[i][j] += seq_waveforms[k][j].get_n_samples()
#
interleave_channels = [(0,1),(0,2)]
def get_j_segments_max_length(seq_waveforms, channels, j, seq_stitch_delays=None):
waveform_lengths = []
if seq_stitch_delays==None:
seq_stitch_delays = np.zeros(np.array(seq_waveforms).shape).tolist()
for ch in channels:
try:
waveform_lengths.append(seq_waveforms[ch][j].get_n_samples() + seq_stitch_delays[ch][j])
except IndexError:
''' Ignore the case where the requested waveform segment doens't exist.'''
pass
print waveform_lengths
return int(max(waveform_lengths)) if waveform_lengths != [] else 0
for i in range(len(seq_waveforms)):
woven_channels = sorted([k for pair in [x for x in interleave_channels if i in x] for k in pair if k!=i])
bck_woven_channels = [k for k in woven_channels if k<i]
fwd_woven_channels = [k for k in woven_channels if k>i]
for j in range(0, len(seq_waveforms[i])):
if j==0:
max_bck_waveforms = get_j_segments_max_length(seq_waveforms, bck_woven_channels, j)
print 'Pre-padding channel{0}(seg{1}) with {2}'.format(i+1, j, max_bck_waveforms)
seq_waveform_data[i] += [0]*max_bck_waveforms
max_bck_waveforms = get_j_segments_max_length(seq_waveforms, bck_woven_channels, j+1)
max_fwd_waveforms = get_j_segments_max_length(seq_waveforms, fwd_woven_channels, j, seq_waveforms_stitch_delays)
print 'Post-padding channel{0}(seg{1}) with max({2},{3})'.format(i+1,j,max_bck_waveforms,max_fwd_waveforms)
seq_waveforms_stitch_delays[i][j] += max(max_bck_waveforms,max_fwd_waveforms)#
'''CURRENT ISSUE IS IF THE DELAY IN A BACK WAVEFORM TAKES THE PREVIOUS J-SEGMENT [AST THE START OF THE CURRENT
TARGET WAVEFORM/SEGMENT.'''
j = 0
for channel, waveform_data, waveforms, delays, channel_abs_offset in zip(awg_chs, seq_waveform_data, seq_waveforms, seq_waveforms_stitch_delays, channel_absolute_offsets):
waveform_aom_calibs = {}
aom_calibration_loc = self.awg_config.waveform_aom_calibrations_locations[j]
print 'For {0} using aom calibrations in {1}'.format(channel, os.path.join(aom_calibration_loc, '*MHz.txt'))
for filename in glob.glob(os.path.join(aom_calibration_loc, '*MHz.txt')):
try:
waveform_aom_calibs[float(re.match(r'\d+\.*\d*', os.path.split(filename)[1]).group(0))] = get_waveform_calib_fnc(filename)
except AttributeError:
pass
marker_data = []
print 'Writing onto channel:', channel
for waveform, delay in zip(waveforms, delays):
if not waveform_aom_calibs:
calib_fun = lambda x: x
else:
calib_fun = waveform_aom_calibs[min(waveform_aom_calibs,
key=lambda calib_freq: np.abs(calib_freq - waveform.get_mod_frequency()*10**-6))]
print '\tFor waveform with freq {0}MHz, using calib for {1}MHz'.format(waveform.get_mod_frequency()*10**-6,
min(waveform_aom_calibs, key=lambda calib_freq: np.abs(calib_freq - waveform.get_mod_frequency()*10**-6)))
seg_length = waveform.get_n_samples() + delay
marker_pos = []
# for i in range(len(queud_markers)):
# print i, queud_markers
# if queud_markers[i] < seg_length:
# marker_pos.append(queud_markers.pop(i))
i=0
while i < len(queud_markers):
print i, queud_markers
if queud_markers[i] < seg_length:
marker_pos.append(queud_markers.pop(i))
i-=1
i+=1
if channel_abs_offset <= seg_length:
marker_pos.append(channel_abs_offset)
else:
queud_markers.append(channel_abs_offset)
print '\tWriting markers at', marker_pos
print '\tWriting waveform {0} with stitch delay {1}'.format(os.path.split(waveform.fname)[1], delay)
waveform_data += waveform.get(sample_rate=self.awg_config.sample_rate, calibration_function=calib_fun) + [0]*delay
marker_data += waveform.get_marker_data(marker_positions=marker_pos, marker_levels=marker_waveform_levs, marker_width=marker_wid, n_pad_right=delay)
# marker_data += waveform.get(sample_rate=self.awg_config.sample_rate) + [0]*delay
queud_markers = [x-seg_length for x in queud_markers]
'''
Wrap any makers still queued into the first waveforms markers (presuming we are looping through this sequence multiple times).
'''
if queud_markers != []:
marker_index = 0
for waveform, delay in zip(waveforms, delays):
seg_length = waveform.get_n_samples() + delay
# queud_markers = [x-(waveforms[-1].get_n_samples()+self.photon_production_config.waveform_stitch_delays[-1]) for x in queud_markers]
if len([x for x in queud_markers if x>=0])>0:
print '\tStill in queue:', [x for x in queud_markers if x>=0]
markers_in_waveform = [x for x in queud_markers if marker_index <= x <= marker_index+seg_length]
print '\tCan wrap from queue:',markers_in_waveform
wrapped_marker_data = waveform.get_marker_data(marker_positions=markers_in_waveform,
marker_levels=marker_waveform_levs,
marker_width=marker_wid,
n_pad_right=delay)
marker_data[marker_index:marker_index+len(wrapped_marker_data)] = \
[marker_waveform_levs[1] if (a==marker_waveform_levs[1] or b==marker_waveform_levs[1]) else marker_waveform_levs[0] if (a==marker_waveform_levs[0] and b==marker_waveform_levs[0]) else a+b
for a,b in zip(marker_data[:len(wrapped_marker_data)], wrapped_marker_data)]
marker_index+=len(wrapped_marker_data)
queud_markers = [x-seg_length for x in queud_markers]
seq_waveform_data[j] = waveform_data
j += 1
print '\t', j, len(seq_waveform_data), [len(x) for x in seq_waveform_data]
'''
Combine the marker data for each marked channel.
'''
print self.awg_config.marked_channels
if channel in self.awg_config.marked_channels:
print '\tAdding marker data for', channel
if seq_marker_data == []:
seq_marker_data += marker_data
else:
j1, j2 = map(len,[seq_marker_data, marker_data])
if j1<j2:
seq_marker_data = [sum(x) for x in zip(seq_marker_data[:j1], marker_data[:j1])]+ marker_data[j1:]
if j2<j1:
seq_marker_data = [sum(x) for x in zip(seq_marker_data[:j2], marker_data[:j2])]+ seq_marker_data[j2:]
if j1==j2:
seq_marker_data = [sum(x) for x in zip(seq_marker_data, marker_data)]
# Convert the marker offset (used to account for lags in writing the AWG waveform and the STIRAP pulse being sent through the cavity)
# from us to AWG units. Ensure the total amount added to the waveform is 16*n samples.
# marker_offset_2 = (np.floor(marker_offset_1/16) + 1) * 16 - marker_offset_1 if marker_offset_1%16 != 0 else 0
#
# print marker_offset_1
# print marker_offset_2
#
# waveform_data = [0]*marker_offset_2 + waveform_data + [0]*marker_offset_1
# marker_data = [marker_waveform_levs[0]]*marker_offset_1 + marker_data + [marker_waveform_levs[0]]*marker_offset_2
#
# # This is a big fix. If the first element of the sequence is 1 (i.e. max high level)
# # then the channel remains high at the end of the sequence. Don't know why...
# if marker_data[0]==1: marker_data[0]=0
# if marker_data[-1]==1: marker_data[-1]=0
'''
Ensure we write the same number of points to each channel.
'''
N = max([len(x) for x in seq_waveform_data])
for x in seq_waveform_data:
if len(x) < N:
x += [0]*(N-len(x))
'''Previously we wrote marker data onto channel2 - we now try to use the marker channels. However, the
above work to produce a waveform-ready set of marker data is kept as it is quick and allows us to easily
revert back to our previous methods (simply uncomment the following line).'''
# wave_handle, marker_handle = awg.create_custom_adv(waveform_data, marker_data)
l_mark, l_seq = len(seq_marker_data), len(seq_waveform_data[0])
if l_mark < l_seq : seq_marker_data += [0]*(l_seq - l_mark)
elif l_seq < l_mark: seq_marker_data = seq_marker_data[:l_seq]
awg.configure_arb_wave_trace_mode(WX218x_TraceMode.SINGLE)
'''Configure each channel for its output data.'''
for channel, rel_offset, data in zip(awg_chs, channel_relative_offsets, seq_waveform_data):
# Roll channel data to account for relative offsets (e.g. AOM lags)
print 'Rolling {0} forward by {1} points'.format(channel, rel_offset)
data = np.roll(np.array(data), rel_offset).tolist()
print 'Writing {0} points to {1}'.format(len(data),channel)
awg.set_active_channel(channel)
awg.create_arbitrary_waveform_custom(data)
for channel in awg_chs:
awg.enable_channel(channel)
awg.configure_arb_gain(channel, 2)
'''Quick hack to write marker data to channel 2'''
# awg.set_active_channel(Channel.CHANNEL_2)
# awg.create_arbitrary_waveform_custom(marker_data)
# awg.enable_channel(Channel.CHANNEL_2)
# awg.configure_arb_gain(Channel.CHANNEL_2, 2)
marker_starts = [x[0] for x in enumerate(zip([0]+seq_marker_data[:-1],seq_marker_data)) if x[1][0]==0 and x[1][1]>0]
if len(marker_starts) > 2:
print 'ERROR: There are more markers required than can be set currently using the marker channels!'
marker_starts = marker_starts[:2]
print 'Writing markers to marker channels at {0}'.format(marker_starts)
marker_channel_index = 1
for marker_pos in marker_starts:
awg.configure_marker(awg_chs[0],
index = marker_channel_index,
position = marker_pos - marker_wid/4,
levels = marker_levs,
width = marker_wid/2)
marker_channel_index += 1
return awg, len(seq_waveform_data[0])/self.awg_config.sample_rate
def __configure_tdc(self):
tdc = TDC_quTAU()
print 'Connecting to quTAU tdc..'
tdc.open()
print '...opened'
print 'Enabling channels: ', self.tdc_config.counter_channels + [self.tdc_config.marker_channel]
tdc.set_enabled_channels(self.tdc_config.counter_channels + [self.tdc_config.marker_channel])
tdc.set_timestamp_buffer_size(self.tdc_config.timestamp_buffer_size)
# Four our need: the exposure time determines the rate at which data is put into the buffer.
# Future proofing: if we use the in-built quTAU functions (e.g. histograms) an exposure time
# of zero may cause issue.
tdc.set_exposure_time(0)
# Set the tdc to high impedance
if tdc.get_dev_type() == TDC_DevType.DEVTYPE_1A:
# Turn 50 Ohm termination off
print 'Device 1A'
tdc.switch_termination(False)
elif tdc.get_dev_type() in [TDC_DevType.DEVTYPE_1B, TDC_DevType.DEVTYPE_1C]:
print 'Device 1B/1C'
print self.tdc_config.marker_channel
tdc.configure_signal_conditioning(self.tdc_config.marker_channel,
TDC_SignalCond.SCOND_MISC,
edge = 1, # rising edge,
term = 0, # Turn 50 Ohm termination off
threshold = 0.5)
for ch in self.tdc_config.counter_channels:
tdc.configure_signal_conditioning(ch,
TDC_SignalCond.SCOND_MISC,
edge = 1, # rising edge,
term = 0, # Turn 50 Ohm termination off
threshold = 0.05)
# tdc.enable_tdc_input(True)
print 'tdc configured'
return tdc
def set_iterations(self, iterations):
'''
Sets the iterations.
'''
self.iterations = iterations
def set_mot_reload_time(self, reload_time):
'''
Sets the MOt reload time. Takes the reload_time in milliseconds.
'''
print 'Setting reload_time to', reload_time
self.mot_reload_time = reload_time*10**-3
class PhotonProductionDataSaver(object):
'''
This object takes raw data from the TDC, parses it into our desired format and saves
it to file. It also enables all of the parsing/saving to be done in a separate thread
so as to not hold up the experiment.
'''
def __init__(self, tdc_timebase, tdc_marker_channel, save_location, data_queue=None, create_log=False):
'''
Initialise the object with the information it will need for saving.
'''
self.tdc_timebase = tdc_timebase
self.tdc_marker_channel = tdc_marker_channel
self.experiment_time = time.strftime("%H-%M-%S")
self.experiment_date = time.strftime("%y-%m-%d")
self.save_location = os.path.join(save_location, self.experiment_date, self.experiment_time)
self.save_location_raw = os.path.join(self.save_location, 'raw')
if not os.path.exists(self.save_location):
os.makedirs(self.save_location)
if not os.path.exists(self.save_location_raw):
os.makedirs(self.save_location_raw)
if create_log:
self.log_file = os.path.join(self.save_location, 'log.txt')
print 'Log file at {0}'.format(self.log_file)
else:
self.log_file = None
self.data_queue = data_queue
self.threads = []
def save_in_thread(self,timestamps, channels, valid, throw_number):
'''
Save the data in a new thread.
'''
thread = threading.Thread(name='Throw {0} save'.format(throw_number),
target=self.__save,
args=(timestamps, channels, valid, throw_number))
thread.start()
self.threads.append(thread)
return thread
def log_in_thread(self, log_input, throw_number):
thread = threading.Thread(name='Throw {0} save'.format(throw_number),
target=self.__log,
args=(log_input, throw_number))
thread.start()
self.threads.append(thread)
return thread
def combine_saves(self):
'''
Combine all the individual files from each MOT throw into a single file.
'''
t = 0
# Check only the main thread is still running i.e. nothing is stills saving.
while True in [thread.is_alive() for thread in self.threads]:
time.sleep(1)
t+=1
if t>60:
print "Timed-out waiting for save-threads to finish. Abandoning combine_saves()."
return
combined_file = open(os.path.join(self.save_location, self.experiment_time + '.txt'), 'w')
for fname in os.listdir(self.save_location_raw):
if fname.endswith(".txt"):
data_file = open(os.path.join(self.save_location_raw, fname))
combined_file.write(data_file.read())
data_file.close()
combined_file.write('nan,nan,nan,nan\n') # Batman!
combined_file.close()
def __save(self, timestamps, channels, valid, throw_number):
'''
Save the data returned from the TDC.
'''
print '__save iter', throw_number
t = time.time()
# print 'Num markers:', channels.tolist().count(self.tdc_marker_channel)
try:
# marker_index = channels.tolist().index(self.tdc_marker_channel)
first_marker_index = next(i for i,elm in enumerate(channels.tolist()) if elm==self.tdc_marker_channel)
last_marker_index = next(len(channels)-1-i for i,elm in enumerate(reversed(channels.tolist())) if elm==self.tdc_marker_channel)
except ValueError as err:
print "__save(throw={0}) Nothing measured on marker channel - so nothing to save.".format(throw_number)
print err
return
print '__save: found first marker index ({0} sec)'.format(time.time()-t)
x_0 = timestamps[first_marker_index]
# t_mot_0 = x_0*self.tdc_timebase
# timestamps = [(x-x_0)*self.tdc_timebase for x in timestamps[marker_index+1:] if x >= 0]
# channels = [x for x in channels[marker_index+1:] if x >= 0]
# This step essentially does two things:
# 1. Converts all the timestamps to picoseconds by *tdc_timebase.
# 2. Makes t=0 be the time of the initial marker pulse, i.e. writes
# all timestamps in terms of the so-called mot-time.
t = time.time()
timestamps = [(x-x_0)*self.tdc_timebase for x in timestamps[first_marker_index:last_marker_index+1]]
channels = channels[first_marker_index:last_marker_index+1]
# print 'create temp data dump'
# t = open(os.path.join(self.save_location, 'temp.txt'), 'w')
# for line in zip(timestamps, channels):
# t.write('{0},{1}\n'.format(*line))
# t.close()
#
print '__save: selected valid timestamps and channels'
t = time.time()
pulse_number = 0
data = []
data_buffer = []
# sti_lens = []
try:
for t, ch in zip(timestamps, channels):
if ch == self.tdc_marker_channel:
# print 'MARKER', t, ch
t_stirap_0 = t
pulse_number += 1
data += data_buffer
# sti_lens.append(len(data_buffer))
data_buffer = []
else:
# print 'DATA', t, ch
data_buffer.append((ch, t-t_stirap_0, t, pulse_number))
except _tkinter.TclError as err:
print t, ch
raise err
if pulse_number > 25000:
print '__save: Too many pulses recorded ({0}) - returning.'.format(pulse_number)
return
# print len(data), sti_lens
print '__save: creating file'
f = open(os.path.join(self.save_location_raw, '{0}.txt'.format(throw_number)), 'w')
print '__save: writing file'
for line in data:
f.write('{0},{1},{2},{3}\n'.format(*line))
print '__save: closing file'
f.close()
# If a push data function is configured, throw it now
if self.data_queue:
print 'Queuing data'
self.data_queue.put((throw_number, data))
print 'iter {0}: counts {1}, pulses recorded {2}'.format(throw_number, len(data), pulse_number)
def __log(self, log_input, throw_number):
if self.log_file != None:
print '__log: writing to log'
if callable(log_input):
log_input = log_input()
if type(log_input) in [list, tuple]:
def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
for sub in flatten(el):
yield sub
else:
yield el
log_input = ' '.join([str(x) for x in flatten([x() if callable(x) else x for x in log_input])])
f = open(self.log_file, 'w')
f.write('Throw {0}: {1}\n'.format(throw_number, log_input))
f.close()
print '__log: closed log file'
else:
print '__log: Can not write. No log file exists.'
class AbsorbtionImagingExperiment(ExperimentalRunner):
shutter_lag = 4.8 #The camera response time to the trigger. Hard coded as it is a physical camera property.
def __init__(self, daq_controller, sequence, absorbtion_imaging_configuration, ic_imaging_control):
'''
Runs an absorbtion imaging experiment. Takes a number of parameters, namely:
daq_controller - The DAQ Controller object for running the daq channels
sequence - The sequence to run whilst taking the images. Note that the camera trigger and
imaging power channels are overwritten by this experiment and so need not be configured
in the original sequence.
absorbtion_imaging_configuration - An instance of AbsorbtionImagingConfiguration.
'''
self.daq_controller = daq_controller
self.sequence = sequence
self.config = c = absorbtion_imaging_configuration
self.results_ready = False # A flag to determine if the experiment has finished running and the results exist yet
# Use the externally provided IC_ImagingControl instances if one is provided
if ic_imaging_control != None:
self.ic_ic = ic_imaging_control
if not self.ic_ic.initialised:
self.ic_ic.init_library()
self.external_ic_ic_provided = True
# Otherwise create and initialise one of our own, setting a flag so it is closed again later.
else:
self.ic_ic = IC_ImagingControl()
self.ic_ic.init_library()
self.external_ic_ic_provided = False
if self.sequence.t_step > 100:
print ('WARNING: Sequence step size is > 100us. This means the fastest possible imaging flash is longer than recommended.\n',
'Typically the order of 10us flashes are appropriate. Continuing with the sequence anyway...')
self.save_location = os.path.join(c.save_location, time.strftime("%y-%m-%d/%H-%M-%S"))
if not os.path.exists(self.save_location):
os.makedirs(self.save_location)
# If the trigger levs have not been set, default them to 0 and the maximum permitted value on the camera/imaging channels.
if c.camera_trig_levs == None:
c.camera_trig_levs = (0, next(ch.chLimits[1] if not ch.isCalibrated else ch.calibrationFromVFunc(ch.chLimits[1])
for ch in daq_controller.getChannels() if ch.chNum == c.camera_trig_ch))
if c.imag_power_levs == None:
c.imag_power_levs = (0, next(ch.chLimits[1] if not ch.isCalibrated else ch.calibrationFromVFunc(ch.chLimits[1])
for ch in daq_controller.getChannels() if ch.chNum == c.imag_power_ch))
# If the camera trigger pulse is shorter than a single time step in the sequence, make it longer so it actually happens!
if c.camera_pulse_width < sequence.t_step:
c.camera_pulse_width = sequence.t_step
# If the imaging pulse width has not been set or is too short, default it to one point in the sequence (i.e. as short
# as possible),
if c.imag_pulse_width == None or c.imag_pulse_width < sequence.t_step:
c.imag_pulse_width = sequence.t_step
# Check the absorbtion imaging flash will be on for background images and other sanity checks
if c.imag_power_ch in c.bkg_off_channels:
print 'WARNING: You specified no to to have the absorption imaging flash on while taking backgrounds. \n' +\
'This will lead to poor background correction so it will be left on for background regardless.'
c.bkg_off_channels.remove(c.imag_power_ch)
if len(c.bkg_off_channels)==0:
print 'WARNING: No channels are turned off when taking background images - this means the images will be taken \n' +\
'using an identical sequence to the absorption images. Please consider turning the MOT repump off to remove \n' +\
'atoms from the background images.'
def __configureExperiment(self):
'''
Perform and configuration that has to occur before the experiment can be safely run.
'''
# Make a list of sequences (in time order) to run in order to take the imaging pictures
self.sequences = []
self.bkg_sequences = []
c = self.config
t_lag = AbsorbtionImagingExperiment.shutter_lag
# t_offset = AbsorbtionImagingExperiment.flash_offset
t_offset = ((1./c.cam_exposure)*10**6)/2
for t in c.t_imgs:
if t==0: t += self.sequence.t_step
sequenceCopy = copy.deepcopy(self.sequence)
# Note the camera triggers on the down slope of the square wave trigger sent to it.
print 'cam trig: {0}-{1}'.format(np.clip(t-c.camera_pulse_width,0,self.sequence.getLength()), t)
sequenceCopy.updateChannel(c.camera_trig_ch, [(0,c.camera_trig_levs[0]),
(np.clip(t-c.camera_pulse_width,0,self.sequence.getLength()), c.camera_trig_levs[1]),
(t,c.camera_trig_levs[0])],
[IntervalStyle.FLAT]*3)
print 'flash: {0}-{1}'.format(np.clip(t+t_lag+t_offset, 0, sequenceCopy.getLength()-c.imag_pulse_width), np.clip(t+t_lag+t_offset+c.imag_pulse_width, 0, sequenceCopy.getLength()-sequenceCopy.t_step ))
sequenceCopy.updateChannel(c.imag_power_ch, [(0,c.imag_power_levs[0]),
(np.clip(t+t_lag+t_offset, 0, sequenceCopy.getLength()-c.imag_pulse_width) ,c.imag_power_levs[1]),
(np.clip(t+t_lag+t_offset+c.imag_pulse_width, 0, sequenceCopy.getLength()-sequenceCopy.t_step),c.imag_power_levs[0])],
[IntervalStyle.FLAT]*3)
# t=1000
# sequenceCopy.updateChannel(c.imag_power_ch, [(0,c.imag_power_levs[0]),
# ( np.clip( t+t_lag+t_offset, 0, sequenceCopy.getLength()-c.imag_pulse_width) ,c.imag_power_levs[1]),
# ( np.clip( t+t_lag+t_offset+c.imag_pulse_width, 0, sequenceCopy.getLength()-sequenceCopy.t_step ),c.imag_power_levs[0])],
# [IntervalStyle.FLAT]*3)
self.sequences.append(sequenceCopy)
sequenceBackground = copy.deepcopy(sequenceCopy)
# Set any channels that should be off for background images to zero.
for ch in c.bkg_off_channels:
sequenceBackground.updateChannel(ch, [(0,0)],[IntervalStyle.FLAT])
self.bkg_sequences.append(sequenceBackground)
# Make a list of labels for the sequences - this is what the images will be saved as.
self.sequence_labels = map(int,c.t_imgs)
if c.scan_abs_img_freq:
new_seqs = []
new_labs = []
try:
calib_units,_,fromVFunc = self.daq_controller.getChannelCalibrationDict()[c.abs_img_freq_ch]
except KeyError:
calib_units,_,fromVFunc = 'V', None, lambda x: x
for freq in c.abs_img_freqs:
seqs_copy = [copy.deepcopy(seq) for seq in self.sequences]
for seq in seqs_copy:
seq.updateChannel(c.abs_img_freq_ch, [(0, freq)], [IntervalStyle.FLAT])
new_seqs += seqs_copy
new_labs += ["{0}_{1}{2}".format(lab, fromVFunc(freq), calib_units) for lab in self.sequence_labels]
self.sequences = new_seqs
self.bkg_sequences = self.bkg_sequences*len(c.abs_img_freqs)
self.sequence_labels = new_labs
self.isDaqContinuousOutput = self.daq_controller.continuousOutput
if not self.isDaqContinuousOutput:
print "DAQ output must be on to run a sequence - turning it on."
self.daq_controller.toggleContinuousOutput()
def run(self, analayse=True, bkg_test=False):
'''
Run the absorbtion imaging. This first generates a series of sequences to run, then
opens and configures the camera, takes the images, saves them and closes the camera.
'''
print 'Running absorbtion imaging experiment'
self.__configureExperiment()
try:
self.__configureCamera()
img_arrs, bkg_arrs = self.__takeImages(save_raw_images=self.config.save_raw_images)
if bkg_test:
self.corr_img_arrs, self.ave_bkg_arrs = None, [sum([b.astype(np.float)/len(bkgs) for b in bkgs]) for bkgs in bkg_arrs]
elif analayse:
self.corr_img_arrs, self.ave_bkg_arrs = self.__analyseImages(img_arrs, bkg_arrs, save_processed_images=self.config.save_processed_images)
else: