-
Notifications
You must be signed in to change notification settings - Fork 9
/
smurf_tune.py
5021 lines (4327 loc) · 196 KB
/
smurf_tune.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 tune module - SmurfTuneMixin class
#-----------------------------------------------------------------------------
# File : pysmurf/tune/smurf_tune.py
# Created : 2018-08-31
#-----------------------------------------------------------------------------
# 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 collections import Counter
import glob
import os
import time
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import numpy as np
import scipy.signal as signal
import scipy.linalg as linalg
import seaborn as sns
from pysmurf.client.base import SmurfBase
from pysmurf.client.command.sync_group import SyncGroup as SyncGroup
from pysmurf.client.util.pub import set_action
from ..util import tools
class SmurfTuneMixin(SmurfBase):
"""
This contains all the tuning scripts
"""
@set_action()
def tune(self, load_tune=True, tune_file=None, last_tune=False,
retune=False, f_min=.02, f_max=.3, df_max=.03,
fraction_full_scale=None, make_plot=False,
save_plot=True, show_plot=False,
new_master_assignment=False, track_and_check=True):
"""
This runs a tuning, does tracking setup, and prunes bad
channels using check lock. When this is done, we should
be ready to take data.
Args
----
load_tune : bool, optional, default True
Whether to load in a tuning file. If False, will do a full
tuning. This will be very slow (~ 1 hour)
tune_file : str or None, optional, default None
The tuning file to load in. If tune_file is None and
last_tune is False, this will load the default tune file
defined in exp.cfg.
last_tune : bool, optional, default False
Whether to load the most recent tuning file.
retune : bool, optional, default False
Whether to re-run tune_band_serial to refind peaks and eta
params. This will take about 5 minutes.
f_min : float, optional, default 0.02
The minimum frequency swing allowable for check_lock.
f_max : float, optional, default 0.3
The maximum frequency swing allowable for check_lock.
df_max : float, optional, default 0.03
The maximum df stddev allowable for check_lock.
fraction_full_scale : float or None, optional, default None
The fraction (between 0-1) to set the flux ramp amplitude.
make_plot : bool, optional, default False
Whether to make a plot.
save_plot : bool, optional, default True
If making plots, whether to save them.
show_plot : bool, optional, default False
Whether to display the plots to screen.
new_master_assignment : bool, optional, default False
Whether to make a new master assignment which forces
resonators at a given frequency to a given channel.
track_and_check : bool, optional, default True
Whether or not after tuning to run track and check.
"""
bands = self._bands
# Load fraction_full_scale from file if not given
if fraction_full_scale is None:
fraction_full_scale = self._fraction_full_scale
if load_tune:
if last_tune:
tune_file = self.last_tune()
self.log(f'Last tune is : {tune_file}')
elif tune_file is None:
tune_file = self._default_tune
self.log(f'Loading default tune file: {tune_file}')
self.load_tune(tune_file)
# Runs find_freq and setup_notches.
else:
for band in bands:
tone_power = self._amplitude_scale[band]
self.find_freq(
band, tone_power=tone_power)
self.setup_notches(
band, tone_power=tone_power,
new_master_assignment=new_master_assignment)
# Runs tune_band_serial to re-estimate eta params
if retune:
for band in bands:
self.log(f'Running tune band serial on band {band}')
self.tune_band_serial(
band, from_old_tune=load_tune, old_tune=tune_file,
make_plot=make_plot, show_plot=show_plot,
save_plot=save_plot,
new_master_assignment=new_master_assignment)
# Starts tracking and runs check_lock to prune bad resonators
if track_and_check:
for band in bands:
self.log(f'Tracking and checking band {band}')
self.track_and_check(
band, fraction_full_scale=fraction_full_scale,
f_min=f_min, f_max=f_max, df_max=df_max,
make_plot=make_plot, save_plot=save_plot,
show_plot=show_plot)
@set_action()
def tune_band(self, band, freq=None, resp=None, nsamp=2**19,
make_plot=False, show_plot=False, plot_chans=[],
save_plot=True, save_data=True, make_subband_plot=False,
n_scan=5, subband_plot_with_slow=False, tone_power=None,
grad_cut=.05, freq_min=-2.5E8, freq_max=2.5E8, amp_cut=.5,
use_slow_eta=False):
"""
This does the full_band_resp, which takes the raw resonance data.
It then finds the where the resonances are. Using the resonance
locations, it calculates the eta parameters.
Args
----
band : int
The band to tune.
freq : float array or None, optional, default None
The frequency information. If both freq and resp are not
None, it will skip full_band_resp.
resp : float array or None, optional, default None
The response information. If both freq and resp are not
None, it will skip full_band_resp.
nsamp : int, optional, default 2**19
The number of samples to take in full_band_resp.
make_plot : bool, optional, default False
Whether to make plots. This is slow, so if you want to
tune quickly, set to False.
show_plot : bool, optional, default False
Whether to display the plots to screen.
plot_chans : list, optional, default []
If making plots, which channels to plot. If empty, will
just plot all of them.
save_plot : bool, optional, default True
Whether to save the plot. If True, it will close the plots
before they are shown. If False, plots will be brought to
the screen.
save_data : bool, optional, default True
If True, saves the data to disk.
make_subband_plot : bool, optional, default False
Whether to make a plot per subband. This is very slow.
n_scan : int, optional, default 5
The number of scans to take and average.
grad_cut : float, optional, default 0.05
The value of the gradient of phase to look for resonances.
freq_min : float, optional, default -2.5e8
The minimum frequency relative to the center of the band
to look for resonances. Units of Hz.
freq_max : float, optional, default 2.5e8
The maximum frequency relative to the center of the band
to look for resonances. Units of Hz.
amp_cut : float, optional, default 0.5
The distance from the median value to decide whether
there is a resonance.
Returns
-------
resonances : dict
A dictionary with resonance frequency, eta, eta_phase,
R^2, and amplitude.
"""
timestamp = self.get_timestamp()
if make_plot and save_plot:
plt.ioff()
if freq is None or resp is None:
self.band_off(band)
self.flux_ramp_off()
self.log('Running full band resp')
# Inject high amplitude noise with known waveform, measure it, and
# then find resonators and etaParameters from cross-correlation.
freq, resp = self.full_band_resp(band, nsamp=nsamp,
make_plot=make_plot, save_data=save_data, timestamp=timestamp,
n_scan=n_scan, show_plot=show_plot)
# Find peaks
peaks = self.find_peak(freq, resp, rolling_med=True, band=band,
make_plot=make_plot, show_plot=show_plot, window=5000,
save_plot=save_plot, grad_cut=grad_cut, freq_min=freq_min,
freq_max=freq_max, amp_cut=amp_cut,
make_subband_plot=make_subband_plot, timestamp=timestamp,
subband_plot_with_slow=subband_plot_with_slow, pad=50, min_gap=50)
# Eta scans
band_center_mhz = self.get_band_center_mhz(band)
resonances = {}
for i, p in enumerate(peaks):
eta, eta_scaled, eta_phase_deg, r2, eta_mag, latency, Q= \
self.eta_fit(band, freq, resp, p, 50E3, make_plot=False,
plot_chans=plot_chans, save_plot=save_plot, res_num=i,
band=band, timestamp=timestamp, use_slow_eta=use_slow_eta)
# Fill the resonances dict
resonances[i] = {
'freq': p*1.0E-6 + band_center_mhz,
'eta': eta,
'eta_scaled': eta_scaled,
'eta_phase': eta_phase_deg,
'r2': r2,
'eta_mag': eta_mag,
'latency': latency,
'Q': Q
}
if save_data:
self.log(f'Saving resonances to {self.output_dir}')
path = os.path.join(
self.output_dir,
f'{timestamp}_b{band}_resonances')
np.save(path, resonances)
self.pub.register_file(path, 'resonances', format='npyt')
# Assign resonances to channels
self.log('Assigning channels')
f = [resonances[k]['freq'] for k in resonances.keys()]
subbands, channels, offsets = self.assign_channels(f, band=band)
for i, k in enumerate(resonances.keys()):
resonances[k].update({'subband': subbands[i]})
resonances[k].update({'channel': channels[i]})
resonances[k].update({'offset': offsets[i]})
self.freq_resp[band]['resonances'] = resonances
if tone_power is None:
tone_power = self._amplitude_scale[band]
# Add tone amplitude to tuning dictionary
self.freq_resp[band]['tone_power'] = tone_power
# Save the data
self.save_tune()
self.relock(band)
self.log('Done tuning')
return resonances
@set_action()
def tune_band_serial(self, band, nsamp=2**19, make_plot=False,
save_plot=True, save_data=True, show_plot=False,
make_subband_plot=False, subband=None, n_scan=5,
subband_plot_with_slow=False, window=5000,
rolling_med=True, grad_cut=.03, freq_min=-2.5E8,
freq_max=2.5E8, amp_cut=.25, del_f=.005, tone_power=None,
new_master_assignment=False, from_old_tune=False,
old_tune=None, pad=50, min_gap=50,
highlight_phase_slip=True, amp_ylim=None):
"""Tunes band using serial_gradient_descent and then
serial_eta_scan. This requires an initial guess, which this
function gets by either loading an old tune or by using the
full_band_resp. This takes about 3 minutes per band if there
are about 150 resonators. This saves the results to the
freq_resp dictionary.
Args
----
band : int
The band the tune.
nsamp : int, optional, default 2**19
The number of samples to take in full_band_resp.
make_plot : bool, optional, default False
Whether to make plots.
save_plot : bool, optional, default True
Whether to save the plot. If True, it will close the plots
before they are shown. If False, plots will be brought to
the screen.
show_plot : bool, optional, default False
If make_plot is True, whether to display the plots to screen.
make_subband_plot : bool, optional, default False
Whether to make a plot per subband. This is very slow.
new_master_assignment : bool, optional, default False
Whether to overwrite the previous master_assignment list.
from_old_tune : bool, optional, default False
Whether to use an old tuning file. This will load a tuning
file and use its peak frequencies as a starting point for
serial_gradient_descent.
old_tune : str or None, optional, default None
The full path to the tuning file.
highlight_phase_slip : bool, optional, default True
Whether to highlight the phase slip.
amp_ylim : float or None, optional, default None
The ylim for the amplitude plot. If None, does nothing.
"""
timestamp = self.get_timestamp()
center_freq = self.get_band_center_mhz(band)
self.flux_ramp_off() # flux ramping messes up eta params
freq=None
resp=None
if from_old_tune:
if old_tune is None:
self.log('Using default tuning file')
old_tune = self._default_tune
self.load_tune(old_tune,band=band)
resonances = np.copy(self.freq_resp[band]['resonances']).item()
if new_master_assignment:
f = np.array([resonances[k]['freq'] for k in resonances.keys()])
# f += self.get_band_center_mhz(band)
subbands, channels, offsets = self.assign_channels(f, band=band,
as_offset=False, new_master_assignment=new_master_assignment)
for i, k in enumerate(resonances.keys()):
resonances[k].update({'subband': subbands[i]})
resonances[k].update({'channel': channels[i]})
resonances[k].update({'offset': offsets[i]})
self.freq_resp[band]['resonances'] = resonances
else:
# Inject high amplitude noise with known waveform, measure it, and
# then find resonators and etaParameters from cross-correlation.
old_att = self.get_att_uc(band)
self.set_att_uc(band, 0, wait_after=.5, write_log=True)
self.get_att_uc(band, write_log=True)
freq, resp = self.full_band_resp(band, nsamp=nsamp,
make_plot=make_plot, save_data=save_data,
show_plot=False, timestamp=timestamp,
n_scan=n_scan)
self.set_att_uc(band, old_att, write_log=True)
# Find peaks
peaks = self.find_peak(freq, resp, rolling_med=rolling_med,
window=window, band=band, make_plot=make_plot,
save_plot=save_plot, show_plot=show_plot, grad_cut=grad_cut,
freq_min=freq_min, freq_max=freq_max, amp_cut=amp_cut,
make_subband_plot=make_subband_plot, timestamp=timestamp,
subband_plot_with_slow=subband_plot_with_slow, pad=pad,
min_gap=min_gap, highlight_phase_slip=highlight_phase_slip,
amp_ylim=amp_ylim)
resonances = {}
for i, p in enumerate(peaks):
resonances[i] = {
'freq': p*1.0E-6 + center_freq, # in MHz
'r2' : 0,
'Q' : 1,
'eta_phase' : 1 , # Fill etas with arbitrary values for now
'eta_scaled' : 1,
'eta_mag' : 0,
'eta' : 0 + 0.j
}
# Assign resonances to channels
self.log('Assigning channels')
f = np.array([resonances[k]['freq'] for k in resonances.keys()])
subbands, channels, offsets = self.assign_channels(f, band=band,
as_offset=False, new_master_assignment=new_master_assignment)
for i, k in enumerate(resonances.keys()):
resonances[k].update({'subband': subbands[i]})
resonances[k].update({'channel': channels[i]})
resonances[k].update({'offset': offsets[i]})
self.freq_resp[band]['resonances'] = resonances
if tone_power is None:
tone_power = self._amplitude_scale[band]
self.freq_resp[band]['tone_power'] = tone_power
self.freq_resp[band]['full_band_resp'] = {}
if freq is not None:
self.freq_resp[band]['full_band_resp']['freq'] = freq * 1.0E-6 + center_freq
if resp is not None:
self.freq_resp[band]['full_band_resp']['resp'] = resp
self.freq_resp[band]['timestamp'] = timestamp
# Set the resonator frequencies without eta params
self.relock(band, tone_power=tone_power)
# Find the resonator minima
self.log('Finding resonator minima...')
self.run_serial_gradient_descent(band, timeout=1200)
# Calculate the eta params
self.log('Calculating eta parameters...')
self.run_serial_eta_scan(band, timeout=1200)
# Read back new eta parameters and populate freq_resp
subband_half_width = self.get_digitizer_frequency_mhz(band)/\
self.get_number_sub_bands(band)
eta_phase = self.get_eta_phase_array(band)
eta_scaled = self.get_eta_mag_array(band)
eta_mag = eta_scaled * subband_half_width
eta = eta_mag * np.cos(np.deg2rad(eta_phase)) + \
1.j * np.sin(np.deg2rad(eta_phase))
# Get the result twice. Pass it to the resonance dict
chs = self.get_eta_scan_result_channel(band)
chs = self.get_eta_scan_result_channel(band)
for i, ch in enumerate(chs):
if ch != -1:
resonances[i]['eta_phase'] = eta_phase[ch]
resonances[i]['eta_scaled'] = eta_scaled[ch]
resonances[i]['eta_mag'] = eta_mag[ch]
resonances[i]['eta'] = eta[ch]
self.freq_resp[band]['resonances'] = resonances
self.save_tune()
self.log('Done with serial tuning')
@set_action()
def plot_tune_summary(self, band, eta_scan=False, show_plot=False,
save_plot=True, eta_width=.3, channels=None,
plot_summary=True, plotname_append=''):
"""
Plots summary of tuning. Requires self.freq_resp to be filled.
In other words, you must run find_freq and setup_notches
before calling this function. Saves the plot to plot_dir.
This will also make individual eta plots as well if {eta_scan}
is True. The eta scan plots are slow because there are many
of them.
Args
----
band : int
The band number to plot.
eta_scan : bool, optional, default False
Whether to also plot individual eta scans. Warning this is
slow.
show_plot : bool, optional, default False
Whether to display the plot.
save_plot : bool, optional, default True
Whether to save the plot.
eta_width : float, optional, default 0.3
The width to plot in MHz.
channels : list of int or None, optional, default None
Which channels to plot. If None, plots all available
channels.
plot_summary : bool, optional, default True
Plot summary.
plotname_append : str, optional, default ''
Appended to the default plot filename.
"""
if show_plot:
plt.ion()
else:
plt.ioff()
timestamp = self.get_timestamp()
if plot_summary:
fig, ax = plt.subplots(2,2, figsize=(10,6))
# Subband
sb = self.get_eta_scan_result_subband(band)
ch = self.get_eta_scan_result_channel(band)
idx = np.where(ch!=-1) # ignore unassigned channels
sb = sb[idx]
c = Counter(sb)
y = np.array([c[i] for i in np.arange(128)])
ax[0,0].plot(np.arange(128), y, '.', color='k')
for i in np.arange(0, 128, 16):
ax[0,0].axvspan(i-.5, i+7.5, color='k', alpha=.2)
ax[0,0].set_ylim((-.2, np.max(y)+1.2))
ax[0,0].set_yticks(np.arange(0,np.max(y)+.1))
ax[0,0].set_xlim((0, 128))
ax[0,0].set_xlabel('Subband')
ax[0,0].set_ylabel('# Res')
ax[0,0].text(.02, .92, f'Total: {len(sb)}',
fontsize=10, transform=ax[0,0].transAxes)
# Eta stuff
eta = self.get_eta_scan_result_eta(band)
eta = eta[idx]
f = self.get_eta_scan_result_freq(band)
f = f[idx]
ax[0,1].plot(f, np.real(eta), '.', label='Real')
ax[0,1].plot(f, np.imag(eta), '.', label='Imag')
ax[0,1].plot(f, np.abs(eta), '.', label='Abs', color='k')
ax[0,1].legend(loc='lower right')
bc = self.get_band_center_mhz(band)
ax[0,1].set_xlim((bc-250, bc+250))
ax[0,1].set_xlabel('Freq [MHz]')
ax[0,1].set_ylabel('Eta')
phase = np.rad2deg(np.angle(eta))
ax[1,1].plot(f, phase, color='k')
ax[1,1].set_xlim((bc-250, bc+250))
ax[1,1].set_ylim((-180,180))
ax[1,1].set_yticks(np.arange(-180, 180.1, 90))
ax[1,1].set_xlabel('Freq [MHz]')
ax[1,1].set_ylabel('Eta phase')
fig.suptitle(f'Band {band} {timestamp}')
plt.subplots_adjust(left=.08, right=.95, top=.92, bottom=.08,
wspace=.21, hspace=.21)
if save_plot:
save_name = (
f'{timestamp}_tune_summary{plotname_append}.png')
path = os.path.join(self.plot_dir, save_name)
plt.savefig(path, bbox_inches='tight')
self.pub.register_file(path, 'tune', plot=True)
if not show_plot:
plt.close()
# Plot individual eta scan
if eta_scan:
keys = self.freq_resp[band]['resonances'].keys()
# If using full band response as input
if 'full_band_resp' in self.freq_resp[band]:
freq = self.freq_resp[band]['full_band_resp']['freq']
resp = self.freq_resp[band]['full_band_resp']['resp']
for k in keys:
r = self.freq_resp[band]['resonances'][k]
channel=r['channel']
# If user provides a channel restriction list, only
# plot channels in that list.
if channel is not None and channel not in channels:
continue
center_freq = r['freq']
idx = np.logical_and(freq > center_freq - eta_width,
freq < center_freq + eta_width)
# Actually plot the data
self.plot_eta_fit(freq[idx], resp[idx],
eta_mag=r['eta_mag'], eta_phase_deg=r['eta_phase'],
band=band, res_num=k, timestamp=timestamp,
save_plot=save_plot, show_plot=show_plot,
peak_freq=center_freq, channel=channel, plotname_append=plotname_append)
# This is for data from find_freq/setup_notches
else:
# For setup_notches plotting, only count & plot existing data;
# e.g. unassigned channels may not be scanned.
scanned_keys=np.array([k for k in keys if self.freq_resp[band]['resonances'][k]['resp_eta_scan'] is not None])
n_scanned_keys=len(scanned_keys)
for skidx,k in enumerate(scanned_keys):
r = self.freq_resp[band]['resonances'][k]
channel=r['channel']
# If user provides a channel restriction list, only
# plot channels in that list.
if channels is not None:
if channel not in channels:
continue
else:
self.log(f'Eta plot for channel {channel}')
else:
self.log(f'Eta plot {skidx+1} of {n_scanned_keys}')
self.plot_eta_fit(r['freq_eta_scan'], r['resp_eta_scan'],
eta=r['eta'], eta_mag=r['eta_mag'],
eta_phase_deg=r['eta_phase'], band=band, res_num=k,
timestamp=timestamp, save_plot=save_plot,
show_plot=show_plot, peak_freq=r['freq'],
channel=channel, plotname_append=plotname_append)
@set_action()
def full_band_resp(self, band, n_scan=1, nsamp=2**19, make_plot=False,
save_plot=True, show_plot=False, save_data=False, timestamp=None,
save_raw_data=False, correct_att=True, swap=False, hw_trigger=True,
write_log=False, return_plot_path=False,
check_if_adc_is_saturated=True):
"""
Injects high amplitude noise with known waveform. The ADC measures it.
The cross correlation contains the information about the resonances.
Args
----
band : int
The band to sweep.
n_scan : int, optional, default 1
The number of scans to take and average.
nsamp : int, optional, default 2**19
The number of samples to take.
make_plot : bool, optional, default False
Whether the make plots.
save_plot : bool, optional, default True
If making plots, whether to save them.
show_plot : bool, optional, default False
Whether to show plots.
save_data : bool, optional, default False
Whether to save the data.
timestamp : str or None, optional, default None
The timestamp as a string. If None, loads the current
timestamp.
save_raw_data : bool, optional, default False
Whether to save the raw ADC/DAC data.
correct_att : bool, optional, default True
Correct the response for the attenuators.
swap : bool, optional, default False
Whether to reverse the data order of the ADC relative to
the DAC. This solved a legacy problem.
hw_trigger : bool, optional, default True
Whether to start the broadband noise file using the
hardware trigger.
write_log : bool, optional, default False
Whether to write output to the log.
return_plot_path : bool, optional, default False
Whether to return the full path to the summary plot.
check_if_adc_is_saturated : bool, optional, default True
Right after playing the noise file, checks if ADC for the
requested band is saturated. If it is saturated, gives up
with an error.
Returns
-------
f : float array
The frequency information. Length nsamp/2.
resp : complex array
The response information. Length nsamp/2.
"""
if timestamp is None:
timestamp = self.get_timestamp()
resp = np.zeros((int(n_scan), int(nsamp/2)), dtype=complex)
for n in np.arange(n_scan):
bay = self.band_to_bay(band)
# Default setup sets to 1
self.set_trigger_hw_arm(bay, 0, write_log=write_log)
self.set_noise_select(band, 1, wait_done=True, write_log=write_log)
# if true, checks whether or not playing noise file saturates the ADC.
#If ADC is saturated, throws an exception.
if check_if_adc_is_saturated:
adc_is_saturated = self.check_adc_saturation(band)
if adc_is_saturated:
raise ValueError('Playing the noise file saturates the '+
f'ADC for band {band}. Try increasing the DC '+
'attenuation for this band.')
# Take read the ADC data
try:
adc = self.read_adc_data(band, nsamp, hw_trigger=hw_trigger,
save_data=False)
except Exception:
self.log('ADC read failed. Trying one more time', self.LOG_ERROR)
adc = self.read_adc_data(band, nsamp, hw_trigger=hw_trigger,
save_data=False)
time.sleep(.05) # Need to wait, otherwise dac call interferes with adc
try:
dac = self.read_dac_data(
band, nsamp, hw_trigger=hw_trigger,
save_data=False)
except BaseException:
self.log('ADC read failed. Trying one more time', self.LOG_ERROR)
dac = self.read_dac_data(
band, nsamp, hw_trigger=hw_trigger,
save_data=False)
time.sleep(.05)
self.set_noise_select(band, 0, wait_done=True, write_log=write_log)
# Account for the up and down converter attenuators
if correct_att:
att_uc = self.get_att_uc(band)
att_dc = self.get_att_dc(band)
self.log(f'UC (DAC) att: {att_uc}')
self.log(f'DC (ADC) att: {att_dc}')
if att_uc > 0:
scale = (10**(-att_uc/2/20))
self.log(f'UC attenuator > 0. Scaling by {scale:4.3f}')
dac *= scale
if att_dc > 0:
scale = (10**(att_dc/2/20))
self.log(f'DC attenuator > 0. Scaling by {scale:4.3f}')
adc *= scale
if save_raw_data:
self.log('Saving raw data...', self.LOG_USER)
path = os.path.join(self.output_dir, f'{timestamp}_adc')
np.save(path, adc)
self.pub.register_file(path, 'adc', format='npy')
path = os.path.join(self.output_dir,f'{timestamp}_dac')
np.save(path, dac)
self.pub.register_file(path, 'dac', format='npy')
# Swap frequency ordering of data of ADC relative to DAC
if swap:
adc = adc[::-1]
# Take PSDs of ADC, DAC, and cross
fs = self.get_digitizer_frequency_mhz() * 1.0E6
f, p_dac = signal.welch(dac, fs=fs, nperseg=nsamp/2,
return_onesided=False)
f, p_adc = signal.welch(adc, fs=fs, nperseg=nsamp/2,
return_onesided=False)
f, p_cross = signal.csd(dac, adc, fs=fs, nperseg=nsamp/2,
return_onesided=False)
# Sort frequencies
idx = np.argsort(f)
f = f[idx]
p_dac = p_dac[idx]
p_adc = p_adc[idx]
p_cross = p_cross[idx]
resp[n] = p_cross / p_dac
# Average over the multiple scans
resp = np.mean(resp, axis=0)
plot_path = None
if make_plot:
if show_plot:
plt.ion()
else:
plt.ioff()
fig, ax = plt.subplots(3, figsize=(5,8), sharex=True)
f_plot = f / 1.0E6
plot_idx = np.where(np.logical_and(f_plot>-250, f_plot<250))
ax[0].semilogy(f_plot, p_dac)
ax[0].set_ylabel('DAC')
ax[1].semilogy(f_plot, p_adc)
ax[1].set_ylabel('ADC')
ax[2].semilogy(f_plot, np.abs(p_cross))
ax[2].set_ylabel('Cross')
ax[2].set_xlabel('Frequency [MHz]')
ax[0].set_title(timestamp)
if save_plot:
path = os.path.join(
self.plot_dir,
f'{timestamp}_b{band}_full_band_resp_raw.png')
plt.savefig(path, bbox_inches='tight')
self.pub.register_file(path, 'response', plot=True)
plt.close()
fig, ax = plt.subplots(1, figsize=(5.5, 3))
# Log y-scale plot
ax.plot(f_plot[plot_idx], np.log10(np.abs(resp[plot_idx])))
ax.set_xlabel('Freq [MHz]')
ax.set_ylabel('Response')
ax.set_title(f'full_band_resp {timestamp}')
plt.tight_layout()
if save_plot:
plot_path = (
os.path.join(
self.plot_dir,
f'{timestamp}_b{band}_full_band_resp.png'))
plt.savefig(plot_path, bbox_inches='tight')
self.pub.register_file(plot_path, 'response', plot=True)
# Show/Close plots
if show_plot:
plt.show()
else:
plt.close()
if save_data:
save_name = timestamp + '_{}_full_band_resp.txt'
path = os.path.join(self.output_dir, save_name.format('freq'))
np.savetxt(path, f)
self.pub.register_file(path, 'full_band_resp', format='txt')
path = os.path.join(self.output_dir, save_name.format('real'))
np.savetxt(path, np.real(resp))
self.pub.register_file(path, 'full_band_resp', format='txt')
path = os.path.join(self.output_dir, save_name.format('imag'))
np.savetxt(path, np.imag(resp))
self.pub.register_file(path, 'full_band_resp', format='txt')
if return_plot_path:
return f, resp, plot_path
else:
return f, resp
@set_action()
def find_peak(self, freq, resp, rolling_med=True, window=5000,
grad_cut=.5, amp_cut=.25, freq_min=-2.5E8, freq_max=2.5E8,
make_plot=False, save_plot=True, plotname_append='', show_plot=False,
band=None, subband=None, make_subband_plot=False,
subband_plot_with_slow=False, timestamp=None, pad=50, min_gap=100,
plot_title=None, grad_kernel_width=8, highlight_phase_slip=True,
amp_ylim=None, flip_phase=False, plot_phase=False):
""" Find the peaks within a given subband.
Args
----
freq : float array
Should be a single row of the broader freq array, in Mhz.
resp : complex array
Complex response for just this subband.
rolling_med : bool, optional, default True
Whether to use a rolling median for the background.
window : int, optional, default 5000
Number of samples to window together for rolling med.
grad_cut : float, optional, default 0.5
The value of the gradient of phase to look for resonances.
flip_phase : bool, optional, default False
Whether to flip the sign of phase before
evaluating the gradient cut.
plot_phase : bool, optional, default False
Whether to generate a plot showing just the phase information
amp_cut : float, optional, default 0.25
The fractional distance from the median value to decide
whether there is a resonance.
freq_min : float, optional, default -2.5e8
The minimum frequency relative to the center of the band
to look for resonances. Units of Hz.
freq_max : float, optional, default 2.5e8
The maximum frequency relative to the center of the band
to look for resonances. Units of Hz.
make_plot : bool, optional, default False
Whether to make a plot.
save_plot : bool, optional, default True
Whether to save the plot to self.plot_dir.
plotname_append : str, optional, default ''
Appended to the default plot filename.
show_plot : bool, optional, default False
Whether or not to show plots.
band : int or None, optional, default None
The band to take find the peaks in. Mainly for saving and plotting.
subband : int or None, optional, default None
The subband to take find the peaks in. Mainly for saving
and plotting.
make_subband_plot : bool, optional, default False
Whether to make a plot per subband. This is very slow.
timestamp : str or None, optional, default None
The timestamp. Mainly for saving and plotting.
pad : int, optional, default 50
Number of samples to pad on either side of a resonance
search window.
min_gap : int, optional, default 100
Minimum number of samples between resonances.
grad_kernel_width : int, optional, default 8
The number of samples to take after a point to calculate
the gradient of phase.
highlight_phase_slip : bool, optional, default True
Whether to highlight the phase slip.
amp_ylim : float or None, optional, default None
The ylim for the amplitude plot. If None, does nothing.
Returns
-------
resonances : float array
The frequency of the resonances in the band in Hz.
"""
if timestamp is None:
timestamp = self.get_timestamp()
# Break apart the data
angle = np.unwrap(np.angle(resp))
x = np.arange(len(angle))
p1 = np.poly1d(np.polyfit(x, angle, 1))
angle -= p1(x)
if flip_phase:
angle *= -1
grad = np.convolve(angle, np.repeat([1,-1], grad_kernel_width),
mode='same')
amp = np.abs(resp)
grad_loc = np.array(grad > grad_cut)
# Calculate the rolling median. This uses pandas.
if rolling_med:
import pandas as pd
med_amp = pd.Series(amp).rolling(window=window, center=True,
min_periods=1).median()
else:
med_amp = np.median(amp) * np.ones(len(amp))
# Get the flagging
starts, ends = self.find_flag_blocks(self.pad_flags(grad_loc,
before_pad=pad, after_pad=pad, min_gap=min_gap))
# Find the peaks locations
peak = np.array([], dtype=int)
for s, e in zip(starts, ends):
if freq[s] > freq_min and freq[e] < freq_max:
idx = np.ravel(np.where(amp[s:e] == np.min(amp[s:e])))[0]
idx += s
if 1-amp[idx]/med_amp[idx] > amp_cut:
peak = np.append(peak, idx)
# Plot the phase information
if plot_phase:
plt.figure()
plt.plot(freq, angle)
if show_plot:
plt.show()
else:
plt.close()
# Make summary plot
if make_plot:
if show_plot:
plt.ion()
else:
plt.ioff()
fig, ax = plt.subplots(2, figsize=(8,6), sharex=True)
if band is not None:
bandCenterMHz = self.get_band_center_mhz(band)
scale = 1
if np.max(freq) > 1.0E8:
self.log('Frequency is probably in Hz. Converting to MHz')
scale = 1.0E-6
plot_freq_mhz = freq*scale + bandCenterMHz
else:
plot_freq_mhz = freq
# Plot response
ax[0].plot(plot_freq_mhz, amp)
ax[0].plot(plot_freq_mhz, med_amp)
# Draw x on peak
ax[0].plot(plot_freq_mhz[peak], amp[peak], 'kx')
ax[1].plot(plot_freq_mhz, grad)
ax[1].set_ylim(-2, 20)
# Highlighht the identified phase slips
if highlight_phase_slip:
for s, e in zip(starts, ends):
ax[0].axvspan(plot_freq_mhz[s], plot_freq_mhz[e], color='k',
alpha=.25)
ax[1].axvspan(plot_freq_mhz[s], plot_freq_mhz[e], color='k',
alpha=.25)
# set ylim
if amp_ylim is not None:
ax[0].set_ylim(amp_ylim)
ax[0].set_ylabel('Amp.')
ax[1].set_ylabel('Deriv Phase')
ax[1].set_xlabel('Freq. [MHz]')
# Text label
text = ''
if band is not None:
text += f'Band: {band}' + '\n'
text += f'Center Freq: {bandCenterMHz} MHz' + '\n'
if subband is not None:
text += f' Subband: {subband}' +'\n'
text += f'Peaks: {len(peak)}'
ax[0].text(.025, .975, text, transform=ax[0].transAxes, ha='left',
va='top')
# Make title
title = timestamp
fig.suptitle(title)
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
if save_plot:
save_name = timestamp
if band is not None:
save_name = save_name + f'_b{band}'
if subband is not None:
save_name = save_name + f'_sb{subband}'
save_name = save_name + '_find_freq' + plotname_append + '.png'
path = os.path.join(self.plot_dir, save_name)
plt.savefig(path, bbox_inches='tight', dpi=300)
self.pub.register_file(path, 'find_freq', plot=True)
if show_plot:
plt.show()
else:
plt.close()
# Make plot per subband
if make_subband_plot:
subbands, subband_freq = self.get_subband_centers(band,
hardcode=True) # remove hardcode mode
plot_freq_mhz = freq
plot_width = 5.5 # width of plotting in MHz
width = (subband_freq[1] - subband_freq[0])