Пример #1
0
def calibrate_epulse_amplitude(folder, ax, *args):
    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='ssro')
    a.get_electron_ROC()
    a.plot_result_vs_sweepparam(ax=ax, name='ssro')
    
    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]
    ax.set_title(a.timestamp)
    
    x0 = fit.Parameter(args[0], 'x0')
    of = fit.Parameter(args[1], 'of')
    a = fit.Parameter(args[2], 'a')
    fitfunc_str = '(1-of) + a (x-x0)**2'
    
    def fitfunc_parabolic(x):
        return (1.-of()) + a() * (x-x0())**2
    
    fit_result = fit.fit1d(x,y, None, p0=[of, a, x0], fitfunc=fitfunc_parabolic,
        fitfunc_str=fitfunc_str, do_print=True, ret=True)
    plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax,
        plot_data=False, print_info=True)


    return fit_result
Пример #2
0
def fit_correlation_parabolic(folder, ax, *args, **kw):
    which_correlation = kw.pop('which_correlation', 2)

    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_correlations(name='adwindata')
    a.plot_results_vs_sweepparam(ax=ax, mode='correlations')

    x = a.sweep_pts.reshape(-1)[:]
    y = a.normalized_correlations[:, which_correlation]

    x0 = fit.Parameter(args[0], 'x0')
    of = fit.Parameter(args[1], 'of')
    a = fit.Parameter(args[2], 'a')
    fitfunc_str = '(1-of) + a (x-x0)**2'

    def fitfunc_parabolic(x):
        return (1. - of()) + a() * (x - x0())**2

    fit_result = fit.fit1d(x,
                           y,
                           None,
                           p0=[of, a, x0],
                           fitfunc=fitfunc_parabolic,
                           fitfunc_str=fitfunc_str,
                           do_print=True,
                           ret=True)
    plot.plot_fit1d(fit_result,
                    np.linspace(x[0], x[-1], 201),
                    ax=ax,
                    plot_data=False,
                    print_info=False)

    return fit_result
Пример #3
0
def fit_population_vs_detuning(folder, ax, *args):
    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC(
    )  # a.get_N_ROC(0.97,0.03,0.96,0.01,0.93,0.01)#(0.99, 0.02, 0.94, 0.005)
    ax = a.plot_results_vs_sweepparam(ret='ax', name='adwindata')

    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]

    guess_a = 1
    guess_A = -0.8
    guess_F = 0.005
    guess_x0 = args[0]

    fit_result = fit.fit1d(x,
                           y,
                           rabi.fit_population_vs_detuning,
                           guess_a,
                           guess_A,
                           guess_F,
                           guess_x0,
                           fixed=[],
                           do_print=True,
                           ret=True)
    plot.plot_fit1d(fit_result,
                    np.linspace(a.sweep_pts[0], a.sweep_pts[-1], 201),
                    ax=ax,
                    plot_data=False)

    return fit_result
Пример #4
0
def fit_linear(folder=None, ax=None, a_guess=1., b_guess=0.):
    """
    fit a x + b from Sequence in folder
    """
    a, ax, x, y = plot_result(folder, ax)

    a = fit.Parameter(a_guess, 'a')
    b = fit.Parameter(b_guess, 'b')
    fitfunc_str = 'a x + b'

    def fitfunc(x):
        return a() * x + b()

    fit_result = fit.fit1d(x,
                           y,
                           None,
                           p0=[a, b],
                           fitfunc=fitfunc,
                           fitfunc_str=fitfunc_str,
                           do_print=True,
                           ret=True)
    plot.plot_fit1d(fit_result,
                    np.linspace(x[0], x[-1], 201),
                    ax=ax,
                    plot_data=False,
                    print_info=False)

    return fit_result
def fit_correlation_parabolic(folder, ax, *args, **kw):
    which_correlation = kw.pop("which_correlation", 2)

    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name="adwindata")
    a.get_correlations(name="adwindata")
    a.plot_results_vs_sweepparam(ax=ax, mode="correlations")

    x = a.sweep_pts.reshape(-1)[:]
    y = a.normalized_correlations[:, which_correlation]

    x0 = fit.Parameter(args[0], "x0")
    of = fit.Parameter(args[1], "of")
    a = fit.Parameter(args[2], "a")
    fitfunc_str = "(1-of) + a (x-x0)**2"

    def fitfunc_parabolic(x):
        return (1.0 - of()) + a() * (x - x0()) ** 2

    fit_result = fit.fit1d(
        x, y, None, p0=[of, a, x0], fitfunc=fitfunc_parabolic, fitfunc_str=fitfunc_str, do_print=True, ret=True
    )
    plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False)

    return fit_result
def calibrate_Npulse_rabi(folder, ax, *args):
    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name="adwindata")
    a.get_electron_ROC()
    a.plot_results_vs_sweepparam(ax=ax, name="adwindata")

    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0[:, 0]

    f = fit.Parameter(args[0], "f")
    A = fit.Parameter(args[1], "A")
    o = fit.Parameter(0.5, "o")
    x0 = fit.Parameter(0, "x0")
    p0 = [f, A, x0, o]

    fitfunc_str = "o + A * cos(2pi f x - 2pi phi)"

    def fitfunc(x):
        return o() + A() * np.cos(2 * np.pi * (f() * (x - x0())))

    fit_result = fit.fit1d(x, y, None, p0=p0, fitfunc=fitfunc, fitfunc_str=fitfunc_str, do_print=True, ret=True)
    plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False)

    return fit_result
def fit_correlation_oscillation(folder, ax, *args, **kw):
    which_correlation = kw.pop("which_correlation", 2)

    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name="adwindata")
    a.get_correlations(name="adwindata")
    a.plot_results_vs_sweepparam(ax=ax, mode="correlations")

    x = a.sweep_pts.reshape(-1)[:]
    y = a.normalized_correlations[:, which_correlation]

    x0 = fit.Parameter(args[0], "x0")
    f = fit.Parameter(args[1], "f")
    A = fit.Parameter(args[2], "A")
    o = fit.Parameter(0.25, "o")
    fitfunc_str = "(1 - A) + A * cos(2pi f (x - x0))"

    def fitfunc(x):
        return o() + A() * np.cos(2 * np.pi * f() * (x - x0()))

    fit_result = fit.fit1d(
        x, y, None, p0=[f, A, x0, o], fitfunc=fitfunc, fitfunc_str=fitfunc_str, do_print=True, ret=True
    )
    plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False)

    return fit_result
Пример #8
0
def fit_rabi(folder=None, ax = None, f_guess=0.9, A_guess=1,fit_phi = False,fit_k = False):
    """
    fit (1 - A) + A * exp(-kx) * cos(2pi f (x - x0)) from Sequence in folder
    """
    a, ax, x, y = plot_result(folder,ax)

    f = fit.Parameter(f_guess, 'f')
    A = fit.Parameter(A_guess, 'A')
    x0 = fit.Parameter(0, 'x0')
    k = fit.Parameter(0, 'k')
    p0 = [f, A]
    if fit_phi:
        p0.append(x0)
    if fit_k:
        p0.append(k)
    fitfunc_str = '(1 - A) + A * exp(-kx) * cos(2pi f (x - x0))'

    def fitfunc(x) : 
        return (1.-A()) + A() * np.exp(-k()*x) * \
            np.cos(2*np.pi*(f()*(x - x0())))

    fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc,
        fitfunc_str=fitfunc_str, do_print=True, ret=True)
    plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax,
        plot_data=False, print_info=False)
        
    return fit_result
Пример #9
0
    def analyse_data(self, filename):
        data = np.loadtxt(filename)
        counts = data[:, 1]
        freq = data[:, 0] * 1e-9
        guess_offset = counts[0]
        guess_amplitude = np.max(counts) - np.min(counts)
        guess_width = 0.005
        guess_ctr = 2.88
        success = False
        fit_result = fit.fit1d(freq,
                               counts,
                               esr.fit_ESR_gauss,
                               guess_offset,
                               guess_amplitude,
                               guess_width,
                               guess_ctr,
                               do_print=False,
                               ret=True)
        if fit_result['success'] == 1 and abs(fit_result['params_dict']['x0'] -
                                              guess_ctr) < 0.1:
            success = True
        plot.plot_fit1d(fit_result,
                        np.linspace(np.min(freq), np.max(freq), 1000),
                        plot_data=True,
                        add_txt=True,
                        plot_title=None)
        plt.savefig(filename + '_fit' + '.png')
        plt.close()

        return success
Пример #10
0
    def plot_relaxation_vs_sweep(self, ms, st, save=True, **kw):
        ret = kw.get('ret', None)
        ax = kw.get('ax', None)
        ax2 = kw.get('ax2', None)
        if ax == None:
            fig = self.default_fig(figsize=(6,4))
            ax = self.default_ax(fig)
            fig2 = self.default_fig(figsize=(10,6))
            #fig2.title('Relaxation fit vs' + self.sweep_name)
        else:
            save = False
        name= '_ms'+ str(ms) + '_' + str(st)
        sweep=self.sweep_pts[::2]
        taus=np.zeros(len(sweep))
        for i,sw in enumerate(sweep):
            #print i
            start,length=getattr(self,'_get_'+st+'_window')(ms,i)
            y,x=self._get_relaxation(ms, i, start, length)
            x=x[:-1]
            res = fit.fit1d(x,y, common.fit_exp_decay_shifted_with_offset, 0, y[0], 1000, x[0], 
            ret=True, do_print=False, fixed=[3])
    
            if res != False:
                ax2=plt.subplot(3,np.ceil(float(len(sweep)+1)/3),i+1)
                plot.plot_fit1d(res, x, ax=ax2, plot_data=True, print_info=False)
                ax2.text(ax2.get_xlim()[-1]*0.8,ax2.get_ylim()[-1]*0.8, '{:.2f}'.format(sw),horizontalalignment='right')
                if (res['params_dict']['A'] > 10*res['params_dict']['a']):
                    taus[i]=res['params_dict']['tau']/1e3
                else:
                    print 'Sweep point {} ignored'.format(i)
            else:
                print 'Could not fit sweep point {}'.format(i)
        skip_points = kw.get('skip_points', 0)
        xx=sweep[taus>1.][skip_points:]
        yy=taus[taus>1.][skip_points:]
        
        #y(x) = A * exp(-(x-x0)/tau) + a
        #g_a : offset
        #g_A : initial Amplitude
        #g_tau : decay constant
        #g_x0 : x offset
        res2 = fit.fit1d(xx,yy, common.fit_exp_decay_with_offset, 10, yy[0], xx[len(xx)/2]/2.,  
                ret=True, do_print=True, fixed=[])
        ax.plot(xx,yy, 'o')
        #ax.plot(sweep,10+yy[0]*np.exp(-(sweep- xx[0])/(xx[len(xx)/2]/2.)))
        
        if res2 != False:
            plot.plot_fit1d(res2, xx, ax=ax, plot_data=False, print_info=True)
        #ax.colorbar()
        ax.set_xlabel(self.sweep_name)
        ax.set_ylabel('ms={} {}-relaxation time [us]'.format(ms,st))
        return res

        if save:
            self.save_fig_incremental_filename(fig,name+'_relaxation_vs_sweep')
        
        if ret == 'ax':
            return ax
        if ret == 'fig':
            return fig
Пример #11
0
def epulse_fidelity(folder, ax, *args):
    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC()
    a.plot_results_vs_sweepparam(ax=ax, name='adwindata')

    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]

    of = fit.Parameter(args[0], 'of')
    fitfunc_str = '(1-of)'

    def fitfunc_fid(x):
        return (1. - of())

    fit_result = fit.fit1d(x,
                           y,
                           None,
                           p0=[of],
                           fitfunc=fitfunc_fid,
                           fitfunc_str=fitfunc_str,
                           do_print=True,
                           ret=True)
    plot.plot_fit1d(fit_result,
                    np.linspace(x[0], x[-1], 201),
                    ax=ax,
                    plot_data=False,
                    print_info=False)

    return fit_result
Пример #12
0
def calibrate_epulse_amplitude(folder, ax, *args, **kw):
    double_ro = kw.pop("double_ro", "False")

    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name="adwindata")
    a.get_electron_ROC()
    a.plot_results_vs_sweepparam(ax=ax, name="adwindata")

    x = a.sweep_pts.reshape(-1)[:]
    if double_ro == "electron":
        y = a.p0[:, 0]
    elif double_ro == "nitrogen":
        y = a.p0[:, 1]
    else:
        y = a.p0.reshape(-1)[:]

    x0 = fit.Parameter(args[0], "x0")
    of = fit.Parameter(args[1], "of")
    a = fit.Parameter(args[2], "a")
    fitfunc_str = "(1-of) + a (x-x0)**2"

    def fitfunc_parabolic(x):
        return (1.0 - of()) + a() * (x - x0()) ** 2

    fit_result = fit.fit1d(
        x, y, None, p0=[of, a, x0], fitfunc=fitfunc_parabolic, fitfunc_str=fitfunc_str, do_print=True, ret=True
    )
    plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False)

    return fit_result
Пример #13
0
def analyze_dark_esr(folder, ax=None, **kw):
    if ax == None:
        fig, ax = plt.subplots(1,1)
    ssro_calib_folder = toolbox.latest_data(contains='AdwinSSRO_SSROCalibration')

    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results('ssro')
    a.get_electron_ROC(ssro_calib_folder=ssro_calib_folder)

    x = a.sweep_pts # convert to MHz
    y = a.p0.reshape(-1)[:]
    a.plot_result_vs_sweepparam(ret=None, name='ssro', ax=ax)

    guess_ctr = x[np.floor(len(x)/2.)]


    fit_result = fit.fit1d(x, y, esr.fit_ESR_gauss, guess_offset,
            guess_amplitude, guess_width, guess_ctr,
            # (2, guess_splitN),
             #(2, guess_splitC),
            # (2, guess_splitB),
            #(3, guess_splitN),
            do_print=True, ret=True, fixed=[])
    
    plot.plot_fit1d(fit_result, np.linspace(min(x), max(x), 1000), ax=ax, plot_data=False, **kw)
       
    ax.set_xlabel('MW frq (GHz)')
    ax.set_ylabel(r'fidelity wrt. $|0\rangle$')
    ax.set_title(a.timestamp+'\n'+a.measurementstring)
    plt.savefig(os.path.join(folder, 'darkesr_analysis.png'),
            format='png')
    return fit_result
Пример #14
0
def fit_gaussian(folder, ax, *args):
    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='ssro')
    a.get_electron_ROC()
    a.plot_result_vs_sweepparam(ax=ax, name='ssro')

    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]
    ax.set_title(a.timestamp)  

    x0 = fit.Parameter(args[0], 'x0')
    a = fit.Parameter(0.5, 'a')
    o = fit.Parameter(0.5, 'o')
    c = fit.Parameter(15, 'c')
    f = fit.Parameter(1./500, 'f')
    fitfunc_str = 'o + a * exp( - ( (x-x0)/c )^2) '

    def fitfunc(x):
        return o() + a() * np.exp( -((x-x0())/ c())**2)

    fit_result = fit.fit1d(x,y, None, p0=[o,x0,a,c], fixed = [], fitfunc=fitfunc,
            fitfunc_str=fitfunc_str, do_print=True, ret=True)
    plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax,
            plot_data=False)

    return fit_result
def fit_parabola(x, y, 
	guess_x0, 
	guess_amp,
	guess_of,
	fixed,
	show_fit = True,
	save = True):
	
	x0 = fit.Parameter(guess_x0, 'x0')
	A = fit.Parameter(guess_amp, 'A')
	o = fit.Parameter(guess_of, 'o')
	p0 = [x0, A, o]
	fitfunc_str = ''

	fitfunc_str = 'o + A*(x - x0)^2'

	def fitfunc(x):
	    return o() + A() * (x - x0) ** 2.

	fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc, fixed=fixed,
	        do_print=True, ret=True)

	if show_fit:
		plot.plot_fit1d(fit_result, np.linspace(0,x[-1],201),
	       plot_data=True)
	# print "pi pulse = {:.5f} ".format(1/f()/2.) + a.sweep_name

	# ax.set_title(a.timestamp+'\n'+a.measurementstring)
	if save:
		plt.savefig(os.path.join(folder, 'Calibrate_Pi_analysis_parabolafit.png'))
Пример #16
0
def calibrate_epulse_rabi(folder, ax, *args, **kws):
    fit_phi = kws.pop('fit_phi', True)
    fit_k = kws.pop('fit_k', True)

    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='ssro')
    a.get_electron_ROC()
    a.plot_result_vs_sweepparam(ax=ax, name='ssro')
    
    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]
    ax.set_title(a.timestamp)

    f = fit.Parameter(args[0], 'f')
    A = fit.Parameter(args[1], 'A')
    x0 = fit.Parameter(0, 'x0')
    k = fit.Parameter(0, 'k')
    p0 = [f, A]
    if fit_phi:
        p0.append(x0)
    if fit_k:
        p0.append(k)
    fitfunc_str = '(1 - A) + A * exp(-kx) * cos(2pi f (x - x0))'

    def fitfunc(x) : 
        return (1.-A()) + A() * np.exp(-k()*x) * \
            np.cos(2*np.pi*(f()*(x - x0())))

    fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc,
        fitfunc_str=fitfunc_str, do_print=True, ret=True)
    plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax,
        plot_data=False, print_info=False)
        
    return fit_result
Пример #17
0
def fit_sin_and_calc_phi(x,y,ax = False):

    g_a = 0.0
    g_A = np.amax(y)
    g_phi = x[np.argmax(y)] 
    ### frequency guess is hardcoded as this is mainly intended for specific entangling oscillations.
    g_f = 1/360.
    p0s, fitfunc,fitfunc_str = common.fit_cos(g_f,g_a,g_A,g_phi)

    fit_result = fit.fit1d(x,y, None, p0=p0s, fitfunc=fitfunc,
         ret=True,fixed=[0,1])

    if ax:
        plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax, 
            plot_data=False,print_info = False)
        A = fit_result['params_dict']['A']
        phi = fit_result['params_dict']['phi']
        if A < 0:
            phi = phi + 180
            A = -A
        phi = np.mod(-phi,360)
        phi_u = fit_result['error_dict']['phi']
        print 'A,phi,phi_u ', A, phi, phi_u
    

    return phi, phi_u  # Phi and Phi_u
Пример #18
0
    def poly_fit_frq(self, **kw):
        plot_fit = kw.pop('plot_fit', True)

        g_x0 = self.x_data[0]
        g_a0 = self.frq_data[0]
        g_a1 = (self.frq_data[-1] - self.frq_data[0]) / (self.x_data[-1] -
                                                         self.x_data[0])
        g_a2 = -0.2
        g_a3 = 2
        fixed = []

        p0, fitfunc, fitfunc_str = common.fit_poly_shifted(
            g_x0, g_a0, g_a1, g_a2, g_a3)
        fit_result = fit.fit1d(self.x_data,
                               self.frq_data,
                               None,
                               p0=p0,
                               fitfunc=fitfunc,
                               do_print=False,
                               ret=True,
                               fixed=fixed)
        if plot_fit:
            plot.plot_fit1d(fit_result,
                            np.linspace(self.x_data[-1], self.x_data[0],
                                        10 * len(self.x_data)),
                            label='Fit',
                            show_guess=False,
                            plot_data=True,
                            color='red',
                            data_linestyle='-',
                            print_info=True)

        self.frq_data = fit_result['fitfunc'](self.x_data)
        return self.frq_data
Пример #19
0
def fit_exp(x,
            y,
            guess_a,
            guess_A,
            guess_tau,
            fixed=[],
            show_fit=True,
            save=True,
            timestamp='',
            **kw):
    '''
	Fit single exponential to T1 data
	'''

    p0, fitfunc, fitfunc_str = common.fit_exp_decay_with_offset(
        guess_a, guess_A, guess_tau)

    fit_result = fit.fit1d(x,
                           y,
                           None,
                           p0=p0,
                           fitfunc=fitfunc,
                           fixed=fixed,
                           do_print=True,
                           ret=True)

    # Plot fit and format if requested
    keys = sorted(kw.keys())

    if show_fit:
        if len(keys) == 0:
            plot.plot_fit1d(fit_result,
                            np.linspace(0, x[-1], 201),
                            plot_data=True)
        elif len(keys) != 0 and 'ax' in keys:
            ax = kw['ax']
            plot.plot_fit1d(fit_result,
                            np.linspace(0, x[-1], 201),
                            plot_data=False,
                            ax=ax)
        elif len(keys) != 0 and 'ax' not in keys:
            print 'length of keyword arguments =', len(keys)
            raise Exception(
                "Your keywords for plot formatting didn't contain a pyplot axis with keyword 'ax'. Please provide it."
            )

    if 'xlabel' in keys:
        ax.set_xlabel(kw['xlabel'])
    if 'ylabel' in keys:
        ax.set_ylabel(kw['ylabel'])

    if timestamp != '':
        if timestamp == None:
            folder = toolbox.latest_data('ElectronT1')
        else:
            folder = toolbox.data_from_time(timestamp)

    if save:
        plt.savefig(os.path.join(folder, 'Calibrate_Pi_analysis_fit.png'))
    return fit_result
Пример #20
0
def fit_linear(folder, ax, value, *args):
    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='ssro')
    a.get_electron_ROC()
    a.plot_result_vs_sweepparam(ax=ax, name='ssro')

    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]
    ax.set_title(a.timestamp)

    a = fit.Parameter(args[0], 'a')
    b = fit.Parameter(args[0], 'b')
    fitfunc_str = 'a x + b'

    def fitfunc(x):
        return a() * x + b()

    fit_result = fit.fit1d(x,
                           y,
                           None,
                           p0=[a, b],
                           fitfunc=fitfunc,
                           fitfunc_str=fitfunc_str,
                           do_print=True,
                           ret=True)
    plot.plot_fit1d(fit_result,
                    np.linspace(x[0], x[-1], 201),
                    ax=ax,
                    plot_data=False,
                    print_info=False)

    return fit_result
Пример #21
0
def calibrate_epulse_amplitude(folder, ax, *args):
    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='ssro')
    a.get_electron_ROC()
    a.plot_result_vs_sweepparam(ax=ax, name='ssro')

    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]
    ax.set_title(a.timestamp)

    x0 = fit.Parameter(args[0], 'x0')
    of = fit.Parameter(args[1], 'of')
    a = fit.Parameter(args[2], 'a')
    fitfunc_str = '(1-of) + a (x-x0)**2'

    def fitfunc_parabolic(x):
        return (1. - of()) + a() * (x - x0())**2

    fit_result = fit.fit1d(x,
                           y,
                           None,
                           p0=[of, a, x0],
                           fitfunc=fitfunc_parabolic,
                           fitfunc_str=fitfunc_str,
                           do_print=True,
                           ret=True)
    plot.plot_fit1d(fit_result,
                    np.linspace(x[0], x[-1], 201),
                    ax=ax,
                    plot_data=False,
                    print_info=True)

    return fit_result
Пример #22
0
def fast_pi2():
    folder = toolbox.latest_data('cal_fast_pi_over_2')

    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC()
    #a.plot_results_vs_sweepparam(ax=ax, name='adwindata')

    x = a.sweep_pts
    y = a.p0.reshape(-1)
    u_y = a.u_p0.reshape(-1)
    n = a.sweep_name

    x2 = x[::2]
    y2 = y[1::2] - y[::2]
    u_y2 = np.sqrt(u_y[1::2]**2 + u_y[::2]**2)

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), sharex=True)
    ax1.errorbar(x2, y2, yerr=u_y2, fmt='o')
    ax1.set_xlabel(n)
    ax1.set_title('Difference btw. Pi/2-Pi and Pi/2' + '\n' + a.timestamp)
    ax1.set_ylabel('Difference')

    m = fit.Parameter((y[-1] - y[0]) / (x[-1] - x[0]), 'm')
    x0 = fit.Parameter(x2.mean(), 'x0')
    p0 = [m, x0]

    def ff(x):
        return m() * (x - x0())

    fitfunc_str = 'm * (x - x0)'

    fit_result = fit.fit1d(x2,
                           y2,
                           None,
                           p0=p0,
                           fitfunc=ff,
                           fitfunc_str=fitfunc_str,
                           do_print=True,
                           ret=True)

    ax2.errorbar(x2, y[0::2], yerr=u_y[0::2], fmt='o', label='Pi/2')
    ax2.errorbar(x2, y[1::2], yerr=u_y[1::2], fmt='o', label='Pi/2 - Pi')
    ax2.legend(frameon=True, framealpha=0.5)
    ax2.set_ylabel('P(0)')
    ax2.set_xlabel(n)
    if fit_result != False:
        ax2.axvline(x0(), c='k', lw=2)
        ax2.axhline(0.5, c='k', lw=2)
        ax2.set_title('X marks the spot')

        plot.plot_fit1d(fit_result,
                        np.linspace(x2[0], x2[-1], 201),
                        ax=ax1,
                        plot_data=False,
                        print_info=True)

    return x0(), 0
Пример #23
0
def analyze_nmr_single(timestamp = None,center_guess = False, ax=None, ret=None,min_dip_depth = 0.85 , **kw):

    if ax == None:
        fig, ax = plt.subplots(1,1)
        
    x = np.zeros((0))
    y = np.zeros((0))
    ysig = np.zeros((0))
    # rdts = np.zeros((0))


    for i in range(20):
        timestamp, folder = toolbox.latest_data(contains = 'NuclearRFRabi_111_1_sil18Rabi_C5_el1_positive_'+str(i)+'run',return_timestamp = True)
        a = mbi.MBIAnalysis(folder)

        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        a.get_electron_ROC()    
        x = np.append(x,a.sweep_pts[:]) 
        y = np.append(y,a.p0[:])
        ysig = np.append(ysig,a.u_p0[:])
    print dir(a)

    for i in range(len(x)-1):
        print x[i], x[i+1]-x[i]



    if center_guess == True:
        guess_ctr = float(raw_input('Center guess?'))
    else:
        guess_ctr = x[y.argmin()]
        print 'guess_ctr = '+str(guess_ctr)
    
    # # try fitting
    fit_result = fit.fit1d(x, y, esr.fit_ESR_gauss, guess_offset,
            guess_amplitude, guess_width, guess_ctr,
            do_print=False, ret=True, fixed=[])
    # fit_result = fit.fit1d(x, y, common.fit_2gauss, guess_offset,
    #         guess_amplitude, guess_ctr-30e-3,guess_width, guess_amplitude, guess_ctr+30e-3,guess_width,
    #         do_print=False, ret=True, fixed=[])
    fit_result['yerr'] = ysig
    plot.plot_fit1d(fit_result, np.linspace(min(x), max(x), 1000), ax=ax, plot_data=True, **kw)

    ax.set_xlabel('RF frq (kHz)')
    ax.set_ylabel(r'fidelity wrt. $|0\rangle$')
    ax.set_title(a.timestamp+'\n'+a.measurementstring)

    plt.savefig(os.path.join(folder, 'nmr_analysis.png'),
            format='png')
    if ret == 'f0':
        f0 = fit_result['params_dict']['x0']
        u_f0 = fit_result['error_dict']['x0']

        ax.text(f0, 0.8, '$f_0$ = ({:.3f} +/- {:.3f})'.format(
            (f0-2.8)*1e3, u_f0*1e3), ha='center')

        return (f0-2.8)*1e3, u_f0*1e3
def Carbon_control_sweep_N_zoom(timestamp=None, measurement_name = ['adwindata'], 
            A = [0.5, 0.5],
            fitfunc_type = 'single', plot_fit = False, do_print = False, show_guess = True,
            yaxis = [-0.05,1.05]):
    ''' Function to analyze data for optimization of the number of pulses for a controlled C13 gate. 
    '''
    
    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        folder = toolbox.latest_data('Decoupling')

    fit_results = []
    for k in range(0,len(measurement_name)):
        a = mbi.MBIAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        a.get_electron_ROC()
        ax = a.plot_results_vs_sweepparam(ret='ax')
        ax.set_ylim(yaxis)
        ax.axhspan(0,0.5,fill=False,ls='dotted')

        x = a.sweep_pts.reshape(-1)[:]
        y = a.p0.reshape(-1)[:]
        y_u = a.u_p0.reshape(-1)[:]

        ax.set_xlim(x[0]-1,x[-1]+1)

        p0, fitfunc, fitfunc_str = common.fit_poly(A)
        
        if show_guess:
            ax.plot(np.linspace(x[0],x[-1],201), fitfunc(np.linspace(x[0],x[-1],201)), ':', lw=2)
        
        fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc, do_print=True, ret=True,fixed=[3])
        if plot_fit == True:
            plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax, plot_data=False,print_info = True)

        fit_results.append(fit_result)
        print folder
        plt.savefig(os.path.join(folder, 'analyzed_result.pdf'),
        format='pdf')
        plt.savefig(os.path.join(folder, 'analyzed_result.png'),
        format='png')

        diff = np.abs(y - 0.5)
        print diff
        print 'Optimum number of pulses N = ' + str(x[np.argmin(diff)])
        print 'with y-0.5 = ' + str(y[np.argmin(diff)]-0.5) + ' +/- ' + str(y_u[np.argmin(diff)])

        # freq = fit_results[0]['params_dict']['f1']
        # period = 1/freq 
        # print 'Period is %s pulses ' %(period)
        # # N_pi = round(period*.5/2)*2.0 
        # N_pi2 = round(period/2*.25)*2.0
        # # print 'Pi pulse: %s pulses' %N_pi
        # print 'Pi2 pulse: %s pulses' %N_pi2
    return fit_results
Пример #25
0
def analyse_Ramsey(folder='',
                   T2=3e3,
                   Ampl=-1. / 3,
                   detuning=3e-3,
                   hf_N=2.17e-3,
                   *arg):

    timestamp = kw.pop(timestamp, None)

    guess_tau = T2
    guess_a = 0.5
    guess_A = Ampl

    guess_hf_N = hf_N
    guess_det = detuning
    guess_hf_C = hf_C

    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    elif folder != '':
        folder = toolbox.latest_data('Ramsey')

    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='ssro')
    a.get_electron_ROC()
    x = a.sweep_pts
    y = a.p0

    ax = a.plot_result_vs_sweepparam(ret='ax', name='ssro')

    params_0, fitfunc_0, fitfunc_str_0 = ramsey.fit_ramsey_14N_fixed_13C_opt(
        guess_tau, guess_A, guess_a, guess_det, guess_hf_N)
    x_0 = np.linspace(0, a.sweep_pts[-1], 1000)
    ax.plot(x_0, fitfunc_0(x_0), 'r--', lw=1)
    #fit_xvals=np.linspace(res['x'][0],res['x'][-1],fit_num_points)

    fit_result = fit.fit1d(x,
                           y,
                           ramsey.fit_ramsey_14N_fixed_13C_opt,
                           guess_tau,
                           guess_A,
                           guess_a,
                           guess_det,
                           guess_hf_N,
                           fixed=[],
                           do_print=True,
                           ret=True)
    #fit_result = False
    if fit_result != False:
        plot.plot_fit1d(fit_result,
                        np.linspace(0, a.sweep_pts[-1], 201),
                        ax=ax,
                        plot_data=False)

    plt.savefig(os.path.join(folder, 'electronramsey_analysis.pdf'),
                format='pdf')
Пример #26
0
def calibrate_pi2_noMBI(folder):
    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results('ssro')
    a.get_electron_ROC()
    x = a.sweep_pts
    y = a.p0
    u_y = a.u_p0
    n = a.sweep_name
    a.finish()

    x2 = x[::2]
    print x2
    y2 = y[1::2] - y[::2]
    u_y2 = np.sqrt(u_y[1::2]**2 + u_y[::2]**2)

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), sharex=True)
    ax1.errorbar(x2, y2, yerr=u_y2, fmt='o')
    ax1.set_xlabel(n)
    ax1.set_title('Difference btw. Pi/2-Pi and Pi/2')
    ax1.set_ylabel('Difference')

    m = fit.Parameter((y[-1] - y[0]) / (x[-1] - x[0]), 'm')
    x0 = fit.Parameter(y2.mean(), 'x0')
    p0 = [m, x0]

    def ff(x):
        return m() * (x - x0())

    fitfunc_str = 'm * (x - x0)'

    fit_result = fit.fit1d(x2,
                           y2,
                           None,
                           p0=p0,
                           fitfunc=ff,
                           fitfunc_str=fitfunc_str,
                           do_print=True,
                           ret=True)

    ax2.errorbar(x2, y[0::2], yerr=u_y[0::2], fmt='o', label='Pi/2')
    ax2.errorbar(x2, y[1::2], yerr=u_y[1::2], fmt='o', label='Pi/2 - Pi')
    ax2.legend(frameon=True, framealpha=0.5)
    ax2.set_ylabel('P(0)')
    ax2.set_xlabel(n)
    ax2.axvline(x0(), c='k', lw=2)
    ax2.axhline(0.5, c='k', lw=2)
    ax2.set_title('X marks the spot')

    plot.plot_fit1d(fit_result,
                    np.linspace(x2[0], x2[-1], 201),
                    ax=ax1,
                    plot_data=False,
                    print_info=True)

    fig.savefig(os.path.join(folder, 'pi2_calibration.png'))
Пример #27
0
def electron_T1_analysis(older_than='20161110_180000',
                         newer_than='20161110_141200',
                         mode='init0',
                         Amplitude=2,
                         offset=1,
                         T1=1e9,
                         do_print=True):

    Folder_list = toolbox.latest_data(
        contains='ElectronT1_111_1_sil18m0to0switch_on',
        older_than=older_than,
        newer_than=newer_than,
        return_all=True)
    x_tot = []
    y_tot = []
    y_var_tot = []

    for i in range(len(Folder_list)):
        print Folder_list[len(Folder_list) - i - 1]
        Folder = Folder_list[len(Folder_list) - i - 1]
        x, y, y_var = get_T1_data(Folder)
        #print y
        x_tot.extend(list(x))
        y_tot.extend(list(y))
        y_var_tot.extend(list(y_var))

    print x_tot
    print y_tot
    print y_var_tot

    p0, fitfunc, fitfunc_str = common.fit_exp_decay_with_offset(
        offset, Amplitude, T1)
    # fit_result = fit.fit1d(x_tot,y_tot, None, p0=p0, fitfunc=fitfunc, do_print=do_print, ret=True)
    # #plt.plot(x_tot,y_tot)
    # plot.plot_fit1d(fit_result, np.linspace(0,x_tot[-1],201), ax= None, plot_data=False)

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.errorbar(x_tot, y_tot, fmt='o', yerr=y_var_tot)
    ax.set_ylim([0.0, 1.1])

    fit_result = fit.fit1d(x_tot,
                           y_tot,
                           None,
                           p0=p0,
                           fitfunc=fitfunc,
                           do_print=do_print,
                           ret=True)
    plot.plot_fit1d(fit_result,
                    np.linspace(0, x[-1], 201),
                    ax=ax,
                    plot_data=False)

    plt.savefig(os.path.join(Folder, 'analyzed_result.pdf'), format='pdf')
    plt.savefig(os.path.join(Folder, 'analyzed_result.png'), format='png')
def analyse_Rabi(guess_frq = 2., guess_amp = 0.2, guess_of = 0.1, **kw) :

    timestamp    = kw.pop('timestamp', None)
    guess_phi    = kw.pop('guess_phi', 0.)
    guess_k      = kw.pop('guess_k', 0.)
    mbi_analysis = kw.pop('mbi_analysis', False)
    do_print     = kw.pop('do_print', False)

    o = fit.Parameter(guess_of, 'o')
    f = fit.Parameter(guess_frq, 'f')
    A = fit.Parameter(guess_amp, 'A')
    phi = fit.Parameter(guess_phi, 'phi')
    k = fit.Parameter(guess_k, 'k')
    p0 = [f, A, phi, o, k]
    fitfunc_str = ''


    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else :
        folder = toolbox.latest_data('ElectronRabi')

    if mbi_analysis:
        a = mbi.MBIAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results('adwindata')
        a.get_electron_ROC()
        ax = a.plot_results_vs_sweepparam(ret='ax', name = 'adwindata')

    else:
        a = sequence.SequenceAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results('ssro')
        a.get_electron_ROC()
        ax = a.plot_result_vs_sweepparam(ret='ax')

    x = a.sweep_pts
    y = a.p0

    fitfunc_str = 'o - A + A*e^(-kx)*cos(2pi (fx-phi))'

    def fitfunc(x):
    	return (o()-A()) + A() * np.exp(-k()*x) * np.cos(2*np.pi*(f()*x - phi()))

    fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc, fixed=[2],
            do_print=do_print, ret=True)
    plot.plot_fit1d(fit_result, np.linspace(0,x[-1],201), ax=ax,
            plot_data=False)

    print "\npi pulse at {:.3f} for .\n".format(1/f()/2.) + a.sweep_name

    # ax.set_title(a.timestamp+'\n'+a.measurementstring)
    plt.savefig(os.path.join(folder, 'electronrabi_analysis_fit.png'))

    return fit_result
Пример #29
0
def fit_parabolic(folder=None,
                  ax=None,
                  x0_guess=0.,
                  of_guess=0.5,
                  a_guess=1.,
                  **kw):
    """
    fit (1-of) + a (x-x0)**2 from Sequence in folder
    """
    do_print = kw.pop('do_print', False)
    fixed = kw.pop('fixed', [])
    a0, ax, x, y = plot_result(folder, ax, **kw)
    x0 = fit.Parameter(x0_guess, 'x0')
    of = fit.Parameter(of_guess, 'of')
    a = fit.Parameter(a_guess, 'a')

    x_min = kw.pop("x_min", None)
    x_max = kw.pop("x_max", None)

    fit_x = x
    fit_y = y

    if x_min is not None:
        mask = fit_x > x_min
        fit_x = fit_x[mask]
        fit_y = fit_y[mask]

    if x_max is not None:
        mask = fit_x < x_max
        fit_x = fit_x[mask]
        fit_y = fit_y[mask]

    fitfunc_str = '(1-of) + a (x-x0)**2'

    def fitfunc_parabolic(x):
        return (1. - of()) + a() * (x - x0())**2

    fit_result = fit.fit1d(fit_x,
                           fit_y,
                           None,
                           p0=[of, a, x0],
                           fitfunc=fitfunc_parabolic,
                           fitfunc_str=fitfunc_str,
                           do_print=do_print,
                           ret=True)
    fit_result['u_y'] = a0.u_p0
    plot.plot_fit1d(fit_result,
                    np.linspace(np.min(fit_x), np.max(fit_x), 201),
                    ax=ax,
                    plot_data=False,
                    **kw)

    return fit_result
def analyze_dark_esr(folder,center_guess = True, ax=None, ret=None, **kw):

    if ax == None:
        fig, ax = plt.subplots(1,1)

    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results('ssro')
    a.get_electron_ROC()

    x = a.sweep_pts # convert to MHz
    y = a.p0.reshape(-1)[:]
    a.plot_result_vs_sweepparam(ret=ret, name='ssro', ax=ax)
    ax.set_ylim(0.6,1.05)

    if center_guess == True:
        guess_ctr = float(raw_input('Center guess?'))
    else:
        j=0
        if j < len(y)-2:
            while y[j]>0.93*y[j+1]: # such that we account for noise
                k = j
                j = j+1
            j = len(y)-2
        guess_ctr = x[k]*1e-3+ guess_splitN #convert to GHz and go to middle dip


    # try fitting
    fit_result = fit.fit1d(x, y, esr.fit_ESR_gauss, guess_offset,
            guess_amplitude, guess_width, guess_ctr,
            # (2, guess_splitN),
            # (2, guess_splitC),
            # (2, guess_splitB),
            (3, guess_splitN),
            do_print=True, ret=True, fixed=[4])
    plot.plot_fit1d(fit_result, np.linspace(min(x), max(x), 1000), ax=ax, plot_data=False, **kw)

    ax.set_xlabel('MW frq (GHz)')
    ax.set_ylabel(r'fidelity wrt. $|0\rangle$')
    ax.set_title(a.timestamp+'\n'+a.measurementstring)

    plt.savefig(os.path.join(folder, 'darkesr_analysis.png'),
            format='png')

    if ret == 'f0':
        f0 = fit_result['params_dict']['x0']
        u_f0 = fit_result['error_dict']['x0']

        ax.text(f0, 0.8, '$f_0$ = ({:.3f} +/- {:.3f})'.format(
            (f0-2.8)*1e3, u_f0*1e3), ha='center')

        return (f0-2.8)*1e3, u_f0*1e3
Пример #31
0
def electron_T2_anal(timestamp=None,
                     measurement_name=['ms0'],
                     Amplitude=1 / 2.,
                     T2=10e3,
                     offset=1. / 2,
                     k=4,
                     do_print=False,
                     ylim=(0., 1.)):
    ''' Function to analyze simple decoupling measurements. Loads the results and fits them to a simple exponential.
    Inputs:
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    Based on electron_T1_anal, modified by Adriaan Rol
    '''

    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        folder = toolbox.latest_data('Decoupling')
    print folder
    fit_results = []
    for k in range(0, len(measurement_name)):
        a = sequence.SequenceAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results(measurement_name[k])
        a.get_electron_ROC()
        ax = a.plot_result_vs_sweepparam(ret='ax')
        ax.set_ylim(ylim)
        x = a.sweep_pts
        p0, fitfunc, fitfunc_str = SE.fit_echo(T2, Amplitude, offset, k)
        y = a.p0

        fit_result = fit.fit1d(x,
                               y,
                               None,
                               p0=p0,
                               fitfunc=fitfunc,
                               do_print=do_print,
                               ret=True,
                               fixed=[3])
        #fit_result = False
        if fit_result != False:
            plot.plot_fit1d(fit_result,
                            np.linspace(0, x[-1], 201),
                            ax=ax,
                            plot_data=False)
        fit_results.append(fit_result)

        plot.ylim = ([0, 0.2])

    return fit_results
Пример #32
0
def calibrate_epulse_rabi(folder, ax, *args, **kws):
    fit_x0 = kws.pop('fit_x0', True)
    fit_k = kws.pop('fit_k', True)
    double_ro = kws.pop('double_ro', 'False')
    guess_x0 = kws.pop('guess_x0', 0)

    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC()
    a.plot_results_vs_sweepparam(ax=ax, name='adwindata')

    x = a.sweep_pts.reshape(-1)[:]
    if double_ro == 'electron':
        y = a.p0[:, 0]
    elif double_ro == 'nitrogen':
        y = a.p0[:, 1]
    else:
        y = a.p0.reshape(-1)[:]

    f = fit.Parameter(args[0], 'f')
    A = fit.Parameter(args[1], 'A')
    x0 = fit.Parameter(guess_x0, 'x0')
    k = fit.Parameter(0, 'k')
    p0 = [f, A]
    if fit_x0:
        p0.append(x0)
    if fit_k:
        p0.append(k)

    fitfunc_str = '(1 - A) + A * exp(-kx) * cos(2pi f (x - x0))'

    def fitfunc(x):
        return (1.-A()) + A() * np.exp(-k()*x) * \
            np.cos(2*np.pi*f()*(x - x0()))

    fit_result = fit.fit1d(x,
                           y,
                           None,
                           p0=p0,
                           fitfunc=fitfunc,
                           fitfunc_str=fitfunc_str,
                           do_print=True,
                           ret=True)
    plot.plot_fit1d(fit_result,
                    np.linspace(x[0], x[-1], 201),
                    ax=ax,
                    plot_data=False,
                    print_info=False)

    return fit_result
Пример #33
0
def fast_pi2():
    folder = toolbox.latest_data('cal_fast_pi_over_2') 
            
    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC()
    #a.plot_results_vs_sweepparam(ax=ax, name='adwindata')

    x = a.sweep_pts
    y = a.p0.reshape(-1)
    u_y = a.u_p0.reshape(-1)
    n = a.sweep_name
   
    x2 = x[::2]
    y2 = y[1::2] - y[::2]
    u_y2 = np.sqrt(  u_y[1::2]**2 + u_y[::2]**2 )  
        
    fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,4), sharex=True)
    ax1.errorbar(x2, y2, yerr=u_y2, fmt='o')
    ax1.set_xlabel(n)
    ax1.set_title('Difference btw. Pi/2-Pi and Pi/2'+'\n'+a.timestamp)
    ax1.set_ylabel('Difference')
    
    m = fit.Parameter((y[-1]-y[0])/(x[-1]-x[0]), 'm')
    x0 = fit.Parameter(x2.mean(), 'x0')
    p0 = [m, x0]
    
    def ff(x):
        return m() * (x-x0())
    fitfunc_str = 'm * (x - x0)'
    
    fit_result = fit.fit1d(x2, y2, None, p0=p0, fitfunc=ff,
        fitfunc_str=fitfunc_str, do_print=True, ret=True)    
        
    ax2.errorbar(x2, y[0::2], yerr=u_y[0::2], fmt='o',
                 label='Pi/2')
    ax2.errorbar(x2, y[1::2], yerr=u_y[1::2], fmt='o',
                 label='Pi/2 - Pi')
    ax2.legend(frameon=True, framealpha=0.5)
    ax2.set_ylabel('P(0)')
    ax2.set_xlabel(n)
    if fit_result != False:
        ax2.axvline(x0(), c='k', lw=2)
        ax2.axhline(0.5, c='k', lw=2)
        ax2.set_title('X marks the spot')
    
        plot.plot_fit1d(fit_result, np.linspace(x2[0],x2[-1],201), ax=ax1,
            plot_data=False, print_info=True)
    
    return x0(), 0
Пример #34
0
def fit_Ramsey_6_cos_hf_fixed(timestamp,
                              ssro_calib_folder,
                              g_tau,
                              g_A,
                              g_a,
                              g_det,
                              g_hf_N,
                              g_hf_C,
                              fixed=[],
                              folder=None):

    if folder is None:
        if timestamp != None:
            folder = toolbox.data_from_time(timestamp)
        else:
            folder = toolbox.latest_data('ElectronRamsey')

    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='ssro')
    if ssro_calib_folder != None:
        a.get_electron_ROC(ssro_calib_folder=ssro_calib_folder)
    else:
        a.get_electron_ROC()

    # Plot data
    ax = a.plot_result_vs_sweepparam(ret='ax', name='ssro')

    p0, fitfunc_0, fitfunc_str_0 = ramsey.fit_ramsey_hyperfinelines_fixed_6cos(
        g_tau, g_A, g_a, g_det, g_hf_N, g_hf_C)

    fit_result = fit.fit1d(a.sweep_pts,
                           a.p0.reshape(-1),
                           ramsey.fit_ramsey_hyperfinelines_fixed_6cos,
                           g_tau,
                           g_A,
                           g_a,
                           g_det,
                           g_hf_N,
                           g_hf_C,
                           fixed=fixed,
                           do_print=True,
                           ret=True)
    if fit_result != False:
        plot.plot_fit1d(fit_result,
                        np.linspace(0, a.sweep_pts[-1], 201),
                        ax=ax,
                        plot_data=False)

    plt.savefig(os.path.join(folder, 'electronramsey_analysis.png'),
                format='png')
Пример #35
0
def sweep_N_analysis(tau,N_steps,plot_fit = False, do_print = True, show_guess = False):


    ###################
    # Add simulated spins #
    ###################

    total_pts = 320/N_steps+1
    pts_per_run=11

    ## Data location ##
    ssro_calib_folder = 'd:\\measuring\\data\\20140419\\111949_AdwinSSRO_SSROCalibration_Hans_sil1'

    a, folder = load_mult_dat(tau, number_of_msmts = total_pts/pts_per_run,N_steps=N_steps, ssro_calib_folder=ssro_calib_folder)
    a.p0 = a.p0*2-1

    ############
    ## Plotting ###
    ############


    ax = a.plot_results_vs_sweepparam(ret='ax')
    # ax.set_xlim(23.4,25)
    # ax.set_xlim(0,73)
    # start, end = ax.get_xlim()
    # ax.xaxis.set_ticks(np.arange(start, end, 0.5))

    ax.set_ylim(-1.05,1.05)
    
    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]
    fit_results = []
    p0, fitfunc, fitfunc_str = common.fit_decaying_cos(1/45.,0, 1, 0, 40000)
    print fitfunc
    #plot the initial guess
    if show_guess:
        ax.plot(np.linspace(0,x[-1],201), fitfunc(np.linspace(0,x[-1],201)), ':', lw=2)
    ax.plot(x,y)
    fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc, do_print=True, ret=True,fixed=[3])
    # print fitfunc(np.linspace(0,x[-1],201))
    ## plot data and fit as function of total time
    if plot_fit == True:
        plot.plot_fit1d(fit_result, np.linspace(0,x[-1],201), ax=ax, plot_data=False)

    fit_results.append(fit_result)

    plt.savefig(os.path.join(folder, 'analyzed_result.pdf'),
    format='pdf')
    plt.savefig(os.path.join(folder, 'analyzed_result.png'),
    format='png')
def fit_Ramsey_gausscos_withoffset(timestamp = None,
	ssro_calib_folder = None,
	guess_avg = 0.5, 
	guess_A = 1./3.,
	guess_t = 10000,
	guess_a = 2,
	guess_f = 1./35,
	guess_phi = 0,
	guess_b = 1,
	fixed = [],
	fit_result = True):
	"""
	Fits cosine with offset modulated by Gaussian decay to electron Ramsey signal.
	fit func = 'avg + A *exp(-(x/t)**2) * (a * cos(2pi * (f*x + phi/360) ) + b)'
	"""

	### script
	if timestamp != None:
	    folder = toolbox.data_from_time(timestamp)
	else:
	    folder = toolbox.latest_data('ElectronRamsey')

	a = sequence.SequenceAnalysis(folder)
	a.get_sweep_pts()
	a.get_readout_results(name='ssro')
	if ssro_calib_folder != None:
		a.get_electron_ROC(ssro_calib_folder = ssro_calib_folder)
	else: 
		a.get_electron_ROC()

	# Plot data
	ax = a.plot_result_vs_sweepparam(ret='ax', name='ssro')
	# ax.set_xlim(0,1000)

	p0, fitfunc_0, fitfunc_str_0 = ramsey.fit_gaussian_decaying_cos_withoffset(guess_avg, guess_A, guess_t, guess_a, guess_f, guess_phi, guess_b)
	# Plot initial guess
	# fit_xvals_0=np.linspace(0,a.sweep_pts[-1],1000)
	# ax.plot(fit_xvals_0,fitfunc_0(fit_xvals_0), 'r--', lw=1)
	#fit_xvals=np.linspace(res['x'][0],res['x'][-1],fit_num_points)

	fit_result = fit.fit1d(a.sweep_pts, a.p0.reshape(-1), ramsey.fit_gaussian_decaying_cos_withoffset,
		guess_avg, guess_A, guess_t, guess_a, guess_f, guess_phi, guess_b,
        fixed=fixed, do_print=True, ret=True)
	
	if fit_result != False :
		plot.plot_fit1d(fit_result, np.linspace(0,a.sweep_pts[-1],2001), ax=ax,
	        plot_data=False)

	plt.savefig(os.path.join(folder, 'electronramsey_analysis.pdf'),
	        format='pdf')
Пример #37
0
    def fit_lorentzian(self, **kw):
        y = kw.pop('y', self.y_data)
        x = kw.pop('x', self.frq_data)
        g_gamma = kw.pop('g_gamma', 15)
        plot_title = kw.pop('plot_title', '')
        plot_fit = kw.pop('plot_fit', False)
        fixed = kw.pop('fixed', [])

        g_a = np.average(y)
        g_A = max(y) - g_a
        g_x0 = self.frq_data[np.argmax(y)]

        p0, fitfunc, fitfunc_str = common.fit_lorentz(g_a, g_A, g_x0, g_gamma)
        fit_result = fit.fit1d(x,
                               y,
                               None,
                               p0=p0,
                               fitfunc=fitfunc,
                               do_print=False,
                               ret=True,
                               fixed=fixed)
        if 'gamma' not in fit_result['params_dict']:
            fig, ax = plt.subplots(figsize=(10, 4))
            ax.plot(x, y)
            print 'WARNING: COULD NOT FIT gamma'
            return 0, 10

        gamma = np.abs(fit_result['params_dict']['gamma'])
        u_gamma = np.abs(fit_result['error_dict']['gamma'])
        x0 = fit_result['params_dict']['x0']
        FWHM = gamma
        u_FWHM = u_gamma

        if plot_fit:
            fig, ax = plt.subplots(figsize=(10, 4))
            plot.plot_fit1d(fit_result,
                            np.linspace(x[0], x[-1],
                                        len(x) * 10),
                            ax=ax,
                            label='Fit',
                            show_guess=True,
                            plot_data=True)
            ax.set_title('FWHM = %.1f +- %.1f GHz %s' %
                         (FWHM, u_FWHM, plot_title))
            fig.savefig(self.folder + '/lorentzian_fit_%s.png' % (plot_title))
            plt.show(fig)
            plt.close(fig)

        return FWHM, u_FWHM
def calibrate_pulse_amplitude(x, y, ax, *args):
    x0 = fit.Parameter(args[0], 'x0')
    of = fit.Parameter(args[1], 'of')
    a = fit.Parameter(args[2], 'a')
    fitfunc_str = '(1-of) + a (x-x0)**2'
    
    def fitfunc_parabolic(x):
        return (1.-of()) + a() * (x-x0())**2
    
    fit_result = fit.fit1d(x,y, None, p0=[of, a, x0], fitfunc=fitfunc_parabolic,
        fitfunc_str=fitfunc_str, do_print=True, ret=True)
    plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax,
        plot_data=False, print_info=False)
        
    return fit_result
def analyze_dark_esr_single(timestamp = None,center_guess = False, ax=None, ret=None,min_dip_depth = 0.85 , **kw):

    if ax == None:
        fig, ax = plt.subplots(1,1)

    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        folder = toolbox.latest_data('DarkESR')


    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results('ssro')
    a.get_electron_ROC()

    x = a.sweep_pts # convert to MHz
    y = a.p0.reshape(-1)[:]
    a.plot_result_vs_sweepparam(ret=ret, name='ssro', ax=ax)
    ax.set_ylim(0.6,1.05)


    if center_guess == True:
        guess_ctr = float(raw_input('Center guess?'))
    else:
        guess_ctr = x[y.argmin()]
        print 'guess_ctr = '+str(guess_ctr)
    
    # try fitting
    fit_result = fit.fit1d(x, y, esr.fit_ESR_gauss, guess_offset,
            guess_amplitude, guess_width, guess_ctr,
            do_print=False, ret=True, fixed=[])
    plot.plot_fit1d(fit_result, np.linspace(min(x), max(x), 1000), ax=ax, plot_data=False, **kw)

    ax.set_xlabel('MW frq (GHz)')
    ax.set_ylabel(r'fidelity wrt. $|0\rangle$')
    ax.set_title(a.timestamp+'\n'+a.measurementstring)

    plt.savefig(os.path.join(folder, 'darkesr_analysis.png'),
            format='png')
    if ret == 'f0':
        f0 = fit_result['params_dict']['x0']
        u_f0 = fit_result['error_dict']['x0']

        ax.text(f0, 0.8, '$f_0$ = ({:.3f} +/- {:.3f})'.format(
            (f0-2.8)*1e3, u_f0*1e3), ha='center')

        return (f0-2.8)*1e3, u_f0*1e3
def fit_exp(x, y,
	guess_a,
	guess_A,
	guess_tau,
	fixed = [],
	show_fit = True,
	save = True,
	timestamp = '',
	**kw):
	'''
	Fit single exponential to T1 data
	'''

	p0, fitfunc, fitfunc_str = common.fit_exp_decay_with_offset(guess_a,guess_A, guess_tau)

	fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc, fixed=fixed,
		        do_print=True, ret=True)
	
	# Plot fit and format if requested
	keys = sorted(kw.keys())

	if show_fit:
		if len(keys) == 0:
			plot.plot_fit1d(fit_result, np.linspace(0,x[-1],201),
	       plot_data=True)
		elif len(keys) != 0 and 'ax' in keys:
			ax = kw['ax']
			plot.plot_fit1d(fit_result, np.linspace(0,x[-1],201),
	       plot_data=False, ax = ax)
		elif len(keys) != 0 and 'ax' not in keys:
			print 'length of keyword arguments =', len(keys)
			raise Exception("Your keywords for plot formatting didn't contain a pyplot axis with keyword 'ax'. Please provide it.")

	if 'xlabel' in keys:
		ax.set_xlabel(kw['xlabel'])
	if 'ylabel' in keys:
		ax.set_ylabel(kw['ylabel'])


	if timestamp != '':
		if timestamp == None:
			folder = toolbox.latest_data('ElectronT1')
		else:
			folder = toolbox.data_from_time(timestamp)

	if save:
		plt.savefig(os.path.join(folder, 'Calibrate_Pi_analysis_fit.png'))
	return fit_result	
Пример #41
0
def electron_T1_anal(timestamp=None,
                     measurement_name=['ms0'],
                     Amplitude=0.1,
                     T1=1000,
                     offset=1,
                     do_print=False):
    ''' Function to analyze T1 measurements. Loads the results and fits them to a simple exponential.
    Inputs:
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    '''

    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        folder = toolbox.latest_data('ElectronT1')

    fit_results = []
    for k in range(0, len(measurement_name)):
        a = sequence.SequenceAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results('ssro')
        #a.get_readout_results(measurement_name[k]) #commented out since newer measurements are no longer grouped which renders the whole for-loop obsolete. NK 20141110
        a.get_electron_ROC()
        ax = a.plot_result_vs_sweepparam(ret='ax')

        x = a.sweep_pts
        p0, fitfunc, fitfunc_str = common.fit_exp_decay_with_offset(
            offset, Amplitude, T1)
        y = a.p0
        #print y
        fit_result = fit.fit1d(x,
                               y,
                               None,
                               p0=p0,
                               fitfunc=fitfunc,
                               do_print=do_print,
                               ret=True)
        plot.plot_fit1d(fit_result,
                        np.linspace(0, x[-1], 201),
                        ax=ax,
                        plot_data=False)
        fit_results.append(fit_result)

        plt.savefig(os.path.join(folder, 'analyzed_result.pdf'), format='pdf')
        plt.savefig(os.path.join(folder, 'analyzed_result.png'), format='png')

    return fit_results
Пример #42
0
def calibrate_pi2_noMBI(folder):
    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results('ssro')
    a.get_electron_ROC()    
    x = a.sweep_pts
    y = a.p0
    u_y = a.u_p0
    n = a.sweep_name
    a.finish()
   
    x2 = x[::2]
    print x2
    y2 = y[1::2] - y[::2]
    u_y2 = np.sqrt(  u_y[1::2]**2 + u_y[::2]**2 )    
    
    fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,4), sharex=True)
    ax1.errorbar(x2, y2, yerr=u_y2, fmt='o')
    ax1.set_xlabel(n)
    ax1.set_title('Difference btw. Pi/2-Pi and Pi/2')
    ax1.set_ylabel('Difference')
    
    m = fit.Parameter((y[-1]-y[0])/(x[-1]-x[0]), 'm')
    x0 = fit.Parameter(y2.mean(), 'x0')
    p0 = [m, x0]
    
    def ff(x):
        return m() * (x-x0())
    fitfunc_str = 'm * (x - x0)'
    
    fit_result = fit.fit1d(x2, y2, None, p0=p0, fitfunc=ff,
        fitfunc_str=fitfunc_str, do_print=True, ret=True)    
        
    ax2.errorbar(x2, y[0::2], yerr=u_y[0::2], fmt='o',
                 label='Pi/2')
    ax2.errorbar(x2, y[1::2], yerr=u_y[1::2], fmt='o',
                 label='Pi/2 - Pi')
    ax2.legend(frameon=True, framealpha=0.5)
    ax2.set_ylabel('P(0)')
    ax2.set_xlabel(n)
    ax2.axvline(x0(), c='k', lw=2)
    ax2.axhline(0.5, c='k', lw=2)
    ax2.set_title('X marks the spot')
    
    plot.plot_fit1d(fit_result, np.linspace(x2[0],x2[-1],201), ax=ax1,
        plot_data=False, print_info=True)
    
    fig.savefig(os.path.join(folder, 'pi2_calibration.png'))
Пример #43
0
def plot_data_and_fit(data, EOM_freq):

    fig, ax = plt.subplots(figsize=(8, 4))
    lw, u_lw, scaling, fit_result = get_linewidth(data, EOM_freq)
    plot.plot_fit1d(fit_result,
                    np.linspace(x[0], x[-1], len(x)),
                    ax=ax,
                    label='Fit',
                    show_guess=True,
                    plot_data=True,
                    color='red',
                    data_linestyle='-',
                    print_info=False)
    ax.set_xlabel("Frequency (GHz)", fontsize=14)
    ax.set_ylabel("Intensity (a.u.)", fontsize=14)
    ax.set_xlim(x[0], x[-1])
    #rescaling x-axis in GHz
    # X_min_freq = ax.get_xlim()[0]*scaling
    # X_max_freq = ax.get_xlim()[-1]*scaling
    # xticks = np.linspace(ax.get_xlim()[0],ax.get_xlim()[-1],n_xticks)
    # xticklabels = np.linspace(X_min_freq,X_max_freq,n_xticks)
    # xticklabels_round=[]
    # for j in xticklabels:
    #   round_ = round(j,2)
    #   xticklabels_round = np.append(xticklabels_round,round_)
    # ax.set_xticklabels(xticklabels_round)
    # ax.set_xticks(xticks)
    plt.show()
    return x, lw, u_lw, scaling


# def set_axes(ax):
#     ax.set_xlabel("Frequency (GHz)", fontsize = 14)
#     ax.set_ylabel("Intensity (a.u.)", fontsize = 14)

#     ax.grid(False)
#     ax.set_axis_bgcolor('white')
#     #ax.set_xlim(x[0],x[-1])

#     ax.tick_params(which = 'both', direction = 'out')
#     xticks = np.linspace(ax.get_xlim()[0],ax.get_xlim()[-1],int((ax.get_xlim()[0]-ax.get_xlim()[-1])/2+1))
#     xticklabels = np.linspace(ax.get_xlim()[0]*scaling,ax.get_xlim()[-1]*scaling,int((ax.get_xlim()[0]-ax.get_xlim()[-1])/2+1))
#     xticklabels = np.round(xticklabels,1)

#     ax.set_xticks(xticks)
#     ax.set_xticklabels(xticklabels, rotation=0)

#     return ax
Пример #44
0
def determine_drift(times, peak_positions, data_folder):
    times_dec = []

    ftr = [3600,60,1]
    for time in times:
        time_dec = sum([a*b for a,b in zip(ftr, [ int(time[0:2]),int(time[2:4]),int(time[4:6]) ]) ])
        times_dec = np.append(times_dec, time_dec)

    times_dec = times_dec - times_dec[0]

    g_a = 2.13
    g_b = 0.0007
    fixed=[]
    p0, fitfunc, fitfunc_str = common.fit_line(g_a, g_b)
    fit_result = fit.fit1d(times_dec,peak_positions, None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True,fixed=fixed)

    b = fit_result['params_dict']['b']
    u_b = fit_result['error_dict']['b']

    fig,ax = plt.subplots(figsize=(6,4.7))

    ax = plot.plot_fit1d(fit_result, np.linspace(times_dec[0],times_dec[-1],10*len(times_dec)), ax=ax,color='r',show_guess=True, plot_data=True, label = 'fit', add_txt=False, ret='ax')
    ax.set_xlabel('time (s)')
    ax.set_ylabel('peak position (V)')
    ax.set_title(data_folder + ' \n Drift is {} $\pm$ {} mV/s '.format(round(b*1.e3,3), round(u_b*1.e3,3)))

    fig.savefig(data_folder +'/'+ "drift "  + ".png")

    plt.show()
    plt.close()
Пример #45
0
def fit_sine(
    x,
    y,
    guess_frq,
    guess_amp,
    guess_phi,
    guess_of,
    guess_k,
    fixed,
    folder,
    show_fit=True,
    save=True,
):

    o = fit.Parameter(guess_of, 'o')
    f = fit.Parameter(guess_frq, 'f')
    A = fit.Parameter(guess_amp, 'A')
    phi = fit.Parameter(guess_phi, 'phi')
    k = fit.Parameter(guess_k, 'k')
    p0 = [f, A, phi, o, k]
    fitfunc_str = ''

    fitfunc_str = 'o - A + A*e^(-(kx)**2)*cos(2pi (fx-phi))'

    def fitfunc(x):
        return (o() -
                A()) + A() * np.exp(-(k() * x)**2) * np.cos(2 * np.pi *
                                                            (f() * x - phi()))

    fit_result = fit.fit1d(x,
                           y,
                           None,
                           p0=p0,
                           fitfunc=fitfunc,
                           fixed=fixed,
                           do_print=True,
                           ret=True)

    if show_fit:
        plot.plot_fit1d(fit_result, np.linspace(0, x[-1], 201), plot_data=True)
    # print "pi pulse = {:.5f} ".format(1/f()/2.) + a.sweep_name

    # ax.set_title(a.timestamp+'\n'+a.measurementstring)
    if save:

        plt.savefig(os.path.join(folder, 'Calibrate_Pi_analysis_fit.png'))
def analyse_Ramsey(folder='', T2 = 3e3, Ampl = -1./3, detuning = 3e-3,hf_N = 2.17e-3, *arg):

	timestamp = kw.pop(timestamp, None)

	guess_tau = T2
	guess_a = 0.5
	guess_A = Ampl

	guess_hf_N = hf_N
	guess_det = detuning
	guess_hf_C = hf_C
	

	if timestamp != None:
	    folder = toolbox.data_from_time(timestamp)
	elif folder !='':
	    folder = toolbox.latest_data('Ramsey')

	a = sequence.SequenceAnalysis(folder)
	a.get_sweep_pts()
	a.get_readout_results(name='ssro')
	a.get_electron_ROC()
	x= a.sweep_pts
	y=a.p0


	ax = a.plot_result_vs_sweepparam(ret='ax', name='ssro')

	params_0, fitfunc_0, fitfunc_str_0 = ramsey.fit_ramsey_14N_fixed_13C_opt(guess_tau, guess_A, guess_a, guess_det, guess_hf_N)
	x_0=np.linspace(0,a.sweep_pts[-1],1000)
	ax.plot(x_0,fitfunc_0(x_0), 'r--', lw=1)
	#fit_xvals=np.linspace(res['x'][0],res['x'][-1],fit_num_points)


	fit_result = fit.fit1d(x, y, ramsey.fit_ramsey_14N_fixed_13C_opt,
	        guess_tau, guess_A, guess_a, guess_det, guess_hf_N,  fixed=[],
	        do_print=True, ret=True)
	#fit_result = False
	if fit_result != False :
		plot.plot_fit1d(fit_result, np.linspace(0,a.sweep_pts[-1],201), ax=ax,
	        plot_data=False)



	plt.savefig(os.path.join(folder, 'electronramsey_analysis.pdf'),
	        format='pdf')
Пример #47
0
def analyze_dark_esr(folder, ax=None, **kw):
    if ax == None:
        fig, ax = plt.subplots(1, 1)
    ssro_calib_folder = toolbox.latest_data(
        contains='AdwinSSRO_SSROCalibration')

    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results('ssro')
    a.get_electron_ROC(ssro_calib_folder=ssro_calib_folder)

    x = a.sweep_pts  # convert to MHz
    y = a.p0.reshape(-1)[:]
    a.plot_result_vs_sweepparam(ret=None, name='ssro', ax=ax)

    guess_ctr = x[np.floor(len(x) / 2.)]

    fit_result = fit.fit1d(
        x,
        y,
        esr.fit_ESR_gauss,
        guess_offset,
        guess_amplitude,
        guess_width,
        guess_ctr,
        # (2, guess_splitN),
        #(2, guess_splitC),
        # (2, guess_splitB),
        #(3, guess_splitN),
        do_print=True,
        ret=True,
        fixed=[])

    plot.plot_fit1d(fit_result,
                    np.linspace(min(x), max(x), 1000),
                    ax=ax,
                    plot_data=False,
                    **kw)

    ax.set_xlabel('MW frq (GHz)')
    ax.set_ylabel(r'fidelity wrt. $|0\rangle$')
    ax.set_title(a.timestamp + '\n' + a.measurementstring)
    plt.savefig(os.path.join(folder, 'darkesr_analysis.png'), format='png')
    return fit_result
Пример #48
0
def calibrate_epulse_rabi(folder, ax, *args, **kws):
    fit_phi = kws.pop('fit_phi', True)
    fit_k = kws.pop('fit_k', True)

    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='ssro')
    a.get_electron_ROC()
    a.plot_result_vs_sweepparam(ax=ax, name='ssro')

    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]
    ax.set_title(a.timestamp)

    f = fit.Parameter(args[0], 'f')
    A = fit.Parameter(args[1], 'A')
    x0 = fit.Parameter(0, 'x0')
    k = fit.Parameter(0, 'k')
    p0 = [f, A]
    if fit_phi:
        p0.append(x0)
    if fit_k:
        p0.append(k)
    fitfunc_str = '(1 - A) + A * exp(-kx) * cos(2pi f (x - x0))'

    def fitfunc(x):
        return (1.-A()) + A() * np.exp(-k()*x) * \
            np.cos(2*np.pi*(f()*(x - x0())))

    fit_result = fit.fit1d(x,
                           y,
                           None,
                           p0=p0,
                           fitfunc=fitfunc,
                           fitfunc_str=fitfunc_str,
                           do_print=True,
                           ret=True)
    plot.plot_fit1d(fit_result,
                    np.linspace(x[0], x[-1], 201),
                    ax=ax,
                    plot_data=False,
                    print_info=False)

    return fit_result
Пример #49
0
def fit_linear(folder=None, ax = None, a_guess=1., b_guess=0.):
    """
    fit a x + b from Sequence in folder
    """
    a, ax, x, y = plot_result(folder,ax)

    a = fit.Parameter(a_guess, 'a')
    b = fit.Parameter(b_guess, 'b')
    fitfunc_str = 'a x + b'

    def fitfunc(x):
        return a() * x + b()

    fit_result = fit.fit1d(x,y, None, p0=[a, b], fitfunc=fitfunc,
        fitfunc_str=fitfunc_str, do_print=True, ret=True)
    plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax,
        plot_data=False, print_info=False)
        
    return fit_result
    def plot_and_fit_single_peak(self,
                                 g_a1,
                                 g_A1,
                                 g_x01,
                                 g_gamma1,
                                 fixed=[],
                                 **kw):

        p0, fitfunc, fitfunc_str = common.fit_lorentz(g_a1, g_A1, g_x01,
                                                      g_gamma1)
        fit_result = fit.fit1d(self.x,
                               self.y,
                               None,
                               p0=p0,
                               fitfunc=fitfunc,
                               do_print=True,
                               ret=True,
                               fixed=fixed)
        fig, ax = plt.subplots(figsize=(8, 4))
        plot.plot_fit1d(fit_result,
                        np.linspace(self.x[0], self.x[-1], 10 * len(self.x)),
                        ax=ax,
                        label='Fit',
                        show_guess=True,
                        plot_data=True,
                        color='red',
                        data_linestyle='-',
                        print_info=False)
        ax.set_xlim(self.x[0], self.x[-1])
        if self.use_timetrace:
            ax.set_xlabel("Time (ms)", fontsize=14)
        else:
            ax.set_xlabel("datapoints", fontsize=14)
        ax.set_ylabel("Intensity (a.u.)", fontsize=14)

        linewidth = fit_result['params_dict']['gamma1']
        u_linewidth = fit_result['error_dict']['gamma1']

        plt.savefig(os.path.join(self.indir, self.filename + '_fit.png'))

        plt.show()

        return linewidth, u_linewidth
Пример #51
0
def calibrate_epulse_rabi(folder, ax, *args, **kws):
    fit_x0 = kws.pop('fit_x0', True)
    fit_k = kws.pop('fit_k', True)
    double_ro = kws.pop('double_ro', 'False')
    guess_x0 = kws.pop('guess_x0', 0)

    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC()
    a.plot_results_vs_sweepparam(ax=ax, name='adwindata')
    
    x = a.sweep_pts.reshape(-1)[:]
    if double_ro == 'electron':
        y = a.p0[:,0]
    elif double_ro == 'nitrogen':
        y = a.p0[:,1]
    else:
        y = a.p0.reshape(-1)[:]

    f = fit.Parameter(args[0], 'f')
    A = fit.Parameter(args[1], 'A')
    x0 = fit.Parameter(guess_x0, 'x0')
    k = fit.Parameter(0, 'k')
    p0 = [f, A]
    if fit_x0:
        p0.append(x0)
    if fit_k:
        p0.append(k)

    fitfunc_str = '(1 - A) + A * exp(-kx) * cos(2pi f (x - x0))'

    def fitfunc(x) : 
        return (1.-A()) + A() * np.exp(-k()*x) * \
            np.cos(2*np.pi*f()*(x - x0()))

    fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc,
        fitfunc_str=fitfunc_str, do_print=True, ret=True)
    plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax,
        plot_data=False, print_info=False)
        
    return fit_result
Пример #52
0
def epulse_fidelity(folder, ax, *args):
    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name="adwindata")
    a.get_electron_ROC()
    a.plot_results_vs_sweepparam(ax=ax, name="adwindata")

    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]

    of = fit.Parameter(args[0], "of")
    fitfunc_str = "(1-of)"

    def fitfunc_fid(x):
        return 1.0 - of()

    fit_result = fit.fit1d(x, y, None, p0=[of], fitfunc=fitfunc_fid, fitfunc_str=fitfunc_str, do_print=True, ret=True)
    plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False)

    return fit_result
def analyze_dark_esr(folder, ax=None, ret=None, **kw):

    if ax == None:
        fig, ax = plt.subplots(1,1)

    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results('ssro')
    a.get_electron_ROC()

    x = a.sweep_pts # convert to MHz
    y = a.p0.reshape(-1)[:]
    a.plot_result_vs_sweepparam(ret=ret, name='ssro', ax=ax)
    ax.set_ylim(0.65,1.05)
    
    guess_ctr = float(raw_input('Center guess?'))
    # try fitting
    fit_result = fit.fit1d(x, y, esr.fit_ESR_gauss, guess_offset,
            guess_amplitude, guess_width, guess_ctr,
            # (2, guess_splitN), 
            # (2, guess_splitC),
            # (2, guess_splitB),
            (3, guess_splitN), 
            do_print=True, ret=True, fixed=[4])
    plot.plot_fit1d(fit_result, x, ax=ax, plot_data=False, **kw)

    ax.set_xlabel('MW frq (GHz)')
    ax.set_ylabel(r'fidelity wrt. $|0\rangle$')
    ax.set_title(a.timestamp+'\n'+a.measurementstring)

    plt.savefig(os.path.join(folder, 'darkesr_analysis.png'),
            format='png')

    if ret == 'f0':
        f0 = fit_result['params_dict']['x0']
        u_f0 = fit_result['error_dict']['x0']

        ax.text(f0, 0.8, '$f_0$ = ({:.3f} +/- {:.3f})'.format(
            (f0-2.8)*1e3, u_f0*1e3), ha='center')

        return (f0-2.8)*1e3, u_f0*1e3
Пример #54
0
def fit_rabi(folder=None,
             ax=None,
             f_guess=0.9,
             A_guess=1,
             fit_phi=False,
             fit_k=False):
    """
    fit (1 - A) + A * exp(-kx) * cos(2pi f (x - x0)) from Sequence in folder
    """
    a, ax, x, y = plot_result(folder, ax)

    f = fit.Parameter(f_guess, 'f')
    A = fit.Parameter(A_guess, 'A')
    x0 = fit.Parameter(0, 'x0')
    k = fit.Parameter(0, 'k')
    p0 = [f, A]
    if fit_phi:
        p0.append(x0)
    if fit_k:
        p0.append(k)
    fitfunc_str = '(1 - A) + A * exp(-kx) * cos(2pi f (x - x0))'

    def fitfunc(x):
        return (1.-A()) + A() * np.exp(-k()*x) * \
            np.cos(2*np.pi*(f()*(x - x0())))

    fit_result = fit.fit1d(x,
                           y,
                           None,
                           p0=p0,
                           fitfunc=fitfunc,
                           fitfunc_str=fitfunc_str,
                           do_print=True,
                           ret=True)
    plot.plot_fit1d(fit_result,
                    np.linspace(x[0], x[-1], 201),
                    ax=ax,
                    plot_data=False,
                    print_info=False)

    return fit_result
Пример #55
0
def fit_parabolic(folder=None, ax = None,x0_guess=0., of_guess=0.5, a_guess=1.,**kw):
    """
    fit (1-of) + a (x-x0)**2 from Sequence in folder
    """
    do_print      = kw.pop('do_print', False)
    a, ax, x, y = plot_result(folder,ax)
    x0 = fit.Parameter(x0_guess, 'x0')
    of = fit.Parameter(of_guess, 'of')
    a = fit.Parameter(a_guess, 'a')

    fitfunc_str = '(1-of) + a (x-x0)**2'
    def fitfunc_parabolic(x):
        return (1.-of()) + a() * (x-x0())**2
    
    fit_result = fit.fit1d(x,y, None, p0=[of, a, x0], fitfunc=fitfunc_parabolic,
        fitfunc_str=fitfunc_str, do_print=do_print, ret=True)
    plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax,
        plot_data=False, **kw)
        
        
    return fit_result
Пример #56
0
def fit_linear(folder, ax, value, *args):
    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name="adwindata")
    a.get_electron_ROC()
    a.plot_results_vs_sweepparam(ax=ax, name="adwindata")

    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]

    a = fit.Parameter(args[0], "a")
    b = fit.Parameter(args[0], "b")
    fitfunc_str = "a x + b"

    def fitfunc(x):
        return a() * x + b()

    fit_result = fit.fit1d(x, y, None, p0=[a, b], fitfunc=fitfunc, fitfunc_str=fitfunc_str, do_print=True, ret=True)
    plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False)

    return fit_result
Пример #57
0
def calibrate_epulse_amplitude(folder, ax, *args, **kw):
    double_ro = kw.pop('double_ro', 'False')

    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC()
    a.plot_results_vs_sweepparam(ax=ax, name='adwindata')

    x = a.sweep_pts.reshape(-1)[:]
    if double_ro == 'electron':
        y = a.p0[:, 0]
    elif double_ro == 'nitrogen':
        y = a.p0[:, 1]
    else:
        y = a.p0.reshape(-1)[:]

    x0 = fit.Parameter(args[0], 'x0')
    of = fit.Parameter(args[1], 'of')
    a = fit.Parameter(args[2], 'a')
    fitfunc_str = '(1-of) + a (x-x0)**2'

    def fitfunc_parabolic(x):
        return (1. - of()) + a() * (x - x0())**2

    fit_result = fit.fit1d(x,
                           y,
                           None,
                           p0=[of, a, x0],
                           fitfunc=fitfunc_parabolic,
                           fitfunc_str=fitfunc_str,
                           do_print=True,
                           ret=True)
    plot.plot_fit1d(fit_result,
                    np.linspace(x[0], x[-1], 201),
                    ax=ax,
                    plot_data=False,
                    print_info=False)

    return fit_result
Пример #58
0
def determine_drift(times, peak_positions, data_folder):
    times_dec = []

    ftr = [3600, 60, 1]
    for time in times:
        time_dec = sum([
            a * b for a, b in zip(
                ftr, [int(time[0:2]),
                      int(time[2:4]),
                      int(time[4:6])])
        ])
        times_dec = np.append(times_dec, time_dec)

    times_dec = times_dec - times_dec[0]

    g_a = 2.13
    g_b = 0.0007
    fixed = []
    p0, fitfunc, fitfunc_str = common.fit_line(g_a, g_b)
    fit_result = fit.fit1d(times_dec,
                           peak_positions,
                           None,
                           p0=p0,
                           fitfunc=fitfunc,
                           do_print=False,
                           ret=True,
                           fixed=fixed)

    b = fit_result['params_dict']['b']
    u_b = fit_result['error_dict']['b']

    fig, ax = plt.subplots(figsize=(6, 4.7))

    ax = plot.plot_fit1d(fit_result,
                         np.linspace(times_dec[0], times_dec[-1],
                                     10 * len(times_dec)),
                         ax=ax,
                         color='r',
                         show_guess=True,
                         plot_data=True,
                         label='fit',
                         add_txt=False,
                         ret='ax')
    ax.set_xlabel('time (s)')
    ax.set_ylabel('peak position (V)')
    ax.set_title(data_folder + ' \n Drift is {} $\pm$ {} mV/s '.format(
        round(b * 1.e3, 3), round(u_b * 1.e3, 3)))

    fig.savefig(data_folder + '/' + "drift " + ".png")

    plt.show()
    plt.close()
Пример #59
0
	def perform_phenom_fit(self,key,plotting = False, ax = None):

		"""performs a fit of time trace data to a gaussian function"""

		if len(key) == 1:
			data = self.pickle_dict[key[0]]
		else:
			data = self.pickle_dict[key[0]][key[1]]
		evotime = data[timetrace_keylist[0]]
		fid = data[timetrace_keylist[1]]
		fid_u = data[timetrace_keylist[2]]

		ii = self.find_index(key[0])

		p0, fitfunc, fitfunc_str = common.fit_gauss(self.fit_offset, 0.43, 0., 8.25)

		fixed =[1]

		if self.use_fixed:
			if int(key[0]) % 2 ==0: ### key[0] is always the number of measurements.
				fixed = [0,1]	
			else: 
				fixed = [1]

		fit_result = fit.fit1d(evotime,fid, None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True,fixed=fixed)

		if plotting:
			plot.plot_fit1d(fit_result, np.linspace(0,200,201), ax=ax, plot_data=False,color = color_list[ii],add_txt = False, lw = fit_lw)

		p1 = abs(round(fit_result['params'][3-len(fixed)],3))
		p1_u = round(fit_result['error'][3-len(fixed)],3)

		self.results.append(key[0] + ' : T = ' + str(round(p1,2)) + ' +- ' + str(round(p1_u,2)))

		# print 'uncertainty ', p1_u;
		if len(key) == 1:
			self.pickle_dict[key[0]]['fit'] = fit_result
		else:
			self.pickle_dict[key[0]][key[1]]['fit'] = fit_result