Пример #1
0
def analysis(meas, data=None):
    if data is None:
        data = meas.get_ys()

    if len(meas.xs) > 1 and len(meas.ys) >1:
        centers = []
        data = data.reshape((len(meas.xs), len(meas.ys)))

        for xidx in range(len(meas.xs)):
            fit = fitter.Fitter('gaussian')
            result = fit.perform_lmfit(meas.ys, data[xidx],
                                       plot=False,
                                       print_report=True)
            centers.append(result.params['x0'].value)

        plt.figure()
        plt.plot(meas.xs, centers)

        fit = fitter.Fitter('linear')
        result = fit.perform_lmfit(meas.xs, centers, plot=False)
        p = result.params
        ys_fit = fit.test_values(meas.xs, p=p)

        plt.plot(meas.xs, ys_fit)

        detuning_MHz = 1e3*result.params['m'].value/(2*np.pi)
        plt.title('Detuning: %0.6f MHz' % detuning_MHz)
        plt.show()

    return detuning_MHz
Пример #2
0
def analysis(meas, data=None, fig=None, detune=None):
    xs = np.array(meas.delays, dtype=np.float) / 1e3  # us
    ys, meas_fig = meas.get_ys_fig(data, fig)
    if data is not None:
        ys = data
    if fig is None:
        fig = meas_fig
    if detune is None:
        detune = meas.detune / 1e3  # in kHz and always positive?

    fig.axes[0].plot(xs, ys, 'ks', ms=3)

    if not meas.double_freq:
        f = fitter.Fitter('exp_decay_sine')
        p = f.get_lmfit_parameters(xs, ys)
        if meas.fix_freq:
            p['f'].value = meas.detune / 1e6
            p['f'].vary = not meas.fix_freq
        result = f.perform_lmfit(xs, ys, p=p, print_report=True, plot=False)
        ys_fit = f.test_values(xs, noise_amp=0.0, p=result.params)

        f = result.params['f'].value * 1e3
        tau = result.params['tau'].value

        txt = 'tau = %0.3f us\n' % (tau)
        txt += 'f = %0.4f kHz\n' % (f)
        txt += 'software df = %0.3f kHz\n' % (detune)
        txt += 'frequency detuning = %0.4f kHz' % (detune - f)

    else:
        f = fitter.Fitter('exp_decay_double_sine')
        result = f.perform_lmfit(xs, ys, print_report=True, plot=False)
        ys_fit = f.test_values(xs, noise_amp=0.0, p=result.params)

        f = result.params['f'].value
        f1 = result.params['f1'].value
        tau = result.params['tau'].value

        txt = 'tau = %0.3f us\n' % (tau)
        txt += 'f = %0.4f kHz\n' % (f)
        txt += 'f1 = %0.4f kHz\n' % (f1)
        txt += 'software df = %0.3f kHz\n' % (detune)

    fig.axes[0].plot(xs, ys_fit, label=txt)
    fig.axes[1].plot(xs, (ys_fit - ys) / ys_fit * 100.0, marker='s')

    fig.axes[0].legend()
    fig.axes[0].set_ylabel('Intensity [AU]')
    fig.axes[1].set_ylabel('Fit error [%]')
    fig.axes[1].set_xlabel('Time [us]')

    fig.canvas.draw()

    return result.params, detune - f
Пример #3
0
def analysis(meas, data=None, fig=None, vary_ofs=False):
    ys, fig = meas.get_ys_fig(data, fig)  # background subtracted.
    xs = meas.xs
    #    fig.axes[1].plot(ys, 'ks-', label='bg subtracted')

    f = fitter.Fitter('poisson')
    p = f.get_lmfit_parameters(xs, ys)
    p['n'].value = meas.proj_num
    p['n'].vary = False
    p['ofs'].value = 0.0
    p['ofs'].vary = vary_ofs
    result = f.perform_lmfit(xs, ys, p=p, plot=False)
    params = result.params
    ys_fit = f.test_values(xs, p=params, noise_amp=0.0)

    txt = 'one photon disp amplitude: %0.3f' % params['xscale'].value
    fig.axes[1].plot(xs, ys_fit, 'g-', label=txt)
    fig.axes[1].legend()

    fig.axes[0].set_ylabel('Intensity [AU]')
    fig.axes[1].set_ylabel('Intensity [AU]')
    fig.axes[2].set_xlabel('Displacement [alpha]')

    fig.axes[2].plot(xs, ys_fit - ys, 'ks-')
    fig.canvas.draw()
    return params
Пример #4
0
 def perform_fit(self):
     if self.fit_func is None:
         return
     xs, ys = self.get_averaged(ret_xs=True)
     f = fitter.Fitter(self.fit_func)
     ret = f.perform_lmfit(xs, ys, plot=False, **self.fit_func_kwargs)
     self.fit_params = ret.params
     self.fit = f
     return f
Пример #5
0
def analysis(xs, ys, fig, double_exp=False):

    #    xs = np.array(meas.delays, dtype=np.float) / 1e3 # us
    #    ys, fig = meas.get_ys_fig(data, fig)

    fig.axes[0].plot(xs, ys, 'ks', ms=3)

    if double_exp == False:
        f = fitter.Fitter('exp_decay')
        result = f.perform_lmfit(xs, ys, print_report=True, plot=False)
        ys_fit = f.eval_func()
        tau = result.params['tau']
        txt = 'tau = %0.3f us +\- %0.4f us' % (tau.value, tau.stderr)
    else:
        f = fitter.Fitter('exp_decay_double')
        result = f.perform_lmfit(xs, ys, print_report=True, plot=False)
        ys_fit = f.eval_func()

        A = result.params['A'].value
        B = result.params['B'].value
        A_weight = A / (A + B) * 100.0
        B_weight = B / (A + B) * 100.0
        tau1 = result.params['tau'].value
        tau1_err = result.params['tau'].stderr
        tau2 = result.params['tau1'].value
        tau2_err = result.params['tau1'].stderr

        txt = 'tau1 (weight) = %0.3f us +/- %0.3f us (%0.2f%%)\n' % (
            tau1, tau1_err, A_weight)
        txt += 'tau2 (weight) = %0.3f us +/- %0.3f us (%0.2f%%)' % (
            tau2, tau2_err, B_weight)

    fig.axes[0].plot(xs, ys_fit, label=txt)
    fig.axes[1].plot(xs, (ys_fit - ys), marker='s')

    fig.axes[0].legend()
    fig.axes[0].set_ylabel('Intensity [AU]')
    fig.axes[1].set_ylabel('Residuals')
    fig.axes[1].set_xlabel('Time [us]')

    fig.canvas.draw()
    return result.params
Пример #6
0
 def analyze_histogram_blob(self, plot=False, nbins=41, fit_func_kwargs={}):
     '''
     Fit single shot histogram with a single Gaussian peak.
     '''
     hist, xs, ys = np.histogram2d(np.real(self.data_se), np.imag(self.data_se), bins=nbins)
     hist = hist.T
     XS, YS = np.meshgrid((xs[:-1]+xs[1:])/2, (ys[:-1]+ys[1:])/2)
     print 'Minmax xs: %s,%s' % (np.min(XS), np.max(XS))
     f = fitter.Fitter('gaussian2d')
     f.perform_lmfit(XS, YS, hist, plot=plot, plot_guess=False, **fit_func_kwargs)
     return f.fit_params
Пример #7
0
def fit_spectroscopy(freqs,
                     IQs,
                     amp_phase=AMP,
                     fit_type=LOR,
                     fig=None,
                     label='',
                     plot_residuals=True):

    if fig is None:
        fig = plt.figure()
        if plot_residuals:
            from matplotlib import gridspec
            gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
            fig.add_subplot(gs[0])
            fig.add_subplot(gs[1])
        else:
            fig.add_subplot(111)

    if freqs[0] > 1e9:
        freqs = freqs / 1e6

    if amp_phase == AMP:
        data = np.abs(IQs)
    elif amp_phase == PHASE:
        data = np.angle(IQs, deg=True)

    fit = fitter.Fitter(fit_type)
    result = fit.perform_lmfit(freqs, data, print_report=False, plot=False)
    datafit = fit.eval_func()

    x0 = result.params['x0']
    fit_label = label + 'center = %0.4f MHz,' % (x0)
    if fit_type == LOR:
        fit_label += ' width = %0.4f MHz' % (result.params['w'])
    elif fit_type == GAUSS:
        fit_label += ' sigma = %0.4f MHz' % (result.params['sigma'])

    fig.axes[0].plot(freqs, data, marker='s', ms=3, label='')
    fig.axes[0].plot(freqs, datafit, ls='-', ms=3, label=fit_label)

    fig.axes[0].legend(loc='best')
    if amp_phase == AMP:
        fig.axes[0].set_ylabel('Intensity [AU]')
    elif amp_phase == PHASE:
        fig.axes[0].set_ylabel('Phase [deg]')
    fig.axes[0].set_xlabel('Frequency [MHz]')

    if plot_residuals:
        fig.axes[1].plot(freqs, (data - datafit) / datafit * 100.0, ls='-')
        fig.axes[1].set_ylabel('error [%]')
        fig.axes[1].set_xlabel('Frequency [MHz]')

    return result, fig
Пример #8
0
 def analyze_jpc_histogram(self, plot=False, nbins=41, fit_func_kwargs={}):
     '''
     Fit single shot histogram with two Gaussian peaks, convenient if a
     measurement is performed after a pi/2 pulse. Due to the arbitrariness
     of which blob represents |g> and |e>, it is probably better to do
     two experiments which result in |g> and |e> separately.
     '''
     hist, xs, ys = np.histogram2d(np.real(self.data_se), np.imag(self.data_se), bins=nbins)
     hist = hist.T
     XS, YS = np.meshgrid((xs[:-1]+xs[1:])/2, (ys[:-1]+ys[1:])/2)
     f = fitter.Fitter('double_gaussian_2dhist')
     f.perform_lmfit(XS, YS, hist, plot=plot, plot_guess=False, **fit_func_kwargs)
     return f.fit_params
Пример #9
0
def analysis(meas,
             data=None,
             fig=None,
             repeat_pulse=1,
             fit_type=FIT_AMP,
             txt=''):
    ys, fig = meas.get_ys_fig(data, fig)
    xs = meas.amps

    if fig is None:
        fig = plt.figure()
        gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
        fig.add_subplot(gs[0])
        fig.add_subplot(gs[1])

    fig.axes[0].plot(xs, ys, 'ks', ms=3)

    if fit_type == FIT_AMPFUNC:
        pass
    else:
        f = fitter.Fitter('sine')
        result = f.perform_lmfit(xs, ys, print_report=False, plot=False)
        p = result.params
        ys_fit = f.eval_func()

        pi_amp = repeat_pulse / (2.0 * p['f'].value)

        txt += 'Amp = %0.3f +/- %0.4f\n' % (p['A'].value, p['A'].stderr)
        txt += 'f = %0.4f +/- %0.5f\n' % (p['f'].value, p['f'].stderr)
        txt += 'phase = %0.3f +/- %0.4f\n' % (p['dphi'].value,
                                              p['dphi'].stderr)
        txt += 'period = %0.4f\n' % (1.0 / p['f'].value)
        txt += 'pi amp = %0.6f; pi/2 amp = %0.6f' % (pi_amp, pi_amp / 2.0)
        fig.axes[0].plot(xs, ys_fit, label=txt)
        fig.axes[1].plot(xs, ys - ys_fit, marker='s')

    fig.axes[0].set_ylabel('Intensity [AU]')
    fig.axes[0].set_xlabel('Pulse amplitude')
    fig.axes[0].legend(loc=0)

    fig.canvas.draw()
    return result.params
Пример #10
0
def analysis(meas, data=None, fig=None, **kwargs):
    #to constrain a fit params, add kwarg 'var_name' = value
    if 'dphi' not in kwargs:
        kwargs['dphi'] = -np.pi / 2

    ys, fig = meas.get_ys_fig(data, fig)
    ys = data
    xs = meas.amps

    fig.axes[0].plot(xs, ys, 'ks', ms=3)

    if meas.fit_type == FIT_AMPFUNC:

        pass

    else:  # meas.fit_type == FIT_AMP

        r = fitter.Fitter('sine')
        result = r.perform_lmfit(xs,
                                 ys,
                                 print_report=False,
                                 plot=False,
                                 **kwargs)
        p = result.params
        # ys_fit = r.test_values(xs, p=p)
        ys_fit = r.eval_func(xs, params=p)

        pi_amp = 1 / (2.0 * p['f'].value)

        txt = 'Amp = %0.3f +/- %0.4f\n' % (p['A'].value, p['A'].stderr)
        txt += 'f = %0.4f +/- %0.5f\n' % (p['f'].value, p['A'].stderr)
        txt += 'phase = %0.3f +/- %0.4f\n' % (p['dphi'].value,
                                              p['dphi'].stderr)
        fig.axes[0].plot(xs, ys_fit, label=txt)
        fig.axes[1].plot(xs, ys - ys_fit, marker='s')

    fig.axes[0].set_ylabel('Intensity [AU]')
    fig.axes[0].set_xlabel('Pulse amplitude')
    fig.axes[0].legend(loc=0)

    fig.canvas.draw()
    return result.params
Пример #11
0
def analysis(meas, data=None, fig=None, txt=''):
    ys, fig = meas.get_ys_fig(data, fig)
    xs = meas.detunings
    #####
    fit = fitter.Fitter('lorentzian')
    p = fit.get_lmfit_parameters(xs, ys)
    result = fit.perform_lmfit(xs, ys, print_report=False, plot=False, p=p)
    datafit = fit.eval_func()

    x0 = result.params['x0']
    fit_label = txt + 'center = %0.4f MHz,' % (
        x0 / 1e6) + ' FWHM = %0.4f MHz' % (result.params['w'] / 1e6)
    ######

    fig.axes[0].plot(xs / 1e6, ys, marker='s', ms=3, label='')
    fig.axes[0].plot(xs / 1e6, datafit, ls='-', ms=3, label=fit_label)  #####

    # fig.axes[0].plot(xs/1e6, ys)
    fig.axes[0].set_xlabel('Detuning (MHz)')
    fig.axes[0].set_ylabel('Intensity (AU)')
    # fig.canvas.draw()
    fig.axes[0].legend(loc='best')

    return result.params
Пример #12
0
def analysis(meas, data=None, fig=None, detune=None):
    xs = np.array(meas.delays, dtype=np.float) / 1e3  # us
    ys, meas_fig = meas.get_ys_fig(data, fig)
    if data is not None:
        ys = data
    if fig is None:
        fig = meas_fig
    if detune is None:
        detune = meas.detune / 1e3  # in kHz and always positive?

    fig.axes[0].plot(xs, ys, 'ks', ms=3)

    f = fitter.Fitter(meas.fit_type)

    if meas.fit_type == 'exp_decay_double_sine':
        result = f.perform_lmfit(xs, ys, print_report=True, plot=False)
        ys_fit = f.eval_func()

        f1 = result.params['f1'].value
        f2 = result.params['f2'].value
        tau = result.params['tau'].value

        txt = 'tau = %0.3f us\n' % (tau)
        txt += 'f1 = %0.4f kHz\n' % (f1 * 1e3)
        txt += 'f2 = %0.4f kHz\n' % (f2 * 1e3)
        txt += 'software df = %0.3f kHz\n' % (detune)

    elif meas.fit_type == 'gaussian_decay':
        result = f.perform_lmfit(xs, ys, print_report=True, plot=False)
        ys_fit = f.eval_func()

        A = result.params['area'].value / (
            2 * result.params['sigma'].value) / np.sqrt(np.pi / 2)
        tau = result.params['sigma'].value

        txt = 'tau = %0.3f us\n' % (tau)
        txt += 'A = %0.4f' % (A)

    elif meas.fit_type == 'exp_decay':
        result = f.perform_lmfit(xs, ys, print_report=True, plot=False)
        ys_fit = f.eval_func()

        tau = result.params['tau'].value

        txt = 'tau = %0.3f us\n' % (tau)

    elif meas.fit_type == 'quadratic':
        result = f.perform_lmfit(xs, ys, print_report=True, plot=False)
        ys_fit = f.eval_func()

        a = result.params['a'].value
        b = result.params['b'].value
        tau = b / 2.0

        txt = 'time offset = %0.3f us\n' % (tau)

    else:  # default case of exp_decay_sine
        p = f.get_lmfit_parameters(xs, ys)
        if meas.fix_freq:
            p['f'].value = meas.detune / 1e6
            p['f'].vary = not meas.fix_freq
        result = f.perform_lmfit(xs, ys, p=p, print_report=True, plot=False)
        ys_fit = f.eval_func()

        f = result.params['f'].value * 1e3
        tau = result.params['tau'].value

        txt = 'tau = %0.3f us\n' % (tau)
        txt += 'f = %0.4f kHz\n' % (f)
        txt += 'software df = %0.3f kHz\n' % (detune)
        txt += 'frequency detuning = %0.4f kHz' % (detune - f)

    fig.axes[0].plot(xs, ys_fit, label=txt)
    fig.axes[1].plot(xs, (ys_fit - ys), marker='s')

    fig.axes[0].legend()
    fig.axes[0].set_ylabel('Intensity [AU]')
    fig.axes[1].set_ylabel('Residuals')
    fig.axes[1].set_xlabel('Time [us]')

    fig.canvas.draw()

    return result.params
Пример #13
0
def analysis(phases, delays, data, fig=None):

    if fig is None:
        fig = plt.figure()
        gs = gridspec.GridSpec(1, 2, width_ratios=[1, 1])
        gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
        fig.add_subplot(gs[0])
        fig.add_subplot(gs[1])

    fig.axes[0].clear()
    fig.axes[1].clear()
    fig.canvas.draw()

    data = data.reshape(len(delays), 2, len(phases))
    params = []

    for i, d in enumerate(delays):
        for j, expt_type in enumerate([u'0-1', u'1-2']):
            xs = phases
            ys = data[i, j, :]

            f = fitter.Fitter('sine')
            p = f.get_lmfit_parameters(xs, ys)
            p['f'].value = 1.0
            p['f'].vary = False
            result = f.perform_lmfit(xs,
                                     ys,
                                     p=p,
                                     print_report=False,
                                     plot=False)
            p = result.params
            ys_fit = f.fit_func(xs, **f.get_params_dict(result.params))

            txt = '%s delay: %d ns; phase: %0.5f' % (expt_type, d,
                                                     p['dphi'].value)
            fig.axes[0].plot(xs, ys, marker='s', ms=3)
            fig.axes[0].plot(xs, ys_fit, label=txt)

            params.append(p)

    fig.axes[0].set_ylabel('Intensity [AU]')
    fig.axes[0].set_xlabel('$\pi$ rotation angle (rad)')
    fig.axes[0].legend(loc=0)

    # fit phases
    phases = np.array([p['dphi'].value for p in params])
    print phases
    #    phases = zip(*[iter(phases)]*2) # (delays, pi/nopi)
    #    dphi = [ps[1] - ps[0] for ps in phases]
    dphi = phases[1::2] - phases[::2]
    #    dphi = np.unwrap(dphi)
    print 'dphi: %s' % (dphi, )
    #    f = fitter.Fitter('linear')
    #    result = f.perform_lmfit(delays, dphi, print_report=False, plot=False)
    #    ys_fit = f.fit_func(delays, **f.get_params_dict(result.params))
    print 'delays: %s' % (delays, )
    f = np.polyfit(delays, dphi, 1)
    ys_fit = np.poly1d(f)(delays)

    txt = 'slope = %0.3f KHz' % (f[0] /
                                 (2 * np.pi) * 1e6)  # result.params['m'].value
    fig.axes[1].plot(delays, dphi, marker='s')
    fig.axes[1].plot(delays, ys_fit, label=txt)
    fig.axes[1].legend(loc=0)

    fig.canvas.draw()

    return params
            atten=atten,
            folder=folder,  # fmt='UPH',
            save=True,
            fpre=title,
            h5file=h5folder,
            display=(not fit_this),
            returnfile=True)

        temperature = (instruments['fridge'].get_temperature() *
                       1000. if instruments['fridge'] else -1.)
        fridge_in_pwr = vna.get_power() + atten
        lbl = '\npwr = %.2f dBm\ntemp = %.3f mK' % (fridge_in_pwr, temperature)

        if fit_this:
            from lib.math import fitter
            f = fitter.Fitter('asymmetric_v_hanger')
            rtdata_f, rtdata_db, _ = np.loadtxt(fn, unpack=True)
            x = rtdata_f[excise_start:]
            ylin = from_dB(rtdata_db[excise_start:])
            result = f.perform_lmfit(x, ylin, print_report=True, plot=True)
            params = result.params

            qi = params['qi'].value
            qierr = params['qi'].stderr
            if qierr == 0.0:
                qierr = qierr  # qi
            goodness = 1 - qierr / np.abs(qi)
            goodness1 = 1 - params['qcr'].stderr / np.abs(params['qcr'].value)
            goodness2 = 1 - params['qci'].stderr / np.abs(params['qci'].value)
            goodness = goodness * goodness1 * goodness2
            print 'qi: %.3e; goodness: %.3f, %.3f, %.3f' % (
Пример #15
0
IQavg = np.average(IQ, 0)
ts = np.arange(len(IQavg)) * 0.020
f = plt.figure()
plt.suptitle('Avg shot')
ax1 = f.add_subplot(211)
ax1.plot(ts, np.real(IQavg), label='Re')
ax1.plot(ts, np.imag(IQavg), label='Im')
ax1.plot(ts, np.abs(IQavg), label='Abs')
ax1.plot(ts, np.abs(IQavg)**2, label='Pwr')
ax1.set_xlabel('Time [usec]')
ax1.set_ylabel('Signal [mV]')
ax2 = f.add_subplot(212)
ax2.plot(np.real(IQavg), np.imag(IQavg))

fit = fitter.Fitter('exp_decay')
imax = np.argmax(np.abs(IQavg)) + 10
ret = fit.perform_lmfit(ts[imax:], np.abs(IQavg[imax:]))
ax1.plot(ts[imax:],
         fit.eval_func(ts[imax:]),
         label='tau = %.01f +- %.01f nsec' %
         (ret.params['tau'].value * 1000, ret.params['tau'].stderr * 1000))
ax1.legend()

envelope = IQavg.conj()
envelope *= (1.99 / np.max(np.abs(envelope)))
if SAVE_ENV:
    np.savez(ENV_FILE, envelope=envelope)
mclient.instruments['readout'].set_envelope(ENV_FILE)

if ROTATION:
Пример #16
0
def power_sweep(vna,pows,fridge=None,folder=None,avgs_start=1,avgs_stop=1,
                IF_BANDWIDTH=20,NUM_POINTS=501,fpre='',fpost=".dat",
                PULSE_TUBE='ON',save=True,revert=True,display=True,atten=0,
                reverse=False,sweep_type='LIN',plot_type='MAG',fmt='PLOG',
                printlog=True, fit=False, h5file=None):
    
    # atten = e.g. -10 dB :: negative if attenuating; enter powers you actually want AFTER attenuation (not VNA output)

    VNA_timeout = None
    NUM_STEPS = np.size(pows)
    if reverse:
        pows = pows[::-1]
        AVGS = np.round(np.logspace(np.log10(avgs_stop),np.log10(avgs_start),NUM_STEPS))
    else:
        AVGS = np.round(np.logspace(np.log10(avgs_start),np.log10(avgs_stop),NUM_STEPS))
    
    if revert:
        _state = "python_temp"
        vna.set_instrument_state_data('CST') # settings and calibration
        vna.set_instrument_state_file(_state)
        vna.save_state()
    
    if save and folder and not os.path.exists(folder):
        os.makedirs(folder)
    elif save and not folder:
        print "Chose to save but no folder provided."
        return

    tot_traces = np.sum(AVGS)
    vna.do_enable_averaging()
    vna.set_points(NUM_POINTS)
    vna.set_if_bandwidth(IF_BANDWIDTH)
    vna.set_sweep_type(sweep_type)
    xs = vna.do_get_xaxis()
    
    if h5file:
        cur_group = strftime('%y%m%d')
        _iteration_start = strftime('%H%M%S')
        datadir = _iteration_start+'//'
                                
        h5f = h5py.File(h5file)
        g = h5f.require_group(cur_group)
        dg1 = g.create_dataset(datadir+'//frequencies', data=xs)
        dg1.attrs.create('run_time', _iteration_start)
        
        h5f.close()
    
    if printlog:
        print "Getting timing information and preparing trigger..."
    sleep(0.1)

    if vna.get_sweep_type()=='SEGM':
        sweep_time = float(vna.get_segment_sweep_time())
    else:
        sweep_time = float(vna.get_sweep_time())
    tot_time = tot_traces * sweep_time
    
    if printlog:
        print "Total duration of this experiment will be %.2f minutes."%(tot_time/60,)
        
    if fridge:
        fridge.do_set_pulse_tube(PULSE_TUBE)
        sleep(5)
        if printlog:
            print "Pulse tube is %s. Beginning measurement."%(fridge.do_get_pulse_tube(),)
    if display:
        fig = plt.figure()
        ax = fig.add_subplot(111)
    try:
        ys = {}
        for idx_power, power in enumerate(pows):
            vna.set_power(power-float(atten))
            this_pwr = vna.get_power()
            out_pwr = this_pwr+atten
            this_avgs = AVGS[idx_power]
            
            if VNA_timeout:
                this_time = (sweep_time * this_avgs * VNA_timeout) + np.size(pows)*NUM_POINTS*10 # ms
            else:
                this_time = (sweep_time * this_avgs * 1250.0) + np.size(pows)*NUM_POINTS*10 # ms
            
            # an approximation based on 10ms/pt for transfer, 25% overhead on waiting/capture
            vna.set_average_factor(this_avgs)
            ys[idx_power] = []
            this_time = np.max(np.array([this_time, 5000.])) # 5s timeout minimum
            if this_time < 30e3:   
                # print this_time
                vna.set_timeout(this_time)
                ys[idx_power] = vna.do_get_data(fmt=fmt, opc=True, timeout=this_time)
            else:
                if printlog:
                    print "[NOTICE] Triggering each average."
                if VNA_timeout:             
                    to = np.max(np.array([sweep_time * VNA_timeout, 5000.]))
                else:
                    to = np.max(np.array([sweep_time * 1250.0, 5000.]))
                vna.set_timeout(to)
                # print to
                ys[idx_power] = vna.do_get_data(fmt=fmt, opc=True, trig_each_avg=True, timeout=this_time)
            power=float(vna.get_power()+atten)
            
            try:
                temp=fridge.do_get_temperature()*1000
            except:
                temp=-1.0
                
            try:
                if display:
                    ax.plot(xs,ys[idx_power][0],label='%.2f dBm, %.2f mK'%(power,temp))
                    fig.canvas.draw()
                    QtGui.QApplication.processEvents()
            except:
                pass
            
            if save and folder:
                fname="%s%s%2.2fdB_%3.2fmK%s"%(folder,fpre,power,temp,fpost)
                if os.path.isfile(fname): # prevent overwrites
                    fname+='_%s'%(strftime('%H%M%S'),)
                data = np.transpose((xs,ys[idx_power][0],ys[idx_power][1]))
                np.savetxt(fname, data, fmt='%.9f', delimiter='\t')
                if fit:
                    # import mag_fit_resonator
                    lbl = '\npwr = %.2f dBm\ntemp = %.3f mK'%(vna.get_power()+atten,temp)
                    print lbl
                    rtdata_f, rtdata_db, _ = np.loadtxt(fname,unpack=True)
                    # params, _, _ = mag_fit_resonator.quick_hanger_fit(rtdata_f, rtdata_db, show=True, extra_info=lbl, returnparams=True)
                    from lib.math import fitter
                    f = fitter.Fitter('asymmetric_v_hanger')
                    # rtdata_f, rtdata_db, _ = np.loadtxt(fn,unpack=True)
                    x = rtdata_f
                    ylin = from_dB(rtdata_db)
                    result = f.perform_lmfit(x, ylin, print_report=True, plot=True)
                    params = result.params
                if printlog:
                    print "Saved %s"%fname
                    print "%.2f minutes remain."%(np.sum(AVGS[idx_power+1:])*sweep_time/60,)

            if save and h5file:
                h5f = h5py.File(h5file)
                g = h5f.require_group(cur_group)
        
                dg = g.create_dataset(datadir+'%.2f'%(out_pwr,)+'//magnitude', data=ys[idx_power][0])
                dg.attrs.create('run_time', _iteration_start)
                dg.attrs.create('VNA_power',this_pwr)
                dg.attrs.create('attenuation',atten)
                dg.attrs.create('averages',this_avgs)
                dg.attrs.create('IFbandwidth',vna.get_if_bandwidth())
                dg.attrs.create('measurement',str(vna.get_measurement()))
                dg.attrs.create('smoothing',vna.get_smoothing())
                dg.attrs.create('electrical_delay',vna.get_electrical_delay())
                dg.attrs.create('phase_offset',vna.get_phase_offset())
                dg.attrs.create('format',fmt)
                if temp>0:
                    dg.attrs.create('fridge_temperature',temp)
                if folder:
                    dg.attrs.create('datafolder',folder)

                dg2 = g.create_dataset(datadir+'%.2f'%(out_pwr,)+'//phase', data=ys[idx_power][1])
                dg2.attrs.create('run_time', _iteration_start)
                
                h5f.close()
                
        if display:
            ax.set_title('VNA Trace')
            ax.set_xlabel("Frequency (Hz)")
            ax.set_ylabel("Magnitude (dB)")
            ax.legend(loc='best')
    except Exception as e:
        print "EXCEPTION", e
        raise
    finally:
        if fridge:
            fridge.do_set_pulse_tube('ON')
        if revert:
            try:
                vna.set_instrument_state_file(_state)
                vna.load_state() # restore original state
            except:
                print "[NOTICE] VNA failed to return to initial state"
                pass
        if h5file:
            del(h5f)
    return (pows,xs,ys)