forked from LFL-Lab/Dissipator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qubit.py
2425 lines (1957 loc) · 103 KB
/
qubit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Created on Mon Oct 4 2022
@author: Evangelos Vlachos <evlachos@usc.edu>
"""
import csv
import glob
import json
import os
import time
import warnings
from collections import OrderedDict
from datetime import date, datetime
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
# from waveform_tools import *
from qm import LoopbackInterface, SimulationConfig, generate_qua_script
from qm.logger import logger
from qm.qua import *
from qm.QuantumMachinesManager import QuantumMachinesManager
from qualang_tools.analysis.discriminator import two_state_discriminator
from qualang_tools.loops import from_array
from scipy.signal import savgol_filter
from scipy.signal.windows import gaussian
import plot_functions as pf
from config import Configuration
from helper_functions import save_data
from Instruments import instruments
from sequence import *
from Utilities import *
logger.setLevel(level='WARNING')
device = 'ocsqp1'
today = date.today()
sDate = today.strftime("%Y%m%d")
class qubit():
#%% INITIALIZATION
#%%% default_pars
default_pars = {
# overall setup parameters
'elements' : ['qubit', 'rr'],
"qubit_LO": 5e9,
"rr_LO": 6e9,
'readout_atten': 25, # default attenuation in dB on variable attenuator
#OPX settings and connections
'host': None, # OPX IP address (eventually, import from local file)
'port': '9510', # OPX port (eventually, import from local file)
'Iout': {'qubit': 3, 'rr': 1}, # OPX output (goes to modulation mixer input I)
'Qout': {'qubit': 4, 'rr': 2}, # OPX output (goes to modulation mixer input Q)
'Iin': 1, # OPX input (comes from demodulation mixer output I)
'Qin': 2, # OPX input (comes from demodulation mixer output Q)
'AWG_trigger_out' : 1, # OPX digital marker output port for triggering AWG
'controller': 'con1', # OPX controller name
# Instrument settings (except OPX)
"qubit_LO": int(4.48e9),
"rr_LO": int(6.42e9),
"readout_atten": 25,
# other measurement setup choices
'n_avg': 100, # number of averages for zero-deadtime measurement
'rr_IF': 50e6,
'qubit_IF': 50e6,
"gauss_len": 48,
"gauss_amp": 0.45,
"amp_r": 0.45,
"readout_pulse_len_in_clk": 500, # length of readout integration weights in clock cycles
"saturation_duration" : clk(10e3), # saturation duration for spectroscopy
'readout_length': 2000, # length of a normal readout in ns,
# qubit parameters
"qubit_freq": int(4.5129e9),
"rr_freq": int(6.2e9),
# calibrated setup parameters
"analog_input_offsets": [0,0],
"analog_input_gain": 3,
"rr_mixer_offsets": [0,0],
"qubit_mixer_offsets": [0,0],
"rr_mixer_imbalance": [0,0],
"qubit_mixer_imbalance": [0,0],
"tof": 260, # time of flight in ns
"smearing": 40, # smearing in ns
# processing choices
"n_avg" : 500,
"IQ_rotation": -0/180*np.pi, # phase rotation applied to IQ data
"switch_weights" : False,
# calibrated device parameters
"resettime" : {"qubit": clk(100e3), "rr" : clk(5e3)},
'kappa': 200e3, # resonator linewidth
'readout_freq': 6.2e9, # resonator center frequency
'Q': 9000, # resonator quality factor
'Qc': 9000, # resonator coupling quality factor
# waveform parameters
'operations': dict(qubit=['const','gauss','arb_op','X180','Y180','X90','Y90'],
rr=['const', 'readout']),
'X180_len': 160, # length of pi pulse in clock cycles
'X180_amp': 0.45, # amplitude of pi pulse
'X90_len': 80, # length of pi/2 pulse in clock cycles
'X90_amp': 0.45, # amplitude of pi/2 pulse
'gauss_len': 48, # length of gaussian pulse in clock cycles
'amp_q': 0.375, # amplitude of qubit pulse, needs to be less than 0.45 to prevent overflowing
'amp_r': 0.375, # amplitude of readout pulse, needs to be less than 0.45
'arb_op_len': 160, # length of arbitrary operation in clock cycles
}
#%%% __init__
def __init__(self, qb, initialize_qmm=True):
# load pars from json, OR create new json file
self._name = qb
try:
print('Loading parameter JSON file')
with open(f'{qb}_pars.json', 'r') as openfile:
self.pars = json.load(openfile)
# compare keys
default_keys = set(self.default_pars.keys())
keys = set(self.pars.keys())
# find all the keys in default_pars that are not in pars, and add them to pars w/ default value
for k in (default_keys - keys):
self.add_key(k, self.default_pars[k])
# find all the keys in pars that are not in default_pars, and remove them from pars
for k in (keys - default_keys):
self.remove_key(k)
except FileNotFoundError:
print('Parameter file not found; loading parameters from template')
self.pars = self.default_pars
self.init_quantum_machine(initialize_qmm)
self.write_pars()
self._directory = f'G:\\Shared drives\\Quasiparticles\\OCS_QP\data\\{self._name}'
self._instruments = instruments()
self.init_instruments()
# self.make_config(self.pars)
self.config_maker = Configuration(self)
self.config = self.config_maker.make_config()
# self.make_config(self.pars)
#%% EXPERIMENTS
#%%% play_pulses
def play_pulses(self, amplitude = 1, element = 'readout'):
"""
DESCRIPTION:
Same as in original code. Plays constant pulses at correct IF frequencies on `element`.
ARGS:
None
KWARGS:
amp (int, 1): Amplitude scaling factor.
RETURNS:
qm (?): ?
"""
with program() as play_pulses:
with infinite_loop_():
play("const" * amp(amplitude), element)
initialized = self.qmm is not None
qmm = self.qmm if initialized else QuantumMachinesManager(host=self.pars['host'], port=self.pars['port'])
qm = qmm.open_qm(self.config)
job = qm.execute(play_pulses)
return qm,job
#%%% punchout
def punchout(self,
df = 0.1e6,
IF_min = 10e6,
IF_max = 20e6,
attenuations = [10,30],
atten_step = 0.1,
savedata=True):
"""
Executes punchout measurement for list of resonator frequencies
Args:
df (TYPE, optional): DESCRIPTION. Defaults to 0.1e6.
n_avg (TYPE, optional): DESCRIPTION. Defaults to 500.
atten_range (TYPE, optional): [min,max] attenuation values.
f_LO (TYPE, optional): list with all the resonator frequencies in GHz. Defaults to [6e9,7.2e9].
res_ringdown_time (TYPE, optional): DESCRIPTION. Defaults to int(4e3).
Returns:
None.
"""
iteration = counter(self._directory,self.experiment,element='rr',extension='*.csv')
data = dict(I=[],Q=[],freqs=[],mag=[],z_data=[])
data['attenuations'] = attenuations
for a in tqdm(attenuations):
print(f'Attenuation = {a} dB')
self._instruments.set('DA','attenuation',a)
spec_data,job = self.resonator_spec(f_LO=self.pars['rr_LO'],IF_min=IF_min,IF_max=IF_max,df=df,showprogress=True,savedata=False,fit=False)
data['freqs'].append(np.around(spec_data['freqs']*1e-9,5))
data['I'].append(spec_data['I'])
data['Q'].append(spec_data['Q'])
data['mag'].append(np.abs(spec_data['I']+1j*spec_data['Q']))
data['z_data'].append(spec_data['I']+1j*spec_data['Q'])
self._instruments.set('DA','attenuation',self.pars['readout_atten'])
if savedata:
metadata = dict(timestamp = datetime.now(),
qubit_pars = self.pars,
attenuation_range = attenuation_range,
atten_step = atten_step,)
dataPath = f'{saveDir}\\{self.experiment}\\rr'
data = dict(I=I,Q=Q,freqs=freq_arr,mag=mag)
save_data(dataPath, iteration, metadata, data)
return data, job
#def find_dispersive_shift(self, ):
#%%% run_scan
def run_scan(self,
df = 0.1e6,
element='resonator',
check_mixers=False,
chunksize = 200e6,
lo_min = 6e9,
lo_max = 7e9,
on_off=True,
amp_q_scaling = 1,
saturation_dur = 20e3,
showprogress=False,
savedata=False):
"""
Scans a broad range of frequencies in search for qubits/resonators
Args:
IF_min (TYPE, optional): DESCRIPTION. Defaults 0.1e6.
IF_max (TYPE, optional): DESCRIPTION. Defaults to 400e6.
df (TYPE, optional): DESCRIPTION. Defaults to 0.1e6.
n_avg (TYPE, optional): DESCRIPTION. Defaults to 500.
res_ringdown_time (TYPE, optional): DESCRIPTION. Defaults to int(4e3).
Returns:
I (TYPE): DESCRIPTION.
Q (TYPE): DESCRIPTION.
freq_arr: DESCRIPTION.
TYPE: DESCRIPTION.
"""
# today = datetime.today()
# sDate = today.strftime("%Y%m%d")
# saveDir = f'G:\\Shared drives\\CavityCooling\data\\{self.name}\\{sDate}'
# dataPath = f'{saveDir}\\spectroscopy\\{element}_spec'
# filename = 'data'
# iteration = get_index_for_filename(dataPath, filename, file_format='csv')
iteration = counter(self._directory,self.experiment,element=element,extension='*.csv')
freq_arr = []
I = []
Q = []
reports = ''
if lo_min != lo_max:
numchunks = int((lo_max-lo_min)/chunksize) + 1
lo_list = [i*chunksize+lo_min for i in range(numchunks)]
else:
numchunks = 1
lo_list = [lo_min]
for f in tqdm(lo_list):
if element == 'resonator':
data, job = self.resonator_spec(f_LO=f,IF_min=df,IF_max=chunksize,df=df,showprogress=showprogress,savedata=False)
elif element == 'qubit':
data,job = self.qubit_spec(f_LO=f,
amp_q_scaling=amp_q_scaling,
check_mixers=check_mixers,
on_off=on_off,
saturation_dur=saturation_dur,
showprogress=showprogress,
IF_min=df,IF_max=chunksize,df=df,
savedata=False)
pf.qubit_spec_plot(data,qb_pars=self.pars,find_peaks=True, amp_q_scaling=amp_q_scaling)
# elif element == 'fflqb':
# dataI, dataQ,freqs, job = self.fflt1_spec(spec='qb',f_LO=f,
# IF_min=df,IF_max=chunksize,df=df,
# n_avg=n_avg,
# amp_ffl_scaling=amp_q_scaling,
# check_mixers= check_mixers,showprogress=True,
# savedata=True, flux=flux)
# elif element == 'fflrr':
# dataI, dataQ,freqs, job = self.fflt1_spec(spec='rr',f_LO=f,
# IF_min=df,IF_max=chunksize,df=df,
# n_avg=n_avg,
# amp_ffl_scaling=amp_q_scaling,
# check_mixers= check_mixers,showprogress=True,
# savedata=True, flux=flux)
# elif element == 'diss':
# dataI, dataQ,freqs, job = self.diss_spec(f_LO=f,
# IF_min=df,IF_max=chunksize,df=df,
# n_avg=n_avg,
# amp_ffl_scale=amp_q_scaling,
# check_mixers= check_mixers,
# savedata=False)
freq_arr.extend(data['freqs'])
I.extend(data['I'])
Q.extend(data['Q'])
reports += str(job.execution_report()) + '\n'
if savedata:
dataPath = f'{self._directory}\{self.experiment}\\rr'
data = {"I": I, "Q": Q, "freqs": freq_arr}
save_data(dataPath, iteration, self.pars, data)
data = dict(I=np.array(I),Q=np.array(Q),freqs=np.array(freq_arr))
return data, job
#%%% resonator_spec
def resonator_spec(self, IF_min = 0.1e6,
f_LO = 7e9,
IF_max = 400e6,
df = 0.1e6,
showprogress=False,
savedata=True,
on_off=False,
flux = None,
**kwargs):
"""
Args:
IF_min (TYPE, optional): DESCRIPTION. Defaults to 0.1e6.
f_LO (TYPE, optional): DESCRIPTION. Defaults to 7e9.
IF_max (TYPE, optional): DESCRIPTION. Defaults to 400e6.
df (TYPE, optional): DESCRIPTION. Defaults to 0.1e6.
atten (TYPE, optional): DESCRIPTION. Defaults to 10.
n_avg (TYPE, optional): DESCRIPTION. Defaults to 500.
res_ringdown_time (TYPE, optional): DESCRIPTION. Defaults to int(4e3).
port_type (TYPE, optional): DESCRIPTION. Defaults to 'notch'.
fit (TYPE, optional): DESCRIPTION. Defaults to True.
plot (TYPE, optional): DESCRIPTION. Defaults to True.
savedata (TYPE, optional): DESCRIPTION. Defaults to True.
Returns:
I (TYPE): DESCRIPTION.
Q (TYPE): DESCRIPTION.
TYPE: DESCRIPTION.
TYPE: DESCRIPTION.
"""
iteration = counter(self._directory,self.experiment,element='rr',extension='*.csv')
freqs = np.arange(IF_min, IF_max + df/2, df, dtype=int)
self.update_value('rr_LO', value = f_LO)
seq = sequence(self,'rr_spec',on_off=on_off,n_avg=self.pars['n_avg'], IF_min=IF_min, IF_max=IF_max, df=df,)
rr_spec = seq.make_resonator_spec_sequence()
datadict,job = self.get_results(rr_spec,result_names=["I","Q"],progress_key='n',showprogress=showprogress)
I = np.array(datadict["I"])
Q = np.array(datadict["Q"])
z_data = I + 1j*Q
freq_arr = np.array(freqs + self.pars['rr_LO'])
data = dict(I=I,Q=Q,z_data=z_data,freqs=freq_arr)
if savedata:
dataPath = f'{self._directory}\{self.experiment}\\rr'
data = {"I": I, "Q": Q, "freqs": freq_arr}
save_data(dataPath, iteration, self.pars, data)
return data, job
def resonator_spec_wffl(self, IF_min = 0.1e6,
f_LO = 7e9,
IF_max = 400e6,
df = 0.1e6,
atten = 10,
n_avg = 500,
port_type = 'notch',
fit=True,
savedata=True,
flux = None,
simulate=True,
**kwargs):
"""
Args:
IF_min (TYPE, optional): DESCRIPTION. Defaults to 0.1e6.
f_LO (TYPE, optional): DESCRIPTION. Defaults to 7e9.
IF_max (TYPE, optional): DESCRIPTION. Defaults to 400e6.
df (TYPE, optional): DESCRIPTION. Defaults to 0.1e6.
atten (TYPE, optional): DESCRIPTION. Defaults to 10.
n_avg (TYPE, optional): DESCRIPTION. Defaults to 500.
res_ringdown_time (TYPE, optional): DESCRIPTION. Defaults to int(4e3).
port_type (TYPE, optional): DESCRIPTION. Defaults to 'notch'.
fit (TYPE, optional): DESCRIPTION. Defaults to True.
plot (TYPE, optional): DESCRIPTION. Defaults to True.
savedata (TYPE, optional): DESCRIPTION. Defaults to True.
Returns:
I (TYPE): DESCRIPTION.
Q (TYPE): DESCRIPTION.
TYPE: DESCRIPTION.
TYPE: DESCRIPTION.
"""
try:
list_of_files = glob.glob(r'D:\weak_measurements\spectroscopy\resonator_spec_wffl\*.csv')
latest_file = max(list_of_files, key=os.path.getctime)
iteration = int(latest_file[-7:-4].lstrip('0')) + 1
except:
iteration = 1
freqs = np.arange(IF_min, IF_max + df/2, df, dtype=int)
# freqs_list = freqs.tolist()
# set attenuation and change rr_LO freq
inst.set_attenuator(attenuation=atten)
self.update_value('rr_LO', value = f_LO)
inst.set_rr_LO(self.pars['rr_LO'])
seq = sequence('spec_wffl',n_avg=n_avg, IF_min=IF_min, IF_max=IF_max, df=df,)
rr_spec_wffl = seq.make_sequence(self)
if simulate:
qmm = QuantumMachinesManager(host=host, port=port)
job = qmm.simulate(config=self.config, program=rr_spec_wffl, simulate=SimulationConfig(duration=9000))
job.get_simulated_samples().con1.plot()
datadict,job = self.get_results(rr_spec_wffl,result_names=["I","Q","n"],showprogress=False)
I = np.array(datadict["I"])
Q = np.array(datadict["Q"])
freq_arr = np.array(freqs + self.pars['rr_LO'])
if fit:
fc,fwhm = pf.fit_res(freq_arr,np.abs(I+1j*Q))
print(f'Resonant Frequency: {fc*1e-9:.5f} GHz\nFWHM = {fwhm*1e-6} MHz\nkappa = {2*np.pi*fwhm*1e-6:.3f} MHz')
else:
fc = np.nan
fwhm= np.nan
if 'fc' in kwargs.keys():
fc = kwargs['fc']
pf.spec_plot(freq_arr,I,Q,attenuation=atten,df=df,iteration=iteration,element='resonator',fwhm=fwhm,fc=fc, flux=flux)
exp_dict = {'date/time': datetime.now(),
'nAverages': n_avg,
'w_LO': self.pars['rr_LO'],
'wait_period': self.pars['rr_resettime'],
}
if savedata:
# save data
dataPath = f'{saveDir}\spectroscopy\\resonator_spec'
if not os.path.exists(dataPath):
Path(dataPath).mkdir(parents=True, exist_ok=True)
with open(f"{dataPath}\data_{iteration:03d}.csv","w") as datafile:
writer = csv.writer(datafile)
writer.writerow(exp_dict.keys())
writer.writerow(exp_dict.values())
writer.writerow(freqs)
writer.writerow(I)
writer.writerow(Q)
return I, Q, freqs+self.pars['rr_LO'], job;
#%%% qubit_spec
def qubit_spec(self,
f_LO = 5e9,
IF_min = 0.1e6, # min IF frequency
IF_max = 400e6, # max IF frequency
check_mixers=False,
df = 0.1e6, # IF frequency step
amp_q_scaling = 0.1, # prefactor to scale default "const" qubit tone, amp_q
saturation_dur = int(10e3), # time qubit saturated w/ qubit tone, in ns
on_off = True, # background subtraction
notify = False,
showprogress=False,
savedata=True,
**kwargs): # create notification on Slack when measurement finishes
iteration = counter(self._directory,self.experiment,element='qubit',extension='*.csv')
freq_arr = np.arange(IF_min, IF_max + df/2, df, dtype=int)
saturation_dur = int(saturation_dur)
self.update_value('qubit_LO',value = f_LO)
if check_mixers:
self.opt_lo_leakage(mode='coarse',element='qubit',sa_span=0.5e6,threshold=-30,plot=True)
#self.update_value('qubit_IF',50e6)
#self.opt_sideband(mode='coarse',element='qubit',sa_span=0.5e6,threshold=-20,plot=True)
# self.opt_lo_leakage(mode='coarse',element='rr',sa_span=0.5e6,threshold=-30,plot=True)
# self.update_value('rr_IF',50e6)
# self.opt_sideband(mode='coarse',element='rr',sa_span=0.5e6,threshold=-20,plot=True)
# prog = self.make_sequence(self,on_off=on_off,saturation_dur=saturation_dur,amp_q_scaling=amp_q_scaling, IF_min=IF_min, IF_max=IF_max, df=df,)
seq = sequence(self,name='qubit_spec',on_off=on_off,saturation_dur=saturation_dur,amp_q_scaling=amp_q_scaling, IF_min=IF_min, IF_max=IF_max, df=df,)
prog = seq.make_qubit_spec_sequence()
# execute 'QubitSpecProg' using configuration settings in 'config'
# fetch averaged I and Q values that were saved
datadict, job = self.get_results(jobtype = prog, result_names = ["I", "Q"], showprogress=showprogress, notify = notify)
# print('qubit power')
# qb_power = self.get_power(sa,freq=self.pars['qubit_LO']+self.pars['qubit_IF'],reference=0,amp_q = amp_q_scaling, span=1e6,config=True,output=False)
# print('rr power')
# rr_power = self.get_power(sa,freq=self.pars['rr_LO']+self.pars['rr_IF'],reference=0,span=1e6,config=True,output=False)
I = np.array(datadict["I"])
Q = np.array(datadict["Q"])
freq_arr = np.array(freq_arr + self.pars['qubit_LO'])
data = dict(I=I,Q=Q,freqs=freq_arr)
# print(f'Qubit Frequency: {fc*1e-9:.5f} GHz\nFWHM = {fwhm*1e-6} MHz\nkappa = {2*np.pi*fwhm*1e-6:.3f} MHz')
if savedata:
exp_dict = {
'n_avg': self.pars["n_avg"],
'amp_r': self.pars["amp_r"],
'amp_q': self.pars["amp_q"],
'readout_atten': self.pars["readout_atten"],
'qubit_LO': self.pars['qubit_LO'],
}
# save data
saveDir = self._directory
dataPath = f'{saveDir}\\spectroscopy\qubit_spec'
if not os.path.exists(dataPath):
Path(dataPath).mkdir(parents=True, exist_ok=True)
if 'saveto' in kwargs:
dataDict = {'metadata': exp_dict,
'time': freq_arr,
'I': I,
'Q': Q,
}
file = kwargs.get('saveto')['file']
name = kwargs.get('saveto')['name']
save_datadict_to_fgroup(file,name , dataDict)
else:
with open(f"{dataPath}\data_{iteration:03d}.csv","w") as datafile:
writer = csv.writer(datafile)
writer.writerow(exp_dict.keys())
writer.writerow(exp_dict.values())
writer.writerow(freq_arr)
writer.writerow(I)
writer.writerow(Q)
return data, job;
def fflt1_spec(self,
sa = 0,
f_LO = 5e9,
IF_min = 0.1e6, # min IF frequency
IF_max = 400e6, # max IF frequency
check_mixers=False,
df = 0.1e6, # IF frequency step
rr_freq = 6e9, #resonator frequency
amp_r_scaling = 1,
amp_q_scaling = 0.1, # prefactor to scale default "const" qubit tone, amp_q
n_avg = 500, # number of averages
atten=10, # readout attenuation
saturation_dur = int(10e3), # time qubit saturated w/ qubit tone, in ns
resettime = int(40e3), # wait time between experiments, in ns
on_off = True, # background subtraction
notify = False,
showprogress=False,
savedata=True,
amp_cav_scaling=0.01,
amp_ffl_scaling=0.01,
flux=0,
spec='rr',
**kwargs): # create notification on Slack when measurement finishes
try:
list_of_files = glob.glob(f'{saveDir}\spectroscopy\qubit_spec\*.csv')
latest_file = max(list_of_files, key=os.path.getctime)
iteration = int(latest_file[-7:-4].lstrip('0')) + 1
except:
iteration = 1
freq_arr = np.arange(IF_min, IF_max + df/2, df, dtype=int)
saturation_dur = int(saturation_dur)
inst.set_attenuator(attenuation=self.pars['rr_atten'])
self.update_value('ffl_LO',value = f_LO)
inst.set_ffl_LO(f_LO)
inst.set_rr_LO(self.pars['rr_LO'])
self.check_mix_cal(sa,check=check_mixers,amp_q = amp_q_scaling, threshold = - 60)
if spec=='qb':
prog = self.make_sequence(exp='fflqb-spec',on_off=on_off,saturation_dur=saturation_dur,var_arr=freq_arr,n_avg=n_avg,amp_q_scaling=amp_q_scaling,amp_r_scale=amp_r_scaling,amp_cav_scaling=amp_cav_scaling,amp_ffl_scaling=amp_ffl_scaling)
else:
prog = self.make_sequence(exp='fflrr-spec',on_off=on_off,saturation_dur=saturation_dur,var_arr=freq_arr,n_avg=n_avg,amp_q_scaling=amp_q_scaling,amp_r_scaling=amp_r_scaling,amp_cav_scaling=amp_cav_scaling,amp_ffl_scaling=amp_ffl_scaling)
# execute 'QubitSpecProg' using configuration settings in 'config'
# fetch averaged I and Q values that were saved
datadict, job = self.get_results(jobtype = prog, result_names = ["I", "Q"], n_total=n_avg,showprogress=showprogress, notify = notify)
# print('qubit power')
# qb_power = self.get_power(sa,freq=self.pars['qubit_LO']+self.pars['qubit_IF'],reference=0,amp_q = amp_q_scaling, span=1e6,config=True,output=False)
# print('rr power')
# rr_power = self.get_power(sa,freq=self.pars['rr_LO']+self.pars['rr_IF'],reference=0,span=1e6,config=True,output=False)
I = np.array(datadict["I"])
Q = np.array(datadict["Q"])
freq_arr = np.array(freq_arr + self.pars['ffl_LO'])
pf.spec_plot(freq_arr,I,Q,iteration=iteration,element='ffl',rrFreq=self.pars['rr_freq'],find_peaks=True, amp_q_scaling=amp_q_scaling, amp_cav_scaling=amp_cav_scaling, amp_ffl_scaling=amp_ffl_scaling, attenuation=self.pars['ffl_atten'],df=df, flux=flux)
# print(f'Qubit Frequency: {fc*1e-9:.5f} GHz\nFWHM = {fwhm*1e-6} MHz\nkappa = {2*np.pi*fwhm*1e-6:.3f} MHz')
if savedata:
exp_dict = {
'n_avg': n_avg,
'amp_r_scale': amp_r_scaling,
'amp_r_scale': amp_q_scaling ,
'rr_atten': inst.get_attenuation(),
'qubit_LO': self.pars['qubit_LO'],
'ffl_LO':self.pars['ffl_LO']
}
# save data
dataPath = f'{saveDir}\\spectroscopy\qubit_spec'
if not os.path.exists(dataPath):
Path(dataPath).mkdir(parents=True, exist_ok=True)
if 'saveto' in kwargs:
dataDict = {'metadata': exp_dict,
'time': freq_arr,
'I': I,
'Q': Q,
}
file = kwargs.get('saveto')['file']
name = kwargs.get('saveto')['name']
save_datadict_to_fgroup(file,name , dataDict)
else:
with open(f"{dataPath}\data_{iteration:03d}.csv","w") as datafile:
writer = csv.writer(datafile)
writer.writerow(exp_dict.keys())
writer.writerow(exp_dict.values())
writer.writerow(freq_arr)
writer.writerow(I)
writer.writerow(Q)
return I, Q, freq_arr, job;
#%%% power_rabi
def power_rabi(self,sa = 0,
a_min = 0.01, # minimum amp_q scaling
a_max = 1, # maximum amp_q scaling
da = 0.005, # step of amp_q
check_mixers = True,
pulse = 'pi',
n_avg = 2000, # number of averages
fit = True,
plot = True,
detuning = 0e6):
amps = np.arange(a_min, a_max + da/2, da)
inst.set_attenuator(attenuation=self.pars['rr_atten'])
# self.check_mix_cal(sa, check = check_mixers, threshold = -55)
prog = self.make_sequence(exp = 'p-rabi', pulse = pulse,
var_arr = amps,
detuning = detuning,
n_avg = n_avg)
qmm = QuantumMachinesManager(host=host, port=port)
job = qmm.simulate(config=self.config, program=prog, simulate=SimulationConfig(duration=3000))
job.get_simulated_samples().con1.plot()
datadict, job = self.get_results(jobtype = prog, result_names = ['I','Q'], showprogress = True, progress_key = 'n', n_total = n_avg)
I = datadict['I']
Q = datadict['Q']
if fit:
fitted_pars,error = pf.fit_data(amps,np.abs(I+1j*Q),sequence='p-rabi',dt=amps[-1]/len(amps),fitFunc='rabi')
if plot:
pf.plot_data(x_vector=amps, y_vector=np.abs(I+1j*Q),sequence='p-rabi',fitted_pars=fitted_pars,
qubitDriveFreq=self.pars['qubit_LO']+self.pars['qubit_IF']+detuning,savefig=False,nAverages=n_avg)
'''Update pulse amplitude'''
A = fitted_pars[1] #self.pars['pi_amp'] * fitted_pars[1]
return amps, I, Q, job, A, fitted_pars
#%%% single_shot
def single_shot(self,
n_reps = 1000,
liveplot = False,
numSamples = 1000):
inst.set_attenuator(attenuation=self.pars['rr_atten'])
prog = self.make_sequence(exp='ss', n_reps = n_reps)
datadict, job = self.get_results(jobtype = prog,result_names=['n', 'I','Q','Iexc','Qexc'], showprogress=True, liveplot = liveplot)
if liveplot == False:
plot, ax = pf.init_IQ_plot()
pf.plot_single_shot(datadict,axes=ax)
return datadict, job, prog
#%%% make_sequence
def make_sequence(self,exp='rabi',IFmin=200e6, IFmax=204e6, df=50e3,var_arr=0,detuning=0,n_avg=0,amp_q_scaling=1,amp_r_scale=1,numPeriods=2,nIterations=1,n_reps=100,on_off=True,saturation_dur=int(10e3),pulse='pi', play_init_pi=True, amp_cav_scaling=0.01, amp_ffl_scaling=0.01):
if exp == 'qubit-spec':
resettime_clk= clk(self.pars['qubit_resettime'])
with program() as prog:
n, f, I, Q = self.declare_vars([int, int, fixed, fixed])
update_frequency("rr", self.pars['rr_IF'])
I_stream, Q_stream, n_stream = self.declare_streams(stream_num=3)
if on_off:
I_b, Q_b, I_tot,Q_tot = self.declare_vars([fixed,fixed, fixed, fixed])
# loop over n_avg iterations
with for_(n, 0, n < n_avg, n + 1):
save(n,n_stream)
# loop over list of IF frequencies
with for_each_(f,var_arr): #with for_(*from_array(f,var_arr)):
# update IF frequency going into qubit mixer
update_frequency("qubit", f)
# measure background
if on_off:
measure("readout"*amp(amp_r_scaling), "rr", None, *self.res_demod(I_b, Q_b))
wait(clk(self.pars['rr_resettime']), "rr")
align("rr", "qubit") # wait for operations on resonator to finish before playing qubit pulse
# play qubit pulse and measure
play("gauss" * amp(amp_q_scaling), "qubit", duration = clk(saturation_dur))
#play('pi','qubit')
play("const"*amp(amp_cav_scaling), "rr", duration=clk(saturation_dur))
play('gaussian'*amp(amp_ffl_scaling), "ffl", duration=clk(saturation_dur))
align("qubit", "rr") # wait for operations on resonator to finish before playing qubit pulse
measure("readout"*amp(amp_r_scaling), "rr", None, *self.res_demod(I, Q))
# subtract background and save to stream
if on_off:
assign(I_tot, I - I_b)
assign(Q_tot, Q - Q_b)
save(I_tot, I_stream)
save(Q_tot, Q_stream)
else:
save(I, I_stream)
save(Q, Q_stream)
# wait some time before continuing to next IF frequency
wait(resettime_clk, "rr")
# average data over iterations and save to stream
with stream_processing():
I_stream.buffer(len(var_arr)).average().save('I')
Q_stream.buffer(len(var_arr)).average().save('Q')
n_stream.save('n')
if exp == 'fflrr-spec':
resettime_clk= clk(self.pars['qubit_resettime'])
with program() as prog:
n, f, I, Q = self.declare_vars([int, int, fixed, fixed])
update_frequency("rr", self.pars['rr_IF'])
I_stream, Q_stream, n_stream = self.declare_streams(stream_num=3)
update_frequency("qubit", self.pars['qubit_IF'])
#update_frequency("ffl", self.pars['ffl_IF'])
# loop over n_avg iterations
with for_(n, 0, n < n_avg, n + 1):
save(n,n_stream)
# loop over list of IF frequencies
with for_each_(f,var_arr): #with for_(*from_array(f,var_arr)):
# update IF frequency going into qubit mixer
update_frequency("ffl", f)
# measure background
#update_frequency("rr", f)
play("readout", "rr")
align("ffl", "rr")
play('gaussian'*amp(amp_ffl_scaling), "ffl", duration=clk(200))
align("ffl", "rr")
measure("void", "rr", None,*self.res_demod(I,Q))
wait(resettime_clk, "rr")
save(I, I_stream)
save(Q, Q_stream)
# average data over iterations and save to stream
with stream_processing():
I_stream.buffer(len(var_arr)).average().save('I')
Q_stream.buffer(len(var_arr)).average().save('Q')
n_stream.save('n')
if exp == 'fflqb-spec':
resettime_clk= clk(self.pars['qubit_resettime'])
with program() as prog:
n, f, I, Q = self.declare_vars([int, int, fixed, fixed])
update_frequency("rr", self.pars['rr_IF'])
I_stream, Q_stream, n_stream = self.declare_streams(stream_num=3)
update_frequency("qubit", self.pars['qubit_IF'])
#update_frequency("ffl", self.pars['ffl_IF'])
# loop over n_avg iterations
with for_(n, 0, n < n_avg, n + 1):
save(n,n_stream)
# loop over list of IF frequencies
with for_each_(f,var_arr): #with for_(*from_array(f,var_arr)):
# update IF frequency going into qubit mixer
update_frequency("ffl", f)
play('pi','qubit')
align('ffl','qubit')
wait(clk(60),'ffl')
play('gaussian'*amp(amp_ffl_scaling), "ffl", duration=clk(10000))
wait(clk(30))
align("ffl","rr")
measure("readout", "rr", None, *self.res_demod(I, Q))
# subtract background and save to stream
save(I, I_stream)
save(Q, Q_stream)
wait(resettime_clk, "qubit")
# wait some time before continuing to next IF frequency
# average data over iterations and save to stream
with stream_processing():
I_stream.buffer(len(var_arr)).average().save('I')
Q_stream.buffer(len(var_arr)).average().save('Q')
n_stream.save('n')
if exp == 'rabi':
resettime_clk= clk(self.pars['qubit_resettime'])
with program() as prog:
n, t, I, Q = self.declare_vars([int, int, fixed, fixed])
I_stream, Q_stream, n_stream = self.declare_streams(stream_num=3)
update_frequency("rr", self.pars['rr_IF'])
update_frequency('qubit', (self.pars['qubit_freq']-self.pars['qubit_LO']) + detuning) # sets the IF frequency of the qubit
with for_(n, 0, n < n_avg, n + 1):
save(n, n_stream)
with for_each_(t,var_arr):
with if_(t==0):
measure("readout", "rr", None, *self.res_demod(I, Q))
# save(t,t_stream)
save(I, I_stream)
save(Q, Q_stream)
wait(resettime_clk,"qubit")
with else_():
play("pi" * amp(amp_q_scaling), "qubit", duration=t)
align("qubit", "rr")
measure("readout", "rr", None, *self.res_demod(I, Q))
# save(t,t_stream)
save(I, I_stream)
save(Q, Q_stream)
wait(resettime_clk,"qubit")
with stream_processing():
I_stream.buffer(len(var_arr)).average().save("I")
Q_stream.buffer(len(var_arr)).average().save("Q")
n_stream.save('n')
elif exp == 'p-rabi':
resettime_clk= clk(self.pars['qubit_resettime'])
with program() as prog:
a, n, I, Q = self.declare_vars([fixed, int, fixed, fixed])
I_stream, Q_stream, n_stream = self.declare_streams(stream_num=3)
update_frequency("rr", self.pars['rr_IF'])
update_frequency('qubit', (self.pars['qubit_freq']-self.pars['qubit_LO']) + detuning) # sets the IF frequency of the qubit
with for_(n, 0, n < n_avg, n + 1):
save(n, n_stream)
with for_each_(a,var_arr): # Sweep pulse duration
play('const'*amp(0.2), "ffl", duration=25)
wait(10,"qubit")
play(pulse * amp(a), "qubit")
#align("qubit", "rr")
align("ffl","rr")
measure("readout", "rr", None, *self.res_demod(I, Q))
save(I, I_stream)
save(Q, Q_stream)
wait(resettime_clk)
with stream_processing():
I_stream.buffer(len(var_arr)).average().save("I")
Q_stream.buffer(len(var_arr)).average().save("Q")
n_stream.save("n")
elif exp == 'ramsey':
resettime_clk= clk(self.pars['qubit_resettime'])
with program() as prog:
update_frequency("rr", self.pars['rr_IF'])
update_frequency('qubit', (self.pars['qubit_freq']-self.pars['qubit_LO']) + detuning)
n, t, I, Q = self.declare_vars([int, int, fixed, fixed])
I_stream,Q_stream,n_stream = self.declare_streams(stream_num=3)
with for_(n, 0, n < n_avg, n + 1):
save(n, n_stream)
with for_each_(t,var_arr):
with if_(t==0):
play("pi_half", "qubit")
play("pi_half", "qubit")
align("qubit","rr")
measure("readout", "rr", None, *self.res_demod(I, Q))
save(I, I_stream)
save(Q, Q_stream)
wait(resettime_clk, "qubit")
with else_():
play("pi_half", "qubit")
wait(t, "qubit")
# frame_rotation_2pi(phi, 'qubit') # this was in Haimeng's code and was commented out by her,
play("pi_half", "qubit")
align("qubit","rr")
measure("readout", "rr", None, *self.res_demod(I, Q))
save(I, I_stream)
save(Q, Q_stream)
wait(resettime_clk, "qubit")
with stream_processing():
I_stream.buffer(len(var_arr)).average().save("I")
Q_stream.buffer(len(var_arr)).average().save("Q")
n_stream.save("n")
elif exp == 'ramsey_chi':
resettime_clk= clk(self.pars['qubit_resettime'])
with program() as prog:
update_frequency("rr", self.pars['rr_IF'])
update_frequency('qubit', (self.pars['qubit_freq']-self.pars['qubit_LO']) + detuning)
n, t, I, Q = self.declare_vars([int, int, fixed, fixed])
I_stream,Q_stream,n_stream = self.declare_streams(stream_num=3)
with for_(n, 0, n < n_avg, n + 1):
save(n, n_stream)
with for_each_(t,var_arr):
with if_(t==0):
play("pi_half", "qubit")
play("pi_half", "qubit")
align("qubit","rr")
measure("readout", "rr", None, *self.res_demod(I, Q))
save(I, I_stream)
save(Q, Q_stream)
wait(resettime_clk, "qubit")
with else_():
play("pi_half", "qubit")
align('qubit','rr')
play("readout"*amp(amp_r_scale), "rr",duration=t)
align('rr','qubit')
# frame_rotation_2pi(phi, 'qubit') # this was in Haimeng's code and was commented out by her,
play("pi_half", "qubit")
align("qubit","rr")
measure("readout", "rr", None, *self.res_demod(I, Q))
save(I, I_stream)
save(Q, Q_stream)
wait(resettime_clk, "qubit")
with stream_processing():
I_stream.buffer(len(var_arr)).average().save("I")
Q_stream.buffer(len(var_arr)).average().save("Q")
n_stream.save("n")