def gate_sweep(self, config):
     print "Configuring card"
     scope_settings = AlazarConfig(config)
     card = Alazar(scope_settings)
     card.configure()
     print "Sweep gate voltage"
     tpts, ch1_pts, ch2_pts = card.acquire_avg_data(excise=(0, 4950))
Example #2
0
    def setup_alazar(self, config_dict):
        self.alazar = Alazar()

        try:
            print("new configuration file")
            cfg = AlazarConfig(config_dict)
            print(
                "config file has to pass through the AlazarConfig middleware.")
            self.alazar.configure(cfg)
            return True
        except:
            return False
Example #3
0
class ScopeDataThread(DataThread):
    def __init__(self):
        DataThread.__init__(self)
        self.settings = AlazarConfig()
        self.card = Alazar()
        self.trace_no = 0
        self.datapath = ""

    def apply_settings(self):
        self.settings.from_dict(self.params)
        self.settings.interpret_constants()
        self.card.configure(self.settings)

    def run_scope(self):
        if "timer" not in dir(self):
            self.timer = QTimer()
            self.timer.timeout.connect(self.acquire_trace)
        self.apply_settings()
        self.acquire_trace()

    def acquire_trace(self):
        self.timer.stop()
        self.trace_no += 1
        ex1, ex2 = (self.params["excise_start"], self.params["excise_end"])
        if not ex2: ex2 = 1
        debug = DEBUG and not self.trace_no % 20
        if debug: tic()
        times, ch1, ch2 = self.card.acquire_avg_data()
        if debug: self.msg("Acquire: %.3f" % toc())
        if ch1 is not None:
            self.plots["ch1"].setVisible(True)
            self.plots["ch1"].set_data(times, ch1[ex1:-ex2])
        else:
            self.plots["ch1"].setVisible(False)
        if ch2 is not None:
            self.plots["ch2"].setVisible(True)
            self.plots["ch2"].set_data(times, ch2[ex1:-ex2])
        else:
            self.plots["ch2"].setVisible(False)
        self.plots["plot"].replot()
        if self.params["autoscale"]:
            self.plots["plot"].do_autoscale()
        if self.params["autorun"] and not self.aborted():
            self.timer.start(1)
    def __init_card_and_gens__(self):

        # im = InstrumentManager()

        # if self._config['num_avgs'] <= 0:
        #     raise NameError("Number of Averages must be a Positive Number")
        #
        # #if self._config['LO'][0]==self._config['RF'][0]:
        homodyne_meas = True
        # print "Homodyne measurement"
        # coup = 'DC'
        # #else:
        # #    homodyne_meas=False
        # #    coup = 'AC'

        # if self._config['num_avgs']==1:
        #     rec_per_buff = 1
        # else:
        #     rec_per_buff = 512


        rec_per_buff = 512
        coup = 'DC'
        # load card
        card__config={'clock_edge': 'rising', 'clock_source': 'reference',
            'trigger_coupling': 'DC',  'trigger_operation': 'or',
            'trigger_source2': 'disabled','trigger_level2': 1.0, 'trigger_edge2': 'rising',
            'trigger_level1': 0.6, 'trigger_edge1': 'rising', 'trigger_source1': 'external',
            'ch1_enabled': True,  'ch1_coupling':coup,'ch1_range':self._config['meas_range'][0], 'ch1_filter': False,
            'ch2_enabled': True, 'ch2_coupling': coup,'ch2_range':self._config['meas_range'][1], 'ch2_filter': False,
            'bufferCount': 10,'recordsPerBuffer': rec_per_buff, 'trigger_delay': 0, 'timeout': 1000,
            'samplesPerRecord':self._config['acq_length'],'recordsPerAcquisition': self._config['num_avgs'], 'sample_rate': 1000000
            }

        scope_settings = AlazarConfig(card__config)

        card = Alazar(scope_settings)
        card.configure(scope_settings)

        RF = [None, None]
        LO = [None, None]
        drive = [None, None]

        return card, drive, RF, LO, homodyne_meas
Example #5
0
    def setup_alazar(self, config_dict):
        self.alazar = Alazar()

        try:
            print("new configuration file")
            cfg = AlazarConfig(config_dict)
            print("config file has to pass through the AlazarConfig middleware.")
            self.alazar.configure(cfg)
            return True
        except:
            return False
 def attach_instruments(self):
     self.im = InstrumentManager()
     self.na = self.im['NWA']
     self.fridge = self.im['FRIDGE']
     self.rf = self.im['RF_1']
     self.masterTrig = self.im['BNC_1']
     self.awgTrig = self.im['BNC_2']
     self.led = self.im['BNC_3']
     self.awg = self.im['AWG']
     self.srs = self.im['SRS']
     self.zMain = self.im['ZMain']
     self.xShim = self.im['XShim']
     self.yShim = self.im['YShim']
     self.zShim = self.im['ZShim']
     self.alazar = Alazar()
 def attach_instruments(self):
     self.im = InstrumentManager()
     self.na = self.im['NWA']
     self.heman = self.im['heman']
     # self.srs = self.im['SRS']
     self.fridge = self.im['FRIDGE']
     self.fil = self.im['fil']
     self.res = self.im['res']
     self.trap = self.im['trap']
     # self.trap = self.im['BNC_trap']
     # self.lb1 = self.im['LB1']
     # self.lb = self.im['labbrick']
     self.rf = self.im['BNC845_RF_0']  # the rf probe tone
     self.lo = self.im['BNC845_RF_1']  # the local oscillator
     self.trigger = self.im['BNC_sync']
     self.alazar = Alazar()
     self.sa = self.im.sa
class eHeExperiment():
    def attach_instruments(self):
        self.im = InstrumentManager()
        self.na = self.im['NWA']
        self.heman = self.im['heman']
        # self.srs = self.im['SRS']
        self.fridge = self.im['FRIDGE']
        self.fil = self.im['fil']
        self.res = self.im['res']
        self.trap = self.im['trap']
        # self.trap = self.im['BNC_trap']
        # self.lb1 = self.im['LB1']
        # self.lb = self.im['labbrick']
        self.rf = self.im['BNC845_RF_0']  # the rf probe tone
        self.lo = self.im['BNC845_RF_1']  # the local oscillator
        self.trigger = self.im['BNC_sync']
        self.alazar = Alazar()
        self.sa = self.im.sa

    def __init__(self, expt_path=None, prefix=None, alazarConfig=None, fridgeParams=None, filamentParams=None,
                 newDataFile=False):
        if expt_path != None and prefix != None:
            self.expt_path = expt_path
            self.prefix = prefix

        self.note_maxLength = 79
        self.config = lambda: None

        if alazarConfig != None and fridgeParams != None and filamentParams != None:
            self.plotter = LivePlotClient()
            self.attach_instruments();
            self.fil.params = filamentParams
            self.fil.update = self.updateFilament
            self.fil.update(self.fil.params)

            # self.na.set_default_state()
            # self.na.params = naParams
            # self.na.update = self.updateNWA
            self.na.set_trigger_source('bus')

            self.fridge.params = fridgeParams

            # # self.lb.set_output(False)
            # self.lb.set_pulse_ext(False)
            # self.lb.set_mod(False)
            # self.lb.set_power(0)

            self.alazar.configure(AlazarConfig(alazarConfig))
            # self.alazarConfig = alazarConfig
            # self.alazar.config = AlazarConfig(alazarConfig)
            # self.alazar.configure()

            self.nwa = lambda: None;
            self.nwa.sweep = self.nwa_sweep;
            self.nwa.scan = self.nwa_scan;
            self.nwa.config = lambda: None;

            # self.res = lambda: 0
            # def set_volt_res(volt):
            #     self.srs.set_volt(volt, channel=1)
            # def get_volt_res():
            #     return self.srs.get_volt(channel=1)

            # self.res.set_volt = set_volt_res
            # self.res.get_volt = get_volt_res
            # self.res.set_Vs = self.res_set_Vs
            self.res.set_output(True)

            self.configNWA()
            self.na.take_one = self.na_take_one;

            #this is the dataCache attached to the experiment.
            self.dataCache = dataCacheProxy(self, newFile=newDataFile)
            self.filename = self.dataCache.filename
        else:
            print "using eHeExperiment as a method proxy."
        self.count = -1
        self.t0 = time.time()

    def note(self, string):
        print string;
        self.dataCache.note(string, maxLength=self.note_maxLength)

    def configNWA(self, params=None):
        if params != None:
            print "now load parameters for network analyzer"
            self.na.set_averages(params['avg'])
            self.na.set_power(params['power'])
            self.na.set_center_frequency(params['center'])
            self.na.set_span(params['span'])
            self.na.set_ifbw(params['ifbw'])
            self.na.set_sweep_points(params['sweep_pts'])
        self.na.set_trigger_source('BUS')
        self.na.set_trigger_average_mode(True)
        self.na.set_timeout(10000)
        self.na.set_format('MLOG')

    def updateFilament(self, params):
        #self.note('update filament driver')
        self.fil.setup_driver(params['fil_amp'], params['fil_off'],
                              params['fil_freq'], params['fil_duration'])

    def set_DC_mode(self, trapHigh=3.5, trapLow=0):

        self.na.set_output('on')
        self.na.set_trigger_source('bus')
        rf_output = self.rf.get_output()
        self.rf.set_output(False)
        lo_output = self.rf.get_output()
        self.lo.set_output(False)
        try:
            self.trap.setup_volt_source(None, trapHigh, trapLow, 'on')
        except AttributeError:
            print 'using YokogawaGS200'

    def set_ramp_mode(self, high=None, low=None, offset=None, amp=None, symmetric=False):
        # if hasattr(self.trap, 'set_burst_phases'):
        self.set_ramp(high, low, offset, amp)
        self.rf.set_output(True)
        self.lo.set_output(True)

        if symmetric:
            self.trap.set_burst_phase(90)
            self.trap.set_symmetry(50)
        else:
            self.trap.set_burst_phase(0)
            self.trap.set_symmetry(0)
        self.trap.set_function('ramp')
        self.trap.set_burst_state('on')
        self.trap.set_trigger_source('ext')
        self.na.set_output('off')

    def set_ramp(self, high=None, low=None, offset=None, amp=None):
        """
        high and low overrides amp and offset.
        """
        # if hasattr(self.trap, 'set_burst_phases'):
        if low != None and high != None:
            amp = abs(high - low)
            offset = max(high, low) - amp / 2.
        if amp != None:
            self.trap.set_amplitude(amp)
        if offset != None:
            self.trap.set_offset(offset)

    def get_trap_high_low(self):
        offset = self.trap.get_offset()
        amp = self.trap.get_amplitude()
        return offset + amp / 2.0, offset - amp / 2.0

    def nwa_sweep(self, fpts=None, config=None):
        """
        this is the alazar nwa sweep code, using the alazar homodyne setup.
        """
        if fpts == None:
            self.nwa.config.fpts = linspace(self.nwa.config.range[0], self.nwa.config.range[1],
                                            self.nwa.config.range[2])
        else:
            self.nwa.config.fpts = fpts;

        if self.alazar.config != config and config != None:
            print "new configuration file"
            self.alazar.config = AlazarConfig(config);
            print "config file has to pass through the AlazarConfig middleware."
            self.alazar.configure()

        self.dataCache.new_stack()
        self.dataCache.note('alazar_nwa_sweep', keyString='type')
        self.dataCache.note(util.get_date_time_string(), keyString='startTime')
        high, low = self.get_trap_high_low()
        self.dataCache.set('rampHigh', high)
        self.dataCache.set('rampLow', low)
        self.dataCache.set('resV', self.res.get_volt())
        self.dataCache.note('ramp high: {}, low: {}'.format(high, low))
        self.dataCache.note('averaging(recordsPerBuffer): {}'.format(self.alazar.config.recordsPerBuffer))
        self.dataCache.set('fpts', self.nwa.config.fpts)
        start, end, n = self.nwa.config.range
        self.dataCache.set('fStart', start)
        self.dataCache.set('fEnd', end)
        self.dataCache.set('fN', n)
        self.dataCache.note('start freq: {}, end freq: {}, number of points: {}'.format(start, end, n))

        for f in self.nwa.config.fpts:
            self.rf.set_frequency(float(f))
            tpts, ch1_pts, ch2_pts = self.alazar.acquire_avg_data(excise=(0, -56))  #excise=(0,4992))

            # ch1_avg = mean(ch1_pts)
            # ch2_avg = mean(ch2_pts)
            mags = sqrt(ch1_pts ** 2 + ch2_pts ** 2)
            phases = map(util.phase, zip(ch1_pts, ch2_pts))

            self.plotter.append_z('nwa mag', mags)
            self.plotter.append_z('nwa phase', phases)
            self.plotter.append_z('nwa I', ch1_pts)
            self.plotter.append_z('nwa Q', ch2_pts)

            # self.dataCache.post('mags', mags)
            # self.dataCache.post('phases', phases)
            self.dataCache.post('I', ch1_pts)
            self.dataCache.post('Q', ch2_pts)
        return mags

    def heterodyne_spectrum(self, fpts=None, config=None):
        if fpts == None:
            self.nwa.config.fpts = linspace(self.nwa.config.range[0], self.nwa.config.range[1],
                                            self.nwa.config.range[2])
        else:
            self.nwa.config.fpts = fpts;

        if self.alazar.config != config and config != None:
            print "new configuration file"
            self.alazar.config = AlazarConfig(config);
            print "config file has to pass through the AlazarConfig middleware."
            self.alazar.configure()

        self.dataCache.new_stack()
        self.dataCache.note('heterodyne_spectrum', keyString='type')
        self.dataCache.note(util.get_date_time_string(), keyString='startTime')
        high, low = self.get_trap_high_low()
        self.dataCache.set('rampHigh', high)
        self.dataCache.set('rampLow', low)
        self.dataCache.set('resV', self.res.get_volt())
        self.dataCache.note('ramp high: {}, low: {}'.format(high, low))
        self.dataCache.note('averaging(recordsPerBuffer): {}'.format(self.alazar.config.recordsPerBuffer))
        self.dataCache.set('fpts', self.nwa.config.fpts)
        start, end, n = self.nwa.config.range
        self.dataCache.set('fStart', start)
        self.dataCache.set('fEnd', end)
        self.dataCache.set('fN', n)
        self.dataCache.set('IF', self.IF)
        self.dataCache.note('start freq: {}, end freq: {}, number of points: {}'.format(start, end, n))
        try:
            temperature = self.fridge.get_temperature()
        except:
            temperature = self.fridge.get_temperature()
        self.dataCache.set('temperature', temperature)

        self.rf.set_frequency(self.nwa.config.fpts[0])
        self.lo.set_frequency(self.nwa.config.fpts[0] + self.IF)

        ampI = []
        ampQ = []
        for f in self.nwa.config.fpts[1:]:
            tpts, ch1_pts, ch2_pts = self.alazar.acquire_avg_data(excise=(0, -56))  #excise=(0,4992))

            # place the setting here to allow time for the rf sources to stablize.
            self.rf.set_frequency(f)
            self.lo.set_frequency(f + self.IF)

            # time.sleep(0.1)
            # print 'sleeping for 0.1 second'

            dtpts, amp1, amp2 = dataanalysis.fast_digital_homodyne(tpts, ch1_pts, ch2_pts, IFfreq=self.IF,
                                                                   AmpPhase=True)
            self.plotter.append_z('heterodyne spectrum mag', amp1)
            self.dataCache.post('amp I', amp1)
            self.dataCache.post('amp Q', amp2)
            ampI.append([amp1])
            ampQ.append([amp2])
            # self.plotter.append_z('phase', phase1)
            # self.dataCache.post('phase', phase1)

            # self.plotter.append_z('ch1', ch1_pts)
            # self.plotter.append_z('ch2', ch2_pts)

            # self.dataCache.post('ch1', ch1_pts)
            # self.dataCache.post('ch2', ch2_pts)

        return concatenate(ampI), concatenate(ampQ)  #, phase1 #ch1_pts, ch2_pts

    def heterodyne_resV_sweep(self, config=None, trackMode=True, trapTrack=True, trapAmp=1, offsetV=0,
                              trackThreshold=50e3, snapshots=None):

        if self.alazar.config != config and config != None:
            print "new configuration file"
            self.alazar.config = AlazarConfig(config);
            print "config file has to pass through the AlazarConfig middleware."
            self.alazar.configure()

        self.dataCache.new_stack()
        self.dataCache.note('heterodyne_resV_sweep', keyString='type')
        self.dataCache.note(util.get_date_time_string(), keyString='startTime')
        if trapTrack == False:
            high, low = self.get_trap_high_low()
            self.dataCache.set('rampHigh', high)
            self.dataCache.set('rampLow', low)
            self.dataCache.note('ramp high: {}, low: {}'.format(high, low))
        else:
            self.get_peak()
            self.get_peak(nwa_center=self.sample.peakF, nwa_span=2e6)

        self.dataCache.set('resVs', self.resVs)
        self.dataCache.note('averaging(recordsPerBuffer): {}'.format(self.alazar.config.recordsPerBuffer))
        self.dataCache.set('IF', self.IF)
        self.dataCache.set('offset_frequency', self.offsetF)
        try:
            temperature = self.fridge.get_temperature()
        except:
            temperature = self.fridge.get_temperature()
        self.dataCache.set('temperature', temperature)

        self.rf.set_frequency(self.sample.peakF + self.offsetF)
        self.lo.set_frequency(self.sample.peakF + self.offsetF + self.IF)

        if snapshots != None:
            snapshots = sorted(snapshots);

        ampI = []
        ampQ = []
        ds = []
        dds = []
        centers = []
        for resV in self.resVs:
            self.res.set_volt(resV)
            print "| {:.4f}".format(resV)

            if trapTrack:
                self.trap.set_amplitude(trapAmp)
                self.trap.set_offset(resV + offsetV)
                high, low = self.get_trap_high_low()
                self.dataCache.post('rampHighs', high)
                self.dataCache.post('rampLows', low)

            if trackMode:
                trapHigh, trapLow = self.get_trap_high_low()
                self.set_DC_mode()
                self.get_peak(nwa_center=self.sample.peakF, nwa_span=5e6)
                self.dataCache.post('peakFs', self.sample.peakF)
                # intelligent jump detection via threshold.
                d = self.sample.peakF
                ds.append(d)
                n = len(ds)
                if n == 0:
                    ds = [d, ]
                    # dds = [0, ] # do nothing about dds.
                    centers.append(d)
                elif n == 1:
                    ds.append(d)
                    # dds.append(ds[-1] - ds[-2])
                    centers.append(2 * ds[-1] - 1 * ds[-2])
                elif n == 2:
                    ds.append(d)
                    centers.append(1.33 * ds[-1] - 0.66 * ds[-2] + 0.33 * ds[-3])
                else:
                    ds.append(d)
                    centers.append(1.25 * ds[-1] - 0.75 * ds[-2] + 0.25 * ds[-3] + 0.25 * ds[-4])
                if abs(d - centers[-1]) >= trackThreshold:
                    ds = []

                self.set_ramp_mode(trapHigh, trapLow)
                centerF = centers[-1] + self.offsetF
                self.rf.set_frequency(centerF)
                self.lo.set_frequency(centerF + self.IF)
                self.dataCache.post('RFs', centerF)
                self.plotter.append_y('RF', centerF)
                print 'center frequency is {}'.format(centerF)
                self.plotter.append_y('peakF', self.sample.peakF)

            tpts, ch1_pts, ch2_pts = self.alazar.acquire_avg_data(excise=(0, -24))  #excise=(0,4992))
            dtpts, amp1, amp2 = dataanalysis.fast_digital_homodyne(tpts, ch1_pts, ch2_pts, IFfreq=self.IF,
                                                                   AmpPhase=True)
            self.plotter.append_z('amp resV sweep', amp1)
            self.dataCache.post('amp I', amp1)
            self.dataCache.post('amp Q', amp2)
            ampI.append([amp1])
            ampQ.append([amp2])

        return concatenate(ampI), concatenate(ampQ)  #, phase1 #ch1_pts, ch2_pts

    def res_set_Vs(self, resStart, resStop, resStep=None, n=None):
        if resStep == None:
            self.resVs = linspace(resStart, resStop, n);
        else:
            self.resVs = util.ramp(resStart, resStop, resStep)

    def set_ramp_stops(self, high, low, window=None, n=None):
        if window != None:
            self.rampHighs = arange(high, low, -abs(window))[:-1]
            self.rampLows = arange(high, low, -abs(window))[1:]
        elif n >= 1:
            self.rampHighs = linspace(high, low, n + 1)[:-1]
            self.rampLows = linspace(high, low, n + 1)[1:]

    def nwa_scan(self, frequency=None):
        """
        nwa scan in [window,] following resVs and rampHighs, rampLows
        """
        if frequency != None:
            self.lb.set_frequency(frequency)
            self.nwa.config.frequency = frequency
        else:
            self.nwa.config.frequency = self.lb.get_frequency();

        self.dataCache.new_stack()
        self.dataCache.note('alazar_single_f_resV_scan', keyString='type')
        self.dataCache.note(util.get_date_time_string(), keyString='startTime')
        self.dataCache.note('averaging(recordsPerBuffer): {}'.format(self.alazar.config.recordsPerBuffer))
        self.dataCache.set('frequency', self.nwa.config.frequency)

        tpts, ch1_pts, ch2_pts = self.alazar.acquire_avg_data()

        I_stack = []
        Q_stack = []
        mags_stack = []
        phases_stack = []

        for resV in self.resVs:
            self.res.set_volt(resV)
            tpts, ch1_pts, ch2_pts = self.alazar.acquire_avg_data(excise=(0, -56))  #excise=(0,4992))

            I_half = []
            Q_half = []

            for ind, high_low in enumerate(zip(self.rampHighs, self.rampLows)):
                group_prefix = 'ramp_{}.'.format(str(1000 + ind)[-3:])

                self.dataCache.post(group_prefix + 'resVs', resV)

                high, low = high_low;
                self.set_ramp(high=high, low=low)
                self.dataCache.post(group_prefix + 'rampHighs', high)
                self.dataCache.post(group_prefix + 'rampLows', low)
                self.dataCache.note(group_prefix + 'ramp high: {}, low: {}'.format(high, low))

                tpts, ch1_pts, ch2_pts = self.alazar.acquire_avg_data(excise=(0, -56))  #excise=(0,4992))

                mags = sqrt(ch1_pts ** 2 + ch2_pts ** 2)
                phases = map(util.phase, zip(ch1_pts, ch2_pts))

                I_half.extend(ch1_pts[:-len(ch1_pts) / 2])
                Q_half.extend(ch2_pts[:-len(ch2_pts) / 2])

                self.dataCache.post(group_prefix + 'I', ch1_pts)
                self.dataCache.post(group_prefix + 'Q', ch2_pts)
                # self.dataCache.post('mags', mags)
                # self.dataCache.post('phases', phases)

            I_stack.append(I_half)
            Q_stack.append(Q_half)
            self.plotter.append_z('nwa I', I_half)
            self.plotter.append_z('nwa Q', Q_half)

        extent = [[self.rampHighs[0], 2 * self.rampLows[-1] - self.rampHighs[0]],
                  [self.resVs[0], self.resVs[-1]]
        ]
        self.plotter.plot_z('nwa I', I_stack, extent=extent)
        self.plotter.plot_z('nwa Q', Q_stack, extent=extent)
        # self.plotter.plot_z('nwa mag', mags_stack, extent=extent)
        # self.plotter.plot_z('nwa phase', phases_stack, extent=extent)

    def set_alazar_average(self, average=1):
        self.alazar.config.recordsPerBuffer = average
        self.alazar.config.recordsPerAcquisition = average
        self.alazar.config.timeout = 1000 * average
        self.alazar.configure()  #self.alazar.config)
        # self.alazarConfig['recordsPerBuffer'] = average
        # self.alazarConfig['recordsPerAcquisition'] = average
        # self.alazar.configure(AlazarConfig(self.alazarConfig))

    def gate_sweep(self, config):
        print "Configuring card"
        scope_settings = AlazarConfig(config)
        card = Alazar(scope_settings)
        card.configure()
        print "Sweep gate voltage"
        tpts, ch1_pts, ch2_pts = card.acquire_avg_data(excise=(0, 4950))

    def na_take_one(self, plotName='na spectrum'):
        """Setup Network Analyzer to take a single averaged trace and grab data,
        returning fpts, mags, phases"""
        self.na.clear_averages()
        self.na.trigger_single()
        self.na.averaging_complete()
        ans = self.na.read_data()
        if plotName == None:
            plotName = 'na spectrum';
        self.plotter.append_z(plotName, ans[1])
        return ans

    def get_na_sweep_voltage(self, center=None, span=None, npts=None, plotName=None):
        if center != None:
            self.na.set_center_frequency(center)
        if span != None:
            self.na.set_span(span)
        if npts != None:
            self.na.set_sweep_points(npts)

        self.dataCache.new_stack()
        self.dataCache.note('na_take_one', keyString='type')
        self.dataCache.note(util.get_date_time_string(), keyString='startTime')

        try:
            trapStart, trapEnd, trapStep, resStart, resEnd, resStep, doublePass = self.config.volt_sweep_range
            self.dataCache.note(
                'trapStart: {} , trapEnd: {} , trapStep: {} , resStart: {} , resEnd: {} , resStep: {} , doublePass: {} '.format(
                    trapStart, trapEnd, trapStep, resStart, resEnd, resStep, doublePass))
            self.dataCache.set('trapStart', trapStart)
            self.dataCache.set('trapEnd', trapEnd)
            self.dataCache.set('trapStep', trapStep)
            self.dataCache.set('resStart', resStart)
            self.dataCache.set('resEnd', resEnd)
            self.dataCache.set('resStep', resStep)
            self.dataCache.set('doublePass', str(doublePass))
        except:
            self.dataCache.set('resVs', self.resVs)
            self.dataCache.set('trapVs', self.trapVs)

        fpts, mag, phase = self.na.take_one(plotName=plotName)
        self.dataCache.set('fpts', fpts)
        for trapV, resV in zip(self.trapVs, self.resVs):
            self.trap.set_volt(trapV)
            self.res.set_volt(resV)
            fpts, mags, phases = self.na.take_one(plotName=plotName)
            # self.dataCache.set('fpts', fpts)
            self.dataCache.post('mags', mags)
            self.dataCache.post('phases', phases)
            offset, amplitude, center, hwhm = dsfit.fitlor(fpts, dBmtoW(mag))
            self.dataCache.post('centers', center)
            self.plotter.append_y('centers', center)

        offset, amplitude, center, hwhm = dsfit.fitlor(fpts, dBmtoW(mag))
        print "center frequency is: ", center
        return center

    def peak_track_voltage_sweep(self, center=None, span=None, npts=None, plotName=None, dynamicWindowing=False):
        '''
        when dynamic windowing is turned off, the peakTracker does not move
        the window around unless the jump is larger than 1/6th of the entire
        span.
        '''
        if center != None:
            self.na.set_center_frequency(center)
        # if span != None:
        #     self.na.set_span(span)
        if npts != None:
            self.na.set_sweep_points(npts)

        self.dataCache.new_stack()
        self.dataCache.note('peak_track_voltage_sweep', keyString='type')
        self.dataCache.note(util.get_date_time_string(), keyString='startTime')

        self.dataCache.set('resVs', self.resVs)
        self.dataCache.set('trapVs', self.trapVs)
        self.dataCache.set('temperature', self.fridge.get_temperature())

        assert (self.sample.peakF, 'no peakF found, need to pre fit the peak before start the script')
        fpts, mag, phase = self.na.take_one(plotName=plotName)
        self.dataCache.set('fpts', fpts)
        centers = []
        for trapV, resV in zip(self.trapVs, self.resVs):
            print "resV: {}, trapV: {}".format(resV, trapV)
            self.res.set_volt(resV)
            self.trap.set_volt(trapV)
            try:
                dynamic_range = (centers[-1] - centers[-2]) * 6.0
            except (TypeError, IndexError):
                dynamic_range = 0
            if dynamic_range > span:
                print "peak out of dynamic window. taking intermediate peak data.---------------------"
                print "dynamicWindowing is :{} ======-------------------------".format(dynamicWindowing)
                nwa_span = dynamic_range
                self.get_peak(nwa_center=self.sample.peakF, nwa_span=nwa_span, npts=npts)
                nwa_span = span
                fpts, mags, phases = self.get_peak(set_nwa=True, nwa_center=self.sample.peakF, nwa_span=nwa_span,
                                                   npts=npts)
            else:
                print "dynamicWindowing is :{} ===============================".format(dynamicWindowing)
                nwa_span = span
                fpts, mags, phases = self.get_peak(set_nwa=dynamicWindowing, nwa_center=self.sample.peakF,
                                                   nwa_span=nwa_span, npts=npts)

            self.dataCache.post('fptss', fpts)
            self.dataCache.post('mags', mags)
            self.dataCache.post('phases', phases)
            self.dataCache.post('centers', self.sample.peakF)
            centers.append(self.sample.peakF)
            self.plotter.append_y('centers {}'.format(npts), self.sample.peakF)

        print 'done with peak track voltage sweep!'

    def set_volt_sweep(self, trapStart, trapEnd, trapStep, resStart, resEnd, resStep, doublePass=False, showPlot=False,
                       straight=False):
        self.config.volt_sweep_range = [trapStart, trapEnd, trapStep, resStart, resEnd, resStep, doublePass]
        if doublePass:
            self.pts = (((trapStart, trapEnd, trapStart), trapStep), )
        else:
            self.pts = (((trapStart, trapEnd), trapStep),)
        self.tvps = util.Vramps(self.pts)
        self.pts = (((resStart, resEnd), resStep),)
        self.rvps = util.Vramps(self.pts)  #, 0.25,0.1])#Vramps(pts)
        self.trapVs = util.flatten(outer(ones(len(self.rvps)), self.tvps))
        self.resVs = util.flatten(outer(self.rvps, ones(len(self.tvps))))

        if straight:
            # straight flag completely overrides the sweep
            # problem is that two not not necessarily the same length
            self.resVs = util.Vramps((((resStart, resEnd), resStep),))
            self.trapVs = util.Vramps((((trapStart, trapEnd), trapStep), ))

        if showPlot:
            plt.plot(self.resVs, self.trapVs)
            plt.xlim(-1.6, 1.6)
            plt.ylim(-0.8, 1.8)
        print "estimated time is %d days %d hr %d minutes." % util.days_hours_minutes(len(self.trapVs))

    def rinse_n_fire(self, threshold=None, intCallback=None, timeout=360, resV=1.5, trapV=1.5, pulses=400, delay=0.01):
        self.note("unbias the trap for a second")
        self.res.set_volt(-3)
        self.res.set_output(True)
        self.note("make sure the probe is off before the baseline")
        time.sleep(1)

        self.note('firing the filament')
        try:
            self.res.set_range(10.0)
            self.trap.set_range(10.0)
        except:
            print "not able to set the range of the bias voltage driver. Check if it is the Yoko."
        self.res.set_volt(resV)
        self.trap.set_volt(trapV)
        print "now the resonator is loaded at {}V".format(self.res.get_volt())
        self.fil.fire_filament(pulses, delay)

        self.note("Now wait for cooldown while taking traces")
        if threshold == None:
            threshold = 60e-3;
        while self.fridge.get_mc_temperature() >= threshold or (time.time() - self.t0) < timeout:
            print '.',
            if intCallback != None:
                intCallback();
        self.note("fridge's cold, start sweeping...")
        self.note("sweep probe frequency and trap electrode")

    def get_peak(self, nwa_center=None, nwa_span=30e6, set_nwa=True, npts=320):
        self.na.set_trigger_source('bus')
        na_rf_state = self.na.get_output()
        self.na.set_output(True)
        rf_output = self.rf.get_output()
        self.rf.set_output(False)
        lo_output = self.rf.get_output()
        self.lo.set_output(False)
        if set_nwa:
            sweep_points = self.na.get_sweep_points()
            self.na.set_sweep_points(npts)
            if nwa_center == None:
                nwa_center = self.sample.freqNoE - nwa_span / 3.
            self.na.set_center_frequency(nwa_center)
            self.na.set_span(nwa_span)
        fpts, mags, phases = self.na.take_one()
        arg = argmax(filters.gaussian_filter1d(mags, 10))
        maxMag = filters.gaussian_filter1d(mags, 10)[arg]
        self.sample.peakF = fpts[arg]
        offset, amplitude, center, hvhm = fitlor(fpts, dBm_to_W(mags))
        print "     center via fitlor is {}, {}, {}, {}".format(offset, amplitude, center, hvhm)
        print "     abs(fit difference) is {}".format(abs(center - self.sample.peakF))
        fit_range = nwa_span / 10.
        print "     the good fit frequency range is {}".format(fit_range)

        if abs(center - self.sample.peakF) <= abs(fit_range):
            print '     peak fitted in range'
            self.sample.peakF = center
        print "     ",
        self.note("peakF: {}, mag @ {}, arg @ {}".format(self.sample.peakF, maxMag, arg))
        self.na.set_output(na_rf_state)
        self.rf.set_output(rf_output)
        self.rf.set_output(lo_output)
        if set_nwa:
            self.na.set_sweep_points(sweep_points)
        print "     the peak is found at: ", self.sample.peakF
        return fpts, mags, phases

    def clear_plotter(self):
        self.plotter.clear('na spectrum')
        self.plotter.clear('nwa mag')
        self.plotter.clear('nwa phase')
        self.plotter.clear('nwa I')
        self.plotter.clear('nwa Q')

    def clear_na_plotter(self):
        self.plotter.clear('na spectrum')

    def clear_nwa_plotter(self):
        self.plotter.clear('nwa mag')
        self.plotter.clear('nwa phase')
        self.plotter.clear('nwa I')
        self.plotter.clear('nwa Q')

    def play_sound(self, tone=None, filename=None):
        sound_file_directory = r'tone_files'
        tone_dict = {100: '100', 250: '250', 440: '440', 1000: '1k', 10000: '10k'}
        if filename == None:
            filename = '{}Hz_44100Hz_16bit_05sec.wav'.format(tone_dict[tone])
        path = os.path.join(sound_file_directory, filename)
        winsound.PlaySound(path, winsound.SND_FILENAME | winsound.SND_ASYNC | winsound.SND_LOOP)

    def stop_sound(self):
        sound_file_directory = r'tone_files'
        filename = 'Silent.wav'
        path = os.path.join(sound_file_directory, filename)
        winsound.PlaySound(path, winsound.SND_FILENAME | winsound.SND_ASYNC)

    def take_spectrum(self, center=None, span=None, resbw=None):
        self.na.set_output(False)
        self.rf.set_output(True)
        if center == None: center = self.sample.peakF
        self.rf.set_frequency(center)
        self.sa.set_center_frequency(center)
        if span != None: self.sa.set_span(span)
        if resbw != None:
            self.sa.set_resbw(resbw)
        else:
            self.sa.set_resbw(self.sa.get_span() / float(self.sa.get_sweep_points()) * 2)
        self.sa.trigger_single()

    def save_spectrum(self, notes=None):
        fpts, mags = self.sa.take_one()  #self.sa.read_data() #
        self.dataCache.new_stack()
        self.dataCache.set('fpts', fpts)
        self.dataCache.set('mags', mags)

        span = self.sa.get_span()
        sweep_pts = self.sa.get_sweep_points()
        resbw = self.sa.get_resbw()
        self.dataCache.set('span', span)
        self.dataCache.set('sweep_pts', sweep_pts)
        self.dataCache.set('resbw', resbw)

        self.dataCache.note(notes)
        self.dataCache.set('temperature', self.fridge.get_temperature())

    def take_spectrum_group(self, note):
        self.take_spectrum(span=20000)
        self.save_spectrum(note)
        self.take_spectrum(span=2000)
        self.save_spectrum(note)
        self.take_spectrum(span=200)
        self.save_spectrum(note)
Example #9
0
            DAx22000Segment(xpts[jj * segment_size:(jj + 1) * segment_size] *
                            4095.0 / max(xpts) * ii / numsegs,
                            loops=0,
                            triggered=triggered))

print(len(segs))
dac.create_segments(chan=1, segments=segs, loops=0)
dac.create_segments(chan=2, segments=segs, loops=0)

print(dac.set_ext_trig(ext_trig=True))
print(dac.run(trigger_now=False))

expt.cfg['alazar']["samplesPerRecord"] = 8192
expt.cfg['alazar']["recordsPerBuffer"] = numsegs
expt.cfg['alazar']["recordsPerAcquisition"] = numsegs
adc = Alazar(expt.cfg['alazar'])

#expt.awg.stop()
trig.set_output(True)


def trig_stop():
    trig.set_output(False)
    dac.stop()
    print("trig stop")


def trig_start():
    trig.set_output(True)
    dac.run(trigger_now=False)
    print("trig start")
Example #10
0
    waveforms.append(waveform)
    generated_waveforms.append(generated_waveform)
    #segs.append(DAx22000Segment(waveform, loops=0, triggered=True))
    #segs.append(DAx22000Segment(xpts * 4095.0 / max(xpts)  * ii / numsegs, loops=0, triggered=True))

#print len(segs)
dac.create_segments(chan=1, segments=segs, loops=0)
dac.create_segments(chan=2, segments=segs, loops=0)

print(dac.set_ext_trig(ext_trig=True))
#print dac.run(trigger_now=False)

expt.cfg['alazar']["samplesPerRecord"]=4096
expt.cfg['alazar']["recordsPerBuffer"]=numsegs
expt.cfg['alazar']["recordsPerAcquisition"]=numsegs
adc = Alazar(expt.cfg['alazar'])

#expt.awg.stop()
trig.set_output(False)

def trig_stop():
    trig.set_output(False)
    dac.stop()
    print("trig stop")

def trig_start():
    trig.set_output(True)
    dac.run(trigger_now=False)
    print("trig start")

tpts, ch1_pts, ch2_pts = adc.acquire_avg_data_by_record(prep_function=trig_stop, start_function=trig_start)
Example #11
0
 def __init__(self):
     DataThread.__init__(self)
     self.settings = AlazarConfig()
     self.card = Alazar()
     self.trace_no = 0
     self.datapath = ""
Example #12
0
def main():
    expt_path = "S:\\_Data\\120425 - 50nm Nb 20um resonator with crystal on top of first 2\\spin echo\\"
    config = "instruments.cfg"
    #datapath='S:\\_Data\\'
    prefix = "test_dynamic"
    #datapath=make_datapath(expt_path,prefix)
    sweep_pts = 1601
    ifbw = 1e3

    Freqs = linspace(5.79125e9 - 2e6, 5.79125e9 + 2e6, 100)

    im = InstrumentManager(expt_path + config)
    RF1 = im['RF1']
    #RF2=im['RF2']
    RF2 = im['LB1']
    #na=im['NWA']

    RF1.set_output(True)
    RF2.set_output(True)
    RF1.set_mod(True)
    RF2.set_mod(False)
    RF1.set_power(12)
    RF2.set_power(0)

    print("Configure NA")
    #    na.set_default_state()
    #    na.set_power(-20)
    #    na.set_ifbw(ifbw)
    #    na.set_span(0.)
    #    na.set_sweep_points(1)

    IFfreq = 1e6
    #na.set_center_frequency(2.5703e9)
    #RF2.set_frequency(2.5703e9+IFfreq)

    config = {
        'clock_edge': 'rising',
        'trigger_delay': 0,
        'ch1_filter': False,
        'ch1_enabled': True,
        'samplesPerRecord': 50048,
        'bufferCount': 1,
        'trigger_edge1': 'rising',
        'trigger_edge2': 'rising',
        'ch2_range': 4,
        'clock_source': 'internal',
        'trigger_level2': 1.0,
        'trigger_level1': 1.0,
        'ch2_coupling': 'DC',
        'trigger_coupling': 'DC',
        'ch2_filter': False,
        'trigger_operation': 'or',
        'ch1_coupling': 'AC',
        'trigger_source2': 'disabled',
        'trigger_source1': 'external',
        'recordsPerBuffer': 1,
        'sample_rate': 1000000,
        'timeout': 5000,
        'ch1_range': 4,
        'ch2_enabled': False,
        'recordsPerAcquisition': 1
    }

    print("Configuring card")
    scope_settings = AlazarConfig(config)

    card = Alazar(scope_settings)
    card.configure(scope_settings)

    print("go")
    print("Taking %d data points." % len(Freqs))
    print("|" + ("  " * (len(Freqs) / 10)) + " |")
    print("|", end=' ')
    #figure(1)
    tpts, ch1_pts, ch2_pts = card.acquire_avg_data()
    #fig1=FigureClient(xlabel='Time',ylabel='Amplitude',title='Scope')
    #fig2=FigureClient(xlabel='Time',ylabel='Amplitude',title='S21')
    #fig3=FigureClient(xlabel='Time',ylabel='Amplitude',title='S21')
    win = ScriptPlotWin(grid_x=2)
    scope_plot = win.add_linePlot(title="Scope")
    S21_plot_1 = win.add_linePlot(title="S21 1")
    S21_plot_2 = win.add_linePlot(title="S21 2")
    win.go()
    Amps = []
    freqs = []
    for ind, ff in enumerate(Freqs):
        if mod(ind, len(Freqs) / 10.) == 0: print("-", end=' ')
        RF1.set_frequency(ff)
        RF2.set_frequency(ff + IFfreq)
        #        na.set_center_frequency(ff)
        #print "freq=%f" % ff
        #time.sleep(1.15)
        tpts, ch1_pts, ch2_pts = card.acquire_avg_data()
        #fig1.update_plot((tpts,ch1_pts))
        scope_plot.send((tpts, ch1_pts))
        dtpts, amp1pts, phi1pts, amp2pts, phi2pts = digital_homodyne(
            tpts, ch1_pts, ch2_pts, IFfreq, AmpPhase=True)
        #print "A1: %f, Phi1: %f, A2: %f, Phi2: %f" % card.heterodyne(tpts,ch1_pts,ch2_pts,IFfreq)
        #A1= heterodyne(tpts,ch1_pts,ch2_pts,IFfreq)[0]
        freqs.append(ff / 1e9)
        Amps.append(mean(amp1pts))
        #fig2.update_plot((dtpts,amp1pts))
        #fig3.update_plot((array(freqs),array(Amps)))
        S21_plot_1.send((dtpts, amp1pts))
        S21_plot_2.send((array(freqs), array(Amps)))

    print("|")
Example #13
0
    # waveform += 2047*cutoff_gauss2
    # waveforms.append(waveform)
    # segs.append(DAx22000Segment(waveform, loops=0, triggered=True))
    segs.append(DAx22000Segment(xpts * 4095.0 / max(xpts)  * ii / numsegs, loops=1, triggered=True))


dac.create_segments(chan=1, segments=segs, loops=0)
dac.create_segments(chan=2, segments=segs, loops=0)

print(dac.set_ext_trig(ext_trig=True))
print(dac.run(trigger_now=False))

expt.cfg['alazar']["samplesPerRecord"]=8192
expt.cfg['alazar']["recordsPerBuffer"]=numsegs
expt.cfg['alazar']["recordsPerAcquisition"]=numsegs
adc = Alazar(expt.cfg['alazar'])

#expt.awg.stop()
trig.set_output(True)

def trig_stop():
    trig.set_output(False)
    dac.stop()
    print("trig stop")

def trig_start():
    trig.set_output(True)
    dac.run(trigger_now=False)
    print("trig start")

tpts, ch1_pts, ch2_pts = adc.acquire_avg_data_by_record(prep_function=None, start_function=None)
Example #14
0
    def sweep_bncrf_frequency(self):
        """
        Sweeps the frequency of the BNC RF source.
        """

        #self.plotsInitialized = False
        alazar_range_raw = str(self.combobox_alazar_range.currentText())
        alazar_ch = str(self.combobox_alazar_channel.currentText())
        sweep_center = np.float(self.lineEdit_bncrf_sweep_center.text())*1E9
        sweep_span = np.float(self.lineEdit_bncrf_sweep_span.text())*1E6
        sweep_numpoints = np.int(self.lineEdit_bncrf_noofpoints.text())

        sweep_points = np.linspace(sweep_center-sweep_span/2., sweep_center+sweep_span/2., sweep_numpoints)

        self.x = None
        self.y = None
        self.update_plots(xlabel='BNC Frequency (Hz)', ylabel='Scope ch%s (V)'%alazar_ch)

        if alazar_range_raw == '40 mV':
            alazar_range = 40E-3
        elif alazar_range_raw == '100 mV':
            alazar_range = 100E-3
        elif alazar_range_raw == '200 mV':
            alazar_range = 200E-3
        elif alazar_range_raw == '400 mV':
            alazar_range = 400E-3
        elif alazar_range_raw == '1 V':
            alazar_range = 1.0
        elif alazar_range_raw == '2 V':
            alazar_range = 2.0
        elif alazar_range_raw == '4 V':
            alazar_range = 4.0

        sample_rate = 20E3 #sample rate in Hz
        noof_samples = 1024
        noof_avgs = 1
        ch1_range = alazar_range
        ch2_range = alazar_range
        ch1_coupling = 'DC'
        ch2_coupling = 'DC'
        ch1_trigger_level = 2.5
        ch2_trigger_level = 2.5
        timeout = int(80E3)
        trigger_rate = 1e1

        print("Your trigger pulse width should be > %.3e s." % (1/sample_rate))
        print("Time out should be higher than %.3e" % (noof_samples/sample_rate*1e3 ))

        config = {'clock_edge': 'rising',
                  'clock_source': 'reference',
                  'samplesPerRecord': noof_samples,
                  'recordsPerBuffer': 1,
                  'recordsPerAcquisition': noof_avgs,
                  'bufferCount': 1,
                  'sample_rate': sample_rate/1E3, #in kHz
                  'timeout': timeout, #After this are ch1 settings
                  'ch1_enabled': True,
                  'ch1_filter': False,
                  'ch1_coupling': ch1_coupling,
                  'ch1_range': ch1_range, #After this are ch2 settings
                  'ch2_enabled': True,
                  'ch2_filter': False,
                  'ch2_coupling': ch2_coupling,
                  'ch2_range': ch2_range, #After this are trigger settings
                  'trigger_source1': 'external',
                  'trigger_level1': ch1_trigger_level,
                  'trigger_edge1': 'rising',
                  'trigger_source2': 'disabled',
                  'trigger_level2': ch2_trigger_level,
                  'trigger_edge2': 'rising',
                  'trigger_operation': 'or',
                  'trigger_coupling': 'DC',
                  'trigger_delay': 0}

        print("Total time trace signal is %.2f seconds" % (noof_samples/float(sample_rate)))

        alazar = Alazar()

        print("new configuration file")
        cfg = AlazarConfig(config)
        print("config file has to pass through the AlazarConfig middleware.")
        alazar.configure(cfg)

        self.x = sweep_points
        self.y = list()

        for idx,f in enumerate(sweep_points):
            self.M.BNC_RF.set_frequency(f)
            self.set_bnc_labels()
            t, ch1, ch2 = alazar.acquire_avg_data(excise=(0, -56))
            time.sleep(0.1)

            if alazar_ch == '1':
                self.y.append(np.mean(ch1))
            else:
                self.y.append(np.mean(ch2))

        self.update_plots(xlabel='BNC Frequency (Hz)', ylabel='Scope ch%s (V)'%alazar_ch)
        gui.QApplication.processEvents()
Example #15
0
class wigglewiggle():
    def __init__(self, msmtname, datapath, scriptname,
                 scriptpath=r'S:\_Data\141224 - M011 Helium Channels v4\experiment_M011_HeliumChannels'):

        self.im = InstrumentManager()
        #self.plotter = LivePlotClient()

        # ############################################
        # ### SETTINGS FOR THE PATH, SAVING ETC. #####
        # ############################################

        self.datapath = datapath
        self.msmtname = msmtname
        self.scriptname = scriptname
        self.scriptpath = scriptpath

        # ############################################
        ################ NWA SETTINGS ###############
        #############################################

        self.na_cfg = {
            'na_power': -30,
            'na_ifbw': 1000,
            'na_start': 4.0E9,
            'na_stop': 8.0E9,
            'na_sweep_pts': 1601,
            'na_avgs': 20,
            'na_delay': 0,
            'na_power_threshold': 0
        }

        self.sa_cfg = {
            'sa_center': 500E3,
            'sa_span': 1000E3,
            'sa_resbw': None,
            'sa_vidbw': 1E3,
            'sa_sweep_pts': 1601,
            'sa_avgs': 10,
            'sa_remote': False}

        self.labbrick_cfg = {
            'lb_freq': 7.785E9,
            'lb_power': -30
        }

        self.jpa_cfg = {
            'flux_bias_limit': 2E-3
        }

        #self.jpa_bias = im['JPA_bias']
        #self.na = im['NWA']
        #self.fridge = im['FRIDGE']
        #self.heman = im['heman']
        #self.lb = im['labbrick']

        #self.sa = im['SA']

        #Hacky solution to get the spectrum analyzer to work
        #from slab.instruments import E4440
        #self.sa = E4440("E4440", address="192.168.14.152")

        self.today = time.strftime('%y%m%d')
        self.timestamp = time.strftime('%H%M%S')

    def find_nearest(self, array, value):
        """
        Finds the nearest value in array. Returns index of array for which this is true.
        """
        idx=(np.abs(array-value)).argmin()
        return idx

    def initiate_instrument(self, name, cfg_name):
        im = InstrumentManager()
        setattr(self, name, im[cfg_name])
        return True

    def create_new_datafolder(self, datapath, measurement_name, date, timestamp):

        if not date in os.listdir(os.path.join(datapath)):
            os.mkdir(os.path.join(datapath, date))
            time.sleep(0.1)

        datafoldername = timestamp + '_' + measurement_name
        os.mkdir(os.path.join(datapath, date, datafoldername))

        return os.path.join(datapath, date, datafoldername)


    def create_new_file(self, datapath, measurement_name):
        datafoldername = self.create_new_datafolder(datapath, measurement_name, self.today, self.timestamp)

        FileHandler, fname = self.create_file_for_write(datafoldername, measurement_name)

        shutil.copy(os.path.join(self.scriptpath, self.scriptname),
                    os.path.join(datafoldername, self.scriptname))

        return datafoldername, fname, FileHandler


    def create_file_for_write(self, datafoldername, measurement_name):
        fname = get_next_filename(datafoldername + '\\', measurement_name, suffix='.h5')
        print('Created file %s...' % fname)
        FileHandler = dataCacheProxy(expInst=measurement_name, filepath=os.path.join(datafoldername, fname + '.h5'))
        return FileHandler, fname


    def test_instruments(self, do_not_test=None):
        """
        Test if instruments are responding
        """
        heman_query = 'get_manifold_status'
        fridge_query = 'get_temperatures'
        bnc845_query = 'get_frequency'
        nwa_query = 'get_start_frequency'
        bncawg_query = 'get_frequency'
        digatt_query = 'get_attenuation'

        instruments = ['NWA', 'heman', 'FRIDGE', 'digi_att', 'BNC845_RF1', 'BNC_sync', 'BNC_drive']
        queries = [nwa_query, heman_query, fridge_query, digatt_query, bnc845_query, bncawg_query, bncawg_query]
        no_error = True

        for instrument, query in zip(instruments, queries):
            if instrument not in do_not_test:
                try:
                    getattr(self.im[instrument], query)()
                    print("Established connection with {}".format(instrument))
                    time.sleep(0.1)
                except:
                    print("ERROR for {}".format(instrument))
                    no_error = False

        if no_error:
            return True
        else:
            return False

    def power_ok(self, power, threshold=0):
        if power > threshold:
            print("Power exceeded threshold of %d dBm. Aborting measurement." % threshold)
            return False
        else:
            return True


    def flux_bias_ok(self, current, threshold):
        if np.abs(current) > threshold:
            print("Current exceeds threshold of %d mA. Aborting measurement." % threshold)
            return False
        else:
            return True


    def setup_alazar(self, config_dict):
        self.alazar = Alazar()

        try:
            print("new configuration file")
            cfg = AlazarConfig(config_dict)
            print("config file has to pass through the AlazarConfig middleware.")
            self.alazar.configure(cfg)
            return True
        except:
            return False


    def take_single_trace(self, FileHandler, fstart, fstop, power, ifbw, sweep_pts,
                          noof_avgs, verbose=True, save=True):
        """
        Uses dataCacheProxy as FileHandler or None if saving is not required.

        Take a single trace with the network analyzer. Specify inputs in the
        dictionary na_cfg. Verbose gives response
        """

        if self.power_ok(power, threshold=self.na_cfg['na_power_threshold']):

            if verbose: print("Configuring the NWA")
            self.na.set_start_frequency(fstart)
            self.na.set_stop_frequency(fstop)
            self.na.set_power(power)
            self.na.set_ifbw(ifbw)
            self.na.set_sweep_points(sweep_pts)
            self.na.set_averages(noof_avgs)

            if noof_avgs > 1: self.na.set_average_state(True)

            time.sleep(0.1)

            if verbose: print("Taking data")
            fpoints, mags, phases = self.na.take_one_averaged_trace()

            if save:
                FileHandler.post('fpoints', fpoints)
                FileHandler.post('mags', mags)
                FileHandler.post('phases', phases)
                self.save_nwa_config(FileHandler)
            else:
                return fpoints, mags, phases


    def nwa_power_sweep(self, FileHandler, pwr_start, pwr_stop, steps, save=True):
        """
        Uses dataCacheProxy as FileHandler

        Sweep the power of the network analyzer using 
        the function take_single_trace. Specify a starting, ending point
        for the power and the number of steps. 
        """
        p = np.linspace(pwr_start, pwr_stop, steps)
        print("Starting NWA powersweep...")

        fpoints = np.empty((steps, self.na_cfg['na_sweep_pts']), dtype=np.float64)
        mags = np.empty((steps, self.na_cfg['na_sweep_pts']), dtype=np.float64)
        phases = np.empty((steps, self.na_cfg['na_sweep_pts']), dtype=np.float64)

        self.plotter.clear()

        for sweep_idx, P in enumerate(p):
            print("\tP = %.2f dBm (%.1f%%)" % (P, sweep_idx / float(steps) * 100))
            f, db, phi = self.take_single_trace(FileHandler,
                                                self.na_cfg['na_start'],
                                                self.na_cfg['na_stop'],
                                                P,
                                                self.na_cfg['na_ifbw'],
                                                self.na_cfg['na_sweep_pts'],
                                                self.na_cfg['na_avgs'],
                                                verbose=False, save=False)

            self.plotter.append_z('phase', phi, ((p[0], p[1]-p[0]), (f[0], f[1] - f[0])))
            self.plotter.append_z('mag', db, ((p[0], p[1]-p[0]), (f[0], f[1] - f[0])))

            fpoints[sweep_idx, :] = f
            mags[sweep_idx, :] = db
            phases[sweep_idx, :] = phi

            if save:
                FileHandler.post('fpoints', f)
                FileHandler.post('mags', db)
                FileHandler.post('phases', phi)
                FileHandler.post('powers', P)

            if msvcrt.kbhit() and msvcrt.getch() == 'q':
                break

        self.na.set_power(min(p))

        if save:
            self.save_nwa_config(FileHandler)
        else:
            return fpoints, mags, phases


    def flux_bias_sweep(self, FileHandler, current_start, current_stop, steps, save=True):
        """
        Uses dataCacheProxy as FileHandler

        Sweep the current from the yokogawa sourc e. The
        linear sweep starts at current_start and stop at 
        current_stop. Resolution is determined by steps. 
        Flag save to save the data. 

        All currents in units of A, i.e. 1 mA = 1E-3
        """

        i = np.linspace(current_start, current_stop, steps)
        print("Starting Yoko currentsweep...")

        self.jpa_bias.set_mode(mode='curr')
        self.jpa_bias.set_current(0)
        self.jpa_bias.set_output()

        fpoints = np.empty((steps, self.na_cfg['na_sweep_pts']), dtype=np.float64)
        mags = np.empty((steps, self.na_cfg['na_sweep_pts']), dtype=np.float64)
        phases = np.empty((steps, self.na_cfg['na_sweep_pts']), dtype=np.float64)

        self.plotter.clear()

        for sweep_idx, I in enumerate(i):

            if self.flux_bias_ok(I, self.jpa_cfg['flux_bias_limit']):
                self.jpa_bias.set_current(I)
                time.sleep(0.2)
                print("\tI = %.6f mA (%.1f%%)" % (I * 1E3, sweep_idx / float(steps) * 100))
                f, db, phi = self.take_single_trace(FileHandler,
                                                    self.na_cfg['na_start'],
                                                    self.na_cfg['na_stop'],
                                                    self.na_cfg['na_power'],
                                                    self.na_cfg['na_ifbw'],
                                                    self.na_cfg['na_sweep_pts'],
                                                    self.na_cfg['na_avgs'],
                                                    verbose=False, save=False)

                fpoints[sweep_idx, :] = f
                mags[sweep_idx, :] = db
                phases[sweep_idx, :] = phi

                if save:
                    FileHandler.append('fpoints', f)
                    FileHandler.append('mags', db)
                    FileHandler.append('phases', phi)
                    FileHandler.append('currents', I)

                self.plotter.append_z('phase', phi, ((1, 1), (f[0], f[1] - f[0])))
                self.plotter.append_z('mag', db, ((1, 1), (f[0], f[1] - f[0])))

                if msvcrt.kbhit() and msvcrt.getch() == 'q':
                    break
            else:
                break

        self.jpa_bias.set_output(0)
        self.jpa_bias.set_current(0)

        if save:
            self.save_nwa_config(FileHandler)

        return fpoints, mags, phases


    def level_meter_expt(self, datapath, measurement_name, noof_puffs, start_stop_pairs=None, manual=True, save=True,
                         pressure_limit=1.5E-2, reps_per_puff=1, puff_pressure=0.25, max_temp=60E-3, pressure_drop_timeout=600):
        """
        Fills the helium lines with a number of puffs specified by noof_puffs. 
        The time between each puff is specified by wait_time, and is 1s by default. 
        After each puff a spectrum is taken and after noof_puffs puffs the file is saved.
        """
        user_is_awake = input("Starting helium puff sequence. Press 'c' to continue.")
        datafoldername = self.create_new_datafolder(datapath, measurement_name, self.today, self.timestamp)
        shutil.copy(os.path.join(self.scriptpath, self.scriptname),
                    os.path.join(datafoldername, self.scriptname))

        self.plotter.clear()
        if user_is_awake == 'c' and self.heman.get_pressure() < pressure_limit:
            # Prepare file for write
            if save:
                FileHandler = dataCacheProxy(expInst=measurement_name,
                                             filepath=os.path.join(datafoldername, '%s.h5' % measurement_name))
                time.sleep(0.1)

            print("Helium puff sequence about to start...")

            puff = np.arange(noof_puffs)

            for puff_idx in puff:

                if manual:
                    another_puff = input("Press 'c' for another puff")
                    if another_puff == 'c':
                        pass
                    else:
                        break
                else:
                    settled = False
                    start_time = time.time()

                    while not settled:
                        print("...", end=' ')
                        settled = (self.fridge.get_mc_temperature() < max_temp) and ((time.time() - start_time) > 60)
                        #start pumping
                        self.heman.set_cryostat(False)
                        self.heman.set_gas(False)
                        self.heman.set_pump(True)
                        time.sleep(1)

                self.heman.puff(pressure=puff_pressure, min_time=60, timeout=pressure_drop_timeout)
                print("\n%s Puff %d (%.1f%% done)" % (time.strftime("%H%M%S"), puff_idx + 1,
                                                      (puff_idx + 1) / float(noof_puffs) * 100))

                if start_stop_pairs is None:

                    points, mags, phases = self.take_single_trace(None,
                                                                  self.na_cfg['na_start'],
                                                                  self.na_cfg['na_stop'],
                                                                  self.na_cfg['na_power'],
                                                                  self.na_cfg['na_ifbw'],
                                                                  self.na_cfg['na_sweep_pts'],
                                                                  self.na_cfg['na_avgs'],
                                                                  verbose=False, save=False)

                    if save:
                        FileHandler.new_stack()
                        for r in range(reps_per_puff):
                            FileHandler.post('fpoints', points)
                            FileHandler.post('mags', mags)
                            FileHandler.post('phases', phases)

                            points, mags, phases = self.take_single_trace(None,
                                                                          self.na_cfg['na_start'],
                                                                          self.na_cfg['na_stop'],
                                                                          self.na_cfg['na_power'],
                                                                          self.na_cfg['na_ifbw'],
                                                                          self.na_cfg['na_sweep_pts'],
                                                                          self.na_cfg['na_avgs'],
                                                                          verbose=False, save=False)



                        FileHandler.post('puff_nr', self.heman.get_puffs())
                        FileHandler.set_dict('Temperatures', self.fridge.get_temperatures())

                    self.plotter.append_z('mags', mags, ((1, 1), (points[0], points[1] - points[0])))
                    self.plotter.append_z('phases', phases, ((1, 1), (points[0], points[1] - points[0])))
                    self.plotter.append_y('puffs', self.heman.get_puffs())

                else:
                    for idx, f_zoom in enumerate(start_stop_pairs):
                        self.na_cfg['na_start'] = f_zoom[0]
                        self.na_cfg['na_stop'] = f_zoom[1]
                        points, mags, phases = self.take_single_trace(None,
                                                                      self.na_cfg['na_start'],
                                                                      self.na_cfg['na_stop'],
                                                                      self.na_cfg['na_power'],
                                                                      self.na_cfg['na_ifbw'],
                                                                      self.na_cfg['na_sweep_pts'],
                                                                      self.na_cfg['na_avgs'],
                                                                      verbose=False, save=False)

                        if save:
                            FileHandler.new_stack() if idx == 0 else None
                            FileHandler.post('fpoints_%d' % idx, points)
                            FileHandler.post('mags_%d' % idx, mags)
                            FileHandler.post('phases_%d' % idx, phases)
                            FileHandler.post('puff_nr_%d' % idx, self.heman.get_puffs())
                            FileHandler.set_dict('Temperatures', self.fridge.get_temperatures())

                if save:
                    self.save_nwa_config(FileHandler)
                    print("Done writing to stack %s..." % FileHandler.current_stack)
                else:
                    return points, mags, phases

        else:
            if self.heman.get_pressure() > pressure_limit:
                print("Measurement aborted, pressure > %.2e mbar" % pressure_limit)
            else:
                print("Measurement aborted by user.")


    def get_sa_trace(self):
        """
        Get single trace from the spectrum analyzer
        :return: fpoints, magnitude
        """

        if self.sa_cfg['sa_avgs'] > 1:
            self.sa.set_average_state(True)
        else:
            self.sa.set_average_state(False)

        self.sa.configure(start=None, stop=None,
                          center=self.sa_cfg['sa_center'],
                          span=self.sa_cfg['sa_span'],
                          resbw=self.sa_cfg['sa_resbw'],
                          vidbw=self.sa_cfg['sa_vidbw'],
                          sweep_pts=self.sa_cfg['sa_sweep_pts'],
                          avgs=self.sa_cfg['sa_avgs'],
                          remote=self.sa_cfg['sa_remote'])

        return self.sa.take_one()


    def fire_filament(self, amplitude, offset, frequency, pulse_length):
        self.initiate_instrument('fil', 'fil')
        self.fil.setup_driver(amplitude, offset, frequency, pulse_length)
        self.fil.fire_filament()


    def monitor_manifold_pressure(self, heman_name = 'heman', runtime = None, dt = 1):
        """

        :param heman_name: Name as it appears in the instrument manager
        :param runtime: For how long should the pressure be monitored?
        :param dt: Timestep for the recording
        :return:
        """
        self.initiate_instrument('heman', heman_name)
        self.plotter.clear()

        t0 = time.time()
        while time.time()-t0 < runtime:
            self.heman.get_pressure()
            time.sleep(dt)

            self.plotter.append_xy('Puffs', time.time()-t0, self.heman.get_puffs())
            self.plotter.append_xy('Pressure (mbar)', time.time()-t0, self.heman.get_pressure()*1E3)
            self.plotter.append_xy('Pump valve state', time.time()-t0, self.heman.get_manifold_status_bits()[1])
            self.plotter.append_xy('Cryostat valve state', time.time()-t0, self.heman.get_manifold_status_bits()[2])
            self.plotter.append_xy('Gas valve state', time.time()-t0, self.heman.get_manifold_status_bits()[0])


    def monitor_cryostat(self, runtime, dt):
        import time
        self.initiate_instrument('fridge', 'FRIDGE')
        self.plotter.clear()

        t0 = time.time()
        while time.time()-t0 < runtime:
            pressures = self.fridge.get_pressures()
            temperatures = self.fridge.get_temperatures()

            time.sleep(dt)
            T = time.time()

            # Pressures
            self.plotter.append_xy('Condense pressure', T-t0, pressures['Condense'])
            self.plotter.append_xy('Forepump pressure', T-t0, pressures['Forepump'])
            self.plotter.append_xy('Tank pressure', T-t0, pressures['Tank'])

            # Temperatures
            self.plotter.append_xy('PT2 plate', T-t0, temperatures['PT2 Plate'])
            self.plotter.append_xy('Still', T-t0, temperatures['Still'])
            self.plotter.append_xy('100 mK plate', T-t0, temperatures['100mK Plate'])
            self.plotter.append_xy('MC RuO2', T-t0, temperatures['MC RuO2'])
            self.plotter.append_xy('MC cernox', T-t0, temperatures['MC cernox'])


    def save_sa_config(self, FileHandler):
        """
        Uses datacache
        :param FileHandler: dataCacheProxy instance
        :return: None
        """
        FileHandler.set_dict("sa_config", self.sa_cfg)


    def save_nwa_config(self, FileHandler):
        """
        Uses datacache
        :param FileHandler: dataCacheProxy instance
        :return: None
        """
        FileHandler.set_dict("nwa_config", self.na_cfg)
class esrExperiment(mckay_master):

    def attach_instruments(self):
        self.im = InstrumentManager()
        self.na = self.im['NWA']
        self.fridge = self.im['FRIDGE']
        self.rf = self.im['RF_1']
        self.masterTrig = self.im['BNC_1']
        self.awgTrig = self.im['BNC_2']
        self.led = self.im['BNC_3']
        self.awg = self.im['AWG']
        self.srs = self.im['SRS']
        self.zMain = self.im['ZMain']
        self.xShim = self.im['XShim']
        self.yShim = self.im['YShim']
        self.zShim = self.im['ZShim']
        self.alazar = Alazar()

    def __init__(self, expt_path=None, prefix=None, alazarConfig=None, newDataFile=False):
        
        mckay_master.__init__(self)
        
        self._config['exp_id'] = 'ESR'
        
        self.esr_data = []

        self.tau_pts = []

        self._config['use_awg'] = True
        
        #custom esr options
        self._config['b_field'] = 0.0
        self._config['tau'] = 10.0 #in us
        self._config['led_delay'] = 2000 #in us
        self._config['led_pulse_length'] = 2.0 #in ms
        self._config['pulse_height'] = [1.0,1.0]
        self._config['pulse_length'] = [100,100] #in ns
        self._config['pulse_phase'] = [0,pi/2]
        self._config['master_trigger'] = self._config['led_pulse_length'] + self._config['led_delay']*1e-3 + 3*self._config['tau'] #ms
        self._config['switch_buffer'] = 2000 #ns
        
        self._config['tau_start'] = 1.0
        self._config['tau_end'] = 2.0
        self._config['tau_pts'] = 100
        
        self._config['trigger_instr'] = 'BNC_1'
        self._config['awg_trigger'] = 'BNC_2'
        self._config['led_trigger'] = 'BNC_3'
        
        #there is only 1 "qubit"
        self._config['qubit_enable'][1] = False
        
        #save single shot
        self._config['save_single_shot'] = False

        # Ge's code
        if expt_path != None and prefix != None:
            self.expt_path = expt_path
            self.prefix = prefix

        self.note_maxLength = 79
        self.config = lambda: None

        if alazarConfig != None:
            self.plotter = LivePlotClient()
            self.attach_instruments()

            # self.na.set_default_state()
            # self.na.params = naParams
            # self.na.update = self.updateNWA
            self.na.set_trigger_source('bus')

            self.xShim.Remote()
            self.xShim.set_voltage(10.0)
            self.xShim.set_output()
            self.yShim.Remote()
            self.yShim.set_voltage(10.0)
            self.yShim.set_output()
            self.zShim.Remote()
            self.zShim.set_voltage(10.0)
            self.zShim.set_output()

            # # self.lb.set_output(False)
            # self.lb.set_pulse_ext(False)
            # self.lb.set_mod(False)
            # self.lb.set_power(0)

            self.alazar.configure(AlazarConfig(alazarConfig))
            # self.alazarConfig = alazarConfig
            # self.alazar.config = AlazarConfig(alazarConfig)
            # self.alazar.configure()

            self.configNWA()
            self.na.take_one = self.na_take_one;

            #this is the dataCache attached to the experiment.
            self.dataCache = dataCacheProxy(self, newFile=newDataFile)
            self.filename = self.dataCache.filename
        else:
            print "using esrExperiment as a method proxy."
        self.count = -1
        self.t0 = time.time()

    def take_esr_data(self,plotter):
        
        #initialize the card and generator
        card, drive, RF, LO, homodyne_meas = self.__init_card_and_gens__()
            
        #define instrument manager    
        im = InstrumentManager()
        
        #setup triggers
        
        #master trigger
        mast_trigger = im[self._config['trigger_instr']]
        mast_trigger.set_function('PULSE')
        mast_trigger.set_pulse_width(100e-9)
        mast_trigger.set_period(self._config['master_trigger']*1.0e-3)
        mast_trigger.set_output(False)
        
        #awg trigger
        awg_trigger = im[self._config['awg_trigger']]
        awg_trigger.set_function('PULSE')
        awg_trigger.set_pulse_width(100e-9)
        awg_trigger.set_period(self._config['tau']*1.0e-6)
        awg_trigger.set_burst_cycles(3)
        awg_trigger.set_burst_mode('triggered')
        awg_trigger.set_burst_state('on')
        awg_trigger.set_trigger_source('EXT')
        
        #led trigger
        led_trigger = im[self._config['led_trigger']]
        led_trigger.set_function('PULSE')
        led_trigger.set_pulse_width(self._config['led_pulse_length']*1.0e-3)
        led_trigger.set_burst_cycles(1)
        led_trigger.set_burst_mode('triggered')
        led_trigger.set_amplitude(5.0)
        led_trigger.set_offset(0.0)
        led_trigger.set_burst_state('on')
        
       
        #Load the waveforms for the card, measurement and drive pulses
        #pulse sequence
        awg_seq = pulse_sequence(3,int(ceil(self._config['total_length']*self._config['awg_clocks'][0])),int(ceil(self._config['total_length']*self._config['awg_clocks'][1])),self._config['awg_clocks'][0],self._config['awg_clocks'][1],self._config['awg_delay'])
            
        pulse_center = self._config['total_length']/2.0
        
        #setup channels
        awg_seq.channel_index['drive_I'][0] = 4
        awg_seq.channel_index['drive_Q'][0] = 5
        
        awg_seq.channel_index['card_trig'] = 8
        awg_seq.channel_index['led_trigger'] = 9
        awg_seq.channel_index['hittite_switch'] = 10
        
        #three pulses
        for j in range(3):
            
            #add new pulses
            ind1a = awg_seq.add_analog_pulse(awg_seq.channel_index['drive_I'][0])
            awg_seq.analog_seq_table[awg_seq.channel_index['drive_I'][0]][j] = ind1a
        
            ind1b = awg_seq.add_analog_pulse(awg_seq.channel_index['drive_Q'][0])
            awg_seq.analog_seq_table[awg_seq.channel_index['drive_Q'][0]][j] = ind1b
        
            ind2 = awg_seq.add_marker_pulse(awg_seq.channel_index['card_trig'])
            awg_seq.marker_seq_table[awg_seq.channel_index['card_trig']][j] = ind2

            ind3 = awg_seq.add_marker_pulse(awg_seq.channel_index['led_trigger'])
            awg_seq.marker_seq_table[awg_seq.channel_index['led_trigger']][j] = ind3

            ind4 = awg_seq.add_marker_pulse(awg_seq.channel_index['hittite_switch'])
            awg_seq.marker_seq_table[awg_seq.channel_index['hittite_switch']][j] = ind4
                     
            if j<2:
                
                #microwave pulses
                awg_seq.analogwf[awg_seq.channel_index['drive_I'][0]][ind1a].square_pulse2(pulse_center,self._config['pulse_length'][j],self._config['pulse_height'][j]*cos(self._config['pulse_phase'][j]))
                awg_seq.analogwf[awg_seq.channel_index['drive_Q'][0]][ind1b].square_pulse2(pulse_center,self._config['pulse_length'][j],self._config['pulse_height'][j]*sin(self._config['pulse_phase'][j]))
                
                #hittite switch
                awg_seq.marker[awg_seq.channel_index['hittite_switch']][ind4].square_pulse2(pulse_center,self._config['pulse_length'][j]+self._config['switch_buffer'])
                
                
            if j==2:
                
                #trigger the card         
                awg_seq.marker[awg_seq.channel_index['card_trig']][ind2].square_pulse2(pulse_center,self._config['acq_length'])
            
                #led switch
                awg_seq.marker[awg_seq.channel_index['led_trigger']][ind3].square_pulse2(self._config['total_length']-100.0,100.0)

        #load the agilent awg
        for i in [1]:
            #load into agilent, but do not sequence!
            awg_seq.load_full_into_agilent(self._config['AWG'][1],True)
            awg=im[self._config['AWG'][i]]
            awg.prep_experiment()
            awg.set_amps_offsets(self._config['awg_amp'][i],self._config['awg_offset'][i],self._config['awg_marker_amps'][i])
            awg.run()
            
            #pause until the awg is loaded
            while not awg.query("*OPC?"):
                pass
            
        #turn on the master trigger
            mast_trigger.set_output(True)
        ###TO DO
        
        #copied
        # if plotter is not None:
        #     for j in range(2):
        #
        #         plotter.init_plot("Scope" + str(j),rank=1,accum=False)
        #         plotter.init_plot("Readout"+ str(j),rank=1,accum=False)
        #         plotter.init_plot("2DData"+ str(j),rank=2,accum=False)
        
        self.tau_pts = linspace(self._config['tau_start'],self._config['tau_end'],self._config['tau_pts'])
        
        if self._config['save_single_shot']:
            self.esr_data = zeros((2,self._config['tau_pts'],self._config['acq_length'],self._config['num_avgs']))
        elif self._config['save_fulldata']:
            self.esr_data = zeros((2,self._config['tau_pts'],self._config['acq_length']))
        else:
            self.esr_data = zeros((2,self._config['tau_pts']))
            
        
        ch_pts = zeros((2,self._config['acq_length']))
        
        for i in range(self._config['tau_pts']):
            
            #TODO: turn off master trigger
            awg_trigger.set_period(self.tau_pts[i]*1.0e-6)
            
            #TODO: turn on master trigger
            
            tpts,ch_pts[0],ch_pts[1]=card.acquire_avg_data()
                
            for k in range(2):
                
                if self._config['save_fulldata']:
                    self.esr_data[k][i] = ch_pts[k]
                else:
                    
                    
                    amp = mean(ch_pts[k][self._config['data_window'][k][0]:self._config['data_window'][k][1]])
                    
                    self.esr_data[k][i] = amp
                   
                    if plotter is not None:
                        plotter.plot(ch_pts,'Scope'+str(k))
                        plotter.plot((self.tau_pts[0:j],self.esr_data[k][0:j]),"Readout"+str(k))

            # if plotter is not None:
            #     for k in range(2):
            #         if self._config['qubit_enable'][k] and not self._config['save_fulldata']:
            #             plotter.plot((self.esr_data[k]),"2DData"+str(k))
                        
    def save_data(self,exp_path,file_prefix,overwrite=False):
        
        #print expt_path+fname
        try:
            if overwrite:
                f=SlabFile(exp_path+file_prefix+'.h5','w')
            else:
                fname=get_next_filename(exp_path,prefix=file_prefix,suffix='.h5')
                print fname
                f=SlabFile(exp_path+fname,'w')
        except NameError:
            print "Error opening file for saving esr data"
            return
            
        #save
        f.create_dataset('esr_data',data=self.esr_data)
        f.create_dataset('tau_pts', data= self.tau_pts)
        
        f.attrs['qubit_data_type'] = "esr"
        
        
        #convert _config dictionary into saveable format (get rid of nested lists)
        b = self._config.copy()
        for i in b.keys():
            if asarray(b[i]).dtype == "object":
                for j in range(len(b[i])):
                    b[i + str(j)] = b[i][j]

                b[i] = []


        #load keys (allow for new keys to be added later)
        f.save_settings(b)
        f.close()

    def configNWA(self, params=None):
        if params != None:
            print "now load parameters for network analyzer"
            self.na.set_averages(params['avg'])
            self.na.set_power(params['power'])
            self.na.set_center_frequency(params['center'])
            self.na.set_span(params['span'])
            self.na.set_ifbw(params['ifbw'])
            self.na.set_sweep_points(params['sweep_pts'])
        self.na.set_trigger_source('BUS')
        self.na.set_trigger_average_mode(True)
        self.na.set_timeout(10000)
        self.na.set_format('MLOG')

    def na_take_one(self, plotName='na spectrum'):
        """Setup Network Analyzer to take a single averaged trace and grab data,
        returning fpts, mags, phases"""
        self.na.clear_averages()
        self.na.trigger_single()
        self.na.averaging_complete()
        ans = self.na.read_data()
        if plotName == None:
            plotName = 'na spectrum';
        self.plotter.append_z(plotName, ans[1])
        return ans
Example #17
0
class wigglewiggle():
    def __init__(
        self,
        msmtname,
        datapath,
        scriptname,
        scriptpath=r'S:\_Data\141224 - M011 Helium Channels v4\experiment_M011_HeliumChannels'
    ):

        self.im = InstrumentManager()
        #self.plotter = LivePlotClient()

        # ############################################
        # ### SETTINGS FOR THE PATH, SAVING ETC. #####
        # ############################################

        self.datapath = datapath
        self.msmtname = msmtname
        self.scriptname = scriptname
        self.scriptpath = scriptpath

        # ############################################
        ################ NWA SETTINGS ###############
        #############################################

        self.na_cfg = {
            'na_power': -30,
            'na_ifbw': 1000,
            'na_start': 4.0E9,
            'na_stop': 8.0E9,
            'na_sweep_pts': 1601,
            'na_avgs': 20,
            'na_delay': 0,
            'na_power_threshold': 0
        }

        self.sa_cfg = {
            'sa_center': 500E3,
            'sa_span': 1000E3,
            'sa_resbw': None,
            'sa_vidbw': 1E3,
            'sa_sweep_pts': 1601,
            'sa_avgs': 10,
            'sa_remote': False
        }

        self.labbrick_cfg = {'lb_freq': 7.785E9, 'lb_power': -30}

        self.jpa_cfg = {'flux_bias_limit': 2E-3}

        #self.jpa_bias = im['JPA_bias']
        #self.na = im['NWA']
        #self.fridge = im['FRIDGE']
        #self.heman = im['heman']
        #self.lb = im['labbrick']

        #self.sa = im['SA']

        #Hacky solution to get the spectrum analyzer to work
        #from slab.instruments import E4440
        #self.sa = E4440("E4440", address="192.168.14.152")

        self.today = time.strftime('%y%m%d')
        self.timestamp = time.strftime('%H%M%S')

    def find_nearest(self, array, value):
        """
        Finds the nearest value in array. Returns index of array for which this is true.
        """
        idx = (np.abs(array - value)).argmin()
        return idx

    def initiate_instrument(self, name, cfg_name):
        im = InstrumentManager()
        setattr(self, name, im[cfg_name])
        return True

    def create_new_datafolder(self, datapath, measurement_name, date,
                              timestamp):

        if not date in os.listdir(os.path.join(datapath)):
            os.mkdir(os.path.join(datapath, date))
            time.sleep(0.1)

        datafoldername = timestamp + '_' + measurement_name
        os.mkdir(os.path.join(datapath, date, datafoldername))

        return os.path.join(datapath, date, datafoldername)

    def create_new_file(self, datapath, measurement_name):
        datafoldername = self.create_new_datafolder(datapath, measurement_name,
                                                    self.today, self.timestamp)

        FileHandler, fname = self.create_file_for_write(
            datafoldername, measurement_name)

        shutil.copy(os.path.join(self.scriptpath, self.scriptname),
                    os.path.join(datafoldername, self.scriptname))

        return datafoldername, fname, FileHandler

    def create_file_for_write(self, datafoldername, measurement_name):
        fname = get_next_filename(datafoldername + '\\',
                                  measurement_name,
                                  suffix='.h5')
        print('Created file %s...' % fname)
        FileHandler = dataCacheProxy(expInst=measurement_name,
                                     filepath=os.path.join(
                                         datafoldername, fname + '.h5'))
        return FileHandler, fname

    def test_instruments(self, do_not_test=None):
        """
        Test if instruments are responding
        """
        heman_query = 'get_manifold_status'
        fridge_query = 'get_temperatures'
        bnc845_query = 'get_frequency'
        nwa_query = 'get_start_frequency'
        bncawg_query = 'get_frequency'
        digatt_query = 'get_attenuation'

        instruments = [
            'NWA', 'heman', 'FRIDGE', 'digi_att', 'BNC845_RF1', 'BNC_sync',
            'BNC_drive'
        ]
        queries = [
            nwa_query, heman_query, fridge_query, digatt_query, bnc845_query,
            bncawg_query, bncawg_query
        ]
        no_error = True

        for instrument, query in zip(instruments, queries):
            if instrument not in do_not_test:
                try:
                    getattr(self.im[instrument], query)()
                    print("Established connection with {}".format(instrument))
                    time.sleep(0.1)
                except:
                    print("ERROR for {}".format(instrument))
                    no_error = False

        if no_error:
            return True
        else:
            return False

    def power_ok(self, power, threshold=0):
        if power > threshold:
            print("Power exceeded threshold of %d dBm. Aborting measurement." %
                  threshold)
            return False
        else:
            return True

    def flux_bias_ok(self, current, threshold):
        if np.abs(current) > threshold:
            print("Current exceeds threshold of %d mA. Aborting measurement." %
                  threshold)
            return False
        else:
            return True

    def setup_alazar(self, config_dict):
        self.alazar = Alazar()

        try:
            print("new configuration file")
            cfg = AlazarConfig(config_dict)
            print(
                "config file has to pass through the AlazarConfig middleware.")
            self.alazar.configure(cfg)
            return True
        except:
            return False

    def take_single_trace(self,
                          FileHandler,
                          fstart,
                          fstop,
                          power,
                          ifbw,
                          sweep_pts,
                          noof_avgs,
                          verbose=True,
                          save=True):
        """
        Uses dataCacheProxy as FileHandler or None if saving is not required.

        Take a single trace with the network analyzer. Specify inputs in the
        dictionary na_cfg. Verbose gives response
        """

        if self.power_ok(power, threshold=self.na_cfg['na_power_threshold']):

            if verbose: print("Configuring the NWA")
            self.na.set_start_frequency(fstart)
            self.na.set_stop_frequency(fstop)
            self.na.set_power(power)
            self.na.set_ifbw(ifbw)
            self.na.set_sweep_points(sweep_pts)
            self.na.set_averages(noof_avgs)

            if noof_avgs > 1: self.na.set_average_state(True)

            time.sleep(0.1)

            if verbose: print("Taking data")
            fpoints, mags, phases = self.na.take_one_averaged_trace()

            if save:
                FileHandler.post('fpoints', fpoints)
                FileHandler.post('mags', mags)
                FileHandler.post('phases', phases)
                self.save_nwa_config(FileHandler)
            else:
                return fpoints, mags, phases

    def nwa_power_sweep(self,
                        FileHandler,
                        pwr_start,
                        pwr_stop,
                        steps,
                        save=True):
        """
        Uses dataCacheProxy as FileHandler

        Sweep the power of the network analyzer using 
        the function take_single_trace. Specify a starting, ending point
        for the power and the number of steps. 
        """
        p = np.linspace(pwr_start, pwr_stop, steps)
        print("Starting NWA powersweep...")

        fpoints = np.empty((steps, self.na_cfg['na_sweep_pts']),
                           dtype=np.float64)
        mags = np.empty((steps, self.na_cfg['na_sweep_pts']), dtype=np.float64)
        phases = np.empty((steps, self.na_cfg['na_sweep_pts']),
                          dtype=np.float64)

        self.plotter.clear()

        for sweep_idx, P in enumerate(p):
            print("\tP = %.2f dBm (%.1f%%)" %
                  (P, sweep_idx / float(steps) * 100))
            f, db, phi = self.take_single_trace(FileHandler,
                                                self.na_cfg['na_start'],
                                                self.na_cfg['na_stop'],
                                                P,
                                                self.na_cfg['na_ifbw'],
                                                self.na_cfg['na_sweep_pts'],
                                                self.na_cfg['na_avgs'],
                                                verbose=False,
                                                save=False)

            self.plotter.append_z('phase', phi,
                                  ((p[0], p[1] - p[0]), (f[0], f[1] - f[0])))
            self.plotter.append_z('mag', db,
                                  ((p[0], p[1] - p[0]), (f[0], f[1] - f[0])))

            fpoints[sweep_idx, :] = f
            mags[sweep_idx, :] = db
            phases[sweep_idx, :] = phi

            if save:
                FileHandler.post('fpoints', f)
                FileHandler.post('mags', db)
                FileHandler.post('phases', phi)
                FileHandler.post('powers', P)

            if msvcrt.kbhit() and msvcrt.getch() == 'q':
                break

        self.na.set_power(min(p))

        if save:
            self.save_nwa_config(FileHandler)
        else:
            return fpoints, mags, phases

    def flux_bias_sweep(self,
                        FileHandler,
                        current_start,
                        current_stop,
                        steps,
                        save=True):
        """
        Uses dataCacheProxy as FileHandler

        Sweep the current from the yokogawa sourc e. The
        linear sweep starts at current_start and stop at 
        current_stop. Resolution is determined by steps. 
        Flag save to save the data. 

        All currents in units of A, i.e. 1 mA = 1E-3
        """

        i = np.linspace(current_start, current_stop, steps)
        print("Starting Yoko currentsweep...")

        self.jpa_bias.set_mode(mode='curr')
        self.jpa_bias.set_current(0)
        self.jpa_bias.set_output()

        fpoints = np.empty((steps, self.na_cfg['na_sweep_pts']),
                           dtype=np.float64)
        mags = np.empty((steps, self.na_cfg['na_sweep_pts']), dtype=np.float64)
        phases = np.empty((steps, self.na_cfg['na_sweep_pts']),
                          dtype=np.float64)

        self.plotter.clear()

        for sweep_idx, I in enumerate(i):

            if self.flux_bias_ok(I, self.jpa_cfg['flux_bias_limit']):
                self.jpa_bias.set_current(I)
                time.sleep(0.2)
                print("\tI = %.6f mA (%.1f%%)" %
                      (I * 1E3, sweep_idx / float(steps) * 100))
                f, db, phi = self.take_single_trace(
                    FileHandler,
                    self.na_cfg['na_start'],
                    self.na_cfg['na_stop'],
                    self.na_cfg['na_power'],
                    self.na_cfg['na_ifbw'],
                    self.na_cfg['na_sweep_pts'],
                    self.na_cfg['na_avgs'],
                    verbose=False,
                    save=False)

                fpoints[sweep_idx, :] = f
                mags[sweep_idx, :] = db
                phases[sweep_idx, :] = phi

                if save:
                    FileHandler.append('fpoints', f)
                    FileHandler.append('mags', db)
                    FileHandler.append('phases', phi)
                    FileHandler.append('currents', I)

                self.plotter.append_z('phase', phi,
                                      ((1, 1), (f[0], f[1] - f[0])))
                self.plotter.append_z('mag', db, ((1, 1), (f[0], f[1] - f[0])))

                if msvcrt.kbhit() and msvcrt.getch() == 'q':
                    break
            else:
                break

        self.jpa_bias.set_output(0)
        self.jpa_bias.set_current(0)

        if save:
            self.save_nwa_config(FileHandler)

        return fpoints, mags, phases

    def level_meter_expt(self,
                         datapath,
                         measurement_name,
                         noof_puffs,
                         start_stop_pairs=None,
                         manual=True,
                         save=True,
                         pressure_limit=1.5E-2,
                         reps_per_puff=1,
                         puff_pressure=0.25,
                         max_temp=60E-3,
                         pressure_drop_timeout=600):
        """
        Fills the helium lines with a number of puffs specified by noof_puffs. 
        The time between each puff is specified by wait_time, and is 1s by default. 
        After each puff a spectrum is taken and after noof_puffs puffs the file is saved.
        """
        user_is_awake = input(
            "Starting helium puff sequence. Press 'c' to continue.")
        datafoldername = self.create_new_datafolder(datapath, measurement_name,
                                                    self.today, self.timestamp)
        shutil.copy(os.path.join(self.scriptpath, self.scriptname),
                    os.path.join(datafoldername, self.scriptname))

        self.plotter.clear()
        if user_is_awake == 'c' and self.heman.get_pressure() < pressure_limit:
            # Prepare file for write
            if save:
                FileHandler = dataCacheProxy(expInst=measurement_name,
                                             filepath=os.path.join(
                                                 datafoldername,
                                                 '%s.h5' % measurement_name))
                time.sleep(0.1)

            print("Helium puff sequence about to start...")

            puff = np.arange(noof_puffs)

            for puff_idx in puff:

                if manual:
                    another_puff = input("Press 'c' for another puff")
                    if another_puff == 'c':
                        pass
                    else:
                        break
                else:
                    settled = False
                    start_time = time.time()

                    while not settled:
                        print("...", end=' ')
                        settled = (self.fridge.get_mc_temperature() < max_temp
                                   ) and ((time.time() - start_time) > 60)
                        #start pumping
                        self.heman.set_cryostat(False)
                        self.heman.set_gas(False)
                        self.heman.set_pump(True)
                        time.sleep(1)

                self.heman.puff(pressure=puff_pressure,
                                min_time=60,
                                timeout=pressure_drop_timeout)
                print("\n%s Puff %d (%.1f%% done)" %
                      (time.strftime("%H%M%S"), puff_idx + 1,
                       (puff_idx + 1) / float(noof_puffs) * 100))

                if start_stop_pairs is None:

                    points, mags, phases = self.take_single_trace(
                        None,
                        self.na_cfg['na_start'],
                        self.na_cfg['na_stop'],
                        self.na_cfg['na_power'],
                        self.na_cfg['na_ifbw'],
                        self.na_cfg['na_sweep_pts'],
                        self.na_cfg['na_avgs'],
                        verbose=False,
                        save=False)

                    if save:
                        FileHandler.new_stack()
                        for r in range(reps_per_puff):
                            FileHandler.post('fpoints', points)
                            FileHandler.post('mags', mags)
                            FileHandler.post('phases', phases)

                            points, mags, phases = self.take_single_trace(
                                None,
                                self.na_cfg['na_start'],
                                self.na_cfg['na_stop'],
                                self.na_cfg['na_power'],
                                self.na_cfg['na_ifbw'],
                                self.na_cfg['na_sweep_pts'],
                                self.na_cfg['na_avgs'],
                                verbose=False,
                                save=False)

                        FileHandler.post('puff_nr', self.heman.get_puffs())
                        FileHandler.set_dict('Temperatures',
                                             self.fridge.get_temperatures())

                    self.plotter.append_z('mags', mags,
                                          ((1, 1),
                                           (points[0], points[1] - points[0])))
                    self.plotter.append_z('phases', phases,
                                          ((1, 1),
                                           (points[0], points[1] - points[0])))
                    self.plotter.append_y('puffs', self.heman.get_puffs())

                else:
                    for idx, f_zoom in enumerate(start_stop_pairs):
                        self.na_cfg['na_start'] = f_zoom[0]
                        self.na_cfg['na_stop'] = f_zoom[1]
                        points, mags, phases = self.take_single_trace(
                            None,
                            self.na_cfg['na_start'],
                            self.na_cfg['na_stop'],
                            self.na_cfg['na_power'],
                            self.na_cfg['na_ifbw'],
                            self.na_cfg['na_sweep_pts'],
                            self.na_cfg['na_avgs'],
                            verbose=False,
                            save=False)

                        if save:
                            FileHandler.new_stack() if idx == 0 else None
                            FileHandler.post('fpoints_%d' % idx, points)
                            FileHandler.post('mags_%d' % idx, mags)
                            FileHandler.post('phases_%d' % idx, phases)
                            FileHandler.post('puff_nr_%d' % idx,
                                             self.heman.get_puffs())
                            FileHandler.set_dict(
                                'Temperatures', self.fridge.get_temperatures())

                if save:
                    self.save_nwa_config(FileHandler)
                    print("Done writing to stack %s..." %
                          FileHandler.current_stack)
                else:
                    return points, mags, phases

        else:
            if self.heman.get_pressure() > pressure_limit:
                print("Measurement aborted, pressure > %.2e mbar" %
                      pressure_limit)
            else:
                print("Measurement aborted by user.")

    def get_sa_trace(self):
        """
        Get single trace from the spectrum analyzer
        :return: fpoints, magnitude
        """

        if self.sa_cfg['sa_avgs'] > 1:
            self.sa.set_average_state(True)
        else:
            self.sa.set_average_state(False)

        self.sa.configure(start=None,
                          stop=None,
                          center=self.sa_cfg['sa_center'],
                          span=self.sa_cfg['sa_span'],
                          resbw=self.sa_cfg['sa_resbw'],
                          vidbw=self.sa_cfg['sa_vidbw'],
                          sweep_pts=self.sa_cfg['sa_sweep_pts'],
                          avgs=self.sa_cfg['sa_avgs'],
                          remote=self.sa_cfg['sa_remote'])

        return self.sa.take_one()

    def fire_filament(self, amplitude, offset, frequency, pulse_length):
        self.initiate_instrument('fil', 'fil')
        self.fil.setup_driver(amplitude, offset, frequency, pulse_length)
        self.fil.fire_filament()

    def monitor_manifold_pressure(self,
                                  heman_name='heman',
                                  runtime=None,
                                  dt=1):
        """

        :param heman_name: Name as it appears in the instrument manager
        :param runtime: For how long should the pressure be monitored?
        :param dt: Timestep for the recording
        :return:
        """
        self.initiate_instrument('heman', heman_name)
        self.plotter.clear()

        t0 = time.time()
        while time.time() - t0 < runtime:
            self.heman.get_pressure()
            time.sleep(dt)

            self.plotter.append_xy('Puffs',
                                   time.time() - t0, self.heman.get_puffs())
            self.plotter.append_xy('Pressure (mbar)',
                                   time.time() - t0,
                                   self.heman.get_pressure() * 1E3)
            self.plotter.append_xy('Pump valve state',
                                   time.time() - t0,
                                   self.heman.get_manifold_status_bits()[1])
            self.plotter.append_xy('Cryostat valve state',
                                   time.time() - t0,
                                   self.heman.get_manifold_status_bits()[2])
            self.plotter.append_xy('Gas valve state',
                                   time.time() - t0,
                                   self.heman.get_manifold_status_bits()[0])

    def monitor_cryostat(self, runtime, dt):
        import time
        self.initiate_instrument('fridge', 'FRIDGE')
        self.plotter.clear()

        t0 = time.time()
        while time.time() - t0 < runtime:
            pressures = self.fridge.get_pressures()
            temperatures = self.fridge.get_temperatures()

            time.sleep(dt)
            T = time.time()

            # Pressures
            self.plotter.append_xy('Condense pressure', T - t0,
                                   pressures['Condense'])
            self.plotter.append_xy('Forepump pressure', T - t0,
                                   pressures['Forepump'])
            self.plotter.append_xy('Tank pressure', T - t0, pressures['Tank'])

            # Temperatures
            self.plotter.append_xy('PT2 plate', T - t0,
                                   temperatures['PT2 Plate'])
            self.plotter.append_xy('Still', T - t0, temperatures['Still'])
            self.plotter.append_xy('100 mK plate', T - t0,
                                   temperatures['100mK Plate'])
            self.plotter.append_xy('MC RuO2', T - t0, temperatures['MC RuO2'])
            self.plotter.append_xy('MC cernox', T - t0,
                                   temperatures['MC cernox'])

    def save_sa_config(self, FileHandler):
        """
        Uses datacache
        :param FileHandler: dataCacheProxy instance
        :return: None
        """
        FileHandler.set_dict("sa_config", self.sa_cfg)

    def save_nwa_config(self, FileHandler):
        """
        Uses datacache
        :param FileHandler: dataCacheProxy instance
        :return: None
        """
        FileHandler.set_dict("nwa_config", self.na_cfg)
Example #18
0
def main():
    expt_path="S:\\_Data\\120425 - 50nm Nb 20um resonator with crystal on top of first 2\\spin echo\\"
    config="instruments.cfg"
    #datapath='S:\\_Data\\'
    prefix="test_dynamic"
    #datapath=make_datapath(expt_path,prefix)
    sweep_pts=1601
    ifbw=1e3
    
    Freqs=linspace(5.79125e9-2e6,5.79125e9+2e6,100)

    
    im=InstrumentManager(expt_path+config)    
    RF1=im['RF1']
    #RF2=im['RF2']
    RF2=im['LB1']
    #na=im['NWA']
    
    RF1.set_output(True)
    RF2.set_output(True)
    RF1.set_mod(True)
    RF2.set_mod(False)
    RF1.set_power(12)
    RF2.set_power(0)
    

    print("Configure NA")
#    na.set_default_state()
#    na.set_power(-20)
#    na.set_ifbw(ifbw)
#    na.set_span(0.)
#    na.set_sweep_points(1)

    IFfreq=1e6
    #na.set_center_frequency(2.5703e9)
    #RF2.set_frequency(2.5703e9+IFfreq)

    config={'clock_edge': 'rising', 'trigger_delay': 0, 'ch1_filter': False, 
            'ch1_enabled': True, 'samplesPerRecord': 50048, 'bufferCount': 1, 
            'trigger_edge1': 'rising', 'trigger_edge2': 'rising', 'ch2_range': 4, 
            'clock_source': 'internal', 'trigger_level2': 1.0, 'trigger_level1': 1.0,
            'ch2_coupling': 'DC', 'trigger_coupling': 'DC', 'ch2_filter': False, 
            'trigger_operation': 'or', 'ch1_coupling': 'AC', 'trigger_source2': 'disabled', 
            'trigger_source1': 'external', 'recordsPerBuffer': 1, 'sample_rate': 1000000, 
            'timeout': 5000, 'ch1_range': 4, 'ch2_enabled': False, 'recordsPerAcquisition': 1}
            
    print("Configuring card")
    scope_settings= AlazarConfig(config)
    
    card=Alazar(scope_settings)
    card.configure(scope_settings)

    print("go")
    print("Taking %d data points." % len(Freqs))
    print("|"+("  "*(len(Freqs)/10))+" |")
    print("|", end=' ')
    #figure(1)
    tpts,ch1_pts,ch2_pts=card.acquire_avg_data()    
    #fig1=FigureClient(xlabel='Time',ylabel='Amplitude',title='Scope')
    #fig2=FigureClient(xlabel='Time',ylabel='Amplitude',title='S21')
    #fig3=FigureClient(xlabel='Time',ylabel='Amplitude',title='S21')
    win = ScriptPlotWin(grid_x=2)
    scope_plot = win.add_linePlot(title="Scope")
    S21_plot_1 = win.add_linePlot(title="S21 1")
    S21_plot_2 = win.add_linePlot(title="S21 2")
    win.go()
    Amps=[]
    freqs=[]
    for ind,ff in enumerate(Freqs):
        if mod(ind,len(Freqs)/10.) ==0: print("-", end=' ')
        RF1.set_frequency(ff)
        RF2.set_frequency(ff+IFfreq)
#        na.set_center_frequency(ff)
        #print "freq=%f" % ff
        #time.sleep(1.15)
        tpts,ch1_pts,ch2_pts=card.acquire_avg_data()    
        #fig1.update_plot((tpts,ch1_pts))
        scope_plot.send((tpts, ch1_pts))
        dtpts,amp1pts,phi1pts,amp2pts,phi2pts=digital_homodyne(tpts,ch1_pts,ch2_pts,IFfreq,AmpPhase=True)
        #print "A1: %f, Phi1: %f, A2: %f, Phi2: %f" % card.heterodyne(tpts,ch1_pts,ch2_pts,IFfreq)      
        #A1= heterodyne(tpts,ch1_pts,ch2_pts,IFfreq)[0]
        freqs.append(ff/1e9)
        Amps.append(mean(amp1pts))
        #fig2.update_plot((dtpts,amp1pts))
        #fig3.update_plot((array(freqs),array(Amps)))
        S21_plot_1.send((dtpts, amp1pts))
        S21_plot_2.send((array(freqs),array(Amps)))
        
    print("|")
Example #19
0
    def sweep_bncrf_frequency(self):
        """
        Sweeps the frequency of the BNC RF source.
        """

        #self.plotsInitialized = False
        alazar_range_raw = str(self.combobox_alazar_range.currentText())
        alazar_ch = str(self.combobox_alazar_channel.currentText())
        sweep_center = np.float(self.lineEdit_bncrf_sweep_center.text()) * 1E9
        sweep_span = np.float(self.lineEdit_bncrf_sweep_span.text()) * 1E6
        sweep_numpoints = np.int(self.lineEdit_bncrf_noofpoints.text())

        sweep_points = np.linspace(sweep_center - sweep_span / 2.,
                                   sweep_center + sweep_span / 2.,
                                   sweep_numpoints)

        self.x = None
        self.y = None
        self.update_plots(xlabel='BNC Frequency (Hz)',
                          ylabel='Scope ch%s (V)' % alazar_ch)

        if alazar_range_raw == '40 mV':
            alazar_range = 40E-3
        elif alazar_range_raw == '100 mV':
            alazar_range = 100E-3
        elif alazar_range_raw == '200 mV':
            alazar_range = 200E-3
        elif alazar_range_raw == '400 mV':
            alazar_range = 400E-3
        elif alazar_range_raw == '1 V':
            alazar_range = 1.0
        elif alazar_range_raw == '2 V':
            alazar_range = 2.0
        elif alazar_range_raw == '4 V':
            alazar_range = 4.0

        sample_rate = 20E3  #sample rate in Hz
        noof_samples = 1024
        noof_avgs = 1
        ch1_range = alazar_range
        ch2_range = alazar_range
        ch1_coupling = 'DC'
        ch2_coupling = 'DC'
        ch1_trigger_level = 2.5
        ch2_trigger_level = 2.5
        timeout = int(80E3)
        trigger_rate = 1e1

        print("Your trigger pulse width should be > %.3e s." %
              (1 / sample_rate))
        print("Time out should be higher than %.3e" %
              (noof_samples / sample_rate * 1e3))

        config = {
            'clock_edge': 'rising',
            'clock_source': 'reference',
            'samplesPerRecord': noof_samples,
            'recordsPerBuffer': 1,
            'recordsPerAcquisition': noof_avgs,
            'bufferCount': 1,
            'sample_rate': sample_rate / 1E3,  #in kHz
            'timeout': timeout,  #After this are ch1 settings
            'ch1_enabled': True,
            'ch1_filter': False,
            'ch1_coupling': ch1_coupling,
            'ch1_range': ch1_range,  #After this are ch2 settings
            'ch2_enabled': True,
            'ch2_filter': False,
            'ch2_coupling': ch2_coupling,
            'ch2_range': ch2_range,  #After this are trigger settings
            'trigger_source1': 'external',
            'trigger_level1': ch1_trigger_level,
            'trigger_edge1': 'rising',
            'trigger_source2': 'disabled',
            'trigger_level2': ch2_trigger_level,
            'trigger_edge2': 'rising',
            'trigger_operation': 'or',
            'trigger_coupling': 'DC',
            'trigger_delay': 0
        }

        print("Total time trace signal is %.2f seconds" %
              (noof_samples / float(sample_rate)))

        alazar = Alazar()

        print("new configuration file")
        cfg = AlazarConfig(config)
        print("config file has to pass through the AlazarConfig middleware.")
        alazar.configure(cfg)

        self.x = sweep_points
        self.y = list()

        for idx, f in enumerate(sweep_points):
            self.M.BNC_RF.set_frequency(f)
            self.set_bnc_labels()
            t, ch1, ch2 = alazar.acquire_avg_data(excise=(0, -56))
            time.sleep(0.1)

            if alazar_ch == '1':
                self.y.append(np.mean(ch1))
            else:
                self.y.append(np.mean(ch2))

        self.update_plots(xlabel='BNC Frequency (Hz)',
                          ylabel='Scope ch%s (V)' % alazar_ch)
        gui.QApplication.processEvents()