def take_data(self):

        ####
        if self.cfg["visdom_plot_livedata"]:

            viz = visdom.Visdom()
            assert viz.check_connection(), "Visdom server not connected!"
            # added two environments "seq_builder.json", and "live_plot.json" in C:\Users\slab\.visdom
            eid = "live_plot"
            viz.close(win=None, env=eid)

            win1 = viz.line( X=np.arange(0, 1), Y=np.arange(0, 1), env=eid,
                opts=dict(height=400, width=700, title='expt_avg_data', showlegend=True, xlabel='expt_pts'))
            win2 = viz.line( X=np.arange(0, 1), Y=np.arange(0, 1), env=eid,
                opts=dict(height=400, width=700, title='expt_avg_data2', showlegend=True, xlabel='expt_pts'))
            win3 = viz.line( X=np.arange(0, 1), Y=np.arange(0, 1), env=eid,
                opts=dict(height=400, width=700, title='single_record (of only first run)', showlegend=True, xlabel='time ns'))
            win4 = viz.scatter(X=array([[1,2,3],[1,2,3]]).transpose(), env=eid,
                        opts=dict(height=400, width=700, title='g/e/f cal single shot', showlegend=True, xlabel=''))

        ####

        if self.pre_run is not None:
            self.pre_run()

        TEST_REDPITAYA = False

        if TEST_REDPITAYA:
            self.awg_run()

        if not TEST_REDPITAYA:

            if self.adc == None:
                print("Prep Card")
                adc = Alazar(self.cfg['alazar'])
            else:
                adc = self.adc

            # debug_alazer = False
            # if debug_alazer:
            #
            #     # save raw time trace, 100 runs only
            #     tpts, single_data1, single_data2 = adc.acquire_singleshot_data2()
            #
            #     self.slab_file = self.datafile(data_file=self.data_file)
            #     with self.slab_file as f:
            #         f.add('tpts', tpts)
            #         f.add('single_data1', single_data1)
            #         f.add('single_data2', single_data2)
            #         f.close()
            #
            #     # hack for post_run
            #     expt_avg_data = self.expt_pts
            #
            # else:

            if not self.cfg['readout']['save_single-shot_data']:

                expt_data = None
                current_data = None
                for ii in tqdm(arange(max(1, self.cfg[self.expt_cfg_name]['averages'] / 100))):
                    tpts, ch1_pts, ch2_pts = adc.acquire_avg_data_by_record(prep_function=self.awg_prep,
                                                                            start_function=self.awg_run,
                                                                            excise=self.cfg['readout']['window'])

                    if not self.cfg[self.expt_cfg_name]['use_pi_calibration']:

                        if expt_data is None:
                            if self.cfg['readout']['channel'] == 1:
                                expt_data = ch1_pts
                            elif self.cfg['readout']['channel'] == 2:
                                expt_data = ch2_pts
                        else:
                            if self.cfg['readout']['channel'] == 1:
                                expt_data = (expt_data * ii + ch1_pts) / (ii + 1.0)
                            elif self.cfg['readout']['channel'] == 2:
                                expt_data = (expt_data * ii + ch2_pts) / (ii + 1.0)

                        if self.cfg['readout']['heterodyne_freq'] == 0:
                            # homodyne
                            expt_avg_data = mean(expt_data, 1)
                        else:
                            # heterodyne
                            heterodyne_freq = self.cfg['readout']['heterodyne_freq']
                            # ifft by numpy default has the correct 1/N normalization
                            expt_data_fft_amp = np.abs(np.fft.ifft(expt_data))
                            hetero_f_ind = int(round(heterodyne_freq * tpts.size * 1e-9))  # position in ifft

                            # todo: do the proper sum here
                            # expt_avg_data = np.average(expt_data_fft_amp[:, (hetero_f_ind - 1):(hetero_f_ind + 1)], axis=1)
                            expt_avg_data = expt_data_fft_amp[:, hetero_f_ind]

                    else:
                        # average first, then divide by pi_calibration values
                        if expt_data is None:
                            if self.cfg['readout']['channel'] == 1:
                                expt_data = ch1_pts[:-2]
                                zero_amp_curr = mean(ch1_pts[-2])
                                pi_amp_curr = mean(ch1_pts[-1])
                            elif self.cfg['readout']['channel'] == 2:
                                expt_data = ch2_pts[:-2]
                                zero_amp_curr = mean(ch2_pts[-2])
                                pi_amp_curr = mean(ch2_pts[-1])
                            zero_amp = zero_amp_curr
                            pi_amp = pi_amp_curr
                        else:
                            if self.cfg['readout']['channel'] == 1:
                                expt_data = (expt_data * ii + ch1_pts[:-2]) / (ii + 1.0)
                                zero_amp_curr = mean(ch1_pts[-2])
                                pi_amp_curr = mean(ch1_pts[-1])
                            elif self.cfg['readout']['channel'] == 2:
                                expt_data = (expt_data * ii + ch2_pts[:-2]) / (ii + 1.0)
                                zero_amp_curr = mean(ch2_pts[-2])
                                pi_amp_curr = mean(ch2_pts[-1])
                            zero_amp = (zero_amp * ii + zero_amp_curr) / (ii + 1.0)
                            pi_amp = (pi_amp * ii + pi_amp_curr) / (ii + 1.0)

                        # todo: add heterodyne with pi_cal
                        expt_avg_data = mean((expt_data - zero_amp) / (pi_amp - zero_amp), 1)

                    # self.slab_file = self.datafile(data_file=self.data_file)

                    with self.slab_file as f:
                        f.add('expt_2d', expt_data)
                        f.add('expt_avg_data', expt_avg_data)
                        f.add('expt_pts', self.expt_pts)

                        # save pi_cal amps, to be able to monitor fluctuations
                        if self.cfg[self.expt_cfg_name]['use_pi_calibration']:
                            f.append_pt('zero_amps', zero_amp_curr)
                            f.append_pt('pi_amps', pi_amp_curr)

                        f.close()


            else:  # here saves all single shot data

                if self.prefix == 'Vacuum_Rabi':

                    print('vacuum_rabi')
                    het_IFreqList = [self.cfg['readout']['heterodyne_freq']]
                    het_read_freq_list = [0]

                elif self.cfg['readout']['is_multitone_heterodyne']:
                    het_carrier_freq = self.cfg['readout']['heterodyne_carrier_freq']
                    het_read_freq_list = array(self.cfg['readout']['heterodyne_freq_list'])
                    het_IFreqList = het_read_freq_list - het_carrier_freq
                else:
                    het_carrier_freq = self.readout_freq - self.cfg['readout']['heterodyne_freq']
                    het_read_freq_list = array([self.readout_freq])
                    het_IFreqList = het_read_freq_list - het_carrier_freq

                avgPerAcquisition = int(min(self.cfg[self.expt_cfg_name]['averages'], 100))
                numAcquisition = int(np.ceil(self.cfg[self.expt_cfg_name]['averages'] / 100))

                # (ch1/2, exp_pts, heterodyne_freq, cos/sin, all averages)
                ss_data = zeros((2, len(self.expt_pts), len(het_IFreqList), 2, avgPerAcquisition * numAcquisition))

                # (ch1/2, heterodyne_freq, cos/sin, all averages)
                ss_cal_g = zeros((2, len(het_IFreqList), 2, avgPerAcquisition * numAcquisition))
                ss_cal_e = zeros((2, len(het_IFreqList), 2, avgPerAcquisition * numAcquisition))
                ss_cal_f = zeros((2, len(het_IFreqList), 2, avgPerAcquisition * numAcquisition))

                if self.cfg['readout']['save_trajectory_data']:

                    # (ch1/2, exp_pts, heterodyne_freq, cos/sin, all averages, traj)
                    traj_data = zeros((2, len(self.expt_pts), len(het_IFreqList), 2, avgPerAcquisition * numAcquisition, self.cfg['readout']['pts_per_traj']))

                    # (ch1/2, heterodyne_freq, cos/sin, all averages, traj)
                    traj_cal_g = zeros((2, len(het_IFreqList), 2, avgPerAcquisition * numAcquisition, self.cfg['readout']['pts_per_traj']))
                    traj_cal_e = zeros((2, len(het_IFreqList), 2, avgPerAcquisition * numAcquisition, self.cfg['readout']['pts_per_traj']))
                    traj_cal_f = zeros((2, len(het_IFreqList), 2, avgPerAcquisition * numAcquisition, self.cfg['readout']['pts_per_traj']))

                for ii in tqdm(arange(numAcquisition)):

                    if not self.cfg['readout']['is_hetero_phase_ref']:

                        # single_data1/2: index: (hetero_freqs, cos/sin, all_seqs)
                        single_data1, single_data2, single_record1, single_record2 = \
                            adc.acquire_singleshot_heterodyne_multitone_data(het_IFreqList, prep_function=self.awg_prep,
                                                                             start_function=self.awg_run,
                                                                             excise=self.cfg['readout']['window'])

                        # saving the raw time traces
                        # single_data1, single_data2, single_record1, single_record2 = \
                        #     adc.acquire_singleshot_heterodyne_multitone_data(het_IFreqList, prep_function=self.awg_prep,
                        #                                                      start_function=self.awg_run,
                        #                                                      excise=None, save_raw_data=True)

                    elif self.cfg['readout']['save_trajectory_data']:

                        excise = [ 0, self.cfg['readout']['window'][1] ]
                        single_data1, single_data2, single_record1, single_record2, single_traj1, single_traj2= \
                            adc.acquire_singleshot_heterodyne_multitone_data_phase_ref_save_traj(het_IFreqList,
                                                                                       self.cfg['readout'][
                                                                                           'hetero_phase_ref_freq'],
                                                                                       prep_function=self.awg_prep,
                                                                                       start_function=self.awg_run,
                                                                                       excise=excise,
                                                                                       isCompensatePhase=True,
                                                                                       save_raw_data=False, pts_per_traj=self.cfg['readout']['pts_per_traj'])
                    else:

                        # single_data1/2: index: (hetero_freqs, cos/sin, all_seqs)
                        single_data1, single_data2, single_record1, single_record2 = \
                            adc.acquire_singleshot_heterodyne_multitone_data_phase_ref(het_IFreqList,
                                                                             self.cfg['readout']['hetero_phase_ref_freq'],
                                                                             prep_function=self.awg_prep,
                                                                             start_function=self.awg_run,
                                                                             excise=self.cfg['readout']['window'],
                                                                             isCompensatePhase=True,
                                                                             save_raw_data=False)

                    single_data = array([single_data1, single_data2])
                    # index: (ch1/2, hetero_freqs, cos / sin, avgs, seq(exp_pts))
                    single_data = np.reshape(single_data,
                                             (single_data.shape[0], single_data.shape[1], single_data.shape[2],
                                              int(self.cfg['alazar'][
                                                  'recordsPerAcquisition'] / self.pulse_sequence.sequence_length),
                                              self.pulse_sequence.sequence_length))

                    # index: (ch1/2, exp_pts, hetero_freqs, cos / sin, avgs)
                    single_data = np.transpose(single_data, (0, 4, 1, 2, 3))

                    if (self.cfg[self.expt_cfg_name]['use_g-e-f_calibration']):

                        ss_data[:, :, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)] = single_data[:,
                                                                                                       0:-3]
                        ss_cal_g[:, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)] = single_data[:, -3]
                        ss_cal_e[:, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)] = single_data[:, -2]
                        ss_cal_f[:, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)] = single_data[:, -1]

                    elif (self.cfg[self.expt_cfg_name]['use_pi_calibration']):

                        ss_data[:, :, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)] = single_data[:,
                                                                                                       0:-2]
                        ss_cal_g[:, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)] = single_data[:, -2]
                        ss_cal_e[:, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)] = single_data[:, -1]

                    else:
                        ss_data[:, :, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)] = single_data[:, :]

                    ####
                    if self.cfg['readout']['save_trajectory_data']:

                        # index: (hetero_freqs, cos/sin, all_seqs, traj)
                        single_traj = array([single_traj1, single_traj2])

                        # index: (ch1/2, hetero_freqs, cos / sin, avgs, seq(exp_pts), traj)
                        single_traj = np.reshape(single_traj,
                                                 (single_traj.shape[0], single_traj.shape[1], single_traj.shape[2],
                                                  self.cfg['alazar']['recordsPerAcquisition'] / self.pulse_sequence.sequence_length,
                                                  self.pulse_sequence.sequence_length, single_traj.shape[-1]))

                        # index: (ch1/2, exp_pts, hetero_freqs, cos / sin, avgs, traj)
                        single_traj = np.transpose(single_traj, (0, 4, 1, 2, 3, 5))
                        # print single_traj.shape

                        if (self.cfg[self.expt_cfg_name]['use_g-e-f_calibration']):

                            traj_data[:, :, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition), :] = single_traj[
                                                                                                           :,
                                                                                                           0:-3, :]
                            traj_cal_g[:, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition), :] = single_traj[:,
                                                                                                         -3, :]
                            traj_cal_e[:, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition), :] = single_traj[:,
                                                                                                         -2, :]
                            traj_cal_f[:, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition), :] = single_traj[:,
                                                                                                         -1, :]

                        elif (self.cfg[self.expt_cfg_name]['use_pi_calibration']):

                            traj_data[:, :, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition), :] = single_traj[
                                                                                                           :,
                                                                                                           0:-2, :]
                            traj_cal_g[:, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition), :] = single_traj[:,
                                                                                                         -2, :]
                            traj_cal_e[:, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition), :] = single_traj[:,
                                                                                                         -1, :]

                        else:
                            traj_data[:, :, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition), :] = single_traj[
                                                                                                           :, :, :]

                    ####

                    # old way for easy plotting
                    # only calculate for 1st het_readout_freq
                    if het_IFreqList[0] == 0:
                        # take cos of ch1/ch2
                        expt_avg_data = mean(ss_data[0, :, 0, 0, 0:((ii + 1) * avgPerAcquisition)], -1)
                        expt_avg_data2 = mean(ss_data[1, :, 0, 0, 0:((ii + 1) * avgPerAcquisition)], -1)

                        if self.cfg[self.expt_cfg_name]['use_pi_calibration']:
                            zero_amp_avg = mean(ss_cal_g[0, 0, 0, 0:((ii + 1) * avgPerAcquisition)], -1)
                            zero_amp_avg2 = mean(ss_cal_g[1, 0, 0, 0:((ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_avg = mean(ss_cal_e[0, 0, 0, 0:((ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_avg2 = mean(ss_cal_e[1, 0, 0, 0:((ii + 1) * avgPerAcquisition)], -1)

                            zero_amp_curr = mean(
                                ss_cal_g[0, 0, 0, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)], -1)
                            zero_amp_curr2 = mean(
                                ss_cal_g[1, 0, 0, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_curr = mean(
                                ss_cal_e[0, 0, 0, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_curr2 = mean(
                                ss_cal_e[1, 0, 0, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)], -1)

                            expt_avg_data = (expt_avg_data - zero_amp_avg) / (pi_amp_avg - zero_amp_avg)
                            expt_avg_data2 = (expt_avg_data2 - zero_amp_avg2) / (pi_amp_avg2 - zero_amp_avg2)

                    else:
                        # take cos/sin of ch1
                        expt_avg_data = mean(ss_data[0, :, 0, 0, 0:((ii + 1) * avgPerAcquisition)], -1)
                        expt_avg_data2 = mean(ss_data[0, :, 0, 1, 0:((ii + 1) * avgPerAcquisition)], -1)

                        if self.cfg[self.expt_cfg_name]['use_pi_calibration']:
                            zero_amp_avg = mean(ss_cal_g[0, 0, 0, 0:((ii + 1) * avgPerAcquisition)], -1)
                            zero_amp_avg2 = mean(ss_cal_g[0, 0, 1, 0:((ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_avg = mean(ss_cal_e[0, 0, 0, 0:((ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_avg2 = mean(ss_cal_e[0, 0, 1, 0:((ii + 1) * avgPerAcquisition)], -1)

                            zero_amp_curr = mean(
                                ss_cal_g[0, 0, 0, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)], -1)
                            zero_amp_curr2 = mean(
                                ss_cal_g[0, 0, 1, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)],
                                -1)
                            pi_amp_curr = mean(
                                ss_cal_e[0, 0, 0, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_curr2 = mean(
                                ss_cal_e[0, 0, 1, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)], -1)

                            expt_avg_data = (expt_avg_data - zero_amp_avg) / (pi_amp_avg - zero_amp_avg)
                            expt_avg_data2 = (expt_avg_data2 - zero_amp_avg2) / (pi_amp_avg2 - zero_amp_avg2)

                    # this needs to stay here
                    # if self.data_file != None:
                    #     self.slab_file = SlabFile(self.data_file)
                    # else:
                    #     self.slab_file = self.datafile()
                    self.slab_file = self.datafile(data_file=self.data_file)

                    with self.slab_file as f:
                        f.add('ss_data', ss_data[:, :, :, :, 0:((ii + 1) * avgPerAcquisition)])
                        f.add('single_record1', single_record1)
                        f.add('single_record2', single_record2)

                        if (self.cfg[self.expt_cfg_name]['use_pi_calibration']):
                            f.add('ss_cal_g', ss_cal_g[:, :, :, 0:((ii + 1) * avgPerAcquisition)])
                            f.add('ss_cal_e', ss_cal_e[:, :, :, 0:((ii + 1) * avgPerAcquisition)])
                        if (self.cfg[self.expt_cfg_name]['use_g-e-f_calibration']):
                            f.add('ss_cal_g', ss_cal_g[:, :, :, 0:((ii + 1) * avgPerAcquisition)])
                            f.add('ss_cal_e', ss_cal_e[:, :, :, 0:((ii + 1) * avgPerAcquisition)])
                            f.add('ss_cal_f', ss_cal_f[:, :, :, 0:((ii + 1) * avgPerAcquisition)])

                        if self.cfg['readout']['save_trajectory_data']:
                            f.add('traj_data', traj_data[:, :, :, :, 0:((ii + 1) * avgPerAcquisition), :])
                            if (self.cfg[self.expt_cfg_name]['use_pi_calibration']):
                                f.add('traj_cal_g', traj_cal_g[:, :, :, 0:((ii + 1) * avgPerAcquisition), :])
                                f.add('traj_cal_e', traj_cal_e[:, :, :, 0:((ii + 1) * avgPerAcquisition), :])
                            if (self.cfg[self.expt_cfg_name]['use_g-e-f_calibration']):
                                f.add('traj_cal_g', traj_cal_g[:, :, :, 0:((ii + 1) * avgPerAcquisition), :])
                                f.add('traj_cal_e', traj_cal_e[:, :, :, 0:((ii + 1) * avgPerAcquisition), :])
                                f.add('traj_cal_f', traj_cal_f[:, :, :, 0:((ii + 1) * avgPerAcquisition), :])

                        f.add('expt_avg_data', expt_avg_data.flatten())
                        f.add('expt_avg_data2', expt_avg_data2.flatten())

                        f.add('expt_pts', self.expt_pts)
                        f.add('het_read_freq_list', het_read_freq_list)

                        if self.cfg[self.expt_cfg_name]['use_pi_calibration']:
                            f.append_pt('zero_amps', zero_amp_curr)
                            f.append_pt('pi_amps', pi_amp_curr)
                            f.append_pt('zero_amps2', zero_amp_curr2)
                            f.append_pt('pi_amps2', pi_amp_curr2)

                        f.close()

                    ####
                    if self.cfg["visdom_plot_livedata"]:
                        viz.updateTrace(X=self.expt_pts, Y=expt_avg_data, env=eid, win=win1, append=False)
                        viz.updateTrace(X=self.expt_pts, Y=expt_avg_data2, env=eid, win=win2, append=False)

                        # if (self.cfg[self.expt_cfg_name]['use_pi_calibration']):
                        #
                        #     f_idx = 0
                        #     viz.scatter(X=array([ss_cal_g[0, f_idx, 0, :],ss_cal_g[0, f_idx, 1, :]]).transpose(),
                        #                     Y=None, env=eid, win=win4, name='test')
                        #
                        # if (self.cfg[self.expt_cfg_name]['use_g-e-f_calibration']):
                        #     pass

                        if ii==0:
                            viz.updateTrace(X=array(range(len(single_record1))), Y=single_record2, env=eid, win=win3, name='2', append=False)
                            viz.updateTrace(X=array(range(len(single_record1))), Y=single_record1, env=eid, win=win3, name='1', append=False)
                    ####

            if self.post_run is not None:
                self.post_run(self.expt_pts, expt_avg_data)

            if self.cfg['stop_awgs'] == True:
                self.awg_prep()
                print('stop_awg = True, seqs stopped.')
            else:
                print('stop_awg = False, seqs left running.')

            # closes Alazar card and releases buffer
            adc.close()
Exemplo n.º 2
0
    def take_data(self):

        print('take_data() in HistogramHetero')

        if self.pre_run is not None:
            self.pre_run()

        if self.adc == None:
            print("Prep Card")
            adc = Alazar(self.cfg['alazar'])
        else:
            adc = self.adc

        ###

        het_IFreqList = array([self.cfg['readout']['heterodyne_freq']])

        avgPerAcquisition = int(
            min(self.cfg[self.expt_cfg_name]['averages'], 100))
        numAcquisition = int(
            np.ceil(self.cfg[self.expt_cfg_name]['averages'] / 100))

        attenpts = arange(self.cfg[self.expt_cfg_name]['atten_start'],
                          self.cfg[self.expt_cfg_name]['atten_stop'],
                          self.cfg[self.expt_cfg_name]['atten_step'])
        freqpts = arange(self.cfg[self.expt_cfg_name]['freq_start'],
                         self.cfg[self.expt_cfg_name]['freq_stop'],
                         self.cfg[self.expt_cfg_name]['freq_step'])

        # (channel, atten, freq, g/e/f, average)
        ss_cos_data_all = zeros((2, len(attenpts), len(freqpts), 3,
                                 avgPerAcquisition * numAcquisition))
        ss_sin_data_all = zeros((2, len(attenpts), len(freqpts), 3,
                                 avgPerAcquisition * numAcquisition))

        for xx, atten in enumerate(attenpts):

            try:
                self.readout_atten.set_attenuator(atten)
                print("Digital atten:", atten)
            except:
                print("Digital attenuator not loaded.")

            # (ch1/2, exp_pts, heterodyne_freq, cos/sin, all averages)
            ss_data = zeros((2, len(self.expt_pts), len(het_IFreqList), 2,
                             avgPerAcquisition * numAcquisition))
            for ii in tqdm(arange(numAcquisition)):

                if not self.cfg['readout']['is_hetero_phase_ref']:

                    # single_data1/2: index: (hetero_freqs, cos/sin, all_seqs)
                    single_data1, single_data2, single_record1, single_record2 = \
                        adc.acquire_singleshot_heterodyne_multitone_data(het_IFreqList, prep_function=self.awg_prep,
                                                                         start_function=self.awg_run,
                                                                         excise=self.cfg['readout']['window'])
                    # saving the raw time traces
                    # single_data1, single_data2, single_record1, single_record2 = \
                    #     adc.acquire_singleshot_heterodyne_multitone_data(het_IFreqList, prep_function=self.awg_prep,
                    #                                                      start_function=self.awg_run,
                    #                                                      excise=None, save_raw_data=True)

                else:
                    # single_data1/2: index: (hetero_freqs, cos/sin, all_seqs)
                    single_data1, single_data2, single_record1, single_record2 = \
                        adc.acquire_singleshot_heterodyne_multitone_data_phase_ref(het_IFreqList,
                                                                         self.cfg['readout']['hetero_phase_ref_freq'],
                                                                         prep_function=self.awg_prep,
                                                                         start_function=self.awg_run,
                                                                         excise=self.cfg['readout']['window'],
                                                                         isCompensatePhase=True,
                                                                         save_raw_data=False)
                single_data = array([single_data1, single_data2])

                # reshape to fit into histogram data
                # index: (ch1/2, hetero_freqs(0), cos / sin, avgs, freqpts(exp seq), g/e/f)
                single_data = np.reshape(
                    single_data, (single_data.shape[0], single_data.shape[1],
                                  single_data.shape[2],
                                  self.cfg['alazar']['recordsPerAcquisition'] /
                                  self.pulse_sequence.sequence_length,
                                  self.pulse_sequence.sequence_length / 3, 3))

                # (channel, hetero_freqs(0), cos/sin, freqpts(exp seq), g/e/f, average)
                single_data = np.transpose(single_data, (0, 1, 2, 4, 5, 3))

                # (channel, atten, freqpts, g/e/f, average)
                ss_cos_data_all[:, xx, :, :, (ii * avgPerAcquisition):(
                    (ii + 1) * avgPerAcquisition)] = single_data[:, 0,
                                                                 0, :, :, :]
                ss_sin_data_all[:, xx, :, :, (ii * avgPerAcquisition):(
                    (ii + 1) * avgPerAcquisition)] = single_data[:, 0,
                                                                 1, :, :, :]

            # this needs to stay here
            self.slab_file = self.datafile(data_file=self.data_file)
            with self.slab_file as f:

                f.add('attenpts', attenpts)
                f.add('freqpts', freqpts)
                f.add('het_IFreqList', het_IFreqList)
                f.add('ss_cos_data_ch1', ss_cos_data_all[0])
                f.add('ss_cos_data_ch2', ss_cos_data_all[1])
                f.add('ss_sin_data_ch1', ss_sin_data_all[0])
                f.add('ss_sin_data_ch2', ss_sin_data_all[1])
                f.append_line('single_record1', single_record1)
                f.append_line('single_record2', single_record2)
                f.close()

        ###

        # if self.post_run is not None:
        #     self.post_run(self.expt_pts, expt_avg_data)

        if self.cfg['stop_awgs'] == True:
            self.awg_prep()

        # close Alazar and release buffer
        adc.close()
def run_sequential_experiment(expt_name):
    import os
    import difflib

    expt_list = [
        'Frequency_Calibration', 'Rabi_Sweep', 'HalfPiXOptimization_sweep',
        'tune_up_experiment'
    ]

    datapath = os.getcwd() + '\data'
    config_file = os.path.join(datapath, "..\\config" + ".json")
    with open(config_file, 'r') as fid:
        cfg_str = fid.read()

    cfg = AttrDict(json.loads(cfg_str))

    expt = None

    experiment_started = False

    if expt_name.lower() == 'calibration_experiment':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RamseyExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RabiExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import EFRabiExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import EFRamseyExperiment

        # Do Frequency Calibration

        expt = RamseyExperiment(path=datapath)
        expt.go()
        print(expt.offset_freq)

        expt = RabiExperiment(path=datapath)
        expt.go()

        expt = EFRabiExperiment(path=datapath)
        expt.go()

        expt = EFRamseyExperiment(path=datapath)
        expt.go()
        del expt
        gc.collect()

    if expt_name.lower() == 'monitor_frequency_experiment':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RamseyExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import EFRamseyExperiment

        # Do Frequency Calibration

        for i in arange(20):
            expt = RamseyExperiment(path=datapath)
            expt.go()
            print(expt.offset_freq)

            expt = EFRamseyExperiment(path=datapath)
            expt.go()
            del expt
            gc.collect()

    if expt_name.lower() == 'sequential_error_amplification':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import SingleQubitErrorAmplificationExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import SingleQubitErrorAmplificationPhaseOffsetExperiment

        for i in arange(5):
            pulse_calibration(phase_exp=True)
            expt = SingleQubitErrorAmplificationPhaseOffsetExperiment(
                path=datapath,
                trigger_period=0.001,
                c0="half_pi",
                ci="half_pi")
            expt.go()
            expt.save_config()
            del expt
            gc.collect()
        for i in arange(5):
            pulse_calibration(phase_exp=True)
            expt = SingleQubitErrorAmplificationPhaseOffsetExperiment(
                path=datapath, trigger_period=0.001, c0="pi", ci="half_pi")
            expt.go()
            expt.save_config()
            del expt
            gc.collect()
        for i in arange(5):
            pulse_calibration(phase_exp=True)
            expt = SingleQubitErrorAmplificationPhaseOffsetExperiment(
                path=datapath, trigger_period=0.001, c0="pi", ci="pi")
            expt.go()
            expt.save_config()
            del expt
            gc.collect()
        for i in arange(5):
            pulse_calibration(phase_exp=True)
            expt = SingleQubitErrorAmplificationPhaseOffsetExperiment(
                path=datapath, trigger_period=0.001, c0="half_pi", ci="pi")
            expt.go()
            expt.save_config()
            del expt
            gc.collect()

    if expt_name.lower() == 'sequential_randomized_benchmarking':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import SingleQubitRandomizedBenchmarkingExperiment

        for i in arange(32):
            pulse_calibration(phase_exp=False)
            expt = SingleQubitRandomizedBenchmarkingExperiment(
                path=datapath, trigger_period=0.001)
            expt.go()
            del expt
            gc.collect()

    if expt_name.lower() == 'sequential_randomized_benchmarking_phase_offset':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import SingleQubitRandomizedBenchmarkingPhaseOffsetExperiment

        for i in arange(32):
            pulse_calibration(phase_exp=True)
            expt = SingleQubitRandomizedBenchmarkingPhaseOffsetExperiment(
                path=datapath, trigger_period=0.001)
            expt.go()
            del expt
            gc.collect()

    if expt_name.lower() == 'tomography_tune_up_experiment':
        experiment_started = True
        print(expt_name + " is running!")
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RamseyExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RabiExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import EFRabiExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import EFRamseyExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import HalfPiYPhaseOptimizationExperiment

        # Do Frequency Calibration

        expt = RamseyExperiment(path=datapath)
        expt.go()
        if (abs(expt.offset_freq) < 50e3):
            pass
        else:
            print(expt.flux)
            flux_offset = -expt.offset_freq / (expt.freq_flux_slope)
            print(flux_offset)
            if (abs(flux_offset) < 0.000002):
                flux2 = expt.flux + flux_offset
                print(flux2)
                expt = RamseyExperiment(path=datapath, flux=flux2)
                expt.go()
                offset_freq2 = expt.offset_freq
                flux_offset2 = -expt.offset_freq / (expt.freq_flux_slope)
                flux3 = flux2 + flux_offset2
                if (abs(offset_freq2) < 50e3):
                    print("Great success! Frequency calibrated")
                    expt.save_config()
                else:
                    if (abs(flux_offset2) < 0.000002):
                        expt = RamseyExperiment(path=datapath, flux=flux3)
                        expt.go()
                        if (abs(expt.offset_freq) < 100e3):
                            print("Frequency calibrated")
                            expt.save_config()
                        else:
                            print("Try again: not converged after 2 tries")
                    else:
                        print(
                            "Large change in flux is required; please do so manually"
                        )
                        pass
            else:
                print(
                    "Large change in flux is required; please do so manually")
                pass

        expt = RabiExperiment(path=datapath)
        expt.go()
        print("ge pi and pi/2 pulses recalibrated")
        expt.save_config()

        expt = EFRabiExperiment(path=datapath)
        expt.go()
        print("ef pi and pi/2 pulses recalibrated")
        expt.save_config()

        expt = EFRamseyExperiment(path=datapath)
        expt.go()
        expt.save_config()
        expt.go()

        # #

        # expt = HalfPiYPhaseOptimizationExperiment(path=datapath)
        # expt.go()
        # #
        # print flux2
        del expt
        gc.collect()

    if expt_name.lower() == 'offset_phase_calibration_experiment':
        qubit_dc_offset_list_pi = array([
            0, 0, 0, 1.7e6, 1.7e6, 1.7e6, 1.8e6, 1.8e6, 1.8e6, 1.9e6, 1.9e6,
            1.9e6, 2e6, 2e6, 2e6
        ])

        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import HalfPiYPhaseOptimizationExperiment
        # Do Frequency Calibration
        # frequency_stabilization()
        j = 0
        for qubit_dc_offset in qubit_dc_offset_list_pi:
            if j > 0 and j % 3 == 0:
                frequency_stabilization()

            expt = HalfPiYPhaseOptimizationExperiment(
                path=datapath, qubit_dc_offset=qubit_dc_offset)
            expt.go()
            expt.save_config()
            del expt
            gc.collect()
            j += 1

    if expt_name.lower() == 'frequency_calibration':
        frequency_stabilization()

    if expt_name.lower() == 'pulse_calibration':
        pulse_calibration(phase_exp=True)

    if expt_name.lower() == 'rabi_sweep':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RabiSweepExperiment

        cfg['alazar']['samplesPerRecord'] = 2**(cfg['readout']['width'] -
                                                1).bit_length()
        sequence_length = (
            cfg[expt_name.lower()]['stop'] -
            cfg[expt_name.lower()]['start']) / cfg[expt_name.lower()]['step']
        if (cfg[expt_name.lower()]['use_pi_calibration']):
            sequence_length += 2

        cfg['alazar']['recordsPerBuffer'] = sequence_length
        cfg['alazar']['recordsPerAcquisition'] = int(
            sequence_length * min(cfg[expt_name.lower()]['averages'], 100))
        print("Prep Card")
        adc = Alazar(cfg['alazar'])

        drive_freq_pts = arange(cfg[expt_name.lower()]['freq_start'],
                                cfg[expt_name.lower()]['freq_stop'],
                                cfg[expt_name.lower()]['freq_step'])
        prefix = 'Rabi_Sweep'
        data_file = os.path.join(
            datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        for ii, drive_freq in enumerate(drive_freq_pts):
            print(drive_freq)
            expt = RabiSweepExperiment(path=datapath,
                                       data_file=data_file,
                                       adc=adc,
                                       drive_freq=drive_freq,
                                       liveplot_enabled=False)
            expt.go()

            expt = None
            del expt

            gc.collect()
    if expt_name.lower() == 'rabi_ramsey_t1_flux_sweep':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RabiRamseyT1FluxSweepExperiment

        prefix = 'rabi_ramsey_t1_flux_sweep'
        data_file = os.path.join(
            datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        flux_pts = np.load(
            r'S:\_Data\160104 - 2D Multimode Qubit (Chip MM3, 11 modes)\iPython Notebooks\flux_sm.npy'
        )
        drive_pts = np.load(
            r'S:\_Data\160104 - 2D Multimode Qubit (Chip MM3, 11 modes)\iPython Notebooks\qubit_frequencies_sm.npy'
        )
        readout_pts = np.load(
            r'S:\_Data\160104 - 2D Multimode Qubit (Chip MM3, 11 modes)\iPython Notebooks\readout_frequencies_sm.npy'
        )

        # flux_pts=[-0.012]
        # drive_pts=[4.844e9]
        # readout_pts=[5257100000.0]

        qubit_alpha = cfg['qubit']['alpha']

        for ii, flux in enumerate(flux_pts):
            drive_freq = drive_pts[ii]
            readout_freq = readout_pts[ii]
            print("Flux: " + str(flux))
            print("Drive frequency: " + str(drive_freq))
            print("Readout frequency: " + str(readout_freq))

            ### 1st Rabi
            print("### Running 1st Rabi.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'rabi')
            expt = RabiRamseyT1FluxSweepExperiment(
                path=datapath,
                exp='rabi',
                flux=flux,
                data_file=data_file,
                adc=adc,
                drive_freq=drive_freq,
                readout_freq=readout_freq,
                liveplot_enabled=liveplot_enabled)
            expt.go()
            pi_length = expt.pi_length
            half_pi_length = expt.half_pi_length

            adc.close()
            expt = None
            del expt
            gc.collect()

            ### 1st Ramsey
            print("### Running 1st Ramsey.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'ramsey')
            expt = RabiRamseyT1FluxSweepExperiment(
                path=datapath,
                exp='ramsey',
                flux=flux,
                half_pi_length=half_pi_length,
                data_file=data_file,
                adc=adc,
                drive_freq=drive_freq,
                readout_freq=readout_freq,
                liveplot_enabled=liveplot_enabled)
            expt.go()
            suggested_qubit_freq = expt.suggested_qubit_freq
            drive_freq = suggested_qubit_freq

            adc.close()
            expt = None
            del expt
            gc.collect()

            ### 2nd Rabi
            print("### Running 2nd Rabi.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'rabi')
            expt = RabiRamseyT1FluxSweepExperiment(
                path=datapath,
                exp='rabi',
                flux=flux,
                data_file=data_file,
                adc=adc,
                drive_freq=drive_freq,
                readout_freq=readout_freq,
                liveplot_enabled=liveplot_enabled)
            expt.go()
            pi_length = expt.pi_length
            half_pi_length = expt.half_pi_length

            adc.close()
            expt = None
            del expt
            gc.collect()

            ### Ramsey long
            print("### Running Ramsey Long.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep',
                                 'ramsey_long')
            expt = RabiRamseyT1FluxSweepExperiment(
                path=datapath,
                exp='ramsey_long',
                flux=flux,
                half_pi_length=half_pi_length,
                data_file=data_file,
                adc=adc,
                drive_freq=drive_freq,
                readout_freq=readout_freq,
                liveplot_enabled=liveplot_enabled)
            expt.go()

            adc.close()
            expt = None
            del expt
            gc.collect()

            ### Rabi Long
            print("### Running Rabi Long.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'rabi_long')
            expt = RabiRamseyT1FluxSweepExperiment(
                path=datapath,
                exp='rabi_long',
                flux=flux,
                data_file=data_file,
                adc=adc,
                drive_freq=drive_freq,
                readout_freq=readout_freq,
                liveplot_enabled=liveplot_enabled)
            expt.go()
            # pi_length = expt.pi_length
            # half_pi_length = expt.half_pi_length

            adc.close()
            expt = None
            del expt
            gc.collect()

            ### remove adc
            adc = None
            del adc

            ### t1
            print("### Running T1.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 't1')
            expt = RabiRamseyT1FluxSweepExperiment(
                path=datapath,
                exp='t1',
                flux=flux,
                pi_length=pi_length,
                data_file=data_file,
                adc=adc,
                drive_freq=drive_freq,
                readout_freq=readout_freq,
                liveplot_enabled=liveplot_enabled)
            expt.go()

            adc.close()
            expt = None
            del expt
            gc.collect()

            ### Pi/2 phase sweep
            print("### Running pi/2 phase sweep experiment")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep',
                                 'half_pi_phase_sweep')
            expt = RabiRamseyT1FluxSweepExperiment(
                path=datapath,
                exp='half_pi_phase_sweep',
                flux=flux,
                half_pi_length=half_pi_length,
                data_file=data_file,
                adc=adc,
                drive_freq=drive_freq,
                readout_freq=readout_freq,
                liveplot_enabled=liveplot_enabled)
            expt.go()

            adc.close()
            expt = None
            del expt
            gc.collect()

            ### EF Rabi
            print("### Running EF Rabi.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'ef_rabi')
            expt = RabiRamseyT1FluxSweepExperiment(
                path=datapath,
                exp='ef_rabi',
                flux=flux,
                pi_length=pi_length,
                data_file=data_file,
                adc=adc,
                drive_freq=drive_freq,
                readout_freq=readout_freq,
                liveplot_enabled=liveplot_enabled,
                alpha=qubit_alpha)
            expt.go()
            ef_pi_length = expt.pi_length
            ef_half_pi_length = expt.half_pi_length

            adc.close()
            expt = None
            del expt
            gc.collect()

            ### EF Ramsey
            print("### Running EF Ramsey.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'ef_ramsey')
            expt = RabiRamseyT1FluxSweepExperiment(
                path=datapath,
                exp='ef_ramsey',
                flux=flux,
                pi_length=pi_length,
                ef_half_pi_length=ef_half_pi_length,
                data_file=data_file,
                adc=adc,
                drive_freq=drive_freq,
                readout_freq=readout_freq,
                liveplot_enabled=liveplot_enabled,
                alpha=qubit_alpha)
            expt.go()
            suggested_alpha_freq = expt.suggested_qubit_alpha
            print("Suggested alpha frequency: " + str(suggested_alpha_freq))
            qubit_alpha = suggested_alpha_freq

            adc.close()
            expt = None
            del expt
            gc.collect()

            ### EF Rabi
            print("### Running EF Rabi.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'ef_rabi')
            expt = RabiRamseyT1FluxSweepExperiment(
                path=datapath,
                exp='ef_rabi',
                flux=flux,
                pi_length=pi_length,
                data_file=data_file,
                adc=adc,
                drive_freq=drive_freq,
                readout_freq=readout_freq,
                liveplot_enabled=liveplot_enabled,
                alpha=qubit_alpha)
            expt.go()
            ef_pi_length = expt.pi_length
            ef_half_pi_length = expt.half_pi_length

            adc.close()
            expt = None
            del expt
            gc.collect()

            ### EF T1
            print("### Running EF T1.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'ef_t1')
            expt = RabiRamseyT1FluxSweepExperiment(
                path=datapath,
                exp='ef_t1',
                flux=flux,
                pi_length=pi_length,
                ef_pi_length=ef_pi_length,
                data_file=data_file,
                adc=adc,
                drive_freq=drive_freq,
                readout_freq=readout_freq,
                liveplot_enabled=liveplot_enabled,
                alpha=qubit_alpha)
            expt.go()

            adc.close()
            expt = None
            del expt
            gc.collect()

            ## EF Ramsey Long
            print("### Running EF Ramsey.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep',
                                 'ef_ramsey_long')
            expt = RabiRamseyT1FluxSweepExperiment(
                path=datapath,
                exp='ef_ramsey_long',
                flux=flux,
                pi_length=pi_length,
                ef_half_pi_length=ef_half_pi_length,
                data_file=data_file,
                adc=adc,
                drive_freq=drive_freq,
                readout_freq=readout_freq,
                liveplot_enabled=liveplot_enabled,
                alpha=qubit_alpha)
            expt.go()
            suggested_alpha_freq = expt.suggested_qubit_alpha
            print("Suggested alpha frequency: " + str(suggested_alpha_freq))
            qubit_alpha = suggested_alpha_freq

            adc.close()
            expt = None
            del expt
            gc.collect()

            ### remove adc
            adc = None
            del adc

            gc.collect()

    if expt_name.lower() == 'halfpixoptimization_sweep':

        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import HalfPiXOptimizationSweepExperiment

        adc = prepare_alazar(cfg, expt_name)

        if cfg[expt_name.lower()]['sweep_param'] == "length":
            pulse_sweep_pts = arange(cfg[expt_name.lower()]['length_start'],
                                     cfg[expt_name.lower()]['length_stop'],
                                     cfg[expt_name.lower()]['length_step'])
            pulse_amp = cfg[expt_name.lower()]['amp']
        elif cfg[expt_name.lower()]['sweep_param'] == "amp":
            pulse_sweep_pts = arange(cfg[expt_name.lower()]['amp_start'],
                                     cfg[expt_name.lower()]['amp_stop'],
                                     cfg[expt_name.lower()]['amp_step'])
            pulse_length = cfg[expt_name.lower()]['length']

        prefix = 'HalfPiXOptimization_Sweep'
        data_file = os.path.join(
            datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        if cfg[expt_name.lower()]['sweep_param'] == "length":
            for ii, pulse_sweep in enumerate(pulse_sweep_pts):
                print("Pulse Sweep: " + str(pulse_sweep))
                expt = HalfPiXOptimizationSweepExperiment(
                    path=datapath,
                    data_file=data_file,
                    adc=adc,
                    pulse_length=pulse_sweep,
                    pulse_amp=pulse_amp,
                    liveplot_enabled=False)
                expt.go()

                expt = None
                del expt

                gc.collect()
        elif cfg[expt_name.lower()]['sweep_param'] == "amp":
            for ii, pulse_sweep in enumerate(pulse_sweep_pts):
                print("Pulse Sweep: " + str(pulse_sweep))
                expt = HalfPiXOptimizationSweepExperiment(
                    path=datapath,
                    data_file=data_file,
                    adc=adc,
                    pulse_length=pulse_length,
                    pulse_amp=pulse_sweep,
                    liveplot_enabled=False)
                expt.go()

                expt = None
                del expt

                gc.collect()

    if expt_name.lower() == 'pixoptimization_sweep':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import PiXOptimizationSweepExperiment

        # cfg['alazar']['samplesPerRecord'] = 2 ** (cfg['readout']['width'] - 1).bit_length()
        # sequence_length = (cfg[expt_name.lower()]['stop']-cfg[expt_name.lower()]['start'])/cfg[expt_name.lower()]['step']
        # if (cfg[expt_name.lower()]['use_pi_calibration']):
        #     sequence_length+=2
        #
        # cfg['alazar']['recordsPerBuffer'] = sequence_length
        # cfg['alazar']['recordsPerAcquisition'] = int(
        #     sequence_length * min(cfg[expt_name.lower()]['averages'], 100))
        # print "Prep Card"
        # adc = Alazar(cfg['alazar'])

        adc = prepare_alazar(cfg, expt_name)

        if cfg[expt_name.lower()]['sweep_param'] == "length":
            pulse_sweep_pts = arange(cfg[expt_name.lower()]['length_start'],
                                     cfg[expt_name.lower()]['length_stop'],
                                     cfg[expt_name.lower()]['length_step'])
            pulse_amp = cfg[expt_name.lower()]['amp']
        elif cfg[expt_name.lower()]['sweep_param'] == "amp":
            pulse_sweep_pts = arange(cfg[expt_name.lower()]['amp_start'],
                                     cfg[expt_name.lower()]['amp_stop'],
                                     cfg[expt_name.lower()]['amp_step'])
            pulse_length = cfg[expt_name.lower()]['length']

        prefix = 'PiXOptimization_Sweep'
        data_file = os.path.join(
            datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        # for ii, pulse_sweep in enumerate(pulse_sweep_pts):
        #     print "Pulse Sweep: " + str(pulse_sweep)
        #     expt = PiXOptimizationSweepExperiment(path=datapath,data_file=data_file, adc=adc, pulse_length=pulse_sweep, liveplot_enabled = False)
        #     expt.go()
        #
        #     expt = None
        #     del expt
        #
        #     gc.collect()

        if cfg[expt_name.lower()]['sweep_param'] == "length":
            for ii, pulse_sweep in enumerate(pulse_sweep_pts):
                print("Pulse Sweep: " + str(pulse_sweep))
                expt = PiXOptimizationSweepExperiment(path=datapath,
                                                      data_file=data_file,
                                                      adc=adc,
                                                      pulse_length=pulse_sweep,
                                                      pulse_amp=pulse_amp,
                                                      liveplot_enabled=False)
                expt.go()

                expt = None
                del expt

                gc.collect()
        elif cfg[expt_name.lower()]['sweep_param'] == "amp":
            for ii, pulse_sweep in enumerate(pulse_sweep_pts):
                print("Pulse Sweep: " + str(pulse_sweep))
                expt = PiXOptimizationSweepExperiment(
                    path=datapath,
                    data_file=data_file,
                    adc=adc,
                    pulse_length=pulse_length,
                    pulse_amp=pulse_sweep,
                    liveplot_enabled=False)
                expt.go()

                expt = None
                del expt

                gc.collect()

    if not experiment_started:
        close_match = difflib.get_close_matches(expt_name, expt_list)
        print("No experiment found for: " + expt_name)
        print("Do you mean: " + close_match[0] + "?")
    def take_data(self):

        ####
        if self.cfg["visdom_plot_livedata"]:

            viz = visdom.Visdom()
            assert viz.check_connection(), "Visdom server not connected!"
            # added two environments "seq_builder.json", and "live_plot.json" in C:\Users\slab\.visdom
            eid = "live_plot"
            viz.close(win=None, env=eid)

            win1 = viz.line(X=np.arange(0, 1),
                            Y=np.arange(0, 1),
                            env=eid,
                            opts=dict(height=400,
                                      width=700,
                                      title='expt_avg_data',
                                      showlegend=True,
                                      xlabel='expt_pts'))
            win2 = viz.line(X=np.arange(0, 1),
                            Y=np.arange(0, 1),
                            env=eid,
                            opts=dict(height=400,
                                      width=700,
                                      title='expt_avg_data2',
                                      showlegend=True,
                                      xlabel='expt_pts'))
            win3 = viz.line(X=np.arange(0, 1),
                            Y=np.arange(0, 1),
                            env=eid,
                            opts=dict(
                                height=400,
                                width=700,
                                title='single_record (of only first run)',
                                showlegend=True,
                                xlabel='time ns'))
        ####

        if self.pre_run is not None:
            self.pre_run()

        TEST_REDPITAYA = False

        if TEST_REDPITAYA:
            self.awg_run()

        if not TEST_REDPITAYA:

            if self.adc == None:
                print("Prep Card")
                adc = Alazar(self.cfg['alazar'])
            else:
                adc = self.adc

            # debug_alazer = False
            # if debug_alazer:
            #
            #     # save raw time trace, 100 runs only
            #     tpts, single_data1, single_data2 = adc.acquire_singleshot_data2()
            #
            #     self.slab_file = self.datafile(data_file=self.data_file)
            #     with self.slab_file as f:
            #         f.add('tpts', tpts)
            #         f.add('single_data1', single_data1)
            #         f.add('single_data2', single_data2)
            #         f.close()
            #
            #     # hack for post_run
            #     expt_avg_data = self.expt_pts
            #
            # else:

            if not self.cfg['readout']['save_single-shot_data']:

                expt_data = None
                current_data = None
                for ii in tqdm(
                        arange(
                            max(1, self.cfg[self.expt_cfg_name]['averages'] /
                                100))):
                    tpts, ch1_pts, ch2_pts = adc.acquire_avg_data_by_record(
                        prep_function=self.awg_prep,
                        start_function=self.awg_run,
                        excise=self.cfg['readout']['window'])

                    if not self.cfg[self.expt_cfg_name]['use_pi_calibration']:

                        if expt_data is None:
                            if self.cfg['readout']['channel'] == 1:
                                expt_data = ch1_pts
                            elif self.cfg['readout']['channel'] == 2:
                                expt_data = ch2_pts
                        else:
                            if self.cfg['readout']['channel'] == 1:
                                expt_data = (expt_data * ii + ch1_pts) / (ii +
                                                                          1.0)
                            elif self.cfg['readout']['channel'] == 2:
                                expt_data = (expt_data * ii + ch2_pts) / (ii +
                                                                          1.0)

                        if self.cfg['readout']['heterodyne_freq'] == 0:
                            # homodyne
                            expt_avg_data = mean(expt_data, 1)
                        else:
                            # heterodyne
                            heterodyne_freq = self.cfg['readout'][
                                'heterodyne_freq']
                            # ifft by numpy default has the correct 1/N normalization
                            expt_data_fft_amp = np.abs(np.fft.ifft(expt_data))
                            hetero_f_ind = int(
                                round(heterodyne_freq * tpts.size *
                                      1e-9))  # position in ifft

                            # todo: do the proper sum here
                            # expt_avg_data = np.average(expt_data_fft_amp[:, (hetero_f_ind - 1):(hetero_f_ind + 1)], axis=1)
                            expt_avg_data = expt_data_fft_amp[:, hetero_f_ind]

                    else:
                        # average first, then divide by pi_calibration values
                        if expt_data is None:
                            if self.cfg['readout']['channel'] == 1:
                                expt_data = ch1_pts[:-2]
                                zero_amp_curr = mean(ch1_pts[-2])
                                pi_amp_curr = mean(ch1_pts[-1])
                            elif self.cfg['readout']['channel'] == 2:
                                expt_data = ch2_pts[:-2]
                                zero_amp_curr = mean(ch2_pts[-2])
                                pi_amp_curr = mean(ch2_pts[-1])
                            zero_amp = zero_amp_curr
                            pi_amp = pi_amp_curr
                        else:
                            if self.cfg['readout']['channel'] == 1:
                                expt_data = (expt_data * ii +
                                             ch1_pts[:-2]) / (ii + 1.0)
                                zero_amp_curr = mean(ch1_pts[-2])
                                pi_amp_curr = mean(ch1_pts[-1])
                            elif self.cfg['readout']['channel'] == 2:
                                expt_data = (expt_data * ii +
                                             ch2_pts[:-2]) / (ii + 1.0)
                                zero_amp_curr = mean(ch2_pts[-2])
                                pi_amp_curr = mean(ch2_pts[-1])
                            zero_amp = (zero_amp * ii + zero_amp_curr) / (ii +
                                                                          1.0)
                            pi_amp = (pi_amp * ii + pi_amp_curr) / (ii + 1.0)

                        # todo: add heterodyne with pi_cal
                        expt_avg_data = mean(
                            (expt_data - zero_amp) / (pi_amp - zero_amp), 1)

                    # self.slab_file = self.datafile(data_file=self.data_file)

                    with self.slab_file as f:
                        f.add('expt_2d', expt_data)
                        f.add('expt_avg_data', expt_avg_data)
                        f.add('expt_pts', self.expt_pts)

                        # save pi_cal amps, to be able to monitor fluctuations
                        if self.cfg[self.expt_cfg_name]['use_pi_calibration']:
                            f.append_pt('zero_amps', zero_amp_curr)
                            f.append_pt('pi_amps', pi_amp_curr)

                        f.close()

            else:  # here saves all single shot data

                if self.prefix == 'Vacuum_Rabi':

                    print('vacuum_rabi')
                    het_IFreqList = [self.cfg['readout']['heterodyne_freq']]
                    het_read_freq_list = [0]

                elif self.cfg['readout']['is_multitone_heterodyne']:
                    het_carrier_freq = self.cfg['readout'][
                        'heterodyne_carrier_freq']
                    het_read_freq_list = array(
                        self.cfg['readout']['heterodyne_freq_list'])
                    het_IFreqList = het_read_freq_list - het_carrier_freq
                else:
                    het_carrier_freq = self.readout_freq - self.cfg['readout'][
                        'heterodyne_freq']
                    het_read_freq_list = array([self.readout_freq])
                    het_IFreqList = het_read_freq_list - het_carrier_freq

                avgPerAcquisition = int(
                    min(self.cfg[self.expt_cfg_name]['averages'], 100))
                numAcquisition = int(
                    np.ceil(self.cfg[self.expt_cfg_name]['averages'] / 100))

                # (ch1/2, exp_pts, heterodyne_freq, cos/sin, all averages)
                ss_data = zeros((2, len(self.expt_pts), len(het_IFreqList), 2,
                                 avgPerAcquisition * numAcquisition))

                # (ch1/2, heterodyne_freq, cos/sin, all averages)
                ss_cal_g = zeros((2, len(het_IFreqList), 2,
                                  avgPerAcquisition * numAcquisition))
                ss_cal_e = zeros((2, len(het_IFreqList), 2,
                                  avgPerAcquisition * numAcquisition))
                ss_cal_f = zeros((2, len(het_IFreqList), 2,
                                  avgPerAcquisition * numAcquisition))

                if self.cfg['readout']['save_trajectory_data']:

                    # (ch1/2, exp_pts, heterodyne_freq, cos/sin, all averages, traj)
                    traj_data = zeros(
                        (2, len(self.expt_pts), len(het_IFreqList), 2,
                         avgPerAcquisition * numAcquisition,
                         self.cfg['readout']['pts_per_traj']))

                    # (ch1/2, heterodyne_freq, cos/sin, all averages, traj)
                    traj_cal_g = zeros((2, len(het_IFreqList), 2,
                                        avgPerAcquisition * numAcquisition,
                                        self.cfg['readout']['pts_per_traj']))
                    traj_cal_e = zeros((2, len(het_IFreqList), 2,
                                        avgPerAcquisition * numAcquisition,
                                        self.cfg['readout']['pts_per_traj']))
                    traj_cal_f = zeros((2, len(het_IFreqList), 2,
                                        avgPerAcquisition * numAcquisition,
                                        self.cfg['readout']['pts_per_traj']))

                for ii in tqdm(arange(numAcquisition)):

                    if not self.cfg['readout']['is_hetero_phase_ref']:

                        # single_data1/2: index: (hetero_freqs, cos/sin, all_seqs)
                        single_data1, single_data2, single_record1, single_record2 = \
                            adc.acquire_singleshot_heterodyne_multitone_data(het_IFreqList, prep_function=self.awg_prep,
                                                                             start_function=self.awg_run,
                                                                             excise=self.cfg['readout']['window'])

                        # saving the raw time traces
                        # single_data1, single_data2, single_record1, single_record2 = \
                        #     adc.acquire_singleshot_heterodyne_multitone_data(het_IFreqList, prep_function=self.awg_prep,
                        #                                                      start_function=self.awg_run,
                        #                                                      excise=None, save_raw_data=True)

                    elif self.cfg['readout']['save_trajectory_data']:

                        excise = [0, self.cfg['readout']['window'][1]]
                        single_data1, single_data2, single_record1, single_record2, single_traj1, single_traj2= \
                            adc.acquire_singleshot_heterodyne_multitone_data_phase_ref_save_traj(het_IFreqList,
                                                                                       self.cfg['readout'][
                                                                                           'hetero_phase_ref_freq'],
                                                                                       prep_function=self.awg_prep,
                                                                                       start_function=self.awg_run,
                                                                                       excise=excise,
                                                                                       isCompensatePhase=True,
                                                                                       save_raw_data=False, pts_per_traj=self.cfg['readout']['pts_per_traj'])
                    else:

                        # single_data1/2: index: (hetero_freqs, cos/sin, all_seqs)
                        single_data1, single_data2, single_record1, single_record2 = \
                            adc.acquire_singleshot_heterodyne_multitone_data_phase_ref(het_IFreqList,
                                                                             self.cfg['readout']['hetero_phase_ref_freq'],
                                                                             prep_function=self.awg_prep,
                                                                             start_function=self.awg_run,
                                                                             excise=self.cfg['readout']['window'],
                                                                             isCompensatePhase=True,
                                                                             save_raw_data=False)

                    single_data = array([single_data1, single_data2])
                    # index: (ch1/2, hetero_freqs, cos / sin, avgs, seq(exp_pts))
                    single_data = np.reshape(
                        single_data,
                        (single_data.shape[0], single_data.shape[1],
                         single_data.shape[2],
                         int(self.cfg['alazar']['recordsPerAcquisition'] /
                             self.pulse_sequence.sequence_length),
                         self.pulse_sequence.sequence_length))

                    # index: (ch1/2, exp_pts, hetero_freqs, cos / sin, avgs)
                    single_data = np.transpose(single_data, (0, 4, 1, 2, 3))

                    if (self.cfg[self.expt_cfg_name]['use_g-e-f_calibration']):

                        ss_data[:, :, :, :, (ii * avgPerAcquisition):(
                            (ii + 1) * avgPerAcquisition)] = single_data[:,
                                                                         0:-3]
                        ss_cal_g[:, :, :, (ii * avgPerAcquisition):(
                            (ii + 1) * avgPerAcquisition)] = single_data[:, -3]
                        ss_cal_e[:, :, :, (ii * avgPerAcquisition):(
                            (ii + 1) * avgPerAcquisition)] = single_data[:, -2]
                        ss_cal_f[:, :, :, (ii * avgPerAcquisition):(
                            (ii + 1) * avgPerAcquisition)] = single_data[:, -1]

                    elif (self.cfg[self.expt_cfg_name]['use_pi_calibration']):

                        ss_data[:, :, :, :, (ii * avgPerAcquisition):(
                            (ii + 1) * avgPerAcquisition)] = single_data[:,
                                                                         0:-2]
                        ss_cal_g[:, :, :, (ii * avgPerAcquisition):(
                            (ii + 1) * avgPerAcquisition)] = single_data[:, -2]
                        ss_cal_e[:, :, :, (ii * avgPerAcquisition):(
                            (ii + 1) * avgPerAcquisition)] = single_data[:, -1]

                    else:
                        ss_data[:, :, :, :, (ii * avgPerAcquisition):(
                            (ii + 1) * avgPerAcquisition)] = single_data[:, :]

                    ####
                    if self.cfg['readout']['save_trajectory_data']:

                        # index: (hetero_freqs, cos/sin, all_seqs, traj)
                        single_traj = array([single_traj1, single_traj2])

                        # index: (ch1/2, hetero_freqs, cos / sin, avgs, seq(exp_pts), traj)
                        single_traj = np.reshape(
                            single_traj,
                            (single_traj.shape[0], single_traj.shape[1],
                             single_traj.shape[2],
                             self.cfg['alazar']['recordsPerAcquisition'] /
                             self.pulse_sequence.sequence_length,
                             self.pulse_sequence.sequence_length,
                             single_traj.shape[-1]))

                        # index: (ch1/2, exp_pts, hetero_freqs, cos / sin, avgs, traj)
                        single_traj = np.transpose(single_traj,
                                                   (0, 4, 1, 2, 3, 5))
                        # print single_traj.shape

                        if (self.cfg[self.expt_cfg_name]
                            ['use_g-e-f_calibration']):

                            traj_data[:, :, :, :, (ii * avgPerAcquisition):(
                                (ii + 1) *
                                avgPerAcquisition), :] = single_traj[:,
                                                                     0:-3, :]
                            traj_cal_g[:, :, :, (ii * avgPerAcquisition):(
                                (ii + 1) *
                                avgPerAcquisition), :] = single_traj[:, -3, :]
                            traj_cal_e[:, :, :, (ii * avgPerAcquisition):(
                                (ii + 1) *
                                avgPerAcquisition), :] = single_traj[:, -2, :]
                            traj_cal_f[:, :, :, (ii * avgPerAcquisition):(
                                (ii + 1) *
                                avgPerAcquisition), :] = single_traj[:, -1, :]

                        elif (self.cfg[self.expt_cfg_name]
                              ['use_pi_calibration']):

                            traj_data[:, :, :, :, (ii * avgPerAcquisition):(
                                (ii + 1) *
                                avgPerAcquisition), :] = single_traj[:,
                                                                     0:-2, :]
                            traj_cal_g[:, :, :, (ii * avgPerAcquisition):(
                                (ii + 1) *
                                avgPerAcquisition), :] = single_traj[:, -2, :]
                            traj_cal_e[:, :, :, (ii * avgPerAcquisition):(
                                (ii + 1) *
                                avgPerAcquisition), :] = single_traj[:, -1, :]

                        else:
                            traj_data[:, :, :, :, (ii * avgPerAcquisition):(
                                (ii + 1) *
                                avgPerAcquisition), :] = single_traj[:, :, :]

                    ####

                    # old way for easy plotting
                    # only calculate for 1st het_readout_freq
                    if het_IFreqList[0] == 0:
                        # take cos of ch1/ch2
                        expt_avg_data = mean(
                            ss_data[0, :, 0, 0,
                                    0:((ii + 1) * avgPerAcquisition)], -1)
                        expt_avg_data2 = mean(
                            ss_data[1, :, 0, 0,
                                    0:((ii + 1) * avgPerAcquisition)], -1)

                        if self.cfg[self.expt_cfg_name]['use_pi_calibration']:
                            zero_amp_avg = mean(
                                ss_cal_g[0, 0, 0,
                                         0:((ii + 1) * avgPerAcquisition)], -1)
                            zero_amp_avg2 = mean(
                                ss_cal_g[1, 0, 0,
                                         0:((ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_avg = mean(
                                ss_cal_e[0, 0, 0,
                                         0:((ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_avg2 = mean(
                                ss_cal_e[1, 0, 0,
                                         0:((ii + 1) * avgPerAcquisition)], -1)

                            zero_amp_curr = mean(
                                ss_cal_g[0, 0, 0, (ii * avgPerAcquisition):(
                                    (ii + 1) * avgPerAcquisition)], -1)
                            zero_amp_curr2 = mean(
                                ss_cal_g[1, 0, 0, (ii * avgPerAcquisition):(
                                    (ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_curr = mean(
                                ss_cal_e[0, 0, 0, (ii * avgPerAcquisition):(
                                    (ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_curr2 = mean(
                                ss_cal_e[1, 0, 0, (ii * avgPerAcquisition):(
                                    (ii + 1) * avgPerAcquisition)], -1)

                            expt_avg_data = (expt_avg_data - zero_amp_avg) / (
                                pi_amp_avg - zero_amp_avg)
                            expt_avg_data2 = (expt_avg_data2 - zero_amp_avg2
                                              ) / (pi_amp_avg2 - zero_amp_avg2)

                    else:
                        # take cos/sin of ch1
                        expt_avg_data = mean(
                            ss_data[0, :, 0, 0,
                                    0:((ii + 1) * avgPerAcquisition)], -1)
                        expt_avg_data2 = mean(
                            ss_data[0, :, 0, 1,
                                    0:((ii + 1) * avgPerAcquisition)], -1)

                        if self.cfg[self.expt_cfg_name]['use_pi_calibration']:
                            zero_amp_avg = mean(
                                ss_cal_g[0, 0, 0,
                                         0:((ii + 1) * avgPerAcquisition)], -1)
                            zero_amp_avg2 = mean(
                                ss_cal_g[0, 0, 1,
                                         0:((ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_avg = mean(
                                ss_cal_e[0, 0, 0,
                                         0:((ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_avg2 = mean(
                                ss_cal_e[0, 0, 1,
                                         0:((ii + 1) * avgPerAcquisition)], -1)

                            zero_amp_curr = mean(
                                ss_cal_g[0, 0, 0, (ii * avgPerAcquisition):(
                                    (ii + 1) * avgPerAcquisition)], -1)
                            zero_amp_curr2 = mean(
                                ss_cal_g[0, 0, 1, (ii * avgPerAcquisition):(
                                    (ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_curr = mean(
                                ss_cal_e[0, 0, 0, (ii * avgPerAcquisition):(
                                    (ii + 1) * avgPerAcquisition)], -1)
                            pi_amp_curr2 = mean(
                                ss_cal_e[0, 0, 1, (ii * avgPerAcquisition):(
                                    (ii + 1) * avgPerAcquisition)], -1)

                            expt_avg_data = (expt_avg_data - zero_amp_avg) / (
                                pi_amp_avg - zero_amp_avg)
                            expt_avg_data2 = (expt_avg_data2 - zero_amp_avg2
                                              ) / (pi_amp_avg2 - zero_amp_avg2)

                    # this needs to stay here
                    # if self.data_file != None:
                    #     self.slab_file = SlabFile(self.data_file)
                    # else:
                    #     self.slab_file = self.datafile()
                    self.slab_file = self.datafile(data_file=self.data_file)

                    with self.slab_file as f:
                        f.add(
                            'ss_data',
                            ss_data[:, :, :, :,
                                    0:((ii + 1) * avgPerAcquisition)])
                        f.add('single_record1', single_record1)
                        f.add('single_record2', single_record2)

                        if (self.cfg[self.expt_cfg_name]['use_pi_calibration']
                            ):
                            f.add(
                                'ss_cal_g',
                                ss_cal_g[:, :, :,
                                         0:((ii + 1) * avgPerAcquisition)])
                            f.add(
                                'ss_cal_e',
                                ss_cal_e[:, :, :,
                                         0:((ii + 1) * avgPerAcquisition)])
                        if (self.cfg[self.expt_cfg_name]
                            ['use_g-e-f_calibration']):
                            f.add(
                                'ss_cal_g',
                                ss_cal_g[:, :, :,
                                         0:((ii + 1) * avgPerAcquisition)])
                            f.add(
                                'ss_cal_e',
                                ss_cal_e[:, :, :,
                                         0:((ii + 1) * avgPerAcquisition)])
                            f.add(
                                'ss_cal_f',
                                ss_cal_f[:, :, :,
                                         0:((ii + 1) * avgPerAcquisition)])

                        if self.cfg['readout']['save_trajectory_data']:
                            f.add(
                                'traj_data',
                                traj_data[:, :, :, :,
                                          0:((ii + 1) * avgPerAcquisition), :])
                            if (self.cfg[self.expt_cfg_name]
                                ['use_pi_calibration']):
                                f.add(
                                    'traj_cal_g',
                                    traj_cal_g[:, :, :,
                                               0:((ii + 1) *
                                                  avgPerAcquisition), :])
                                f.add(
                                    'traj_cal_e',
                                    traj_cal_e[:, :, :,
                                               0:((ii + 1) *
                                                  avgPerAcquisition), :])
                            if (self.cfg[self.expt_cfg_name]
                                ['use_g-e-f_calibration']):
                                f.add(
                                    'traj_cal_g',
                                    traj_cal_g[:, :, :,
                                               0:((ii + 1) *
                                                  avgPerAcquisition), :])
                                f.add(
                                    'traj_cal_e',
                                    traj_cal_e[:, :, :,
                                               0:((ii + 1) *
                                                  avgPerAcquisition), :])
                                f.add(
                                    'traj_cal_f',
                                    traj_cal_f[:, :, :,
                                               0:((ii + 1) *
                                                  avgPerAcquisition), :])

                        f.add('expt_avg_data', expt_avg_data.flatten())
                        f.add('expt_avg_data2', expt_avg_data2.flatten())

                        f.add('expt_pts', self.expt_pts)
                        f.add('het_read_freq_list', het_read_freq_list)

                        if self.cfg[self.expt_cfg_name]['use_pi_calibration']:
                            f.append_pt('zero_amps', zero_amp_curr)
                            f.append_pt('pi_amps', pi_amp_curr)
                            f.append_pt('zero_amps2', zero_amp_curr2)
                            f.append_pt('pi_amps2', pi_amp_curr2)

                        f.close()

                    ####
                    if self.cfg["visdom_plot_livedata"]:
                        viz.updateTrace(X=self.expt_pts,
                                        Y=expt_avg_data,
                                        env=eid,
                                        win=win1,
                                        append=False)
                        viz.updateTrace(X=self.expt_pts,
                                        Y=expt_avg_data2,
                                        env=eid,
                                        win=win2,
                                        append=False)
                        if ii == 0:
                            viz.updateTrace(X=array(range(
                                len(single_record1))),
                                            Y=single_record2,
                                            env=eid,
                                            win=win3,
                                            name='2',
                                            append=False)
                            viz.updateTrace(X=array(range(
                                len(single_record1))),
                                            Y=single_record1,
                                            env=eid,
                                            win=win3,
                                            name='1',
                                            append=False)
                    ####

            if self.post_run is not None:
                self.post_run(self.expt_pts, expt_avg_data)

            if self.cfg['stop_awgs'] == True:
                self.awg_prep()
                print('stop_awg = True, seqs stopped.')
            else:
                print('stop_awg = False, seqs left running.')

            # closes Alazar card and releases buffer
            adc.close()
Exemplo n.º 5
0
    def take_data(self):

        print('take_data() in HistogramHetero')

        if self.pre_run is not None:
            self.pre_run()

        if self.adc == None:
            print("Prep Card")
            adc = Alazar(self.cfg['alazar'])
        else:
            adc = self.adc

        ###

        het_IFreqList = array([self.cfg['readout']['heterodyne_freq']])

        avgPerAcquisition = int(min(self.cfg[self.expt_cfg_name]['averages'], 100))
        numAcquisition = int(np.ceil(self.cfg[self.expt_cfg_name]['averages'] / 100))

        attenpts = arange(self.cfg[self.expt_cfg_name]['atten_start'], self.cfg[self.expt_cfg_name]['atten_stop'], self.cfg[self.expt_cfg_name]['atten_step'])
        freqpts = arange(self.cfg[self.expt_cfg_name]['freq_start'], self.cfg[self.expt_cfg_name]['freq_stop'], self.cfg[self.expt_cfg_name]['freq_step'])

        # (channel, atten, freq, g/e/f, average)
        ss_cos_data_all = zeros((2, len(attenpts), len(freqpts), 3, avgPerAcquisition * numAcquisition) )
        ss_sin_data_all = zeros((2, len(attenpts), len(freqpts), 3, avgPerAcquisition * numAcquisition) )

        for xx, atten in enumerate(attenpts):

            try:
                # im = InstrumentManager()
                # atten2 = im['atten2']
                # atten2.set_attenuator(atten)
                self.readout_atten.set_attenuator(atten)
                print(atten, "Digital atten:") #, self.readout_atten.get_attenuator())
                time.sleep(0.5)
                atten2 = None
            except:
                print("Digital attenuator not loaded.")

            # pump_freqs = arange(6.90e9, 7.04e9, 4e6)
            # pump_powers = arange(-6.0, -5, 0.2)
            #
            # self.im['RF6'].set_power( pump_powers[(atten % 5)] )
            # print("TWPA Pump power:", pump_powers[(atten % 5)])
            # self.im['RF6'].set_frequency( pump_freqs[int(atten/5)] )
            # print("TWPA Pump freq:", pump_freqs[int(atten/5)])
            #
            # try:
            #     self.readout_atten.set_attenuator(16.0)
            #     # print("Digital atten:", atten)
            # except:
            #     print("Digital attenuator not loaded.")


            # (ch1/2, exp_pts, heterodyne_freq, cos/sin, all averages)
            ss_data = zeros((2, len(self.expt_pts), len(het_IFreqList), 2, avgPerAcquisition * numAcquisition))
            for ii in tqdm(arange(numAcquisition)):

                if not self.cfg['readout']['is_hetero_phase_ref']:

                    # single_data1/2: index: (hetero_freqs, cos/sin, all_seqs)
                    single_data1, single_data2, single_record1, single_record2 = \
                        adc.acquire_singleshot_heterodyne_multitone_data(het_IFreqList, prep_function=self.awg_prep,
                                                                         start_function=self.awg_run,
                                                                         excise=self.cfg['readout']['window'])
                    # saving the raw time traces
                    # single_data1, single_data2, single_record1, single_record2 = \
                    #     adc.acquire_singleshot_heterodyne_multitone_data(het_IFreqList, prep_function=self.awg_prep,
                    #                                                      start_function=self.awg_run,
                    #                                                      excise=None, save_raw_data=True)

                else:
                    # single_data1/2: index: (hetero_freqs, cos/sin, all_seqs)
                    single_data1, single_data2, single_record1, single_record2 = \
                        adc.acquire_singleshot_heterodyne_multitone_data_phase_ref(het_IFreqList,
                                                                         self.cfg['readout']['hetero_phase_ref_freq'],
                                                                         prep_function=self.awg_prep,
                                                                         start_function=self.awg_run,
                                                                         excise=self.cfg['readout']['window'],
                                                                         isCompensatePhase=True,
                                                                         save_raw_data=False)
                single_data = array([single_data1, single_data2])

                # reshape to fit into histogram data
                # index: (ch1/2, hetero_freqs(0), cos / sin, avgs, freqpts(exp seq), g/e/f)
                single_data = np.reshape(single_data,
                                         (single_data.shape[0], single_data.shape[1], single_data.shape[2],
                                            int(self.cfg['alazar'][
                                              'recordsPerAcquisition'] / self.pulse_sequence.sequence_length),
                                          int(self.pulse_sequence.sequence_length/3), 3))

                # (channel, hetero_freqs(0), cos/sin, freqpts(exp seq), g/e/f, average)
                single_data = np.transpose(single_data, (0, 1, 2, 4, 5, 3))

                # (channel, atten, freqpts, g/e/f, average)
                ss_cos_data_all[:, xx, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)] = single_data[:, 0, 0, :, :, :]
                ss_sin_data_all[:, xx, :, :, (ii * avgPerAcquisition):((ii + 1) * avgPerAcquisition)] = single_data[:, 0, 1, :, :, :]

            # this needs to stay here
            self.slab_file = self.datafile(data_file=self.data_file)
            with self.slab_file as f:

                f.add('attenpts', attenpts)
                f.add('freqpts', freqpts)
                f.add('het_IFreqList', het_IFreqList)
                f.add('ss_cos_data_ch1', ss_cos_data_all[0])
                f.add('ss_cos_data_ch2', ss_cos_data_all[1])
                f.add('ss_sin_data_ch1', ss_sin_data_all[0])
                f.add('ss_sin_data_ch2', ss_sin_data_all[1])
                f.append_line('single_record1', single_record1)
                f.append_line('single_record2', single_record2)
                f.close()

        ###

        # if self.post_run is not None:
        #     self.post_run(self.expt_pts, expt_avg_data)

        if self.cfg['stop_awgs'] == True:
            self.awg_prep()

        # close Alazar and release buffer
        adc.close()
Exemplo n.º 6
0
    def go(self):
        if self.liveplot_enabled:
            self.plotter.clear()

        print("Prep Instruments")
        self.readout.set_frequency(self.cfg['readout']['frequency'])
        self.readout.set_power(self.cfg['readout']['power'])
        self.readout.set_ext_pulse(mod=True)
        # self.readout_shifter.set_phase(self.cfg['readout']['start_phase'] + self.cfg['readout']['phase_slope'] * (
        #     self.cfg['readout']['frequency'] - self.cfg['readout']['bare_frequency']), self.cfg['readout']['frequency'])

        self.drive.set_frequency(
            self.cfg['qubit']['frequency'] -
            self.cfg['pulse_info'][self.pulse_type]['iq_freq'])
        self.drive.set_power(self.cfg['drive']['power'])
        self.drive.set_ext_pulse(mod=True)
        self.drive.set_output(True)
        self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])

        self.trigger.set_period(self.trigger_period)

        try:
            self.cfg['freq_flux']['flux'] = self.extra_args['flux']
        except:
            pass

        try:
            self.cfg['freq_flux']['freq_flux_slope'] = self.extra_args[
                'freq_flux_slope']
        except:
            pass

        try:
            self.cfg['freq_flux']['flux_offset'] += self.extra_args[
                'flux_offset']
        except:
            pass

        if self.cfg['freq_flux']['current']:
            try:
                self.flux_volt.ramp_current(self.cfg['freq_flux']['flux'])
            except:
                pass
        elif self.cfg['freq_flux']['voltage']:
            try:
                self.flux_volt.ramp_volt(self.cfg['freq_flux']['flux'])
            except:
                pass

        self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'],
                                  self.cfg['cal']['iq_offsets'])

        if self.pre_run is not None:
            self.pre_run()

        if self.adc == None:
            print("Prep Card")
            adc = Alazar(self.cfg['alazar'])
        else:
            adc = self.adc

        expt_data = None
        current_data = None
        for ii in tqdm(
                arange(max(1,
                           self.cfg[self.expt_cfg_name]['averages'] / 100))):
            tpts, ch1_pts, ch2_pts = adc.acquire_avg_data_by_record(
                prep_function=self.awg_prep,
                start_function=self.awg.run,
                excise=self.cfg['readout']['window'])

            ### to skip the first 100 averages data point, because we saw a weird ramp in the RF output
            if ii == 0:
                time.sleep(0.1)
                continue

            mag = sqrt(ch1_pts**2 + ch2_pts**2)
            if not self.cfg[self.expt_cfg_name]['use_pi_calibration']:

                if expt_data is None:
                    if self.cfg['readout']['channel'] == 1:
                        expt_data = ch1_pts
                    elif self.cfg['readout']['channel'] == 2:
                        expt_data = ch2_pts
                else:
                    if self.cfg['readout']['channel'] == 1:
                        expt_data = (expt_data * ii + ch1_pts) / (ii + 1.0)
                    elif self.cfg['readout']['channel'] == 2:
                        expt_data = (expt_data * ii + ch2_pts) / (ii + 1.0)

                expt_avg_data = mean(expt_data, 1)

            else:

                if expt_data is None:
                    if self.cfg['readout']['channel'] == 1:
                        expt_data = ch1_pts
                    elif self.cfg['readout']['channel'] == 2:
                        expt_data = ch2_pts
                else:
                    if self.cfg['readout']['channel'] == 1:
                        expt_data = (expt_data * ii + ch1_pts) / (ii + 1.0)
                    elif self.cfg['readout']['channel'] == 2:
                        expt_data = (expt_data * ii + ch2_pts) / (ii + 1.0)

                expt_avg_data = mean(expt_data, 1)

                expt_avg_data = (expt_avg_data[:-2] - expt_avg_data[-2]) / (
                    expt_avg_data[-1] - expt_avg_data[-2])

            # temporary hack. Alazar card seems to shift two data points (problem disappeared after reboot computer)
            # expt_avg_data = np.concatenate((expt_avg_data[2:],expt_avg_data[:2]))
            # if self.cfg[self.expt_cfg_name]['use_pi_calibration']:
            #     expt_avg_data = (expt_avg_data[:-2]-expt_avg_data[-2])/(expt_avg_data[-1]-expt_avg_data[-2])

            # else:
            #     if self.cfg['readout']['channel']==1:
            #         zero_amp = mean(ch1_pts[-2])
            #         pi_amp = mean(ch1_pts[-1])
            #         current_data= (ch1_pts[:-2]-zero_amp)/(pi_amp-zero_amp)
            #     elif self.cfg['readout']['channel']==2:
            #         zero_amp = mean(ch2_pts[-2])
            #         pi_amp = mean(ch2_pts[-1])
            #         current_data= (ch2_pts[:-2]-zero_amp)/(pi_amp-zero_amp)
            #     if expt_data is None:
            #         expt_data = current_data
            #     else:
            #         expt_data = (expt_data * ii + current_data) / (ii + 1.0)

            # expt_avg_data = mean(expt_data, 1)

            if self.liveplot_enabled:
                self.plotter.plot_z(self.prefix + ' Data', expt_data.T)
                self.plotter.plot_xy(self.prefix + ' XY',
                                     self.pulse_sequence.expt_pts,
                                     expt_avg_data)

            # print ii * min(self.cfg[self.expt_cfg_name]['averages'], 100)

            if self.data_file == None:
                self.slab_file = self.datafile()
                with self.slab_file as f:
                    f.add('expt_2d', expt_data)
                    f.add('expt_avg_data', expt_avg_data)
                    f.add('expt_pts', self.expt_pts)
                    f.close()

        if self.data_file != None:
            self.slab_file = SlabFile(self.data_file)
            with self.slab_file as f:
                f.append_line('expt_avg_data', expt_avg_data)
                f.append_line('expt_pts', self.expt_pts)
                f.close()

        if not self.adc_predefined:
            adc.close()

        if self.post_run is not None:
            self.post_run(self.expt_pts, expt_avg_data)
def run_multimode_sequential_experiment(expt_name):
    import os
    import difflib

    expt_list = ['Multimode_Rabi']
    datapath = os.getcwd() + '\data'

    config_file = os.path.join(datapath, "..\\config" + ".json")
    with open(config_file, 'r') as fid:
        cfg_str = fid.read()

    cfg = AttrDict(json.loads(cfg_str))

    def prepare_alazar(cfg, expt_name, expt=None):
        if expt == None:
            cfg['alazar']['samplesPerRecord'] = 2**(cfg['readout']['width'] -
                                                    1).bit_length()
            sequence_length = int((cfg[expt_name.lower()]['stop'] -
                                   cfg[expt_name.lower()]['start']) /
                                  cfg[expt_name.lower()]['step'])
            if (cfg[expt_name.lower()]['use_pi_calibration']):
                sequence_length += 2

            cfg['alazar']['recordsPerBuffer'] = sequence_length
            cfg['alazar']['recordsPerAcquisition'] = int(
                sequence_length * min(cfg[expt_name.lower()]['averages'], 100))
            print("Prep Card")
            adc = Alazar(cfg['alazar'])
        else:
            cfg['alazar']['samplesPerRecord'] = 2**(cfg['readout']['width'] -
                                                    1).bit_length()
            sequence_length = int((cfg[expt_name.lower()][expt]['stop'] -
                                   cfg[expt_name.lower()][expt]['start']) /
                                  cfg[expt_name.lower()][expt]['step'])
            if (cfg[expt_name.lower()]['use_pi_calibration']):
                sequence_length += 2

            cfg['alazar']['recordsPerBuffer'] = sequence_length
            cfg['alazar']['recordsPerAcquisition'] = int(
                sequence_length *
                min(cfg[expt_name.lower()][expt]['averages'], 100))
            print("Prep Card")
            adc = Alazar(cfg['alazar'])
        return adc

    expt = None

    experiment_started = False

    if expt_name.lower() == 'calibrate_multimode':
        experiment_started = True
        multimode_pulse_calibration()

    if expt_name.lower() == 'multimode_rabi_sweep':
        experiment_started = True
        cfg['alazar']['samplesPerRecord'] = 2**(cfg['readout']['width'] -
                                                1).bit_length()
        sequence_length = (
            cfg[expt_name.lower()]['stop'] -
            cfg[expt_name.lower()]['start']) / cfg[expt_name.lower()]['step']
        if (cfg[expt_name.lower()]['use_pi_calibration']):
            sequence_length += 2

        cfg['alazar']['recordsPerBuffer'] = sequence_length
        cfg['alazar']['recordsPerAcquisition'] = int(
            sequence_length * min(cfg[expt_name.lower()]['averages'], 100))
        print("Prep Card")
        adc = Alazar(cfg['alazar'])
        flux_freq_pts = arange(cfg[expt_name.lower()]['freq_start'],
                               cfg[expt_name.lower()]['freq_stop'],
                               cfg[expt_name.lower()]['freq_step'])
        prefix = 'Multimode_Rabi_Sweep'
        data_file = os.path.join(
            datapath, get_next_filename(datapath, prefix, suffix='.h5'))
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeRabiSweepExperiment
        # Do Multimode Rabi
        for ii, flux_freq in enumerate(flux_freq_pts):
            print("Running Multimode Rabi Sweep with flux frequency: " +
                  str(flux_freq))
            expt = MultimodeRabiSweepExperiment(path=datapath,
                                                data_file=data_file,
                                                adc=adc,
                                                flux_freq=flux_freq,
                                                liveplot_enabled=False)
            expt.go()

            expt = None
            del expt

            gc.collect()
        pass

    if expt_name.lower() == 'multimode_ef_rabi_sweep':
        experiment_started = True
        cfg['alazar']['samplesPerRecord'] = 2**(cfg['readout']['width'] -
                                                1).bit_length()
        sequence_length = (
            cfg[expt_name.lower()]['stop'] -
            cfg[expt_name.lower()]['start']) / cfg[expt_name.lower()]['step']
        if (cfg[expt_name.lower()]['use_pi_calibration']):
            sequence_length += 2

        cfg['alazar']['recordsPerBuffer'] = sequence_length
        cfg['alazar']['recordsPerAcquisition'] = int(
            sequence_length * min(cfg[expt_name.lower()]['averages'], 100))
        print("Prep Card")
        adc = Alazar(cfg['alazar'])
        flux_freq_pts = arange(cfg[expt_name.lower()]['freq_start'],
                               cfg[expt_name.lower()]['freq_stop'],
                               cfg[expt_name.lower()]['freq_step'])
        prefix = 'Multimode_EF_Rabi_Sweep'
        data_file = os.path.join(
            datapath, get_next_filename(datapath, prefix, suffix='.h5'))
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeEFRabiSweepExperiment
        # Do Multimode Rabi
        for ii, flux_freq in enumerate(flux_freq_pts):
            print("Running Multimode EF Rabi Sweep with flux frequency: " +
                  str(flux_freq))
            expt = MultimodeEFRabiSweepExperiment(path=datapath,
                                                  data_file=data_file,
                                                  adc=adc,
                                                  flux_freq=flux_freq,
                                                  liveplot_enabled=False)
            expt.go()

            expt = None
            del expt

            gc.collect()
        pass

    if expt_name.lower() == 'multimode_cphase_optimization_sweep':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import CPhaseOptimizationSweepExperiment

        adc = prepare_alazar(cfg, expt_name)

        idle_time_pts = arange(cfg[expt_name.lower()]['length_start'],
                               cfg[expt_name.lower()]['length_stop'],
                               cfg[expt_name.lower()]['length_step'])

        prefix = 'multimode_cphase_optimization_sweep'
        data_file = os.path.join(
            datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        for ii, idle_time in enumerate(idle_time_pts):
            print("Idle_time: " + str(idle_time))
            expt = CPhaseOptimizationSweepExperiment(path=datapath,
                                                     data_file=data_file,
                                                     adc=adc,
                                                     idle_time=idle_time,
                                                     liveplot_enabled=True)
            expt.go()

            expt = None
            del expt
            gc.collect()

    if expt_name.lower() == 'multimode_general_entanglement':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeGeneralEntanglementExperiment

        adc = prepare_alazar(cfg, expt_name)

        list_num = array([7])
        for list in list_num:

            if (list == 2):
                idm_list = array([9, 1, 6, 4, 5, 3])
                numberlist = arange(3, 1, -1)
            elif (list == 3):
                idm_list = array([9, 6, 1, 4, 5, 3])
                numberlist = arange(6, 1, -1)
            elif (list == 4):
                idm_list = array([6, 1, 4, 5, 9, 3])
                numberlist = arange(6, 1, -1)

            elif (list == 5):
                idm_list = array([1, 4, 6, 5, 9, 3])
                numberlist = array([3])
            elif (list == 6):
                idm_list = array([1, 6, 9, 4, 5, 3])
                # numberlist =arange(6,1,-1)
                numberlist = array([3])
            elif (list == 7):
                idm_list = array([6, 1, 9, 4, 5, 3])
                # numberlist =arange(6,1,-1)
                numberlist = array([3])

            for number in numberlist:
                # frequency_stabilization()
                for ii, idm in enumerate(idm_list):
                    prefix = 'multimode_general_entanglement_' + str(
                        number) + '_l_' + str(list) + '_experiment'
                    data_file = os.path.join(
                        datapath,
                        get_next_filename(datapath, prefix, suffix='.h5'))
                    print("Measured mode " + str(idm))
                    expt = MultimodeGeneralEntanglementExperiment(
                        path=datapath,
                        data_file=data_file,
                        adc=adc,
                        idm=idm,
                        id1=idm_list[0],
                        id2=idm_list[1],
                        id3=idm_list[2],
                        id4=idm_list[3],
                        id5=idm_list[4],
                        id6=idm_list[5],
                        number=number,
                        liveplot_enabled=True)
                    expt.go()
                    # expt.save_config()
                    expt = None
                    del expt
                    gc.collect()

    if expt_name.lower() == 'multimode_two_resonator_tomography_phase_sweep':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import \
            MultimodeTwoResonatorTomographyPhaseSweepExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RamseyExperiment

        adc = prepare_alazar(cfg, expt_name)

        tom_pts = arange(0, 15)
        state_pts = arange(3, 7)

        prefix = 'multimode_two_resonator_tomography_phase_sweep'
        data_file = os.path.join(
            datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        for state_num in state_pts:
            print("State_number: " + str(state_num))
            # frequency_stabilization()

            for ii, tomography_num in enumerate(tom_pts):
                prefix = 'multimode_two_resonator_tomography_phase_sweep_' + str(
                    state_num) + '_' + str(tomography_num) + '_experiment'
                data_file = os.path.join(
                    datapath, get_next_filename(datapath, prefix,
                                                suffix='.h5'))
                print("Tomography_pulse_number: " + str(tomography_num))
                expt = MultimodeTwoResonatorTomographyPhaseSweepExperiment(
                    path=datapath,
                    data_file=data_file,
                    adc=adc,
                    tomography_num=tomography_num,
                    state_num=state_num,
                    liveplot_enabled=True)
                expt.go()

                expt = None
                del expt
                gc.collect()

    if expt_name.lower() == 'multimode_three_mode_correlation_experiment':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import \
            MultimodeThreeModeCorrelationExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RamseyExperiment

        adc = prepare_alazar(cfg, expt_name)

        # tom_pts = arange(0, 9)
        state_pts = array([0])
        tom_pts = array([7])
        prefix = 'multimode_two_resonator_tomography_phase_sweep'
        data_file = os.path.join(
            datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        for state_num in state_pts:
            print("State_number: " + str(state_num))
            # frequency_stabilization()

            for ii, tomography_num in enumerate(tom_pts):
                prefix = 'multimode_three_mode_tomography_4_' + str(
                    state_num) + '_' + str(tomography_num) + '_experiment'
                data_file = os.path.join(
                    datapath, get_next_filename(datapath, prefix,
                                                suffix='.h5'))
                print("Tomography_pulse_number: " + str(tomography_num))
                expt = MultimodeThreeModeCorrelationExperiment(
                    path=datapath,
                    data_file=data_file,
                    adc=adc,
                    tomography_num=tomography_num,
                    state_num=state_num,
                    liveplot_enabled=True)
                expt.go()

                expt = None
                del expt
                gc.collect()

    if expt_name.lower() == 'multimode_calibrate_offset_experiment':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeCalibrateOffsetExperiment

        calibrate_sideband = False
        save_to_file = True
        # mode_pts = array([0, 1, 3, 4, 5, 6, 9])
        mode_pts = array([4])

        for ii, mode_num in enumerate(mode_pts):

            if calibrate_sideband:
                adc = prepare_alazar(cfg, expt_name, 'multimode_rabi')
                prefix = 'multimode_rabi_mode_' + str(mode_num) + '_experiment'
                data_file = os.path.join(
                    datapath, get_next_filename(datapath, prefix,
                                                suffix='.h5'))
                expt = MultimodeCalibrateOffsetExperiment(
                    path=datapath,
                    data_file=data_file,
                    adc=adc,
                    exp='multimode_rabi',
                    dc_offset_guess=0,
                    mode=mode_num,
                    data_prefix=prefix,
                    liveplot_enabled=True)
                expt.go()
                if save_to_file:
                    expt.save_config()
                    print(
                        "Saved Multimode Rabi pi and 2pi lengths to the config file"
                    )
                else:
                    pass

                adc.close()
                expt = None

                del expt
                gc.collect()

            else:

                adc = prepare_alazar(cfg, expt_name, 'short_multimode_ramsey')
                prefix = 'short_multimode_ramsey_mode_' + str(
                    mode_num) + '_experiment'
                data_file = os.path.join(
                    datapath, get_next_filename(datapath, prefix,
                                                suffix='.h5'))
                expt = MultimodeCalibrateOffsetExperiment(
                    path=datapath,
                    data_file=data_file,
                    adc=adc,
                    exp='short_multimode_ramsey',
                    dc_offset_guess=0,
                    mode=mode_num,
                    liveplot_enabled=True)
                expt.go()
                print(expt.suggested_dc_offset_freq)
                dc_offset_guess = expt.suggested_dc_offset_freq
                adc.close()
                expt = None

                del expt
                gc.collect()

                adc = prepare_alazar(cfg, expt_name, 'long_multimode_ramsey')
                prefix = 'long_multimode_ramsey_mode_' + str(
                    mode_num) + '_experiment'
                data_file = os.path.join(
                    datapath, get_next_filename(datapath, prefix,
                                                suffix='.h5'))
                expt = MultimodeCalibrateOffsetExperiment(
                    path=datapath,
                    data_file=data_file,
                    adc=adc,
                    exp='long_multimode_ramsey',
                    mode=mode_num,
                    dc_offset_guess=dc_offset_guess,
                    liveplot_enabled=True)
                expt.go()
                print(expt.suggested_dc_offset_freq)
                expt.save_config()
                expt = None
                adc.close()

                gc.collect()

    if expt_name.lower() == 'multimode_calibrate_ef_sideband_experiment':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeCalibrateEFSidebandExperiment

        mode_pts = array([6, 9])

        calibrate_sideband = False
        save_to_file = True
        for ii, mode_num in enumerate(mode_pts):

            if calibrate_sideband:

                adc = prepare_alazar(cfg, expt_name, 'multimode_ef_rabi')
                prefix = 'multimode_ef_rabi_mode_' + str(
                    mode_num) + '_experiment'
                data_file = os.path.join(
                    datapath, get_next_filename(datapath, prefix,
                                                suffix='.h5'))
                expt = MultimodeCalibrateEFSidebandExperiment(
                    path=datapath,
                    data_file=data_file,
                    adc=adc,
                    exp='multimode_ef_rabi',
                    dc_offset_guess_ef=0,
                    mode=mode_num,
                    liveplot_enabled=True)
                expt.go()
                expt.save_config()
                adc.close()
                expt = None
                print()
                del expt
                gc.collect()

                print("Calibrated ge sideband for mode %s" % (mode_num))
            else:

                adc = prepare_alazar(cfg, expt_name,
                                     'short_multimode_ef_ramsey')
                prefix = 'multimode_ef_ramsey_mode_' + str(
                    mode_num) + '_experiment'
                data_file = os.path.join(
                    datapath, get_next_filename(datapath, prefix,
                                                suffix='.h5'))
                expt = MultimodeCalibrateEFSidebandExperiment(
                    path=datapath,
                    data_file=data_file,
                    adc=adc,
                    exp='short_multimode_ef_ramsey',
                    dc_offset_guess_ef=0,
                    mode=mode_num,
                    liveplot_enabled=True)
                expt.go()
                print(expt.suggested_dc_offset_freq_ef)
                dc_offset_guess_ef = expt.suggested_dc_offset_freq_ef
                adc.close()
                expt = None
                print()
                del expt
                gc.collect()

                adc = prepare_alazar(cfg, expt_name,
                                     'long_multimode_ef_ramsey')
                prefix = 'long_multimode_ef_ramsey_mode_' + str(
                    mode_num) + '_experiment'
                data_file = os.path.join(
                    datapath, get_next_filename(datapath, prefix,
                                                suffix='.h5'))
                expt = MultimodeCalibrateEFSidebandExperiment(
                    path=datapath,
                    data_file=data_file,
                    adc=adc,
                    exp='long_multimode_ef_ramsey',
                    mode=mode_num,
                    dc_offset_guess_ef=dc_offset_guess_ef,
                    liveplot_enabled=True)
                expt.go()
                print(expt.suggested_dc_offset_freq_ef)
                expt.save_config()
                expt = None
                adc.close()
                gc.collect()

    if expt_name.lower() == 'multimode_dc_offset_experiment':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeDCOffsetExperiment

        # freq_pts = [2.14e9,2.45e9,2.63e9,2.94e9]
        freq_pts = linspace(1328859060.4, 2e9, 100)
        amp_pts = array([0.25])
        i = 7
        j = 0
        frequency_stabilization()
        adc = prepare_alazar(cfg, expt_name)
        for freq in freq_pts:
            # i+=1

            for ii, amp in enumerate(amp_pts):
                if j % 10 == 0:
                    frequency_stabilization()
                j += 1

                prefix1 = 'Multimode_DC_Offset_'
                prefix2 = str(i)
                prefix3 = '_Experiment'
                prefix = prefix1 + prefix2 + prefix3
                data_file = os.path.join(
                    datapath, get_next_filename(datapath, prefix,
                                                suffix='.h5'))
                expt = MultimodeDCOffsetExperiment(path=datapath,
                                                   data_file=data_file,
                                                   adc=adc,
                                                   amp=amp,
                                                   freq=freq,
                                                   data_prefix=prefix,
                                                   liveplot_enabled=True)
                expt.go()
                expt = None
                print()
                del expt
                gc.collect()

        adc.close()

    if expt_name.lower() == 'sequential_single_mode_randomized_benchmarking':
        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeSingleResonatorRandomizedBenchmarkingExperiment

        for i in arange(32):
            pulse_calibration(phase_exp=True)
            multimode_pulse_calibration()
            expt = MultimodeSingleResonatorRandomizedBenchmarkingExperiment(
                liveplot_enabled=False, path=datapath, trigger_period=0.001)
            expt.go()
            del expt
            gc.collect()

    if not experiment_started:
        close_match = difflib.get_close_matches(expt_name, expt_list)
        print("No experiment found for: " + expt_name)
        print("Do you mean: " + close_match[0] + "?")
def run_multimode_sequential_experiment(expt_name):
    import os
    import difflib

    expt_list = ['Multimode_Rabi']
    datapath = os.getcwd() + '\data'

    config_file = os.path.join(datapath, "..\\config" + ".json")
    with open(config_file, 'r') as fid:
        cfg_str = fid.read()

    cfg = AttrDict(json.loads(cfg_str))

    def prepare_alazar(cfg, expt_name, expt=None):
        if expt == None:
            cfg['alazar']['samplesPerRecord'] = 2 ** (cfg['readout']['width'] - 1).bit_length()
            sequence_length = int(
                (cfg[expt_name.lower()]['stop'] - cfg[expt_name.lower()]['start']) / cfg[expt_name.lower()]['step'])
            if (cfg[expt_name.lower()]['use_pi_calibration']):
                sequence_length += 2

            cfg['alazar']['recordsPerBuffer'] = sequence_length
            cfg['alazar']['recordsPerAcquisition'] = int(
                sequence_length * min(cfg[expt_name.lower()]['averages'], 100))
            print("Prep Card")
            adc = Alazar(cfg['alazar'])
        else:
            cfg['alazar']['samplesPerRecord'] = 2 ** (cfg['readout']['width'] - 1).bit_length()
            sequence_length = int((cfg[expt_name.lower()][expt]['stop'] - cfg[expt_name.lower()][expt]['start']) /
                                  cfg[expt_name.lower()][expt]['step'])
            if (cfg[expt_name.lower()]['use_pi_calibration']):
                sequence_length += 2

            cfg['alazar']['recordsPerBuffer'] = sequence_length
            cfg['alazar']['recordsPerAcquisition'] = int(
                sequence_length * min(cfg[expt_name.lower()][expt]['averages'], 100))
            print("Prep Card")
            adc = Alazar(cfg['alazar'])
        return adc


    expt = None

    experiment_started = False

    if  expt_name.lower() == 'calibrate_multimode':
        experiment_started = True
        multimode_pulse_calibration()

    if expt_name.lower() == 'multimode_rabi_sweep':
        experiment_started = True
        cfg['alazar']['samplesPerRecord'] = 2 ** (cfg['readout']['width'] - 1).bit_length()
        sequence_length = (cfg[expt_name.lower()]['stop'] - cfg[expt_name.lower()]['start']) / cfg[expt_name.lower()][
            'step']
        if (cfg[expt_name.lower()]['use_pi_calibration']):
            sequence_length += 2

        cfg['alazar']['recordsPerBuffer'] = sequence_length
        cfg['alazar']['recordsPerAcquisition'] = int(
            sequence_length * min(cfg[expt_name.lower()]['averages'], 100))
        print("Prep Card")
        adc = Alazar(cfg['alazar'])
        flux_freq_pts = arange(cfg[expt_name.lower()]['freq_start'], cfg[expt_name.lower()]['freq_stop'],
                               cfg[expt_name.lower()]['freq_step'])
        prefix = 'Multimode_Rabi_Sweep'
        data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeRabiSweepExperiment
        # Do Multimode Rabi
        for ii, flux_freq in enumerate(flux_freq_pts):
            print("Running Multimode Rabi Sweep with flux frequency: " + str(flux_freq))
            expt = MultimodeRabiSweepExperiment(path=datapath, data_file=data_file, adc=adc, flux_freq=flux_freq,
                                                liveplot_enabled=False)
            expt.go()

            expt = None
            del expt

            gc.collect()
        pass

    if expt_name.lower() == 'multimode_ef_rabi_sweep':
        experiment_started = True
        cfg['alazar']['samplesPerRecord'] = 2 ** (cfg['readout']['width'] - 1).bit_length()
        sequence_length = (cfg[expt_name.lower()]['stop'] - cfg[expt_name.lower()]['start']) / cfg[expt_name.lower()][
            'step']
        if (cfg[expt_name.lower()]['use_pi_calibration']):
            sequence_length += 2

        cfg['alazar']['recordsPerBuffer'] = sequence_length
        cfg['alazar']['recordsPerAcquisition'] = int(
            sequence_length * min(cfg[expt_name.lower()]['averages'], 100))
        print("Prep Card")
        adc = Alazar(cfg['alazar'])
        flux_freq_pts = arange(cfg[expt_name.lower()]['freq_start'], cfg[expt_name.lower()]['freq_stop'],
                               cfg[expt_name.lower()]['freq_step'])
        prefix = 'Multimode_EF_Rabi_Sweep'
        data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeEFRabiSweepExperiment
        # Do Multimode Rabi
        for ii, flux_freq in enumerate(flux_freq_pts):
            print("Running Multimode EF Rabi Sweep with flux frequency: " + str(flux_freq))
            expt = MultimodeEFRabiSweepExperiment(path=datapath, data_file=data_file, adc=adc, flux_freq=flux_freq,
                                                  liveplot_enabled=False)
            expt.go()

            expt = None
            del expt

            gc.collect()
        pass

    if expt_name.lower() == 'multimode_cphase_optimization_sweep':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import CPhaseOptimizationSweepExperiment

        adc = prepare_alazar(cfg, expt_name)

        idle_time_pts = arange(cfg[expt_name.lower()]['length_start'], cfg[expt_name.lower()]['length_stop'],
                               cfg[expt_name.lower()]['length_step'])

        prefix = 'multimode_cphase_optimization_sweep'
        data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        for ii, idle_time in enumerate(idle_time_pts):
            print("Idle_time: " + str(idle_time))
            expt = CPhaseOptimizationSweepExperiment(path=datapath, data_file=data_file, adc=adc, idle_time=idle_time,
                                                     liveplot_enabled=True)
            expt.go()

            expt = None
            del expt
            gc.collect()

    if expt_name.lower() == 'multimode_general_entanglement':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeGeneralEntanglementExperiment

        adc = prepare_alazar(cfg, expt_name)

        list_num = array([7])
        for list in list_num:

            if(list == 2):
                idm_list = array([9, 1, 6, 4, 5, 3])
                numberlist =arange(3,1,-1)
            elif(list==3):
                idm_list = array([9, 6, 1, 4, 5, 3])
                numberlist =arange(6,1,-1)
            elif(list==4):
                idm_list = array([6, 1, 4, 5, 9, 3])
                numberlist =arange(6,1,-1)

            elif(list==5):
                idm_list = array([1, 4, 6, 5, 9, 3])
                numberlist =array([3])
            elif(list==6):
                idm_list = array([1,6,9,4,5,3])
                # numberlist =arange(6,1,-1)
                numberlist =array([3])
            elif(list==7):
                idm_list = array([6,1,9,4,5,3])
                # numberlist =arange(6,1,-1)
                numberlist =array([3])

            for number in numberlist:
                # frequency_stabilization()
                for ii, idm in enumerate(idm_list):
                    prefix = 'multimode_general_entanglement_' + str(number) + '_l_' + str(list)+'_experiment'
                    data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))
                    print("Measured mode " + str(idm))
                    expt = MultimodeGeneralEntanglementExperiment(path=datapath, data_file=data_file, adc=adc, idm=idm, id1=idm_list[0],
                                                                  id2=idm_list[1], id3=idm_list[2], id4=idm_list[3], id5=idm_list[4], id6=idm_list[5], number=number,
                                                                  liveplot_enabled=True)
                    expt.go()
                    # expt.save_config()
                    expt = None
                    del expt
                    gc.collect()

    if expt_name.lower() == 'multimode_two_resonator_tomography_phase_sweep':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import \
            MultimodeTwoResonatorTomographyPhaseSweepExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RamseyExperiment

        adc = prepare_alazar(cfg, expt_name)

        tom_pts = arange(0, 15)
        state_pts = arange(3, 7)

        prefix = 'multimode_two_resonator_tomography_phase_sweep'
        data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        for state_num in state_pts:
            print("State_number: " + str(state_num))
            # frequency_stabilization()

            for ii, tomography_num in enumerate(tom_pts):
                prefix = 'multimode_two_resonator_tomography_phase_sweep_' + str(state_num) + '_' + str(
                    tomography_num) + '_experiment'
                data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))
                print("Tomography_pulse_number: " + str(tomography_num))
                expt = MultimodeTwoResonatorTomographyPhaseSweepExperiment(path=datapath, data_file=data_file, adc=adc,
                                                                           tomography_num=tomography_num,
                                                                           state_num=state_num, liveplot_enabled=True)
                expt.go()

                expt = None
                del expt
                gc.collect()

    if expt_name.lower() == 'multimode_three_mode_correlation_experiment':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import \
            MultimodeThreeModeCorrelationExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RamseyExperiment

        adc = prepare_alazar(cfg, expt_name)

        # tom_pts = arange(0, 9)
        state_pts = array([0])
        tom_pts =array([7])
        prefix = 'multimode_two_resonator_tomography_phase_sweep'
        data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        for state_num in state_pts:
            print("State_number: " + str(state_num))
            # frequency_stabilization()

            for ii, tomography_num in enumerate(tom_pts):
                prefix = 'multimode_three_mode_tomography_4_' + str(state_num) + '_' + str(
                    tomography_num) + '_experiment'
                data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))
                print("Tomography_pulse_number: " + str(tomography_num))
                expt = MultimodeThreeModeCorrelationExperiment(path=datapath, data_file=data_file, adc=adc,
                                                                           tomography_num=tomography_num,
                                                                           state_num=state_num, liveplot_enabled=True)
                expt.go()

                expt = None
                del expt
                gc.collect()



    if expt_name.lower() == 'multimode_calibrate_offset_experiment':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeCalibrateOffsetExperiment

        calibrate_sideband = False
        save_to_file = True
        # mode_pts = array([0, 1, 3, 4, 5, 6, 9])
        mode_pts = array([4])



        for ii, mode_num in enumerate(mode_pts):

            if calibrate_sideband:
                adc = prepare_alazar(cfg, expt_name, 'multimode_rabi')
                prefix = 'multimode_rabi_mode_' + str(mode_num) + '_experiment'
                data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))
                expt = MultimodeCalibrateOffsetExperiment(path=datapath, data_file=data_file, adc=adc,
                                                          exp='multimode_rabi', dc_offset_guess=0, mode=mode_num,
                                                          data_prefix = prefix,
                                                          liveplot_enabled=True)
                expt.go()
                if save_to_file:
                    expt.save_config()
                    print("Saved Multimode Rabi pi and 2pi lengths to the config file")
                else:
                    pass

                adc.close()
                expt = None

                del expt
                gc.collect()

            else:

                adc = prepare_alazar(cfg, expt_name, 'short_multimode_ramsey')
                prefix = 'short_multimode_ramsey_mode_' + str(mode_num) + '_experiment'
                data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))
                expt = MultimodeCalibrateOffsetExperiment(path=datapath, data_file=data_file, adc=adc,
                                                          exp='short_multimode_ramsey', dc_offset_guess=0,
                                                          mode=mode_num, liveplot_enabled=True)
                expt.go()
                print(expt.suggested_dc_offset_freq)
                dc_offset_guess = expt.suggested_dc_offset_freq
                adc.close()
                expt = None

                del expt
                gc.collect()

                adc = prepare_alazar(cfg, expt_name, 'long_multimode_ramsey')
                prefix = 'long_multimode_ramsey_mode_' + str(mode_num) + '_experiment'
                data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))
                expt = MultimodeCalibrateOffsetExperiment(path=datapath, data_file=data_file, adc=adc,
                                                          exp='long_multimode_ramsey', mode=mode_num,
                                                          dc_offset_guess=dc_offset_guess, liveplot_enabled=True)
                expt.go()
                print(expt.suggested_dc_offset_freq)
                expt.save_config()
                expt = None
                adc.close()

                gc.collect()


    if expt_name.lower() == 'multimode_calibrate_ef_sideband_experiment':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeCalibrateEFSidebandExperiment

        mode_pts = array([6,9])

        calibrate_sideband = False
        save_to_file = True
        for ii, mode_num in enumerate(mode_pts):

            if calibrate_sideband:

                adc = prepare_alazar(cfg, expt_name, 'multimode_ef_rabi')
                prefix = 'multimode_ef_rabi_mode_' + str(mode_num) + '_experiment'
                data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))
                expt = MultimodeCalibrateEFSidebandExperiment(path=datapath, data_file=data_file, adc=adc,
                                                              exp='multimode_ef_rabi', dc_offset_guess_ef=0,
                                                              mode=mode_num, liveplot_enabled=True)
                expt.go()
                expt.save_config()
                adc.close()
                expt = None
                print()
                del expt
                gc.collect()

                print("Calibrated ge sideband for mode %s" %(mode_num))
            else:

                adc = prepare_alazar(cfg, expt_name, 'short_multimode_ef_ramsey')
                prefix = 'multimode_ef_ramsey_mode_' + str(mode_num) + '_experiment'
                data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))
                expt = MultimodeCalibrateEFSidebandExperiment(path=datapath, data_file=data_file, adc=adc,
                                                              exp='short_multimode_ef_ramsey', dc_offset_guess_ef=0,
                                                              mode=mode_num, liveplot_enabled=True)
                expt.go()
                print(expt.suggested_dc_offset_freq_ef)
                dc_offset_guess_ef = expt.suggested_dc_offset_freq_ef
                adc.close()
                expt = None
                print()
                del expt
                gc.collect()

                adc = prepare_alazar(cfg, expt_name, 'long_multimode_ef_ramsey')
                prefix = 'long_multimode_ef_ramsey_mode_' + str(mode_num) + '_experiment'
                data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))
                expt = MultimodeCalibrateEFSidebandExperiment(path=datapath, data_file=data_file, adc=adc,
                                                              exp='long_multimode_ef_ramsey', mode=mode_num,
                                                              dc_offset_guess_ef=dc_offset_guess_ef,
                                                              liveplot_enabled=True)
                expt.go()
                print(expt.suggested_dc_offset_freq_ef)
                expt.save_config()
                expt = None
                adc.close()
                gc.collect()



    if expt_name.lower() == 'multimode_dc_offset_experiment':

        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeDCOffsetExperiment

        # freq_pts = [2.14e9,2.45e9,2.63e9,2.94e9]
        freq_pts = linspace(1328859060.4,2e9,100)
        amp_pts = array([0.25])
        i=7
        j=0
        frequency_stabilization()
        adc = prepare_alazar(cfg, expt_name)
        for freq in freq_pts:
            # i+=1

            for ii, amp in enumerate(amp_pts):
                if j%10 == 0:
                    frequency_stabilization()
                j+=1

                prefix1 = 'Multimode_DC_Offset_'
                prefix2 = str(i)
                prefix3 = '_Experiment'
                prefix = prefix1 + prefix2 + prefix3
                data_file = os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))
                expt = MultimodeDCOffsetExperiment(path=datapath, data_file=data_file, adc=adc,amp = amp, freq= freq, data_prefix = prefix, liveplot_enabled=True)
                expt.go()
                expt = None
                print()
                del expt
                gc.collect()

        adc.close()



    if expt_name.lower() == 'sequential_single_mode_randomized_benchmarking':
        experiment_started = True
        from slab.experiments.Multimode.MultimodePulseSequenceExperiment import MultimodeSingleResonatorRandomizedBenchmarkingExperiment

        for i in arange(32):
            pulse_calibration(phase_exp=True)
            multimode_pulse_calibration()
            expt = MultimodeSingleResonatorRandomizedBenchmarkingExperiment(liveplot_enabled=False, path=datapath, trigger_period=0.001)
            expt.go()
            del expt
            gc.collect()

    if not experiment_started:
        close_match = difflib.get_close_matches(expt_name, expt_list)
        print("No experiment found for: " + expt_name)
        print("Do you mean: " + close_match[0] + "?")
def run_sequential_experiment(expt_name):
    import os
    import difflib

    expt_list = ['Frequency_Calibration','Rabi_Sweep','HalfPiXOptimization_sweep', 'tune_up_experiment']

    datapath = os.getcwd() + '\data'
    config_file = os.path.join(datapath, "..\\config" + ".json")
    with open(config_file, 'r') as fid:
        cfg_str = fid.read()

    cfg = AttrDict(json.loads(cfg_str))

    expt = None

    experiment_started = False

    if expt_name.lower() == 'calibration_experiment':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RamseyExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RabiExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import EFRabiExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import EFRamseyExperiment


        # Do Frequency Calibration

        expt = RamseyExperiment(path=datapath)
        expt.go()
        print(expt.offset_freq)

        expt = RabiExperiment(path=datapath)
        expt.go()

        expt = EFRabiExperiment(path=datapath)
        expt.go()

        expt = EFRamseyExperiment(path=datapath)
        expt.go()
        del expt
        gc.collect()

    if expt_name.lower() == 'monitor_frequency_experiment':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RamseyExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import EFRamseyExperiment


        # Do Frequency Calibration

        for i in arange(20):
            expt = RamseyExperiment(path=datapath)
            expt.go()
            print(expt.offset_freq)


            expt = EFRamseyExperiment(path=datapath)
            expt.go()
            del expt
            gc.collect()

    if expt_name.lower() == 'tomography_tune_up_experiment':
        experiment_started = True
        print(expt_name + " is running!")
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RamseyExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RabiExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import EFRabiExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import EFRamseyExperiment
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import HalfPiYPhaseOptimizationExperiment


        # Do Frequency Calibration

        expt = RamseyExperiment(path=datapath)
        expt.go()
        if (abs(expt.offset_freq) < 50e3):
            pass
        else:
            print(expt.flux)
            flux_offset = -expt.offset_freq/(expt.freq_flux_slope)
            print(flux_offset)
            if (abs(flux_offset) < 0.000002):
                flux2 = expt.flux + flux_offset
                print(flux2)
                expt = RamseyExperiment(path=datapath, flux = flux2)
                expt.go()
                offset_freq2 = expt.offset_freq
                flux_offset2 = -expt.offset_freq/(expt.freq_flux_slope)
                flux3 = flux2 + flux_offset2
                if (abs(offset_freq2) < 50e3):
                    print("Great success! Frequency calibrated")
                    expt.save_config()
                else:
                    if (abs(flux_offset2) < 0.000002):
                        expt = RamseyExperiment(path=datapath, flux = flux3)
                        expt.go()
                        if (abs(expt.offset_freq) < 100e3):
                            print("Frequency calibrated")
                            expt.save_config()
                        else:
                            print("Try again: not converged after 2 tries")
                    else:
                        print("Large change in flux is required; please do so manually")
                        pass
            else:
                print("Large change in flux is required; please do so manually")
                pass


        expt = RabiExperiment(path=datapath)
        expt.go()
        print("ge pi and pi/2 pulses recalibrated")
        expt.save_config()

        expt = EFRabiExperiment(path=datapath)
        expt.go()
        print("ef pi and pi/2 pulses recalibrated")
        expt.save_config()


        expt = EFRamseyExperiment(path=datapath)
        expt.go()
        expt.save_config()
        expt.go()

        # #

        # expt = HalfPiYPhaseOptimizationExperiment(path=datapath)
        # expt.go()
        # #
        # print flux2
        del expt
        gc.collect()

    if expt_name.lower() == 'offset_phase_calibration_experiment':
        qubit_dc_offset_list_pi = linspace(-0.25e6,0.25e6,5)

        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import HalfPiYPhaseOptimizationExperiment
        # Do Frequency Calibration
        frequency_stabilization()
        for qubit_dc_offset in qubit_dc_offset_list_pi:

            expt = HalfPiYPhaseOptimizationExperiment(path=datapath, qubit_dc_offset = qubit_dc_offset)
            expt.go()
            expt.save_config()
            del expt
            gc.collect()


    if expt_name.lower() == 'frequency_calibration':
        frequency_stabilization()

    if expt_name.lower() == 'rabi_sweep':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RabiSweepExperiment

        cfg['alazar']['samplesPerRecord'] = 2 ** (cfg['readout']['width'] - 1).bit_length()
        sequence_length = (cfg[expt_name.lower()]['stop']-cfg[expt_name.lower()]['start'])/cfg[expt_name.lower()]['step']
        if (cfg[expt_name.lower()]['use_pi_calibration']):
            sequence_length+=2

        cfg['alazar']['recordsPerBuffer'] = sequence_length
        cfg['alazar']['recordsPerAcquisition'] = int(
            sequence_length * min(cfg[expt_name.lower()]['averages'], 100))
        print("Prep Card")
        adc = Alazar(cfg['alazar'])

        drive_freq_pts = arange(cfg[expt_name.lower()]['freq_start'],cfg[expt_name.lower()]['freq_stop'],cfg[expt_name.lower()]['freq_step'])
        prefix = 'Rabi_Sweep'
        data_file =  os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        for ii, drive_freq in enumerate(drive_freq_pts):
            print(drive_freq)
            expt = RabiSweepExperiment(path=datapath,data_file=data_file, adc=adc, drive_freq=drive_freq, liveplot_enabled=False)
            expt.go()

            expt = None
            del expt

            gc.collect()
    if expt_name.lower() == 'rabi_ramsey_t1_flux_sweep':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import RabiRamseyT1FluxSweepExperiment



        prefix = 'rabi_ramsey_t1_flux_sweep'
        data_file =  os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        flux_pts = load(r'S:\_Data\160711 - Nb Tunable Coupler\data\flux_total.npy')
        drive_pts = load(r'S:\_Data\160711 - Nb Tunable Coupler\data\probe_frequencies_total.npy')
        readout_pts = load(r'S:\_Data\160711 - Nb Tunable Coupler\data\read_frequencies_7_28.npy')


        # flux_pts=[-0.012]
        # drive_pts=[4.844e9]
        # readout_pts=[5257100000.0]

        qubit_alpha = cfg['qubit']['alpha']

        for ii, flux in enumerate(flux_pts):
            drive_freq = drive_pts[ii]
            readout_freq = readout_pts[ii]
            print("Flux: " + str(flux))
            print("Drive frequency: " + str(drive_freq))
            print("Readout frequency: " + str(readout_freq))


            ### 1st Rabi
            print("### Running 1st Rabi.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep','rabi')
            expt = RabiRamseyT1FluxSweepExperiment(path=datapath,exp = 'rabi', flux = flux,data_file=data_file, adc=adc,drive_freq=drive_freq, readout_freq = readout_freq,liveplot_enabled=liveplot_enabled)
            expt.go()
            pi_length = expt.pi_length
            half_pi_length = expt.half_pi_length

            adc.close()
            expt = None
            del expt
            gc.collect()

            ### 1st Ramsey
            print("### Running 1st Ramsey.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep','ramsey')
            expt = RabiRamseyT1FluxSweepExperiment(path=datapath,exp = 'ramsey', flux = flux,half_pi_length=half_pi_length,data_file=data_file, adc=adc, drive_freq=drive_freq, readout_freq = readout_freq, liveplot_enabled=liveplot_enabled)
            expt.go()
            suggested_qubit_freq = expt.suggested_qubit_freq
            drive_freq = suggested_qubit_freq

            adc.close()
            expt = None
            del expt
            gc.collect()


            ### 2nd Rabi
            print("### Running 2nd Rabi.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep','rabi')
            expt = RabiRamseyT1FluxSweepExperiment(path=datapath,exp = 'rabi', flux = flux,data_file=data_file, adc=adc, drive_freq=drive_freq, readout_freq = readout_freq, liveplot_enabled=liveplot_enabled)
            expt.go()
            pi_length = expt.pi_length
            half_pi_length = expt.half_pi_length

            adc.close()
            expt = None
            del expt
            gc.collect()


            ### Ramsey long
            print("### Running Ramsey Long.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep','ramsey_long')
            expt = RabiRamseyT1FluxSweepExperiment(path=datapath,exp = 'ramsey_long', flux = flux,half_pi_length=half_pi_length,data_file=data_file, adc=adc, drive_freq=drive_freq, readout_freq = readout_freq, liveplot_enabled=liveplot_enabled)
            expt.go()

            adc.close()
            expt = None
            del expt
            gc.collect()

            ## Rabi Long
            # print "### Running Rabi Long."
            # adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep','rabi_long')
            # expt = RabiRamseyT1FluxSweepExperiment(path=datapath,exp = 'rabi_long', flux = flux,data_file=data_file, adc=adc, drive_freq=drive_freq, readout_freq = readout_freq, liveplot_enabled=liveplot_enabled)
            # expt.go()
            # # pi_length = expt.pi_length
            # # half_pi_length = expt.half_pi_length
            #
            # adc.close()
            # expt = None
            # del expt
            # gc.collect()

            ### remove adc
            adc = None
            del adc


            ### t1
            print("### Running T1.")
            adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 't1')
            expt = RabiRamseyT1FluxSweepExperiment(path=datapath,exp = 't1', flux = flux,pi_length=pi_length,data_file=data_file, adc=adc, drive_freq=drive_freq, readout_freq = readout_freq, liveplot_enabled=liveplot_enabled)
            expt.go()

            adc.close()
            expt = None
            del expt
            gc.collect()


            # ### Pi/2 phase sweep
            # print "### Running pi/2 phase sweep experiment"
            # adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep','half_pi_phase_sweep')
            # expt = RabiRamseyT1FluxSweepExperiment(path=datapath,exp = 'half_pi_phase_sweep', flux = flux,half_pi_length=half_pi_length,data_file=data_file, adc=adc,drive_freq=drive_freq, readout_freq = readout_freq,liveplot_enabled=liveplot_enabled)
            # expt.go()
            #
            # adc.close()
            # expt = None
            # del expt
            # gc.collect()
            #
            #
            # ### EF Rabi
            # print "### Running EF Rabi."
            # adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'ef_rabi')
            # expt = RabiRamseyT1FluxSweepExperiment(path=datapath,exp = 'ef_rabi', flux = flux,pi_length=pi_length,data_file=data_file, adc=adc, drive_freq=drive_freq, readout_freq = readout_freq, liveplot_enabled=liveplot_enabled, alpha=qubit_alpha)
            # expt.go()
            # ef_pi_length = expt.pi_length
            # ef_half_pi_length = expt.half_pi_length
            #
            # adc.close()
            # expt = None
            # del expt
            # gc.collect()
            #
            # ### EF Ramsey
            # print "### Running EF Ramsey."
            # adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'ef_ramsey')
            # expt = RabiRamseyT1FluxSweepExperiment(path=datapath,exp = 'ef_ramsey', flux = flux,pi_length=pi_length,ef_half_pi_length=ef_half_pi_length,data_file=data_file, adc=adc, drive_freq=drive_freq, readout_freq = readout_freq, liveplot_enabled=liveplot_enabled, alpha=qubit_alpha)
            # expt.go()
            # suggested_alpha_freq = expt.suggested_qubit_alpha
            # print "Suggested alpha frequency: " + str(suggested_alpha_freq)
            # qubit_alpha = suggested_alpha_freq
            #
            # adc.close()
            # expt = None
            # del expt
            # gc.collect()
            #
            # ### EF Rabi
            # print "### Running EF Rabi."
            # adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'ef_rabi')
            # expt = RabiRamseyT1FluxSweepExperiment(path=datapath,exp = 'ef_rabi', flux = flux,pi_length=pi_length,data_file=data_file, adc=adc, drive_freq=drive_freq, readout_freq = readout_freq, liveplot_enabled=liveplot_enabled, alpha=qubit_alpha)
            # expt.go()
            # ef_pi_length = expt.pi_length
            # ef_half_pi_length = expt.half_pi_length
            #
            # adc.close()
            # expt = None
            # del expt
            # gc.collect()
            #
            #
            # ### EF T1
            # print "### Running EF T1."
            # adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'ef_t1')
            # expt = RabiRamseyT1FluxSweepExperiment(path=datapath,exp = 'ef_t1', flux = flux,pi_length=pi_length,ef_pi_length=ef_pi_length,data_file=data_file, adc=adc, drive_freq=drive_freq, readout_freq = readout_freq, liveplot_enabled=liveplot_enabled, alpha=qubit_alpha)
            # expt.go()
            #
            # adc.close()
            # expt = None
            # del expt
            # gc.collect()
            #
            #
            # ## EF Ramsey Long
            # print "### Running EF Ramsey."
            # adc = prepare_alazar(cfg, 'rabi_ramsey_t1_flux_sweep', 'ef_ramsey_long')
            # expt = RabiRamseyT1FluxSweepExperiment(path=datapath,exp = 'ef_ramsey_long', flux = flux,pi_length=pi_length,ef_half_pi_length=ef_half_pi_length,data_file=data_file, adc=adc, drive_freq=drive_freq, readout_freq = readout_freq, liveplot_enabled=liveplot_enabled, alpha=qubit_alpha)
            # expt.go()
            # suggested_alpha_freq = expt.suggested_qubit_alpha
            # print "Suggested alpha frequency: " + str(suggested_alpha_freq)
            # qubit_alpha = suggested_alpha_freq
            #
            # adc.close()
            # expt = None
            # del expt
            # gc.collect()
            #
            # ### remove adc
            # adc = None
            # del adc
            #
            # gc.collect()

    if expt_name.lower() == 'halfpixoptimization_sweep':

        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import HalfPiXOptimizationSweepExperiment

        adc = prepare_alazar(cfg, expt_name)

        if cfg[expt_name.lower()]['sweep_param'] == "length":
            pulse_sweep_pts = arange(cfg[expt_name.lower()]['length_start'],cfg[expt_name.lower()]['length_stop'],cfg[expt_name.lower()]['length_step'])
            pulse_amp = cfg[expt_name.lower()]['amp']
        elif cfg[expt_name.lower()]['sweep_param'] == "amp":
            pulse_sweep_pts = arange(cfg[expt_name.lower()]['amp_start'],cfg[expt_name.lower()]['amp_stop'],cfg[expt_name.lower()]['amp_step'])
            pulse_length = cfg[expt_name.lower()]['length']

        prefix = 'HalfPiXOptimization_Sweep'
        data_file =  os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        if cfg[expt_name.lower()]['sweep_param'] == "length":
            for ii, pulse_sweep in enumerate(pulse_sweep_pts):
                print("Pulse Sweep: " + str(pulse_sweep))
                expt = HalfPiXOptimizationSweepExperiment(path=datapath,data_file=data_file, adc=adc, pulse_length=pulse_sweep, pulse_amp = pulse_amp, liveplot_enabled = False)
                expt.go()

                expt = None
                del expt

                gc.collect()
        elif cfg[expt_name.lower()]['sweep_param'] == "amp":
            for ii, pulse_sweep in enumerate(pulse_sweep_pts):
                print("Pulse Sweep: " + str(pulse_sweep))
                expt = HalfPiXOptimizationSweepExperiment(path=datapath,data_file=data_file, adc=adc, pulse_length=pulse_length, pulse_amp = pulse_sweep, liveplot_enabled = False)
                expt.go()

                expt = None
                del expt

                gc.collect()


    if expt_name.lower() == 'pixoptimization_sweep':
        experiment_started = True
        from slab.experiments.General.SingleQubitPulseSequenceExperiment import PiXOptimizationSweepExperiment

        # cfg['alazar']['samplesPerRecord'] = 2 ** (cfg['readout']['width'] - 1).bit_length()
        # sequence_length = (cfg[expt_name.lower()]['stop']-cfg[expt_name.lower()]['start'])/cfg[expt_name.lower()]['step']
        # if (cfg[expt_name.lower()]['use_pi_calibration']):
        #     sequence_length+=2
        #
        # cfg['alazar']['recordsPerBuffer'] = sequence_length
        # cfg['alazar']['recordsPerAcquisition'] = int(
        #     sequence_length * min(cfg[expt_name.lower()]['averages'], 100))
        # print "Prep Card"
        # adc = Alazar(cfg['alazar'])

        adc = prepare_alazar(cfg, expt_name)

        if cfg[expt_name.lower()]['sweep_param'] == "length":
            pulse_sweep_pts = arange(cfg[expt_name.lower()]['length_start'],cfg[expt_name.lower()]['length_stop'],cfg[expt_name.lower()]['length_step'])
            pulse_amp = cfg[expt_name.lower()]['amp']
        elif cfg[expt_name.lower()]['sweep_param'] == "amp":
            pulse_sweep_pts = arange(cfg[expt_name.lower()]['amp_start'],cfg[expt_name.lower()]['amp_stop'],cfg[expt_name.lower()]['amp_step'])
            pulse_length = cfg[expt_name.lower()]['length']

        prefix = 'PiXOptimization_Sweep'
        data_file =  os.path.join(datapath, get_next_filename(datapath, prefix, suffix='.h5'))

        # for ii, pulse_sweep in enumerate(pulse_sweep_pts):
        #     print "Pulse Sweep: " + str(pulse_sweep)
        #     expt = PiXOptimizationSweepExperiment(path=datapath,data_file=data_file, adc=adc, pulse_length=pulse_sweep, liveplot_enabled = False)
        #     expt.go()
        #
        #     expt = None
        #     del expt
        #
        #     gc.collect()

        if cfg[expt_name.lower()]['sweep_param'] == "length":
            for ii, pulse_sweep in enumerate(pulse_sweep_pts):
                print("Pulse Sweep: " + str(pulse_sweep))
                expt = PiXOptimizationSweepExperiment(path=datapath,data_file=data_file, adc=adc, pulse_length=pulse_sweep, pulse_amp = pulse_amp, liveplot_enabled = False)
                expt.go()

                expt = None
                del expt

                gc.collect()
        elif cfg[expt_name.lower()]['sweep_param'] == "amp":
            for ii, pulse_sweep in enumerate(pulse_sweep_pts):
                print("Pulse Sweep: " + str(pulse_sweep))
                expt = PiXOptimizationSweepExperiment(path=datapath,data_file=data_file, adc=adc, pulse_length=pulse_length, pulse_amp = pulse_sweep, liveplot_enabled = False)
                expt.go()

                expt = None
                del expt

                gc.collect()


    if not experiment_started:
        close_match = difflib.get_close_matches(expt_name, expt_list)
        print("No experiment found for: " + expt_name)
        print("Do you mean: " + close_match[0] + "?")
    def go(self):
        if self.liveplot_enabled:
            self.plotter.clear()

        print("Prep Instruments")
        self.readout.set_frequency(self.cfg['readout']['frequency'])
        self.readout.set_power(self.cfg['readout']['power'])
        self.readout.set_ext_pulse(mod=True)
        # self.readout_shifter.set_phase(self.cfg['readout']['start_phase'] + self.cfg['readout']['phase_slope'] * (
        #     self.cfg['readout']['frequency'] - self.cfg['readout']['bare_frequency']), self.cfg['readout']['frequency'])

        self.drive.set_frequency(self.cfg['qubit']['frequency'] - self.cfg['pulse_info'][self.pulse_type]['iq_freq'])
        self.drive.set_power(self.cfg['drive']['power'])
        self.drive.set_ext_pulse(mod=True)
        self.drive.set_output(True)
        self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])

        self.trigger.set_period(self.trigger_period)

        try:
            self.cfg['freq_flux']['flux']=self.extra_args['flux']
        except:
            pass

        try:
            self.cfg['freq_flux']['freq_flux_slope']=self.extra_args['freq_flux_slope']
        except:
            pass

        try:
            self.cfg['freq_flux']['flux_offset']+=self.extra_args['flux_offset']
        except:
            pass


        if self.cfg['freq_flux']['current']:
            try: self.flux_volt.ramp_current(self.cfg['freq_flux']['flux'])
            except:pass
        elif self.cfg['freq_flux']['voltage']:
            try: self.flux_volt.ramp_volt(self.cfg['freq_flux']['flux'])
            except: pass

        self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'], self.cfg['cal']['iq_offsets'])

        if self.pre_run is not None:
            self.pre_run()

        if self.adc==None:
            print("Prep Card")
            adc = Alazar(self.cfg['alazar'])
        else:
            adc = self.adc

        expt_data = None
        current_data = None
        for ii in tqdm(arange(max(1, self.cfg[self.expt_cfg_name]['averages'] / 100))):
            tpts, ch1_pts, ch2_pts = adc.acquire_avg_data_by_record(prep_function=self.awg_prep,
                                                                    start_function=self.awg.run,
                                                                    excise=self.cfg['readout']['window'])

            ### to skip the first 100 averages data point, because we saw a weird ramp in the RF output
            if ii == 0:
                time.sleep(0.1)
                continue

            mag = sqrt(ch1_pts**2+ch2_pts**2)
            if not self.cfg[self.expt_cfg_name]['use_pi_calibration']:

                if expt_data is None:
                    if self.cfg['readout']['channel']==1:
                        expt_data = ch1_pts
                    elif self.cfg['readout']['channel']==2:
                        expt_data = ch2_pts
                else:
                    if self.cfg['readout']['channel']==1:
                        expt_data = (expt_data * ii + ch1_pts) / (ii + 1.0)
                    elif self.cfg['readout']['channel']==2:
                        expt_data = (expt_data * ii + ch2_pts) / (ii + 1.0)

                expt_avg_data = mean(expt_data, 1)


            else:

                if expt_data is None:
                    if self.cfg['readout']['channel']==1:
                        expt_data = ch1_pts
                    elif self.cfg['readout']['channel']==2:
                        expt_data = ch2_pts
                else:
                    if self.cfg['readout']['channel']==1:
                        expt_data = (expt_data * ii + ch1_pts) / (ii + 1.0)
                    elif self.cfg['readout']['channel']==2:
                        expt_data = (expt_data * ii + ch2_pts) / (ii + 1.0)

                expt_avg_data = mean(expt_data, 1)

                expt_avg_data = (expt_avg_data[:-2]-expt_avg_data[-2])/(expt_avg_data[-1]-expt_avg_data[-2])

            # temporary hack. Alazar card seems to shift two data points (problem disappeared after reboot computer)
            # expt_avg_data = np.concatenate((expt_avg_data[2:],expt_avg_data[:2]))
            # if self.cfg[self.expt_cfg_name]['use_pi_calibration']:
            #     expt_avg_data = (expt_avg_data[:-2]-expt_avg_data[-2])/(expt_avg_data[-1]-expt_avg_data[-2])

            # else:
            #     if self.cfg['readout']['channel']==1:
            #         zero_amp = mean(ch1_pts[-2])
            #         pi_amp = mean(ch1_pts[-1])
            #         current_data= (ch1_pts[:-2]-zero_amp)/(pi_amp-zero_amp)
            #     elif self.cfg['readout']['channel']==2:
            #         zero_amp = mean(ch2_pts[-2])
            #         pi_amp = mean(ch2_pts[-1])
            #         current_data= (ch2_pts[:-2]-zero_amp)/(pi_amp-zero_amp)
            #     if expt_data is None:
            #         expt_data = current_data
            #     else:
            #         expt_data = (expt_data * ii + current_data) / (ii + 1.0)


            # expt_avg_data = mean(expt_data, 1)


            if self.liveplot_enabled:
                self.plotter.plot_z(self.prefix + ' Data', expt_data.T)
                self.plotter.plot_xy(self.prefix + ' XY', self.pulse_sequence.expt_pts, expt_avg_data)

            # print ii * min(self.cfg[self.expt_cfg_name]['averages'], 100)

            if self.data_file == None:
                self.slab_file = self.datafile()
                with self.slab_file as f:
                    f.add('expt_2d', expt_data)
                    f.add('expt_avg_data', expt_avg_data)
                    f.add('expt_pts', self.expt_pts)
                    f.close()

        if self.data_file != None:
            self.slab_file = SlabFile(self.data_file)
            with self.slab_file as f:
                f.append_line('expt_avg_data', expt_avg_data)
                f.append_line('expt_pts', self.expt_pts)
                f.close()


        if not self.adc_predefined:
            adc.close()


        if self.post_run is not None:
            self.post_run(self.expt_pts, expt_avg_data)