-
Notifications
You must be signed in to change notification settings - Fork 9
/
smurf_util.py
4843 lines (4037 loc) · 180 KB
/
smurf_util.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 python
#-----------------------------------------------------------------------------
# Title : pysmurf util module - SmurfUtilMixin class
#-----------------------------------------------------------------------------
# File : pysmurf/util/smurf_util.py
# Created : 2018-08-29
#-----------------------------------------------------------------------------
# This file is part of the pysmurf software package. It is subject to
# the license terms in the LICENSE.txt file found in the top-level directory
# of this distribution and at:
# https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.
# No part of the pysmurf software package, including this file, may be
# copied, modified, propagated, or distributed except according to the terms
# contained in the LICENSE.txt file.
#-----------------------------------------------------------------------------
from contextlib import contextmanager
import glob
import os
import threading
import time
import re
import matplotlib.pyplot as plt
import numpy as np
from scipy import signal
from pysmurf.client.base import SmurfBase
from pysmurf.client.command.sync_group import SyncGroup as SyncGroup
from pysmurf.client.util.SmurfFileReader import SmurfStreamReader
from pysmurf.client.util.pub import set_action
class SmurfUtilMixin(SmurfBase):
@set_action()
def take_debug_data(self, band, channel=None, nsamp=2**19, filename=None,
IQstream=1, single_channel_readout=1, debug=False, rf_iq=False,
write_log=True):
"""Takes raw debugging data.
Args
----
band : int
The band to take data on.
channel : int or None, optional, default None
The channel to take debug data on in single_channel_mode.
nsamp : int, optional, default 2**19
The number of samples to take.
filename : str or None, optional, default None
The name of the file to save to.
IQstream : int, optional, default 1
Whether to take the raw IQ stream.
single_channel_readout : int, optional, default 1
Whether to look at one channel.
debug : bool, optional, default False
Whether to take data in debug mode.
rf_iq : bool, optional, default False
Return the RF IQ. Must provide channel.
write_log : bool, optional, default True
Whether to write low-level commands to the log file.
Returns
-------
f : float array
The frequency response.
df : float array
The frequency error.
sync : float array
The sync count.
"""
# Set proper single channel readout
if channel is not None:
if rf_iq:
IQstream = False
single_channel_readout = 2
self.set_rf_iq_stream_enable(band, 1)
if single_channel_readout == 1:
self.set_single_channel_readout(band, 1)
self.set_single_channel_readout_opt2(band, 0)
elif single_channel_readout == 2:
self.set_single_channel_readout(band, 0)
self.set_single_channel_readout_opt2(band, 1)
else:
self.log('single_channel_readout must be 1 or 2',
self.LOG_ERROR)
raise ValueError('single_channel_readout must be 1 or 2')
self.set_readout_channel_select(band, channel, write_log=write_log)
else: # exit single channel otherwise
self.set_single_channel_readout(band, 0, write_log=write_log)
self.set_single_channel_readout_opt2(band, 0, write_log=write_log)
# Set IQstream
if IQstream == 1:
self.set_iq_stream_enable(band, 1)
else:
self.set_iq_stream_enable(band, 0)
# set filename
if filename is not None:
data_filename = os.path.join(self.output_dir, filename+'.dat')
self.log(f'Writing to file : {data_filename}',
self.LOG_USER)
else:
timestamp = self.get_timestamp()
data_filename = os.path.join(self.output_dir, timestamp+'.dat')
self.log(f'Writing to file : {data_filename}',
self.LOG_USER)
dtype = 'debug'
dchannel = 0 # I don't really know what this means and I'm sorry -CY
self.setup_daq_mux(dtype, dchannel, nsamp, band=band, debug=debug)
self.log('Data acquisition in progress...', self.LOG_USER)
char_array = [ord(c) for c in data_filename] # convert to ascii
write_data = np.zeros(300, dtype=int)
for j in np.arange(len(char_array)):
write_data[j] = char_array[j]
self.set_streamdatawriter_datafile(write_data) # write this
#self.set_streamdatawriter_open('True') # str and not bool
self.set_streamdatawriter_open(True)
bay=self.band_to_bay(band)
self.set_trigger_daq(bay, 1, write_log=True) # this seems to = TriggerDM
time.sleep(.1) # maybe unnecessary
done=False
while not done:
done=True
for k in range(2):
# see pysmurf issue 161. This call is no longer used,
# and causes take_debug_data to crash if
# get_waveform_wr_addr is called before the
# acquisition completes.
#wr_addr = self.get_waveform_wr_addr(bay, engine=0)
empty = self.get_waveform_empty(bay, engine=k)
if not empty:
done=False
time.sleep(1)
time.sleep(.25) # do we need all of these?
# Close the streamdatawriter
self.set_streamdatawriter_close(True)
self.log('Done taking data', self.LOG_USER)
self.pub.register_file(data_filename, 'debug', format='dat')
if rf_iq:
self.set_rf_iq_stream_enable(band, 0)
if single_channel_readout > 0:
f, df, sync = self.decode_single_channel(data_filename)
else:
f, df, sync = self.decode_data(data_filename)
return f, df, sync
# the JesdWatchdog will check if an instance of the JesdWatchdog is already
# running and kill itself if there is
def start_jesd_watchdog(self):
import pysmurf.client.watchdog.JesdWatchdog as JesdWatchdog
import subprocess
import sys
subprocess.Popen([sys.executable,JesdWatchdog.__file__])
# Shawn needs to make this better and add documentation.
@set_action()
def estimate_phase_delay(self, band, nsamp=2**19, make_plot=True,
show_plot=True, save_plot=True, save_data=True, n_scan=5,
timestamp=None, uc_att=None, dc_att=None, freq_min=-2.4E6, freq_max=2.4E6):
"""Estimates total system latency for requested band.
Measures the analog and digital (=processing) phase delay (or
latency) by sweeping the [`freq_min`, `freq_max`] interval of the
requested 500 MHz band. Estimates the best values for the
`refPhaseDelay` and `refPhaseDelayFine` firmware registers to
compensate for the measured delay. Three steps:
1. Measures the analog latency using the [`freq_min`, `freq_max`]
sub-interval of data taken using the
:func:`~pysmurf.client.tune.smurf_tune.SmurfTuneMixin.full_band_resp`
routine.
2. Measures the total latency using the
:func:`~pysmurf.client.tune.smurf_tune.SmurfTuneMixin.find_freq`
routine.
3. Sets the `refPhaseDelay` and `refPhaseDelayFine` registers
to the values computed to best compensate for the total
measured latency and re-measures the total latency again
using the
:func:`~pysmurf.client.tune.smurf_tune.SmurfTuneMixin.find_freq`
routine.
On completion, the `refPhaseDelay` and `refPhaseDelayFine`
registers are set to the estimated optimal values.
Args
----
band : int
The band to estimate phase delay on.
nsamp : int, optional, default 2**19
The number of samples to take.
make_plot : bool, optional, default True
Whether or not to make plots.
show_plot : bool, optional, default True
Whether or not to show plots.
save_plot : bool, optional, default True
Whether or not to save plot to file.
save_data : bool, optional, default True
Whether or not to save data to file.
n_scan : int, optional, default 5
Number of scans to do to estimate analog phase delay,
passed to
:func:`~pysmurf.client.tune.smurf_tune.SmurfTuneMixin.full_band_resp`.
timestamp : str or None, optional, default None
ctime to timestamp the plot and data with (if saved to
file). If None, it gets the time stamp right before
acquiring data.
uc_att : int or None, optional, default None
UC attenuator setting to use during measurements. If None,
uses currently programmed setting.
dc_att : int or None, optional, default None
DC attenuator setting to use during measurements. If None,
uses currently programmed setting.
freq_min : float, optional, default -2.4E6
Lower bound of the frequency interval used to estimate the
phase delay, in Hz. From the center of the 500 MHz band.
freq_max : float, optional, default 2.4E6
Upper bound of the frequency interval used to estimate the
phase delay, in Hz. From the center of the 500 MHz band.
Returns
-------
processing_delay_us : float
Estimated processing phase delay, in microseconds.
dsp_corr_delay_us : float
Residual total phase delay, for estimated `refPhaseDelay`
and `refPhaseDelayFine`.
"""
self.set_band_delay_us(band, 0)
uc_att0 = self.get_att_uc(band)
dc_att0 = self.get_att_dc(band)
if uc_att is None:
uc_att = self.get_att_uc(band)
if dc_att is None:
dc_att = self.get_att_dc(band)
self.set_att_uc(band, uc_att, write_log=True)
self.set_att_dc(band, dc_att, write_log=True)
# only loop over dsp subbands in requested frequency range (to
# save time)
n_subbands = self.get_number_sub_bands(band)
digitizer_frequency_mhz = self.get_digitizer_frequency_mhz(band)
subband_half_width_mhz = digitizer_frequency_mhz/\
n_subbands
subbands,subband_centers=self.get_subband_centers(band)
subband_freq_min=-subband_half_width_mhz/2.
subband_freq_max=subband_half_width_mhz/2.
dsp_subbands=[]
for sb,sbc in zip(subbands,subband_centers):
# ignore unprocessed sub-bands
if sb not in subbands:
continue
lower_sb_freq=sbc+subband_freq_min
upper_sb_freq=sbc+subband_freq_max
if lower_sb_freq>=(freq_min/1.e6-subband_half_width_mhz) and \
upper_sb_freq<=(freq_max/1.e6+subband_half_width_mhz):
dsp_subbands.append(sb)
if timestamp is None:
timestamp = self.get_timestamp()
if make_plot:
if show_plot:
plt.ion()
else:
plt.ioff()
bay=int(band/4)
fw_abbrev_sha=self.get_fpga_git_hash_short()
self.band_off(band)
self.flux_ramp_off()
self.log('Running full band resp')
freq_cable, resp_cable = self.full_band_resp(
band, nsamp=nsamp, make_plot=make_plot,
save_data=save_data, n_scan=n_scan)
idx_cable = np.where( (freq_cable > freq_min) & (freq_cable < freq_max) )
cable_z = np.polyfit(freq_cable[idx_cable], np.unwrap(np.angle(resp_cable[idx_cable])), 1)
cable_p = np.poly1d(cable_z)
cable_delay_us=np.abs(1.e6*cable_z[0]/2/np.pi)
freq_cable_subset=freq_cable[idx_cable]
resp_cable_subset=resp_cable[idx_cable]
#### done measuring cable delay
#### start measuring dsp delay (cable+processing)
## FIXME -- should be able to scan with "0" delay, not working
self.set_band_delay_us(band, 1)
self.log('Running find_freq')
#freq_dsp,resp_dsp=self.find_freq(band, start_freq=freq_min, stop_freq=freq_max)
freq_dsp,resp_dsp=self.find_freq(band,subband=dsp_subbands)
# only preserve data in the subband half width
freq_dsp_subset=[]
resp_dsp_subset=[]
est_delay=[]
for sb,sbc in zip(subbands,subband_centers):
freq_subband=freq_dsp[sb]-sbc
idx = np.where( ( freq_subband > subband_freq_min ) &
(freq_subband < subband_freq_max) )
if len(idx[0]) > 0:
dsp_z = np.polyfit(freq_dsp[sb][idx]*1e6, np.unwrap(np.angle(resp_dsp[sb][idx])), 1)
dsp_p = np.poly1d(dsp_z)
dsp_delay_us=np.abs(1.e6*dsp_z[0]/2/np.pi)
dsp_delay_us=dsp_delay_us + self.get_band_delay_us(band)
est_delay.append(dsp_delay_us)
freq_dsp_subset.extend(freq_dsp[sb][idx])
resp_dsp_subset.extend(resp_dsp[sb][idx])
freq_dsp_subset=np.array(freq_dsp_subset)
resp_dsp_subset=np.array(resp_dsp_subset)
idx_dsp = np.where( (freq_dsp_subset > freq_min) &
(freq_dsp_subset < freq_max) )
# restrict to requested frequencies only
freq_dsp_subset=freq_dsp_subset[idx_dsp]
resp_dsp_subset=resp_dsp_subset[idx_dsp]
# to Hz
freq_dsp_subset=(freq_dsp_subset)*1.0E6
# fit
dsp_z = np.polyfit(freq_dsp_subset, np.unwrap(np.angle(resp_dsp_subset)), 1)
dsp_p = np.poly1d(dsp_z)
dsp_delay_us=np.abs(1.e6*dsp_z[0]/2/np.pi)
dsp_delay_us=dsp_delay_us + self.get_band_delay_us(band)
dsp_delay_us=np.mean(est_delay)
processing_delay_us=dsp_delay_us-cable_delay_us
print('-------------------------------------------------------')
print(f'Estimated cable_delay_us={cable_delay_us}')
print(f'Estimated dsp_delay_us={dsp_delay_us}')
print(f'Estimated processing_delay_us={processing_delay_us}')
print('-------------------------------------------------------')
#### done measuring dsp delay (cable+processing)
#### start measuring total (DSP + cable) delay with estimated correction applied
self.set_band_delay_us(band, dsp_delay_us)
self.log('Running find_freq')
freq_dsp_corr,resp_dsp_corr=self.find_freq(band,subband=dsp_subbands)
freq_dsp_corr_subset=[]
resp_dsp_corr_subset=[]
first = True
for sb,sbc in zip(subbands,subband_centers):
freq_subband=freq_dsp_corr[sb]-sbc
idx = np.where( ( freq_subband > subband_freq_min ) & (freq_subband < subband_freq_max) )
if len(idx[0]) > 0:
if not first:
last_phase = np.angle(resp_dsp_corr_subset[-1])
new_phase = np.angle(resp_dsp_corr[sb][idx[0]])
resp_dsp_corr[sb][idx] = resp_dsp_corr[sb][idx] * np.exp(1j*(last_phase - new_phase))
if first:
first = False
freq_dsp_corr_subset.extend(freq_dsp_corr[sb][idx])
resp_dsp_corr_subset.extend(resp_dsp_corr[sb][idx])
freq_dsp_corr_subset=np.array(freq_dsp_corr_subset)
resp_dsp_corr_subset=np.array(resp_dsp_corr_subset)
# restrict to requested frequency subset
idx_dsp_corr = np.where( (freq_dsp_corr_subset > freq_min) & (freq_dsp_corr_subset < freq_max) )
# restrict to requested frequencies only
freq_dsp_corr_subset=freq_dsp_corr_subset[idx_dsp_corr]
resp_dsp_corr_subset=resp_dsp_corr_subset[idx_dsp_corr]
# to Hz
freq_dsp_corr_subset=(freq_dsp_corr_subset)*1.0E6
# fit
dsp_corr_z = np.polyfit(freq_dsp_corr_subset, np.unwrap(np.angle(resp_dsp_corr_subset)), 1)
dsp_corr_delay_us=np.abs(1.e6*dsp_corr_z[0]/2/np.pi)
#### done measuring total (DSP) delay with estimated correction applied
# plot unwraped phase in top panel, subtracted in bottom
fig, ax = plt.subplots(3, figsize=(6,7.5), sharex=True)
f_cable_plot = (freq_cable_subset) / 1.0E6
cable_phase = np.unwrap(np.angle(resp_cable_subset))
f_dsp_plot = (freq_dsp_subset) / 1.0E6
dsp_phase = np.unwrap(np.angle(resp_dsp_subset))
f_dsp_corr_plot = (freq_dsp_corr_subset) / 1.0E6
dsp_corr_phase = np.unwrap(np.angle(resp_dsp_corr_subset))
ax[0].set_title(f'AMC in Bay {bay}, Band {band} Cable Delay')
ax[0].plot(f_cable_plot,cable_phase,label='Cable (full_band_resp)',
c='g', lw=3)
ax[0].plot(f_cable_plot,cable_p(f_cable_plot*1.0E6),'m--',
label='Cable delay fit',lw=3)
ax[1].set_title(f'AMC in Bay {bay}, Band {band} DSP Delay')
ax[1].plot(f_dsp_plot,dsp_phase,label='DSP (find_freq)',c='c',lw=3)
ax[1].plot(f_dsp_plot,dsp_p(f_dsp_plot*1.0E6), c='orange', ls='--',
label='DSP delay fit', lw=3)
ax[0].set_ylabel("Phase [rad]")
ax[0].set_xlabel('Frequency offset from band center [MHz]')
ax[1].set_ylabel("Phase [rad]")
ax[1].set_xlabel('Frequency offset from band center [MHz]')
ax[0].legend(loc='lower left',fontsize=8)
ax[1].legend(loc='lower left',fontsize=8)
bbox = dict(boxstyle="round", ec='w', fc='w', alpha=.65)
ax[0].text(.97, .90, f'cable delay={cable_delay_us:.5f} us',
transform=ax[0].transAxes, fontsize=10,
bbox=bbox,horizontalalignment='right')
ax[1].text(.97, .90, f'dsp delay={dsp_delay_us:.5f} us',
transform=ax[1].transAxes, fontsize=10,
bbox=bbox,horizontalalignment='right')
cable_residuals=cable_phase-(cable_p(f_cable_plot*1.0E6))
ax[2].plot(f_cable_plot,cable_residuals-np.median(cable_residuals),
label='Cable (full_band_resp)',c='g')
ax[2].plot(f_dsp_corr_plot,dsp_corr_phase-np.median(dsp_corr_phase),
label='DSP (find_freq)', c='c')
ax[2].set_title(f'AMC in Bay {bay}, Band {band} Residuals'.format(bay,band))
ax[2].set_ylabel("Residual [rad]")
ax[2].set_xlabel('Frequency offset from band center [MHz]')
ax[2].set_ylim([-5,5])
ax[2].text(.97, .76,
f'processing delay={processing_delay_us:.5f} us (fw={fw_abbrev_sha})',
transform=ax[2].transAxes, fontsize=8,
bbox=bbox,horizontalalignment='right')
ax[2].text(.97, .68, f'delay post-correction={dsp_corr_delay_us*1000.:.3f} ns',
transform=ax[2].transAxes, fontsize=8,
bbox=bbox,horizontalalignment='right')
ax[2].legend(loc='upper left',fontsize=8)
plt.tight_layout()
if save_plot:
save_name = f'{timestamp}_b{band}_delay.png'
path = os.path.join(self.plot_dir, save_name)
plt.savefig(path,bbox_inches='tight')
self.pub.register_file(path, 'delay', plot=True)
if not show_plot:
plt.close()
self.log('Setting attenuator values back to original values')
self.log(f'UC Att: {uc_att0}')
self.log(f'DC Att: {dc_att0}')
self.set_att_uc(band, uc_att0, write_log=True)
self.set_att_dc(band, dc_att0, write_log=True)
if show_plot:
plt.show()
return dsp_delay_us, dsp_corr_delay_us
def process_data(self, filename, dtype=np.uint32):
""" Reads a file taken with take_debug_data and processes it into data
and header.
Args
----
filename : str
Path to file
dtype : numpy.dtype, optional, default numpy.uint32
datatype to cast to.
Returns
-------
header : numpy.ndarray
The header information.
data : numpy.ndarray
The resonator data.
"""
n_chan = 2 # number of stream channels
#header_size = 4 # 8 bytes in 16-bit word
rawdata = np.fromfile(filename, dtype='<u4').astype(dtype)
# -1 is equiv to [] in Matlab
rawdata = np.transpose(np.reshape(rawdata, (n_chan, -1)))
if dtype==np.uint32:
header = rawdata[:2, :]
data = np.delete(rawdata, (0,1), 0).astype(dtype)
elif dtype==np.int32:
header = np.zeros((2,2))
header[:,0] = rawdata[:2,0].astype(np.uint32)
header[:,1] = rawdata[:2,1].astype(np.uint32)
data = np.double(np.delete(rawdata, (0,1), 0))
elif dtype==np.int16:
header1 = np.zeros((4,2))
header1[:,0] = rawdata[:4,0].astype(np.uint16)
header1[:,1] = rawdata[:4,1].astype(np.uint16)
header1 = np.double(header1)
header = header1[::2] + header1[1::2] * (2**16) # what am I doing
else:
raise TypeError(f'Type {dtype} not yet supported!')
if (header[1,1]>>24 == 2) or (header[1,1]>>24 == 0):
header = np.fliplr(header)
data = np.fliplr(data)
return header, data
@set_action()
def decode_data(self, filename, swapFdF=False, recast=True, truncate=True):
""" Take a dataset from take_debug_data and spit out results.
Args
----
filename : str
Path to file.
swapFdF : bool, optional, default False
Whether the F and dF (or I/Q) streams are flipped.
recast : bool, optional, default True
Whether to recast from size n_channels_processed to
n_channels.
truncate : bool, optional, default True
Truncates the data if the number of elements returned is
not an integer multiple of the sample rate.
Returns
-------
f : numpy.ndarray
If iqStreamEnable = 0. f is the tracking frequency.
Otherwise if iqStreamEnable = 1. f is the demodulated
in-phase tracking component.
df : numpy.ndarray
If iqStreamEnable = 0. df is the tracking frequency error.
Otherwise if iqStreamEnable = 1. f is the demodulated
quadrature tracking component.
flux_ramp_strobe : numpy.ndarray
The synchronizing pulse.
"""
n_proc = self.get_number_processed_channels()
n_chan = self.get_number_channels()
n_subbands = self.get_number_sub_bands()
digitizer_frequency_mhz = self.get_digitizer_frequency_mhz()
subband_half_width_mhz = (digitizer_frequency_mhz / n_subbands)
header, rawdata = self.process_data(filename)
# decode strobes
strobes = np.floor(rawdata / (2**30))
data = 0x00FFFFFF & rawdata
ch0_strobe = np.remainder(strobes, 2)
flux_ramp_strobe = np.floor((strobes - ch0_strobe) / 2)
# decode frequencies
ch0_idx = np.where(ch0_strobe[:,0] == 1)[0]
f_first = ch0_idx[0]
f_last = ch0_idx[-1]
freqs = data[f_first:f_last, 0]
neg = np.where(freqs >= 2**23)[0]
f = np.double(freqs)
if len(neg) > 0:
f[neg] = f[neg] - 2**24
if np.remainder(len(f), n_proc)!=0:
if truncate:
self.log(f'Number of points in f not a multiple of {n_proc}.' +
f' Truncating f to the nearest multiple of {n_proc}.',
self.LOG_USER)
f=f[:(len(f)-np.remainder(len(f),n_proc))]
else:
self.log(f'Number of points in f not a multiple of {n_proc}.'+
' Cannot decode', self.LOG_ERROR)
f = np.reshape(f, (-1, n_proc)) * subband_half_width_mhz / 2**23
# frequency errors
ch0_idx_df = np.where(ch0_strobe[:,1] == 1)[0]
if len(ch0_idx_df) > 0:
d_first = ch0_idx_df[0]
d_last = ch0_idx_df[-1]
dfreq = data[d_first:d_last, 1]
neg = np.where(dfreq >= 2**23)[0]
df = np.double(dfreq)
if len(neg) > 0:
df[neg] = df[neg] - 2**24
if np.remainder(len(df), n_proc)!=0:
if truncate:
self.log('Number of points in df not a multiple of '+
f'{n_proc}. Truncating df to the nearest multiple ' +
f' of {n_proc}.', self.LOG_USER)
df=df[:(len(df)-np.remainder(len(df),n_proc))]
else:
self.log(f'Number of points in df not a multiple of {n_proc}.' +
'Cannot decode', self.LOG_ERROR)
df = np.reshape(df, (-1, n_proc)) * subband_half_width_mhz / 2**23
else:
df = []
if recast:
nsamp, nprocessed = np.shape(f)
nsamp_df, _ = np.shape(df)
if nsamp != nsamp_df:
self.log('f and df are different sizes. Choosing the smaller'
' value. Not sure why this is happening.')
nsamp = np.min([nsamp, nsamp_df])
ftmp = np.zeros((nsamp, n_chan))
dftmp = np.zeros_like(ftmp)
processed_ind = self.get_processed_channels()
ftmp[:, processed_ind] = f[:nsamp]
dftmp[:, processed_ind] = df[:nsamp]
f = ftmp
df = dftmp
return f, df, flux_ramp_strobe
@set_action()
def decode_single_channel(self, filename, swapFdF=False):
"""
decode take_debug_data file if in singlechannel mode
Args
----
filename : str
Path to file to decode.
swapFdF : bool, optional, default False
Whether to swap f and df streams.
Returns
-------
list
[f, df, sync] if iq_stream_enable = False
[I, Q, sync] if iq_stream_enable = True
"""
n_subbands = self.get_number_sub_bands()
digitizer_frequency_mhz = self.get_digitizer_frequency_mhz()
subband_half_width_mhz = (digitizer_frequency_mhz / n_subbands)
if swapFdF:
nF = 1
nDF = 0
else:
nF = 0
nDF = 1
header, rawdata = self.process_data(filename)
# decode strobes
strobes = np.floor(rawdata / (2**30))
data = rawdata - (2**30)*strobes
ch0_strobe = np.remainder(strobes, 2)
flux_ramp_strobe = np.floor((strobes - ch0_strobe) / 2)
# decode frequencies
freqs = data[:,nF]
neg = np.where(freqs >= 2**23)[0]
f = np.double(freqs)
if len(neg) > 0:
f[neg] = f[neg] - 2**24
f = np.transpose(f) * subband_half_width_mhz / 2**23
dfreqs = data[:,nDF]
neg = np.where(dfreqs >= 2**23)[0]
df = np.double(dfreqs)
if len(neg) > 0:
df[neg] = df[neg] - 2**24
df = np.transpose(df) * subband_half_width_mhz / 2**23
return f, df, flux_ramp_strobe
@set_action(action=None)
def take_stream_data(self, meas_time, downsample_factor=None,
write_log=True, update_payload_size=True,
reset_unwrapper=True, reset_filter=True,
return_data=False, make_freq_mask=True,
register_file=False):
"""
Takes streaming data for a given amount of time
To do: move downsample_factor to config table
Args
----
meas_time : float
The amount of time to observe for in seconds.
downsample_factor : int or None, optional, default None
The number of fast sample (the flux ramp reset rate -
typically 4kHz) to skip between reporting. If None, does
not update.
write_log : bool, optional, default True
Whether to write to the log file.
update_payload_size : bool, optional, default True
Whether to update the payload size (the number of channels
written to disk). If the number of channels on is greater
than the payload size, then only the first N channels are
written. This bool will update the payload size to be the
same as the number of channels on across all bands)
reset_unwrapper : bool, optional, default True
Whether to reset the unwrapper before taking data.
reset_filter : bool, optional, default True
Whether to reset the filter before taking data.
return_data : bool, optional, default False
Whether to return the data. If False, returns the full
path to the data.
make_freq_mask : bool, optional, default True
Whether to write a text file with resonator frequencies.
register_file : bool, optional, default False
Whether to register the data file with the pysmurf
publisher.
Returns
-------
data_filename : str
The fullpath to where the data is stored.
"""
if write_log:
self.log('Starting to take data.', self.LOG_USER)
data_filename = self.stream_data_on(downsample_factor=downsample_factor,
update_payload_size=update_payload_size, write_log=write_log,
reset_unwrapper=reset_unwrapper, reset_filter=reset_filter,
make_freq_mask=make_freq_mask)
# Sleep for the full measurement time
time.sleep(meas_time)
# Stop acq
self.stream_data_off(write_log=write_log, register_file=register_file)
if write_log:
self.log('Done taking data.', self.LOG_USER)
if return_data:
t, d, m = self.read_stream_data(data_filename)
return t, d, m
else:
return data_filename
@contextmanager
def stream_data_cm(self, write_log=True, register_file=False,
**stream_on_kwargs):
"""
Context manager for data streaming. If you intend to turn streaming
on, do something, and then turn streaming off this is a safe way to make
sure streaming is in fact stopped properly even if an error is raised.
Args
----
write_config : bool, optional, default False
Whether to dump the entire config. Warning this can be
slow.
data_filename : str or None, optional, default None
The full path to store the data. If None, it uses the
timestamp.
downsample_factor : int or None, optional, default None
The number of fast samples to skip between sending.
write_log : bool, optional, default True
Whether to write to the log file.
update_payload_size : bool, optional, default True
Whether to update the payload size (the number of channels
written to disk). If the number of channels on is greater
than the payload size, then only the first N channels are
written. This bool will update the payload size to be the
same as the number of channels on across all bands)
reset_filter : bool, optional, default True
Whether to reset the filter before taking data.
reset_unwrapper : bool, optional, default True
Whether to reset the unwrapper before taking data.
make_freq_mask : bool, optional, default True
Whether to write a text file with resonator frequencies.
register_file : bool, optional, default False
If true, the stream data file will be registered through
the publisher.
Yields
-------
data_filename : str
The fullpath to where the data is stored.
"""
data_filename = self.stream_data_on(write_log=write_log, **stream_on_kwargs)
try:
yield data_filename
finally:
self.stream_data_off(write_log=write_log,
register_file=register_file)
@set_action()
def stream_data_on(self, write_config=False, data_filename=None,
downsample_factor=None, write_log=True,
update_payload_size=True, reset_filter=True,
reset_unwrapper=True, make_freq_mask=True,
channel_mask=None, make_datafile=True,
filter_wait_time=0.1):
"""
Turns on streaming data.
Args
----
write_config : bool, optional, default False
Whether to dump the entire config. Warning this can be
slow.
data_filename : str or None, optional, default None
The full path to store the data. If None, it uses the
timestamp.
downsample_factor : int or None, optional, default None
The number of fast samples to skip between sending.
write_log : bool, optional, default True
Whether to write to the log file.
update_payload_size : bool, optional, default True
Whether to update the payload size (the number of channels
written to disk). If this is True, will set the payload size to
0, which tells rogue to automatically adjust it based on the
channel count.
reset_filter : bool, optional, default True
Whether to reset the filter before taking data.
reset_unwrapper : bool, optional, default True
Whether to reset the unwrapper before taking data.
make_freq_mask : bool, optional, default True
Whether to write a text file with resonator frequencies.
channel_mask : list or None, optional, default None
Channel mask to set before streamig data. This should be an array
of absolute smurf channels between 0 and
``nbands * chans_per_band``. If None will create the channel mask
containing all channels with a non-zero tone amplitude.
make_datafile : bool, optional, default True
Whether to create a datafile.
filter_wait_time : float, optional, default 0.1
Time in seconds to wait after filter reset.
Returns
-------
data_filename : str
The fullpath to where the data is stored.
"""
bands = self._bands
if downsample_factor is not None:
self.set_downsample_factor(downsample_factor)
else:
downsample_factor = self.get_downsample_factor()
if write_log:
self.log('Input downsample factor is None. Using '+
'value already in pyrogue:'+
f' {downsample_factor}')
if update_payload_size:
self.set_payload_size(0)
# Check if flux ramp is non-zero
ramp_max_cnt = self.get_ramp_max_cnt()
if ramp_max_cnt == 0:
self.log('Flux ramp frequency is zero. Cannot take data.',
self.LOG_ERROR)
else:
# check which flux ramp relay state we're in
# read_ac_dc_relay_status() should be 0 in DC mode, 3 in
# AC mode. this check is only possible if you're using
# one of the newer C02 cryostat cards.
flux_ramp_ac_dc_relay_status = self.C.read_ac_dc_relay_status()
if flux_ramp_ac_dc_relay_status == 0:
if write_log:
self.log("FLUX RAMP IS DC COUPLED.", self.LOG_USER)
elif flux_ramp_ac_dc_relay_status == 3:
if write_log:
self.log("Flux ramp is AC-coupled.", self.LOG_USER)
else:
self.log("flux_ramp_ac_dc_relay_status = " +
f"{flux_ramp_ac_dc_relay_status} " +
"- NOT A VALID STATE.", self.LOG_ERROR)
if channel_mask is None:
# Creates a channel mask with all channels that have enabled
# tones
smurf_chans = {}
for b in bands:
smurf_chans[b] = self.which_on(b)
channel_mask = self.make_channel_mask(bands, smurf_chans)
self.set_channel_mask(channel_mask)
else:
channel_mask = np.atleast_1d(channel_mask)
self.set_channel_mask(channel_mask)
time.sleep(0.5)
# start streaming before opening file
# to avoid transient filter step
self.set_stream_enable(1, write_log=False, wait_done=True)
if reset_unwrapper:
self.set_unwrapper_reset(write_log=write_log)
if reset_filter:
self.set_filter_reset(write_log=write_log)
if reset_unwrapper or reset_filter:
time.sleep(filter_wait_time)
# Make the data file
timestamp = self.get_timestamp()
if data_filename is None:
data_filename = os.path.join(self.output_dir, timestamp+'.dat')
if make_datafile:
self.set_data_file_name(data_filename)
# Optionally write PyRogue configuration
if write_config:
config_filename=os.path.join(self.output_dir, timestamp+'.yml')
if write_log:
self.log('Writing PyRogue configuration to file : ' +
f'{config_filename}', self.LOG_USER)
self.write_config(config_filename)
# short wait
time.sleep(5.)
if write_log:
self.log(f'Writing to file : {data_filename}',
self.LOG_USER)
# Save mask file as text file. Eventually this will be in the
# raw data output
mask_fname = os.path.join(data_filename.replace('.dat',
'_mask.txt'))
np.savetxt(mask_fname, channel_mask, fmt='%i')
self.pub.register_file(mask_fname, 'mask')
self.log(mask_fname)
if make_freq_mask:
if write_log:
self.log("Writing frequency mask.")
freq_mask = self.make_freq_mask(channel_mask)
np.savetxt(os.path.join(data_filename.replace('.dat',
'_freq.txt')), freq_mask, fmt='%4.4f')
self.pub.register_file(
os.path.join(data_filename.replace('.dat', '_freq.txt')),
'mask', format='txt')
if make_datafile:
self.open_data_file(write_log=write_log)
return data_filename
@set_action()
def stream_data_off(self, write_log=True, register_file=False):
"""
Turns off streaming data.
Args
----
write_log : bool, optional, default True
Whether to log the CA commands or not.
register_file : bool, optional, default False
If true, the stream data file will be registered through
the publisher.
"""
self.close_data_file(write_log=write_log)
if register_file:
datafile = self.get_data_file_name().tostring().decode()
if datafile:
self.log(f"Registering File {datafile}")
self.pub.register_file(datafile, 'data', format='dat')
self.set_stream_enable(0, write_log=write_log, wait_after=.15)