Example #1
0
    def go(self):

        if self.liveplot_enabled:
            self.plotter.clear()

        print("Prep Instruments")
        self.readout.set_output(True)
        self.readout.set_power(self.cfg['readout']['power'])
        self.readout.set_ext_pulse(mod=False)
        try:
            self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])
        except:
            print("error in setting digital attenuator")
        self.readout.set_frequency(self.cfg['readout']['frequency'])
        self.readout_shifter.set_phase((self.cfg['readout']['start_phase'])%360, self.cfg['readout']['frequency'])

        self.drive.set_output(True)
        self.drive.set_power(self.cfg['drive']['power'])
        self.drive.set_ext_pulse(mod=False)

        try:
            self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'],self.cfg[self.expt_cfg_name]['iq_offsets'])
        except:
            print("error in setting awg")

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

        for freq in self.expt_pts:
            self.drive.set_frequency(freq)

            expt_data_ch1 = None
            expt_data_ch2 = None
            expt_data_mag = 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()

                mag = sqrt(ch1_pts ** 2 + ch2_pts ** 2)

                if expt_data_ch1 is None:
                    expt_data_ch1 = ch1_pts
                    expt_data_ch2 = ch2_pts
                else:
                    expt_data_ch1 = (expt_data_ch1 * ii + ch1_pts) / (ii + 1.0)
                    expt_data_ch2 = (expt_data_ch2 * ii + ch2_pts) / (ii + 1.0)
            expt_mag = sqrt(expt_data_ch1 ** 2 + expt_data_ch2 ** 2)

            if self.liveplot_enabled:
                self.plotter.append_xy('readout_avg_freq_scan1', freq, mean(expt_data_ch1[0:]))
                self.plotter.append_xy('readout_avg_freq_scan2', freq, mean(expt_data_ch2[0:]))
                self.plotter.append_xy('readout_avg_freq_scan_mag', freq, mean(expt_mag[0:]))
                self.plotter.append_z('scope1', expt_data_ch1)
                self.plotter.append_z('scope2', expt_data_ch2)
                self.plotter.append_z('scope_mag', expt_mag)

            with self.datafile() as f:
                f.append_pt('freq', freq)
                f.append_pt('ch1_mean', mean(expt_data_ch1[0:]))
                f.append_pt('ch2_mean', mean(expt_data_ch2[0:]))
                f.append_pt('mag_mean', mean(expt_mag[0:]))
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
Example #3
0
    def go(self):
        self.plotter.clear()

        print("Prep Instruments")
        self.readout.set_output(True)
        self.readout.set_power(self.cfg['readout']['power'])
        if (self.cfg[self.expt_cfg_name]['pulsed']):
            self.readout.set_ext_pulse(mod=True)
        else:
            self.readout.set_ext_pulse(mod=False)

        if (self.cfg[self.expt_cfg_name]['pi_pulse']):
            self.drive.set_output(True)
            self.drive.set_ext_pulse(mod=True)
        else:
            self.drive.set_output(False)
            self.drive.set_ext_pulse(mod=False)

        # self.drive.set_ext_pulse(mod=False)
        self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])

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

        self.awg.run()

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

        for freq in self.expt_pts:
            self.readout.set_frequency(freq)
            self.readout_shifter.set_phase(
                (self.cfg['readout']['start_phase'] +
                 self.cfg['readout']['phase_slope'] *
                 (freq - self.cfg['readout']['frequency'])) % 360, freq)
            # print self.readout_shifter.get_phase()
            tpts, ch1_pts, ch2_pts = adc.acquire_avg_data()

            mag = sqrt(ch1_pts**2 + ch2_pts**2)

            self.plotter.append_xy('readout_avg_freq_scan1', freq,
                                   mean(ch1_pts[0:]))
            self.plotter.append_xy('readout_avg_freq_scan2', freq,
                                   mean(ch2_pts[0:]))
            self.plotter.append_xy('readout_avg_freq_scan_mag', freq,
                                   mean(mag[0:]))
            self.plotter.append_z('scope1', ch1_pts)
            self.plotter.append_z('scope2', ch2_pts)
            self.plotter.append_z('scope_mag', mag)

            with self.datafile() as f:
                f.append_pt('freq', freq)
                f.append_pt('ch1_mean', mean(ch1_pts[0:]))
                f.append_pt('ch2_mean', mean(ch2_pts[0:]))
                f.append_pt('mag_mean', mean(mag[0:]))
Example #4
0
    def go(self):
        self.plotter.clear()

        print("Prep Instruments")
        self.readout.set_output(True)
        self.readout.set_power(self.cfg['readout']['power'])
        if (self.cfg[self.expt_cfg_name]['pulsed']):
            self.readout.set_ext_pulse(mod=True)
        else:
            self.readout.set_ext_pulse(mod=False)

        if (self.cfg[self.expt_cfg_name]['pi_pulse']):
            self.drive.set_output(True)
            self.drive.set_ext_pulse(mod=True)
        else:
            self.drive.set_output(False)
            self.drive.set_ext_pulse(mod=False)


        # self.drive.set_ext_pulse(mod=False)
        self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])

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

        self.awg.run()

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


        for freq in self.expt_pts:
            self.readout.set_frequency(freq)
            self.readout_shifter.set_phase((self.cfg['readout']['start_phase'] + self.cfg['readout']['phase_slope'] * (freq - self.cfg['readout']['frequency']))%360, freq)
            # print self.readout_shifter.get_phase()
            tpts, ch1_pts, ch2_pts = adc.acquire_avg_data()

            mag = sqrt(ch1_pts**2+ch2_pts**2)

            self.plotter.append_xy('readout_avg_freq_scan1', freq, mean(ch1_pts[0:]))
            self.plotter.append_xy('readout_avg_freq_scan2', freq, mean(ch2_pts[0:]))
            self.plotter.append_xy('readout_avg_freq_scan_mag', freq, mean(mag[0:]))
            self.plotter.append_z('scope1',ch1_pts)
            self.plotter.append_z('scope2',ch2_pts)
            self.plotter.append_z('scope_mag',mag)

            with self.datafile() as f:
                f.append_pt('freq', freq)
                f.append_pt('ch1_mean', mean(ch1_pts[0:]))
                f.append_pt('ch2_mean', mean(ch2_pts[0:]))
                f.append_pt('mag_mean', mean(mag[0:]))
    def go(self):
        self.plotter.clear()

        # self.save_config()

        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']%360, self.cfg['readout']['frequency'])


        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.awg.set_amps_offsets(self.cfg['cal']['iq_amps'], self.cfg['cal']['iq_offsets'])

        self.awg.run()

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

        for freq in self.expt_pts:
            self.drive.set_frequency(freq)

            tpts, ch1_pts, ch2_pts = adc.acquire_avg_data()



            mag = sqrt(ch1_pts**2+ch2_pts**2)

            self.plotter.append_xy('avg_pulse_probe_freq_scan1', freq, mean(ch1_pts[0:]))
            self.plotter.append_xy('avg_pulse_probe_freq_scan2', freq, mean(ch2_pts[0:]))
            self.plotter.append_xy('avg_pulse_probe_freq_mag', freq, mean(mag[0:]))
            self.plotter.append_z('scope1',ch1_pts)
            self.plotter.append_z('scope2',ch2_pts)
            self.plotter.append_z('scope_mag',mag)

            with self.datafile() as f:
                f.append_pt('freq', freq)
                f.append_pt('ch1_mean', mean(ch1_pts[0:]))
                f.append_pt('ch2_mean', mean(ch2_pts[0:]))
                f.append_pt('mag_mean', mean(mag[0:]))
    def go(self):
        self.plotter.clear()

        print "Prep Instruments"
        self.readout.set_output(True)
        self.readout.set_power(self.cfg["readout"]["power"])
        self.readout.set_ext_pulse(mod=False)
        self.readout_atten.set_attenuator(self.cfg["readout"]["dig_atten"])
        self.readout.set_frequency(self.cfg["readout"]["frequency"])
        self.readout_shifter.set_phase((self.cfg["readout"]["start_phase"]) % 360, self.cfg["readout"]["frequency"])

        self.drive.set_output(True)
        self.drive.set_power(self.cfg["drive"]["power"])
        self.drive.set_ext_pulse(mod=False)

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

        print "Prep Card"
        adc = Alazar(self.cfg["alazar"])

        for freq in self.expt_pts:
            self.drive.set_frequency(freq)

            tpts, ch1_pts, ch2_pts = adc.acquire_avg_data()

            mag = sqrt(ch1_pts ** 2 + ch2_pts ** 2)

            self.plotter.append_xy("avg_cw_drive_freq_scan1", freq, mean(ch1_pts[0:]))
            self.plotter.append_xy("avg_cw_drive_freq_scan2", freq, mean(ch2_pts[0:]))
            self.plotter.append_xy("avg_cw_drive_freq_scan_mag", freq, mean(mag[0:]))
            self.plotter.append_z("scope1", ch1_pts)
            self.plotter.append_z("scope2", ch2_pts)
            self.plotter.append_z("scope_mag", mag)

            with self.datafile() as f:
                f.append_pt("freq", freq)
                f.append_pt("ch1_mean", mean(ch1_pts[0:]))
                f.append_pt("ch2_mean", mean(ch2_pts[0:]))
                f.append_pt("mag_mean", mean(mag[0:]))
Example #7
0
    def go(self):
        # if self.liveplot_enabled:
        #     self.plotter.clear()

        print("Prep Instruments")

        try:
            self.readout.set_frequency(self.readout_freq)
            self.readout.set_power(self.cfg['readout']['power'])
            self.readout.set_ext_pulse(mod=True)
            self.readout.set_output(True)
        except:
            print("No readout found.")

        try:
            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'])
        except:
            print("Digital phase shifter not loaded.")

        try:
            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=False)
            self.drive.set_output(True)
        except:
            print("No drive found")

        try:
            self.flux_drive.set_frequency(
                self.cfg['sidebands']['blue'] +
                self.cfg['flux_pulse_info'][self.pulse_type]['iq_freq'])
            self.flux_drive.set_power(self.cfg['drive']['power'])
            self.flux_drive.set_ext_pulse(mod=False)
            self.flux_drive.set_output(False)
        except:
            print("No flux drive found")

        try:
            self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])
        except:
            print("Digital attenuator not loaded.")

        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

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

        except:
            print("Voltage source not loaded.")

        try:
            self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'],
                                      self.cfg['cal']['iq_offsets'])
        except:
            print("self.awg not loaded.")

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

        # What is this for?
        TEST_REDPITAYA = False

        if TEST_REDPITAYA:
            self.awg_run()

        if not TEST_REDPITAYA:

            if self.cfg['readout']['adc'] == 'redpitaya':
                print("Using Red Pitaya ADC")

                if not self.cfg[self.expt_cfg_name]['use_pi_calibration']:
                    num_experiments = len(self.pulse_sequence.expt_pts)
                else:
                    num_experiments = len(self.pulse_sequence.expt_pts) + 2

                testing_redpitaya = False

                if not testing_redpitaya:
                    expt_avg_data_raw1, expt_avg_data_raw2 = setup_redpitaya_adc(
                        num_experiments=num_experiments,
                        window=self.cfg['readout']['window'],
                        shots=self.cfg[self.expt_cfg_name]['averages'],
                        plot_data=self.cfg['readout']['plot'],
                        start_function=self.awg_run,
                        stop_function=self.awg_prep)
                    if self.cfg['readout']['channel'] == 1:
                        expt_avg_data_raw = expt_avg_data_raw1
                    else:
                        expt_avg_data_raw = expt_avg_data_raw2

                ## This is for testing the redpitaya behaviour
                if testing_redpitaya:
                    correct_counter = 0
                    repeat = 100
                    for ii in range(repeat):
                        expt_avg_data_raw = setup_redpitaya_adc(
                            num_experiments=num_experiments,
                            window=self.cfg['readout']['window'],
                            shots=self.cfg[self.expt_cfg_name]['averages'],
                            plot_data=False,
                            start_function=self.awg_run,
                            stop_function=self.awg_prep())
                        if ((expt_avg_data_raw[1:] - expt_avg_data_raw[:-1]) >
                                0).all():
                            correct_counter += 1

                    print("correct percent: " +
                          str(correct_counter / float(repeat)))

                if self.cfg[self.expt_cfg_name]['use_pi_calibration']:
                    zero_amp = expt_avg_data_raw[-2]
                    pi_amp = expt_avg_data_raw[-1]
                    expt_avg_data = (expt_avg_data_raw[:-2] -
                                     zero_amp) / (pi_amp - zero_amp)

                    # #saves pi calibration data
                    # expt_avg_data = expt_avg_data_raw
                else:
                    expt_avg_data = expt_avg_data_raw

                print(shape(expt_avg_data))
                expt_avg_data = expt_avg_data.flatten()
                print(shape(expt_avg_data))

                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()

                else:
                    self.slab_file = self.datafile()

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

            else:
                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'])

                    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)

                    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 = SlabFile(self.data_file)
                else:
                    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 self.post_run is not None:
                self.post_run(self.expt_pts, expt_avg_data)
Example #8
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 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()
Example #10
0
    def go(self):
        # self.plotter.clear()

        print("Prep Instruments")
        self.readout.set_output(True)
        self.readout.set_power(self.cfg['readout']['power'])
        if (self.cfg[self.expt_cfg_name]['pulsed']):
            self.readout.set_ext_pulse(mod=True)
        else:
            self.readout.set_ext_pulse(mod=False)

        if (self.cfg[self.expt_cfg_name]['pi_pulse']):
            self.drive.set_output(True)
            self.drive.set_ext_pulse(mod=True)
        else:
            self.drive.set_output(False)
            self.drive.set_ext_pulse(mod=False)

        # self.drive.set_ext_pulse(mod=False)
        self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])

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

        self.awg.run()

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

        self.tek2 = InstrumentManager()["TEK2"]

        self.slab_file = self.datafile()
        with self.slab_file as f:
            f.append_line('expt_pts', self.expt_pts)
            f.close()

        for freq in self.expt_pts:
            self.readout.set_frequency(freq)
            self.readout_shifter.set_phase(
                (self.cfg['readout']['start_phase'] +
                 self.cfg['readout']['phase_slope'] *
                 (freq - self.cfg['readout']['frequency'])) % 360, freq)
            # print self.readout_shifter.get_phase()

            ## taking data

            expt_data_1 = None

            expt_data_2 = None

            for ii in tqdm(
                    arange(
                        max(1, self.cfg[self.expt_cfg_name]['averages'] /
                            10000))):
                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'])

                mag = sqrt(ch1_pts**2 + ch2_pts**2)

                if expt_data_1 is None:
                    expt_data_1 = ch1_pts
                    expt_data_2 = ch2_pts
                else:
                    expt_data_1 = (expt_data_1 * ii + ch1_pts) / (ii + 1.0)
                    expt_data_2 = (expt_data_2 * ii + ch2_pts) / (ii + 1.0)

                expt_avg_data_1 = mean(expt_data_1, 1)
                expt_avg_data_2 = mean(expt_data_2, 1)
                # if self.liveplot_enabled:
                #     self.plotter.plot_z(self.prefix + ' Data', expt_data.T)
                #     self.plotter.plot_xy(self.prefix + ' XY', array([0,1]), expt_avg_data)

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

            self.slab_file = self.datafile()
            with self.slab_file as f:
                f.append_line('expt_avg_data_1', expt_avg_data_1)
                f.append_line('expt_avg_data_2', expt_avg_data_2)
                f.close()
Example #11
0
    def go(self):
        if self.liveplot_enabled:
            self.plotter.clear()

        # self.save_config()

        print("Prep Instruments")
        self.readout.set_frequency(self.cfg['readout']['frequency']-self.cfg['readout']['heterodyne_freq'])
        self.readout.set_power(self.cfg['readout']['power'])
        self.readout.set_ext_pulse(mod=self.cfg['readout']['mod'])
        self.readout.set_output(True)
        self.readout_shifter.set_phase(self.cfg['readout']['start_phase']%360, self.cfg['readout']['frequency'])


        self.drive.set_power(self.cfg['drive']['power'])
        self.drive.set_ext_pulse(mod=self.cfg['drive']['mod'])
        self.drive.set_output(True)
        try:
            self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])
        except:
            print("error in setting digital attenuator")

        try:
            self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'], self.cfg['cal']['iq_offsets'])
            self.awg.run()
        except:
            print("error in setting awg")

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

        for freq in self.expt_pts:
            self.drive.set_frequency(freq-self.cfg[self.expt_cfg_name]['iq_freq'])

            expt_data_ch1 = None
            expt_data_ch2 = None
            expt_data_mag = 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()

                mag = sqrt(ch1_pts ** 2 + ch2_pts ** 2)

                if expt_data_ch1 is None:
                    expt_data_ch1 = ch1_pts
                    expt_data_ch2 = ch2_pts
                else:
                    expt_data_ch1 = (expt_data_ch1 * ii + ch1_pts) / (ii + 1.0)
                    expt_data_ch2 = (expt_data_ch2 * ii + ch2_pts) / (ii + 1.0)
            expt_mag = sqrt(expt_data_ch1 ** 2 + expt_data_ch2 ** 2)

            if self.liveplot_enabled:
                self.plotter.append_xy('readout_avg_freq_scan1', freq, mean(expt_data_ch1[0:]))
                self.plotter.append_xy('readout_avg_freq_scan2', freq, mean(expt_data_ch2[0:]))
                self.plotter.append_xy('readout_avg_freq_scan_mag', freq, mean(expt_mag[0:]))
                self.plotter.append_z('scope1', expt_data_ch1)
                self.plotter.append_z('scope2', expt_data_ch2)
                self.plotter.append_z('scope_mag', expt_mag)

            with self.datafile() as f:
                f.append_pt('freq', freq)
                f.append_pt('ch1_mean', mean(expt_data_ch1[0:]))
                f.append_pt('ch2_mean', mean(expt_data_ch2[0:]))
                f.append_pt('mag_mean', mean(expt_mag[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=self.cfg['readout']['mod'])

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

        try:
            self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'], self.cfg['cal']['iq_offsets'])
        except:
            print("self.awg not loaded.")

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

        heterodyne_carrier_freq = self.cfg['readout']['heterodyne_carrier_freq']
        heterodyne_read_freqs = self.cfg['readout']['heterodyne_read_freq']

        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'])
        num_bins = self.cfg[self.expt_cfg_name]['num_bins']

        ss_cos_data_all = zeros((2, len(attenpts), len(freqpts), len(self.expt_pts),
                             self.cfg['alazar']['recordsPerAcquisition'] / len(self.expt_pts))
                            )  # (channel, atten, freq, g/e/(f), average)
        ss_sin_data_all = zeros((2, len(attenpts), len(freqpts), len(self.expt_pts),
                                 self.cfg['alazar']['recordsPerAcquisition'] / len(self.expt_pts))
                                )  # (channel, atten, freq, g/e/(f), average)

        for xx, atten in enumerate(attenpts):
            #self.im.atten.set_attenuator(atten)
            try:
                self.readout_atten.set_attenuator(atten)
            except:
                print("Digital attenuator not loaded.")

            max_contrast_data = zeros((2,len(freqpts)))

            if self.liveplot_enabled:
                self.plotter.clear('max contrast')

            for yy, freq in enumerate(freqpts):
                self.readout.set_frequency(freq-self.cfg['readout']['heterodyne_freq'])
                #self.readout_shifter.set_phase(self.cfg['readout']['start_phase'] , freq)
                self.readout_shifter.set_phase((self.cfg['readout']['start_phase'] + self.cfg['readout']['phase_slope'] * (freq - self.cfg['readout']['frequency']))%360, freq)

                ss_data = zeros((len(self.expt_pts), num_bins))
                sss_data = zeros((len(self.expt_pts), num_bins))

                print("runnning atten no.", xx, ", freq no.", yy)

                single_data1, single_data2, single_record1, single_record2 = \
                    adc.acquire_singleshot_heterodyne_data(self.cfg['readout']['heterodyne_freq'],\
                                                       prep_function=self.awg_prep, start_function=self.awg_run, excise=self.cfg['readout']['window'])

                ss_cos_data_all[0, xx, yy, :, :] = reshape(single_data1[0], (self.cfg['alazar']['recordsPerAcquisition'] / len(self.expt_pts), len(self.expt_pts))).T
                ss_cos_data_all[1, xx, yy, :, :] = reshape(single_data2[0], (self.cfg['alazar']['recordsPerAcquisition'] / len(self.expt_pts), len(self.expt_pts))).T
                ss_sin_data_all[0, xx, yy, :, :] = reshape(single_data1[1], (self.cfg['alazar']['recordsPerAcquisition'] / len(self.expt_pts), len(self.expt_pts))).T
                ss_sin_data_all[1, xx, yy, :, :] = reshape(single_data2[1], (self.cfg['alazar']['recordsPerAcquisition'] / len(self.expt_pts), len(self.expt_pts))).T

                with self.datafile() as f:
                    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.cfg['readout']['heterodyne_freq']==0:
                    # ch1 cos, ch2 cos
                    ss1 = single_data1[0]
                    ss2 = single_data2[0]
                else:
                    # ch1 cos, ch1 sin
                    ss1 = single_data1[0]
                    ss2 = single_data1[1]

                for kk, ssthis in enumerate([ss1, ss2]):

                    ssthis = reshape(ssthis, (self.cfg['alazar']['recordsPerAcquisition'] / len(self.expt_pts), len(self.expt_pts))).T

                    print('ss i/q ch', str(kk+1), 'max/min =', ssthis.max(), ssthis.min())
                    dist = ssthis.max() - ssthis.min()
                    histo_range = (ssthis.min() - 0.01*dist, ssthis.max() + 0.01*dist)

                    for jj, ss in enumerate(ssthis):
                        sshisto, ssbins = np.histogram(ss, bins=num_bins, range=histo_range)
                        ss_data[jj] += sshisto
                        sss_data[jj] = cumsum(ss_data[[jj]])
                        if self.liveplot_enabled:
                            self.plotter.plot_xy('histogram %d' % jj, ssbins[:-1], ss_data[jj])
                            self.plotter.plot_xy('cum histo %d' % jj, ssbins[:-1], sss_data[jj])

                    max_contrast_data[kk, yy] = abs(((sss_data[0] - sss_data[1]) / ss_data[0].sum())).max()

                    if self.liveplot_enabled:
                        self.plotter.plot_xy('contrast_ch' + str(kk+1), ssbins[:-1], abs(sss_data[0] - sss_data[1]) / ss_data[0].sum())
                        self.plotter.append_xy('max contrast_ch' + str(kk+1), freq, max_contrast_data[kk,yy])

            with self.datafile() as f:
                f.append_pt('atten', atten)
                f.add('attenpts', attenpts)
                f.append_line('freq', freqpts)
                f.append_line('max_contrast_data_ch1', max_contrast_data[0, :])
                f.append_line('max_contrast_data_ch2', max_contrast_data[1, :])
                #f.add('single_record1', single_record1)
                f.close()
Example #13
0
    def go(self):
        # self.plotter.clear()

        print("Prep Instruments")
        self.readout.set_output(True)
        self.readout.set_power(self.cfg['readout']['power'])
        if (self.cfg[self.expt_cfg_name]['pulsed']):
            self.readout.set_ext_pulse(mod=True)
        else:
            self.readout.set_ext_pulse(mod=False)

        if (self.cfg[self.expt_cfg_name]['pi_pulse']):
            self.drive.set_output(True)
            self.drive.set_ext_pulse(mod=True)
        else:
            self.drive.set_output(False)
            self.drive.set_ext_pulse(mod=False)


        # self.drive.set_ext_pulse(mod=False)
        self.trigger_period = self.cfg['expt_trigger']['period']
        self.trigger.set_period(self.trigger_period)
        self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])

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

        self.awg.run()

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


        for freq in self.expt_pts:
            self.readout.set_frequency(freq)
            # self.readout_shifter.set_phase((self.cfg['readout']['start_phase'] + self.cfg['readout']['phase_slope'] * (freq - self.cfg['readout']['frequency']))%360, freq)
            # print self.readout_shifter.get_phase()
            tpts, ch1_pts, ch2_pts = adc.acquire_avg_data()

            expt_data_ch1 = None
            expt_data_ch2 = None
            expt_data_mag = 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()

                mag = sqrt(ch1_pts ** 2 + ch2_pts ** 2)


                if expt_data_ch1 is None:
                    expt_data_ch1 = ch1_pts
                    expt_data_ch2 = ch2_pts
                else:
                    expt_data_ch1 = (expt_data_ch1 * ii + ch1_pts) / (ii + 1.0)
                    expt_data_ch2 = (expt_data_ch2 * ii + ch2_pts) / (ii + 1.0)
            expt_mag = sqrt(expt_data_ch1 ** 2 + expt_data_ch2 ** 2)


            # self.plotter.append_xy('readout_avg_freq_scan1', freq, mean(ch1_pts[0:]))
            # self.plotter.append_xy('readout_avg_freq_scan2', freq, mean(ch2_pts[0:]))
            # self.plotter.append_xy('readout_avg_freq_scan_mag', freq, mean(mag[0:]))
            # self.plotter.append_z('scope1',ch1_pts)
            # self.plotter.append_z('scope2',ch2_pts)
            # self.plotter.append_z('scope_mag',mag)

            with self.datafile() as f:
                f.append_pt('freq', freq)
                f.append_pt('ch1_mean', mean(expt_data_ch1[0:]))
                f.append_pt('ch2_mean', mean(expt_data_ch2[0:]))
                f.append_pt('mag_mean', mean(expt_mag[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 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 go(self):
        # self.plotter.clear()

        print("Prep Instruments")
        self.readout.set_output(True)
        self.readout.set_power(self.cfg['readout']['power'])
        if (self.cfg[self.expt_cfg_name]['pulsed']):
            self.readout.set_ext_pulse(mod=True)
        else:
            self.readout.set_ext_pulse(mod=False)

        if (self.cfg[self.expt_cfg_name]['pi_pulse']):
            self.drive.set_output(True)
            self.drive.set_ext_pulse(mod=True)
        else:
            self.drive.set_output(False)
            self.drive.set_ext_pulse(mod=False)


        # self.drive.set_ext_pulse(mod=False)
        self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])

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

        self.awg.run()

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

        self.tek2 = InstrumentManager()["TEK2"]


        self.slab_file = self.datafile()
        with self.slab_file as f:
            f.append_line('expt_pts', self.expt_pts)
            f.close()

        for freq in self.expt_pts:
            self.readout.set_frequency(freq)
            self.readout_shifter.set_phase((self.cfg['readout']['start_phase'] + self.cfg['readout']['phase_slope'] * (freq - self.cfg['readout']['frequency']))%360, freq)
            # print self.readout_shifter.get_phase()

            ## taking data

            expt_data_1 = None

            expt_data_2 = None

            for ii in tqdm(arange(max(1, self.cfg[self.expt_cfg_name]['averages'] / 10000))):
                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'])

                mag = sqrt(ch1_pts**2+ch2_pts**2)

                if expt_data_1 is None:
                    expt_data_1 = ch1_pts
                    expt_data_2 = ch2_pts
                else:
                    expt_data_1 = (expt_data_1 * ii + ch1_pts) / (ii + 1.0)
                    expt_data_2 = (expt_data_2 * ii + ch2_pts) / (ii + 1.0)



                expt_avg_data_1 = mean(expt_data_1, 1)
                expt_avg_data_2 = mean(expt_data_2, 1)
                # if self.liveplot_enabled:
                #     self.plotter.plot_z(self.prefix + ' Data', expt_data.T)
                #     self.plotter.plot_xy(self.prefix + ' XY', array([0,1]), expt_avg_data)

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


            self.slab_file = self.datafile()
            with self.slab_file as f:
                f.append_line('expt_avg_data_1', expt_avg_data_1)
                f.append_line('expt_avg_data_2', expt_avg_data_2)
                f.close()
Example #17
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.drive.set_frequency(
            self.cfg['qubit']['frequency'] -
            self.cfg['pulse_info'][self.pulse_type]['iq_freq'])
        self.drive.set_power(self.cfg[self.expt_cfg_name]['power'])
        self.drive.set_ext_pulse(mod=False)
        self.drive.set_output(True)

        try:
            self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'],
                                      self.cfg['cal']['iq_offsets'])
        except:
            print("self.awg not loaded.")

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

        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'])
        num_bins = self.cfg[self.expt_cfg_name]['num_bins']

        for xx, atten in enumerate(attenpts):
            #self.im.atten.set_attenuator(atten)
            try:
                self.readout_atten.set_attenuator(atten)
            except:
                print("Digital attenuator not loaded.")

            max_contrast_data = zeros(len(freqpts))

            if self.liveplot_enabled:
                self.plotter.clear('max contrast')

            for yy, freq in enumerate(freqpts):
                self.readout.set_frequency(freq)
                #self.readout_shifter.set_phase(self.cfg['readout']['start_phase'] , freq)
                self.readout_shifter.set_phase(
                    (self.cfg['readout']['start_phase'] +
                     self.cfg['readout']['phase_slope'] *
                     (freq - self.cfg['readout']['frequency'])) % 360, freq)

                #tpts, ch1_pts, ch2_pts = adc.acquire_avg_data_by_record(prep_function=self.awg.stop_and_prep, start_function=self.awg.run,excise=None)

                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 self.liveplot_enabled:
                    self.plotter.plot_z("current", ch1_pts)

                # with self.datafile() as f:
                #     f.append('time_trace', ch1_pts)
                ss_data = zeros((len(self.expt_pts), num_bins))
                sss_data = zeros((len(self.expt_pts), num_bins))

                # ss1, ss2 = adc.acquire_singleshot_data(prep_function=None, start_function=None,
                #                                        excise=self.cfg['readout']['window'])
                ss1, ss2 = adc.acquire_singleshot_data(
                    prep_function=self.awg_prep,
                    start_function=self.awg_run,
                    excise=self.cfg['readout']['window'])

                ss1 = reshape(ss1,
                              (self.cfg['alazar']['recordsPerAcquisition'] /
                               len(self.expt_pts), len(self.expt_pts))).T
                histo_range = (ss1.min() / 1.5, ss1.max() * 1.5)
                for jj, ss in enumerate(ss1):
                    sshisto, ssbins = np.histogram(ss,
                                                   bins=num_bins,
                                                   range=histo_range)
                    ss_data[jj] += sshisto
                    sss_data[jj] = cumsum(ss_data[[jj]])
                    if self.liveplot_enabled:
                        self.plotter.plot_xy('histogram %d' % jj, ssbins[:-1],
                                             ss_data[jj])
                        self.plotter.plot_xy('cum histo %d' % jj, ssbins[:-1],
                                             sss_data[jj])

                if self.liveplot_enabled:
                    self.plotter.plot_xy(
                        'contrast', ssbins[:-1],
                        abs(sss_data[0] - sss_data[1]) / ss_data[0].sum())
                max_contrast_data[yy] = abs(
                    ((sss_data[0] - sss_data[1]) / ss_data[0].sum())).max()
                if self.liveplot_enabled:
                    self.plotter.append_xy('max contrast', freq,
                                           max_contrast_data[yy])
            if len(attenpts) > 1:
                if self.liveplot_enabled:
                    print("plotting max contrast 2")
                    self.plotter.append_z(
                        'max contrast 2',
                        max_contrast_data,
                        start_step=((attenpts[0], attenpts[1] - attenpts[0]),
                                    (freqpts[0] / 1.0e9,
                                     (freqpts[1] - freqpts[0]) / 1.0e9)))

            with self.datafile() as f:
                f.append_pt('atten', atten)
                f.append_line('freq', freqpts)
                f.append_line('max_contrast_data', max_contrast_data)
                f.close()
    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)
Example #19
0
    def go(self):

        if self.liveplot_enabled:
            self.plotter.clear()

        print("Prep Instruments")
        self.readout.set_output(True)
        self.readout.set_power(self.cfg['readout']['power'])
        if (self.cfg[self.expt_cfg_name]['pulsed']):
            self.readout.set_ext_pulse(mod=True)
        else:
            self.readout.set_ext_pulse(mod=False)

        if (self.cfg[self.expt_cfg_name]['pi_pulse']):
            self.drive.set_output(True)
            self.drive.set_ext_pulse(mod=False)
        else:
            self.drive.set_output(False)
            self.drive.set_ext_pulse(mod=False)


        # self.drive.set_output(True)
        # self.drive.set_ext_pulse(mod=False)
        # # self.drive.set_ext_pulse(mod=False)

        try:
            self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])
        except:
            print("Error in setting digital attenuator.")

        try:
            self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'], self.cfg['cal']['iq_offsets'])
            self.awg.run()
        except:
            print("error in setting self.awg")




        for freq in self.expt_pts:
            self.readout.set_frequency(freq)
            self.readout_shifter.set_phase((self.cfg['readout']['start_phase'] + self.cfg['readout']['phase_slope'] * (freq - self.cfg['readout']['frequency']))%360, freq)
            print(self.readout_shifter.get_phase())

            expt_data_ch1 = None
            expt_data_ch2 = None
            expt_data_mag = None

            if self.cfg['readout']['adc'] == 'redpitaya':
                num_experiments = 1
                ch1_pts, ch2_pts = setup_redpitaya_adc(num_experiments=num_experiments,
                                                       window=self.cfg['readout']['window'],
                                                       shots=self.cfg[self.expt_cfg_name][
                                                           'averages'],
                                                       plot_data=False,
                                                       start_function=self.awg_run,
                                                       stop_function=self.awg_prep)

                with self.datafile() as f:
                    f.append_pt('freq', freq)
                    f.append_pt('ch1_mean', ch1_pts)
                    f.append_pt('ch2_mean', ch2_pts)

            else:
                print("Prep Card")
                adc = Alazar(self.cfg['alazar'])
                for ii in tqdm(arange(max(1, self.cfg[self.expt_cfg_name]['averages'] / 100))):



                    tpts, ch1_pts, ch2_pts = adc.acquire_avg_data()

                    mag = sqrt(ch1_pts ** 2 + ch2_pts ** 2)


                    if expt_data_ch1 is None:
                        expt_data_ch1 = ch1_pts
                        expt_data_ch2 = ch2_pts
                    else:
                        expt_data_ch1 = (expt_data_ch1 * ii + ch1_pts) / (ii + 1.0)
                        expt_data_ch2 = (expt_data_ch2 * ii + ch2_pts) / (ii + 1.0)
                expt_mag = sqrt(expt_data_ch1 ** 2 + expt_data_ch2 ** 2)

                if self.liveplot_enabled:
                    self.plotter.append_xy('readout_avg_freq_scan1', freq, mean(expt_data_ch1[0:]))
                    self.plotter.append_xy('readout_avg_freq_scan2', freq, mean(expt_data_ch2[0:]))
                    self.plotter.append_xy('readout_avg_freq_scan_mag', freq, mean(expt_mag[0:]))
                    self.plotter.append_z('scope1',expt_data_ch1)
                    self.plotter.append_z('scope2',expt_data_ch2)
                    self.plotter.append_z('scope_mag',expt_mag)

                with self.datafile() as f:
                    f.append_pt('freq', freq)
                    f.append_pt('ch1_mean', mean(expt_data_ch1[0:]))
                    f.append_pt('ch2_mean', mean(expt_data_ch2[0:]))
                    f.append_pt('mag_mean', mean(expt_mag[0:]))


                print(cfg['readout']['start_phase'])
Example #20
0
    def run_vary_twpa(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=self.cfg['readout']['mod'])
        self.readout.set_output(True)

        self.readout_shifter.set_phase(self.cfg['readout']['start_phase'],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[self.expt_cfg_name]['power'])
        self.drive.set_ext_pulse(mod=self.cfg['drive']['mod'])
        self.drive.set_output(True)

        try:
            self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'], self.cfg['cal']['iq_offsets'])
        except:
            print("self.awg not loaded.")

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

        attenpts = arange(self.cfg[self.expt_cfg_name]['twpa_pow_start'], self.cfg[self.expt_cfg_name]['twpa_pow_stop'],
                          self.cfg[self.expt_cfg_name]['twpa_pow_step'])
        freqpts = arange(self.cfg[self.expt_cfg_name]['twpa_freq_start'], self.cfg[self.expt_cfg_name]['twpa_freq_stop'],
                         self.cfg[self.expt_cfg_name]['twpa_freq_step'])
        num_bins = self.cfg[self.expt_cfg_name]['num_bins']

        ss_data_all = zeros((2, len(attenpts), len(freqpts), len(self.expt_pts),
                             self.cfg['alazar']['recordsPerAcquisition'] / len(self.expt_pts))
                            )  # (channel, atten, freq, g/e(/f), average)

        for xx, atten in enumerate(attenpts):

            # twpa pump
            self.twpa_pump.set_power(atten)
            self.twpa_pump.set_ext_pulse(mod=False)

            max_contrast_data = zeros((2, len(freqpts)))  # (chn, freq)
            max_contrast_data_ef = zeros((2, len(freqpts)))  # (chn, freq)

            if self.liveplot_enabled:
                self.plotter.clear('max contrast')

            for yy, freq in enumerate(freqpts):

                # twpa pump
                self.twpa_pump.set_frequency(freq)
                self.twpa_pump.set_output(True)

                ss_data = zeros((len(self.expt_pts), num_bins))
                sss_data = zeros((len(self.expt_pts), num_bins))

                print("runnning atten no.", xx, ", freq no.", yy)

                ss1, ss2 = adc.acquire_singleshot_data(prep_function=self.awg_prep, start_function=self.awg_run,
                                                       excise=self.cfg['readout']['window'])

                for kk, ssthis in enumerate([ss1, ss2]):

                    ssthis = reshape(ssthis, (
                    self.cfg['alazar']['recordsPerAcquisition'] / len(self.expt_pts), len(self.expt_pts))).T
                    ss_data_all[kk, xx, yy, :, :] = ssthis

                    print('ss ch', str(kk + 1), 'max/min =', ssthis.max(), ssthis.min())
                    dist = ssthis.max() - ssthis.min()
                    histo_range = (ssthis.min() - 0.01 * dist, ssthis.max() + 0.01 * dist)

                    for jj, ss in enumerate(ssthis):
                        sshisto, ssbins = np.histogram(ss, bins=num_bins, range=histo_range)
                        ss_data[jj] += sshisto
                        sss_data[jj] = cumsum(ss_data[[jj]])
                        if self.liveplot_enabled:
                            self.plotter.plot_xy('histogram %d' % jj, ssbins[:-1], ss_data[jj])
                            self.plotter.plot_xy('cum histo %d' % jj, ssbins[:-1], sss_data[jj])

                    max_contrast_data[kk, yy] = abs(((sss_data[0] - sss_data[1]) / ss_data[0].sum())).max()

                    if len(self.expt_pts) > 2:
                        max_contrast_data_ef[kk, yy] = abs(((sss_data[1] - sss_data[2]) / ss_data[1].sum())).max()

                    if self.liveplot_enabled:
                        self.plotter.plot_xy('contrast_ch' + str(kk + 1), ssbins[:-1],
                                             abs(sss_data[0] - sss_data[1]) / ss_data[0].sum())
                        self.plotter.append_xy('max contrast_ch' + str(kk + 1), freq, max_contrast_data[kk, yy])

            # initialize datafile by kwarg data_file
            # self.slab_file = self.datafile(data_file=self.data_file)

            self.slab_file = self.datafile()

            with self.slab_file as f:
                f.append_pt('atten', atten)
                f.add('attenpts', attenpts)
                f.append_line('freq', freqpts)
                f.append_line('max_contrast_data_ch1', max_contrast_data[0, :])
                f.append_line('max_contrast_data_ch2', max_contrast_data[1, :])

                if len(self.expt_pts) > 2:
                    f.append_line('max_contrast_data_ef_ch1', max_contrast_data_ef[0, :])
                    f.append_line('max_contrast_data_ef_ch2', max_contrast_data_ef[1, :])

                f.add('ss_data_ch1', ss_data_all[0])
                f.add('ss_data_ch2', ss_data_all[1])

                f.close()
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 go(self):
        # if self.liveplot_enabled:
        #     self.plotter.clear()

        print("Prep Instruments")

        try:
            self.readout.set_frequency(self.readout_freq)
            self.readout.set_power(self.cfg['readout']['power'])
            self.readout.set_ext_pulse(mod=True)
            self.readout.set_output(True)
        except:
            print("No readout found.")

        try:
            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'])
        except:
            print("Digital phase shifter not loaded.")

        try:
            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=False)
            self.drive.set_output(True)
        except:
            print("No drive found")

        try:
            self.flux_drive.set_frequency(self.cfg['sidebands']['blue'] + self.cfg['flux_pulse_info'][self.pulse_type]['iq_freq'])
            self.flux_drive.set_power(self.cfg['drive']['power'])
            self.flux_drive.set_ext_pulse(mod=False)
            self.flux_drive.set_output(False)
        except:
            print("No flux drive found")

        try:
            self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])
        except:
            print("Digital attenuator not loaded.")

        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


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

        except:
            print("Voltage source not loaded.")

        try:
            self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'], self.cfg['cal']['iq_offsets'])
        except:
            print("self.awg not loaded.")

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

        # What is this for?
        TEST_REDPITAYA = False

        if TEST_REDPITAYA:
            self.awg_run()


        if not TEST_REDPITAYA:

            if self.cfg['readout']['adc'] == 'redpitaya':
                print("Using Red Pitaya ADC")

                if not self.cfg[self.expt_cfg_name]['use_pi_calibration']:
                    num_experiments = len(self.pulse_sequence.expt_pts)
                else:
                    num_experiments = len(self.pulse_sequence.expt_pts) + 2

                testing_redpitaya = False

                if not testing_redpitaya:
                    expt_avg_data_raw1, expt_avg_data_raw2 = setup_redpitaya_adc(num_experiments=num_experiments,
                                                            window=self.cfg['readout']['window'],
                                                            shots=self.cfg[self.expt_cfg_name]['averages'],
                                                            plot_data=self.cfg['readout']['plot'],start_function=self.awg_run,stop_function=self.awg_prep)
                    if self.cfg['readout']['channel'] == 1:
                        expt_avg_data_raw = expt_avg_data_raw1
                    else:
                        expt_avg_data_raw = expt_avg_data_raw2

                ## This is for testing the redpitaya behaviour
                if testing_redpitaya:
                    correct_counter = 0
                    repeat = 100
                    for ii in range(repeat):
                        expt_avg_data_raw = setup_redpitaya_adc(num_experiments=num_experiments,
                                                                window=self.cfg['readout']['window'],
                                                                shots=self.cfg[self.expt_cfg_name]['averages'],
                                                                plot_data=False,start_function=self.awg_run,stop_function=self.awg_prep())
                        if ((expt_avg_data_raw[1:] - expt_avg_data_raw[:-1]) > 0).all():
                            correct_counter += 1

                    print("correct percent: " + str(correct_counter / float(repeat)))

                if self.cfg[self.expt_cfg_name]['use_pi_calibration']:
                    zero_amp = expt_avg_data_raw[-2]
                    pi_amp = expt_avg_data_raw[-1]
                    expt_avg_data = (expt_avg_data_raw[:-2] - zero_amp) / (pi_amp - zero_amp)

                    # #saves pi calibration data
                    # expt_avg_data = expt_avg_data_raw
                else:
                    expt_avg_data = expt_avg_data_raw

                print(shape(expt_avg_data))
                expt_avg_data = expt_avg_data.flatten()
                print(shape(expt_avg_data))

                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()

                else:
                    self.slab_file = self.datafile()

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

            else:
                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'])

                    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)


                    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 = SlabFile(self.data_file)
                else:
                    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 self.post_run is not None:
                self.post_run(self.expt_pts, expt_avg_data)
Example #23
0
import json
from slab.instruments.Alazar import Alazar

flux_freq_pts = arange(2.515, 3.0, 0.001)

path = r"S:\_Data\150716 - 2D multimode (Chip 1)\data"
prefix = 'MM_Flux_Sideband_Rabi_Freq_Sweep_3_'
data_file = os.path.join(path, get_next_filename(path, prefix, suffix='.h5'))
config_file = os.path.join(path, "..\\config" + ".json")
with open(config_file, 'r') as fid:
    cfg_str = fid.read()

cfg = AttrDict(json.loads(cfg_str))

print("Prep Card")
adc = Alazar(cfg['alazar'])

for ii, flux_freq in enumerate(flux_freq_pts):

    mm_flux_sideband_rabi_freq_sweep = MultimodeFluxSideBandFreqSweepExperiment3(
        path=path,
        prefix=prefix,
        config_file='..\\config.json',
        flux_freq=flux_freq,
        data_file=data_file)
    # if ii == 0:
    #     mm_flux_sideband_rabi_freq_sweep.plotter.clear()
    if mm_flux_sideband_rabi_freq_sweep.ready_to_go:
        mm_flux_sideband_rabi_freq_sweep.go(adc=adc)

    mm_flux_sideband_rabi_freq_sweep = None
Example #24
0
    def go(self):
        #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.drive.set_frequency(self.cfg['qubit']['frequency'] - self.cfg['pulse_info'][self.pulse_type]['iq_freq'])
        self.drive.set_power(self.cfg[self.expt_cfg_name]['power'])
        self.drive.set_ext_pulse(mod=True)
        self.drive.set_output(True)

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

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

        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'])
        num_bins = self.cfg[self.expt_cfg_name]['num_bins']

        for xx, atten in enumerate(attenpts):
            self.im.atten.set_attenuator(atten)
            max_contrast_data_ch1 = zeros(len(freqpts))
            max_contrast_data_ch2 = zeros(len(freqpts))
            #self.plotter.clear('max contrast')

            print("atten at: %s" %atten)

            for yy, freq in enumerate(freqpts):
                self.readout.set_frequency(freq)
                #self.readout_shifter.set_phase(self.cfg['readout']['start_phase'] , freq)
                # self.readout_shifter.set_phase((self.cfg['readout']['start_phase'] + self.cfg['readout']['phase_slope'] * (freq - self.cfg['readout']['frequency']))%360, freq)
                tpts, ch1_pts, ch2_pts = adc.acquire_avg_data_by_record(prep_function=self.awg.stop_and_prep, start_function=self.awg.run,excise=self.cfg['readout']['window'])
                # self.plotter.plot_z("current",ch1_pts)
                # with self.datafile() as f:
                #     f.append('time_trace', ch1_pts)
                ss_data = zeros((len(self.expt_pts), num_bins))
                sss_data = zeros((len(self.expt_pts), num_bins))

                ss1, ss2 = adc.acquire_singleshot_data(prep_function=self.awg.stop_and_prep, start_function=self.awg.run,
                                                       excise=self.cfg['readout']['window'])

                #with self.datafile() as f:
                #    f.append_line('ss1', ss1)
                #    f.append_line('ss2', ss2)


                ss1 = reshape(ss1, (int(self.cfg['alazar']['recordsPerAcquisition'] / len(self.expt_pts)), len(self.expt_pts))).T
                histo_range = (ss1.min() / 1.05, ss1.max() * 1.05)
                for jj, ss in enumerate(ss1):
                    sshisto, ssbins = np.histogram(ss, bins=num_bins, range=histo_range)
                    ss_data[jj] += sshisto
                    sss_data[jj] = cumsum(ss_data[[jj]])
                #     self.plotter.plot_xy('histogram %d' % jj, ssbins[:-1], ss_data[jj])
                #     self.plotter.plot_xy('cum histo %d' % jj, ssbins[:-1], sss_data[jj])

                max_contrast_data_ch1[yy] = abs(((sss_data[0] - sss_data[1]) / ss_data[0].sum())).max()

                ss2 = reshape(ss2, (int(self.cfg['alazar']['recordsPerAcquisition'] / len(self.expt_pts)), len(self.expt_pts))).T
                histo_range = (ss2.min() / 1.05, ss2.max() * 1.05)
                for jj, ss in enumerate(ss2):
                    sshisto, ssbins = np.histogram(ss, bins=num_bins, range=histo_range)
                    ss_data[jj] += sshisto
                    sss_data[jj] = cumsum(ss_data[[jj]])
                    #self.plotter.plot_xy('histogram %d' % jj, ssbins[:-1], ss_data[jj])
                    #self.plotter.plot_xy('cum histo %d' % jj, ssbins[:-1], sss_data[jj])

                #self.plotter.plot_xy('contrast', ssbins[:-1], abs(sss_data[0] - sss_data[1]) / ss_data[0].sum())
                max_contrast_data_ch2[yy] = abs(((sss_data[0] - sss_data[1]) / ss_data[0].sum())).max()
                #self.plotter.append_xy('max contrast', freq, max_contrast_data[yy])
            if len(attenpts)>1:
                print("plotting max contrast 2")
                pass
                # self.plotter.append_z('max contrast 2', max_contrast_data, start_step=(
                #  (attenpts[0], attenpts[1] - attenpts[0]),(freqpts[0] / 1.0e9, (freqpts[1] - freqpts[0]) / 1.0e9)))
            with self.datafile() as f:
                f.append_pt('atten', atten)
                f.append_line('freq', freqpts)
                f.append_line('max_contrast_data_ch1', max_contrast_data_ch1)
                f.append_line('max_contrast_data_ch2', max_contrast_data_ch2)
Example #25
0
    def go(self):

        if self.liveplot_enabled:
            self.plotter.clear()

        print("Prep Instruments")
        self.readout.set_output(True)
        self.readout.set_power(self.cfg['readout']['power'])
        if (self.cfg[self.expt_cfg_name]['pulsed']):
            self.readout.set_ext_pulse(mod=True)
        else:
            self.readout.set_ext_pulse(mod=False)

        try:
            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=self.cfg['drive']['mod'])

            if (self.cfg[self.expt_cfg_name]['pi_pulse']):
                self.drive.set_output(True)
            else:
                self.drive.set_output(False)
            print("Drive set successfully..")

        except:
            print("No drive found")

        self.drive.set_ext_pulse(mod=False)

        try:
            self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])
        except:
            print("Error in setting digital attenuator.")

        try:
            self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'],
                                      self.cfg['cal']['iq_offsets'])
            self.awg.run()
        except:
            print("error in setting self.awg")

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

        for freq in self.expt_pts:
            self.readout.set_frequency(freq -
                                       self.cfg['readout']['heterodyne_freq'])
            self.readout_shifter.set_phase(
                (self.cfg['readout']['start_phase'] +
                 self.cfg['readout']['phase_slope'] *
                 (freq - self.cfg['readout']['frequency'])) % 360, freq)
            # print self.readout_shifter.get_phase()

            expt_data_ch1 = None
            expt_data_ch2 = None
            expt_data_mag = 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()

                mag = sqrt(ch1_pts**2 + ch2_pts**2)

                if expt_data_ch1 is None:
                    expt_data_ch1 = ch1_pts
                    expt_data_ch2 = ch2_pts
                else:
                    expt_data_ch1 = (expt_data_ch1 * ii + ch1_pts) / (ii + 1.0)
                    expt_data_ch2 = (expt_data_ch2 * ii + ch2_pts) / (ii + 1.0)
            expt_mag = sqrt(expt_data_ch1**2 + expt_data_ch2**2)

            # todo: fix heterodyne - need to take cos/sin of one channel
            # todo: & excise window

            if self.cfg['readout']['heterodyne_freq'] == 0:
                # homodyne
                mean_ch1 = mean(expt_data_ch1)
                mean_ch2 = mean(expt_data_ch2)
                mean_mag = mean(expt_mag)
            else:
                # heterodyne
                heterodyne_freq = self.cfg['readout']['heterodyne_freq']
                # ifft by numpy default has the correct 1/N normalization
                fft_ch1 = np.abs(np.fft.ifft(expt_data_ch1))
                fft_ch2 = np.abs(np.fft.ifft(expt_data_ch2))
                fft_mag = np.abs(np.fft.ifft(expt_mag))

                hetero_f_ind = int(round(heterodyne_freq * tpts.size *
                                         1e-9))  # position in ifft

                # todo: single freq v.s. finite freq window (latter: more robust but noisier and with distortion)
                # expt_avg_data = np.average(expt_data_fft_amp[:, (hetero_f_ind - 1):(hetero_f_ind + 1)], axis=1)
                mean_ch1 = fft_ch1[hetero_f_ind]
                mean_ch2 = fft_ch2[hetero_f_ind]
                mean_mag = fft_mag[hetero_f_ind]

            if self.liveplot_enabled:
                self.plotter.append_xy('readout_avg_freq_scan1', freq,
                                       mean_ch1)
                self.plotter.append_xy('readout_avg_freq_scan2', freq,
                                       mean_ch2)
                self.plotter.append_xy('readout_avg_freq_scan_mag', freq,
                                       mean_mag)
                self.plotter.append_z('scope1', expt_data_ch1)
                self.plotter.append_z('scope2', expt_data_ch2)
                self.plotter.append_z('scope_mag', expt_mag)

            with self.datafile() as f:
                f.append_pt('freq', freq)
                f.append_pt('ch1_mean', mean_ch1)
                f.append_pt('ch2_mean', mean_ch2)
                f.append_pt('mag_mean', mean_mag)
                f.append_line('expt_2d_ch1', expt_data_ch1)
                f.append_line('expt_2d_ch2', expt_data_ch2)
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 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=self.cfg['readout']['mod'])

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

        try:
            self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'],
                                      self.cfg['cal']['iq_offsets'])
        except:
            print("self.awg not loaded.")

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

        heterodyne_carrier_freq = self.cfg['readout'][
            'heterodyne_carrier_freq']
        heterodyne_read_freqs = self.cfg['readout']['heterodyne_read_freq']

        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'])
        num_bins = self.cfg[self.expt_cfg_name]['num_bins']

        ss_cos_data_all = zeros(
            (2, len(attenpts), len(freqpts), len(self.expt_pts),
             self.cfg['alazar']['recordsPerAcquisition'] /
             len(self.expt_pts)))  # (channel, atten, freq, g/e/(f), average)
        ss_sin_data_all = zeros(
            (2, len(attenpts), len(freqpts), len(self.expt_pts),
             self.cfg['alazar']['recordsPerAcquisition'] /
             len(self.expt_pts)))  # (channel, atten, freq, g/e/(f), average)

        for xx, atten in enumerate(attenpts):
            #self.im.atten.set_attenuator(atten)
            try:
                self.readout_atten.set_attenuator(atten)
            except:
                print("Digital attenuator not loaded.")

            max_contrast_data = zeros((2, len(freqpts)))

            if self.liveplot_enabled:
                self.plotter.clear('max contrast')

            for yy, freq in enumerate(freqpts):
                self.readout.set_frequency(
                    freq - self.cfg['readout']['heterodyne_freq'])
                #self.readout_shifter.set_phase(self.cfg['readout']['start_phase'] , freq)
                self.readout_shifter.set_phase(
                    (self.cfg['readout']['start_phase'] +
                     self.cfg['readout']['phase_slope'] *
                     (freq - self.cfg['readout']['frequency'])) % 360, freq)

                ss_data = zeros((len(self.expt_pts), num_bins))
                sss_data = zeros((len(self.expt_pts), num_bins))

                print("runnning atten no.", xx, ", freq no.", yy)

                single_data1, single_data2, single_record1, single_record2 = \
                    adc.acquire_singleshot_heterodyne_data(self.cfg['readout']['heterodyne_freq'],\
                                                       prep_function=self.awg_prep, start_function=self.awg_run, excise=self.cfg['readout']['window'])

                ss_cos_data_all[0, xx, yy, :, :] = reshape(
                    single_data1[0],
                    (self.cfg['alazar']['recordsPerAcquisition'] /
                     len(self.expt_pts), len(self.expt_pts))).T
                ss_cos_data_all[1, xx, yy, :, :] = reshape(
                    single_data2[0],
                    (self.cfg['alazar']['recordsPerAcquisition'] /
                     len(self.expt_pts), len(self.expt_pts))).T
                ss_sin_data_all[0, xx, yy, :, :] = reshape(
                    single_data1[1],
                    (self.cfg['alazar']['recordsPerAcquisition'] /
                     len(self.expt_pts), len(self.expt_pts))).T
                ss_sin_data_all[1, xx, yy, :, :] = reshape(
                    single_data2[1],
                    (self.cfg['alazar']['recordsPerAcquisition'] /
                     len(self.expt_pts), len(self.expt_pts))).T

                with self.datafile() as f:
                    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.cfg['readout']['heterodyne_freq'] == 0:
                    # ch1 cos, ch2 cos
                    ss1 = single_data1[0]
                    ss2 = single_data2[0]
                else:
                    # ch1 cos, ch1 sin
                    ss1 = single_data1[0]
                    ss2 = single_data1[1]

                for kk, ssthis in enumerate([ss1, ss2]):

                    ssthis = reshape(
                        ssthis, (self.cfg['alazar']['recordsPerAcquisition'] /
                                 len(self.expt_pts), len(self.expt_pts))).T

                    print('ss i/q ch', str(kk + 1), 'max/min =', ssthis.max(),
                          ssthis.min())
                    dist = ssthis.max() - ssthis.min()
                    histo_range = (ssthis.min() - 0.01 * dist,
                                   ssthis.max() + 0.01 * dist)

                    for jj, ss in enumerate(ssthis):
                        sshisto, ssbins = np.histogram(ss,
                                                       bins=num_bins,
                                                       range=histo_range)
                        ss_data[jj] += sshisto
                        sss_data[jj] = cumsum(ss_data[[jj]])
                        if self.liveplot_enabled:
                            self.plotter.plot_xy('histogram %d' % jj,
                                                 ssbins[:-1], ss_data[jj])
                            self.plotter.plot_xy('cum histo %d' % jj,
                                                 ssbins[:-1], sss_data[jj])

                    max_contrast_data[kk, yy] = abs(
                        ((sss_data[0] - sss_data[1]) /
                         ss_data[0].sum())).max()

                    if self.liveplot_enabled:
                        self.plotter.plot_xy(
                            'contrast_ch' + str(kk + 1), ssbins[:-1],
                            abs(sss_data[0] - sss_data[1]) / ss_data[0].sum())
                        self.plotter.append_xy('max contrast_ch' + str(kk + 1),
                                               freq, max_contrast_data[kk, yy])

            with self.datafile() as f:
                f.append_pt('atten', atten)
                f.add('attenpts', attenpts)
                f.append_line('freq', freqpts)
                f.append_line('max_contrast_data_ch1', max_contrast_data[0, :])
                f.append_line('max_contrast_data_ch2', max_contrast_data[1, :])
                #f.add('single_record1', single_record1)
                f.close()
    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 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'])

        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']:
            self.flux_volt.ramp_current(self.cfg['freq_flux']['flux'])
        elif self.cfg['freq_flux']['voltage']:
            self.flux_volt.ramp_volt(self.cfg['freq_flux']['flux'])

        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'])

            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)


            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 = SlabFile(self.data_file)
            else:
                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.post_run is not None:
            self.post_run(self.expt_pts, expt_avg_data)
    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()
    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()
Example #32
0
    def go(self):

        if self.liveplot_enabled:
            self.plotter.clear()

        print("Prep Instruments")
        self.readout.set_output(True)
        self.readout.set_power(self.cfg['readout']['power'])
        if (self.cfg[self.expt_cfg_name]['pulsed']):
            self.readout.set_ext_pulse(mod=True)
        else:
            self.readout.set_ext_pulse(mod=False)

        try:
            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=self.cfg['drive']['mod'])

            if (self.cfg[self.expt_cfg_name]['pi_pulse']):
                self.drive.set_output(True)
            else:
                self.drive.set_output(False)
            print("Drive set successfully..")

        except:
            print("No drive found")

        self.drive.set_ext_pulse(mod=False)

        try:
            self.readout_atten.set_attenuator(self.cfg['readout']['dig_atten'])
        except:
            print("Error in setting digital attenuator.")

        try:
            self.awg.set_amps_offsets(self.cfg['cal']['iq_amps'], self.cfg['cal']['iq_offsets'])
            self.awg.run()
        except:
            print("error in setting self.awg")

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


        for freq in self.expt_pts:
            self.readout.set_frequency(freq-self.cfg['readout']['heterodyne_freq'])
            self.readout_shifter.set_phase((self.cfg['readout']['start_phase'] + self.cfg['readout']['phase_slope'] * (freq - self.cfg['readout']['frequency']))%360, freq)
            # print self.readout_shifter.get_phase()

            expt_data_ch1 = None
            expt_data_ch2 = None
            expt_data_mag = 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()

                mag = sqrt(ch1_pts ** 2 + ch2_pts ** 2)


                if expt_data_ch1 is None:
                    expt_data_ch1 = ch1_pts
                    expt_data_ch2 = ch2_pts
                else:
                    expt_data_ch1 = (expt_data_ch1 * ii + ch1_pts) / (ii + 1.0)
                    expt_data_ch2 = (expt_data_ch2 * ii + ch2_pts) / (ii + 1.0)
            expt_mag = sqrt(expt_data_ch1 ** 2 + expt_data_ch2 ** 2)


            # todo: fix heterodyne - need to take cos/sin of one channel
            # todo: & excise window

            if self.cfg['readout']['heterodyne_freq'] == 0:
                # homodyne
                mean_ch1 = mean(expt_data_ch1)
                mean_ch2 = mean(expt_data_ch2)
                mean_mag = mean(expt_mag)
            else:
                # heterodyne
                heterodyne_freq = self.cfg['readout']['heterodyne_freq']
                # ifft by numpy default has the correct 1/N normalization
                fft_ch1 = np.abs(np.fft.ifft(expt_data_ch1))
                fft_ch2 = np.abs(np.fft.ifft(expt_data_ch2))
                fft_mag = np.abs(np.fft.ifft(expt_mag))

                hetero_f_ind = int(round(heterodyne_freq * tpts.size * 1e-9))  # position in ifft

                # todo: single freq v.s. finite freq window (latter: more robust but noisier and with distortion)
                # expt_avg_data = np.average(expt_data_fft_amp[:, (hetero_f_ind - 1):(hetero_f_ind + 1)], axis=1)
                mean_ch1 = fft_ch1[hetero_f_ind]
                mean_ch2 = fft_ch2[hetero_f_ind]
                mean_mag = fft_mag[hetero_f_ind]

            if self.liveplot_enabled:
                self.plotter.append_xy('readout_avg_freq_scan1', freq, mean_ch1)
                self.plotter.append_xy('readout_avg_freq_scan2', freq, mean_ch2)
                self.plotter.append_xy('readout_avg_freq_scan_mag', freq, mean_mag)
                self.plotter.append_z('scope1',expt_data_ch1)
                self.plotter.append_z('scope2',expt_data_ch2)
                self.plotter.append_z('scope_mag',expt_mag)

            with self.datafile() as f:
                f.append_pt('freq', freq)
                f.append_pt('ch1_mean', mean_ch1)
                f.append_pt('ch2_mean', mean_ch2)
                f.append_pt('mag_mean', mean_mag)
                f.append_line('expt_2d_ch1', expt_data_ch1)
                f.append_line('expt_2d_ch2', expt_data_ch2)