def fit_gauss(x, y, **kw):
    a = kw.pop('a', 0.1)
    A = kw.pop('A', 0.7)
    x0 = kw.pop('x0', 0)
    T = kw.pop('T', 1000)
    n = kw.pop('n', 2)
    fixed = kw.pop('fixed', [0, 2, 4])
    show_guess = kw.pop('show_guess', False)
    do_print = kw.pop('do_print', False)
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(a, A, x0, T, n)
    if show_guess:
        ax.plot(np.linspace(0, x[-1], 201),
                fitfunc(np.linspace(0, x[-1], 201)),
                ':',
                lw=2)
    fit_result = fit.fit1d(x,
                           y,
                           None,
                           p0=p0,
                           fitfunc=fitfunc,
                           do_print=do_print,
                           ret=True,
                           fixed=fixed)

    return fit_result
def fit_gauss(x,y,**kw):
    a = kw.pop('a',0.1)
    A = kw.pop('A',0.7)
    x0 = kw.pop('x0',0)
    T = kw.pop('T',1000)
    n = kw.pop('n',2)
    fixed=kw.pop('fixed',[0,2,4])
    show_guess = kw.pop('show_guess',False)
    do_print = kw.pop('do_print',False)
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(a,A,x0,T,n)
    if show_guess:
        ax.plot(np.linspace(0,x[-1],201), fitfunc(np.linspace(0,x[-1],201)), ':', lw=2)
    fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc, do_print=do_print, ret=True,fixed=fixed)
    
    return fit_result
Beispiel #3
0
def Carbon_T1_analysis(measurement_name=['adwindata'],
                       ssro_calib_timestamp=None,
                       offset=0.5,
                       amplitude=0.5,
                       decay_constant=0.04,
                       x0=0,
                       exponent=1,
                       Addressed_carbon=1,
                       plot_fit=True,
                       do_print=False,
                       show_guess=False,
                       el_state='both'):
    ''' 
    Function to gather and analyze T1 measurements of a specific carbon.

    Addressed_carbon: selects the used timestamps and therefore the analyzed carbon

    measurement_name: list of measurement names

    Possible inputs for initial guesses: offset, amplitude, decay_constant,exponent
    '''

    #general plot parameters
    ylim = (0.5, 1.0)
    figsize = (6, 4.7)

    ######################################
    #    carbon_init= up el_state=0      #
    ######################################
    if el_state == '0' or el_state == 'both':

        if Addressed_carbon == 1:
            timestamp_pos = [
                '20141104_194723', '20141104_200359', '20141104_215235'
            ]
            timestamp_neg = [
                '20141104_195541', '20141104_205814', '20141104_231030'
            ]
        elif Addressed_carbon == 5:
            timestamp_pos = ['20150316_041301']
            timestamp_neg = ['20150316_054506']
            # timestamp_pos=['20141105_192118','20141105_193818','20141105_212709']
            # timestamp_neg=['20141105_192948','20141105_203243','20141105_231521']
            #timestamp_pos=['20141105_002824','20141105_004556','20141105_023521']
            #timestamp_neg=['20141105_003711','20141105_014037','20141105_035322']
        elif Addressed_carbon == 2:
            timestamp_pos = [
                '20141106_010336', '20141106_012019', '20141106_030844'
            ]
            timestamp_neg = [
                '20141106_011155', '20141106_021431', '20141106_045651'
            ]

        if ssro_calib_timestamp == None:
            ssro_calib_folder = toolbox.latest_data('SSRO')
        else:
            ssro_dstmp, ssro_tstmp = toolbox.verify_timestamp(
                ssro_calib_timestamp)
            ssro_calib_folder = toolbox.datadir + '/' + ssro_dstmp + '/' + ssro_tstmp + '_AdwinSSRO_SSROCalibration_111_1_sil18'
            print ssro_calib_folder

        ##accumulate data and average over positive and negative RO##

        cum_pts = 0

        for kk in range(len(timestamp_pos)):
            folder_pos = toolbox.data_from_time(timestamp_pos[kk])
            folder_neg = toolbox.data_from_time(timestamp_neg[kk])
            a = mbi.MBIAnalysis(folder_pos)
            a.get_sweep_pts()
            a.get_readout_results(name='adwindata')
            a.get_electron_ROC(ssro_calib_folder)
            cum_pts += a.pts

            b = mbi.MBIAnalysis(folder_neg)
            b.get_sweep_pts()
            b.get_readout_results(name='adwindata')
            b.get_electron_ROC(ssro_calib_folder)

            if kk == 0:
                cum_sweep_pts = a.sweep_pts
                cum_p0 = (a.p0 + (1 - b.p0)) / 2.
                cum_u_p0 = np.sqrt(a.u_p0**2 + b.u_p0**2) / 2
            else:
                cum_sweep_pts = np.concatenate((cum_sweep_pts, a.sweep_pts))
                cum_p0 = np.concatenate((cum_p0, (a.p0 + (1 - b.p0)) / 2))
                cum_u_p0 = np.concatenate(
                    (cum_u_p0, np.sqrt(a.u_p0**2 + b.u_p0**2) / 2))

        a.pts = cum_pts
        a.sweep_pts = cum_sweep_pts
        a.p0 = cum_p0
        a.u_p0 = cum_u_p0

        ## accumulate data with negative RO

        #sort data by free evolution time.
        sorting_order = a.sweep_pts.argsort()
        a.sweep_pts.sort()
        a.p0 = a.p0[sorting_order]
        a.u_p0 = a.u_p0[sorting_order]

        ## generate plot of the raw data ##

        #uncomment this part to plot without error bars, but including obtained fit parameters.
        # fig = a.default_fig(figsize=(6,5))
        # ax = a.default_ax(fig)
        # ax.plot(a.sweep_pts, a.p0, 'bo',label='T1 of Carbon'+str(Addressed_carbon),lw=1.2)

        ax = a.plot_results_vs_sweepparam(ret='ax',
                                          ax=None,
                                          figsize=figsize,
                                          ylim=(0.4, 1.0))

        ## fit to a general exponential##

        fit_results = []

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

        ax.plot(x, y)
        plt.show()
        p0, fitfunc, fitfunc_str = common.fit_general_exponential(
            offset, amplitude, x0, decay_constant, exponent)
        #p0, fitfunc, fitfunc_str = common.fit_line(0.5,-0.5/7.)

        #plot the initial guess

        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=[0, 2])

        ## plot data and fit as function of total time

        if plot_fit == True:
            plot.plot_fit1d(fit_result,
                            np.linspace(x[0], x[-1], 1001),
                            ax=ax,
                            plot_data=False)

        fit_results.append(fit_result)

        filename = 'C13_T1_analysis_up_C' + str(Addressed_carbon)
        print 'plots are saved in ' + folder_pos

        #configure the plot
        plt.title('Sample_111_No1_C13_T1_up_C' + str(Addressed_carbon) +
                  'el_state_0')
        plt.xlabel('Free evolution time (s)')
        plt.ylabel('Fidelity')
        plt.axis([a.sweep_pts[0], a.sweep_pts[a.pts - 1], 0.4, 1.])

        plt.savefig(os.path.join(folder_pos, filename + '.pdf'), format='pdf')
        plt.savefig(os.path.join(folder_pos, filename + '.png'), format='png')

    ######################################
    #    carbon_init= up el_state=1      #
    ######################################
    if el_state == '1' or el_state == 'both':

        if Addressed_carbon == 1:
            timestamp_pos = [
                '20141104_195135', '20141104_203107', '20141104_223132'
            ]
            timestamp_neg = [
                '20141104_195949', '20141104_212524', '20141104_234927'
            ]
        elif Addressed_carbon == 5:
            timestamp_neg = ['20150316_055528']
            timestamp_pos = ['20150316_042310']
            # timestamp_neg=['20150312_001153']
            # timestamp_pos=['20150311_231635']
            # timestamp_neg=['20141105_193405','20141105_205957','20141106_000928']
            #timestamp_pos=['20141105_003250','20141105_011316','20141105_031420']
            #timestamp_neg=['20141105_004136','20141105_020802','20141105_043221']
        elif Addressed_carbon == 2:
            timestamp_pos = [
                '20141106_010748', '20141106_014724', '20141106_040245'
            ]
            timestamp_neg = [
                '20141106_011609', '20141106_024138', '20141106_055052'
            ]

        if ssro_calib_timestamp == None:
            ssro_calib_folder = toolbox.latest_data('SSRO')
        else:
            ssro_dstmp, ssro_tstmp = toolbox.verify_timestamp(
                ssro_calib_timestamp)
            ssro_calib_folder = toolbox.datadir + '/' + ssro_dstmp + '/' + ssro_tstmp + '_AdwinSSRO_SSROCalibration_111_1_sil18'
            print ssro_calib_folder

        ##accumulate data and average over positive and negative RO##

        cum_pts = 0

        for kk in range(len(timestamp_pos)):
            folder_pos = toolbox.data_from_time(timestamp_pos[kk])
            folder_neg = toolbox.data_from_time(timestamp_neg[kk])
            a = mbi.MBIAnalysis(folder_pos)
            a.get_sweep_pts()
            a.get_readout_results(name='adwindata')
            timestamp_SSRO, ssro_calib_folder = toolbox.latest_data(
                'AdwinSSRO',
                older_than=timestamp_pos[kk],
                return_timestamp=True)
            a.get_electron_ROC(ssro_calib_folder)
            cum_pts += a.pts

            b = mbi.MBIAnalysis(folder_neg)
            b.get_sweep_pts()
            b.get_readout_results(name='adwindata')
            timestamp_SSRO, ssro_calib_folder = toolbox.latest_data(
                'AdwinSSRO',
                older_than=timestamp_neg[kk],
                return_timestamp=True)
            b.get_electron_ROC(ssro_calib_folder)

            print a.p0.transpose()
            print b.p0.transpose()

            if kk == 0:
                cum_sweep_pts = a.sweep_pts
                cum_p0 = (a.p0 + (1 - b.p0)) / 2.
                cum_u_p0 = np.sqrt(a.u_p0**2 + b.u_p0**2) / 2
            else:
                cum_sweep_pts = np.concatenate((cum_sweep_pts, a.sweep_pts))
                cum_p0 = np.concatenate((cum_p0, (a.p0 + (1 - b.p0)) / 2))
                cum_u_p0 = np.concatenate(
                    (cum_u_p0, np.sqrt(a.u_p0**2 + b.u_p0**2) / 2))

        a.pts = cum_pts
        a.sweep_pts = cum_sweep_pts
        a.p0 = cum_p0
        a.u_p0 = cum_u_p0

        print a.p0
        ## accumulate data with negative RO

        #sort data by free evolution time.
        sorting_order = a.sweep_pts.argsort()
        a.sweep_pts.sort()
        a.p0 = a.p0[sorting_order]
        a.u_p0 = a.u_p0[sorting_order]

        ## generate plot of the raw data ##

        #uncomment this part to plot without error bars, but including obtained fit parameters.
        # fig = a.default_fig(figsize=(6,5))
        # ax = a.default_ax(fig)
        # ax.plot(a.sweep_pts, a.p0, 'bo',label='T1 of Carbon'+str(Addressed_carbon),lw=1.2)

        ax = a.plot_results_vs_sweepparam(ret='ax',
                                          figsize=figsize,
                                          ax=None,
                                          ylim=ylim)
        ## fit to a general exponential##

        fit_results = []

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

        ax.plot(x, y)
        # plt.show()
        p0, fitfunc, fitfunc_str = common.fit_general_exponential(
            offset, amplitude, x0, decay_constant, exponent)

        #plot the initial guess

        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=[0, 2])

        ## plot data and fit as function of total time

        if plot_fit == True:
            plot.plot_fit1d(fit_result,
                            np.linspace(x[0], x[-1], 1001),
                            ax=ax,
                            plot_data=False)

        fit_results.append(fit_result)

        filename = 'C13_T1_analysis_up_C' + str(Addressed_carbon)
        print 'plots are saved in ' + folder_pos

        #configure the plot
        plt.title('Sample_111_No1_C13_T1_up_C' + str(Addressed_carbon) +
                  'el_state_1')
        plt.xlabel('Free evolution time (s)')
        plt.ylabel('Fidelity')
        plt.axis([a.sweep_pts[0], a.sweep_pts[a.pts - 1], ylim[0], ylim[1]])

        plt.savefig(os.path.join(folder_pos, filename + '.pdf'), format='pdf')
        plt.savefig(os.path.join(folder_pos, filename + '.png'), format='png')
def Carbon_T1(timestamp=None, measurement_name = 'adwindata', ssro_calib_timestamp =None,
            offset = 0.5, 
            x0 = 0,  
            amplitude = 0.5,  
            decay_constant = 200, 
            exponent = 2, 
            plot_fit = False, do_print = False, fixed = [2], show_guess = True):
    ''' 
    Inputs:
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    List of parameters (order important for 'fixed') 
    offset, amplitude, decay_constant,exponent,frequency ,phase 
    '''
    figsize=(6,4.7)

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

    if ssro_calib_timestamp == None: 
        ssro_calib_folder = toolbox.latest_data('SSRO')
    else:
        ssro_dstmp, ssro_tstmp = toolbox.verify_timestamp(ssro_calib_timestamp)
        ssro_calib_folder = toolbox.datadir + '/'+ssro_dstmp+'/'+ssro_tstmp+'_AdwinSSRO_SSROCalibration_Hans_sil1'
        print ssro_calib_folder


    fit_results = []
    
    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC(ssro_calib_folder)
    # print a.result_corrected
    # print a.p0[:,0]
    # print a.sweep_pts
    # print a.labels
    # print a.u_p0[:,0]
    # print a.readouts
    ax=a.plot_results_vs_sweepparam(ret='ax',ax=None, 
                                    figsize=figsize, 
                                    ylim=(0.0,1.0)
                                    )

    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]
    # ax.plot(x,y)
    
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, 
             x0, decay_constant,exponent)

         #plot the initial guess
    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=fixed)

    ## plot data and fit as function of total time
    if plot_fit == True:
        plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],1001), 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
def Carbon_T1_analysis(measurement_name = ['adwindata'], ssro_calib_timestamp =None, 
            offset = 0.5, 
            amplitude = 0.5,  
            decay_constant = 0.1, 
            x0=0,
            exponent = 1, 
            Addressed_carbon=1,
            el_RO='positive',
            plot_fit = True, do_print = True, show_guess = False):
    ''' 
    Function to gather and analyze T1 measurements of a specific carbon.

    Addressed_carbon: selects the used timestamps and therefore the analyzed carbon

    measurement_name: list of measurement names

    Possible inputs for initial guesses: offset, amplitude, decay_constant,exponent
    '''

    #general plot parameters
    ylim=(0.0,1.0)
    figsize=(6,4.7)



    ######################################
    #    carbon_init= up el_state=0      #
    ######################################


    if Addressed_carbon == 1:
        if el_RO=='positive':
            timestamp=['20141104_194723','20141104_200359','20141104_215235']
        else:
            timestamp=['20141104_195541','20141104_205814','20141104_231030']
    elif Addressed_carbon == 5:
        if el_RO=='positive':
            timestamp=['20150316_041301']
            # timestamp=['20141105_002824','20141105_004556','20141105_023521']
        else:
            timestamp=['20150316_054506']
            # timestamp=['20141105_003711','20141105_014037','20141105_035322']

    if ssro_calib_timestamp == None: 
        ssro_calib_folder = toolbox.latest_data('SSRO')
    else:
        ssro_dstmp, ssro_tstmp = toolbox.verify_timestamp(ssro_calib_timestamp)
        ssro_calib_folder = toolbox.datadir + '/'+ssro_dstmp+'/'+ssro_tstmp+'_AdwinSSRO_SSROCalibration_111_1_sil18'
        print ssro_calib_folder


    ##accumulate data and average over positive and negative RO##

    cum_pts = 0

    for kk in range(len(timestamp)):
        folder = toolbox.data_from_time(timestamp[kk])
        a = mbi.MBIAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        timestamp_SSRO, ssro_calib_folder = toolbox.latest_data('AdwinSSRO', older_than = timestamp[kk], return_timestamp = True)
        a.get_electron_ROC(ssro_calib_folder)
        cum_pts += a.pts

        if kk == 0:
            cum_sweep_pts = a.sweep_pts
            cum_p0 = a.p0
            cum_u_p0 = a.u_p0
        else:
            cum_sweep_pts = np.concatenate((cum_sweep_pts, a.sweep_pts))
            cum_p0 = np.concatenate((cum_p0, a.p0))
            cum_u_p0 = np.concatenate((cum_u_p0, a.u_p0))

    a.pts   = cum_pts
    a.sweep_pts = cum_sweep_pts
    a.p0    = cum_p0
    a.u_p0  = cum_u_p0


    ## accumulate data with negative RO


    
    #sort data by free evolution time.
    sorting_order=a.sweep_pts.argsort()
    a.sweep_pts.sort()
    a.p0=a.p0[sorting_order]
    a.u_p0=a.u_p0[sorting_order]


    ## generate plot of the raw data ##


    #uncomment this part to plot without error bars, but including obtained fit parameters.
    # fig = a.default_fig(figsize=(6,5))
    # ax = a.default_ax(fig)
    # ax.plot(a.sweep_pts, a.p0, 'bo',label='T1 of Carbon'+str(Addressed_carbon),lw=1.2)


    ax=a.plot_results_vs_sweepparam(ret='ax',ax=None, 
                                    figsize=figsize, 
                                    ylim=(0.0,1.0)
                                    )


    ## fit to a general exponential##

    fit_results = []

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

    ax.plot(x,y)
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, x0, decay_constant,exponent)
    #p0, fitfunc, fitfunc_str = common.fit_line(0.5,-0.5/7.)

    #plot the initial guess

    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=[0,2])

    ## plot data and fit as function of total time

    if plot_fit == True:
        plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],1001), ax=ax, plot_data=False)

    fit_results.append(fit_result)

    filename= 'C13_T1_analysis_up_positive_C'+str(Addressed_carbon)+'_'+el_RO
    print 'plots are saved in ' + folder

    #configure the plot
    plt.title('Sample_111_No1_C13_T1_up_positive_C'+str(Addressed_carbon)+'el_state_0')
    plt.xlabel('Free evolution time (s)')
    plt.ylabel('Fidelity')
    plt.axis([a.sweep_pts[0],a.sweep_pts[a.pts-1],0.0,1.])


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


    ######################################
    #    carbon_init= up el_state=1      #
    ######################################


    if Addressed_carbon == 1:
        if el_RO=='positive':
            timestamp=['20141104_195135','20141104_203107','20141104_223132']
        else:
            timestamp=['20141104_195949','20141104_212524','20141104_234927']
    elif Addressed_carbon == 5:
        if el_RO=='positive':
            timestamp=['20150316_055528']
            # timestamp=['20141105_003250','20141105_011316','20141105_031420']
        else:
            timestamp=['20150316_042310']
            # timestamp=['20141105_004136','20141105_020802','20141105_043221']

    if ssro_calib_timestamp == None: 
        ssro_calib_folder = toolbox.latest_data('SSRO')
    else:
        ssro_dstmp, ssro_tstmp = toolbox.verify_timestamp(ssro_calib_timestamp)
        ssro_calib_folder = toolbox.datadir + '/'+ssro_dstmp+'/'+ssro_tstmp+'_AdwinSSRO_SSROCalibration_111_1_sil18'
        print ssro_calib_folder


    ##accumulate data and average over positive and negative RO##

    cum_pts = 0

    for kk in range(len(timestamp)):
        folder = toolbox.data_from_time(timestamp[kk])
        a = mbi.MBIAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        timestamp_SSRO, ssro_calib_folder = toolbox.latest_data('AdwinSSRO', older_than = timestamp[kk], return_timestamp = True)
        a.get_electron_ROC(ssro_calib_folder)
        cum_pts += a.pts

        if kk == 0:
            cum_sweep_pts = a.sweep_pts
            cum_p0 = a.p0
            cum_u_p0 = a.u_p0
        else:
            cum_sweep_pts = np.concatenate((cum_sweep_pts, a.sweep_pts))
            cum_p0 = np.concatenate((cum_p0, a.p0))
            cum_u_p0 = np.concatenate((cum_u_p0, a.u_p0))
            print

    a.pts   = cum_pts
    a.sweep_pts = cum_sweep_pts
    a.p0    = cum_p0
    a.u_p0  = cum_u_p0


    ## accumulate data with negative RO


    
    #sort data by free evolution time.
    sorting_order=a.sweep_pts.argsort()
    a.sweep_pts.sort()
    a.p0=a.p0[sorting_order]
    a.u_p0=a.u_p0[sorting_order]


    ## generate plot of the raw data ##


    #uncomment this part to plot without error bars, but including obtained fit parameters.
    # fig = a.default_fig(figsize=(6,5))
    # ax = a.default_ax(fig)
    # ax.plot(a.sweep_pts, a.p0, 'bo',label='T1 of Carbon'+str(Addressed_carbon),lw=1.2)


    ax=a.plot_results_vs_sweepparam(ret='ax',figsize=figsize, ax=None, ylim=ylim)
    ## fit to a general exponential##

    fit_results = []

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

    ax.plot(x,y)
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, x0, decay_constant,exponent)
    #p0, fitfunc, fitfunc_str = common.fit_line(0.5,-0.5/7.)

    #plot the initial guess

    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=[0,2])

    ## plot data and fit as function of total time

    if plot_fit == True:
        plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],1001), ax=ax, plot_data=False)

    fit_results.append(fit_result)

    filename= 'C13_T1_analysis_up_negative_C'+str(Addressed_carbon)+'_'+el_RO
    print 'plots are saved in ' + folder

    #configure the plot
    plt.title('Sample_111_No1_C13_T1_up_negative_C'+str(Addressed_carbon)+'el_state_1')
    plt.xlabel('Free evolution time (s)')
    plt.ylabel('Fidelity')
    plt.axis([a.sweep_pts[0],a.sweep_pts[a.pts-1],ylim[0],ylim[1]])


    plt.savefig(os.path.join(folder, filename+'.pdf'),
    format='pdf')
    plt.savefig(os.path.join(folder, filename+'.png'),
    format='png')
Beispiel #6
0
def DFS_comparison(msmts_dict,
    offset = 0.5, 
    x0 = 0,  
    amplitude = 0.4,  
    decay_constant = 0.426546, 
    exponent = 1.75, fixed = [0,2,4]):

    plt.close('all')

    # msmts_list = ['pX,mX,XX']
    
    color = ['r','b','g','m','k']
    x = []
    y = []
    y_err = []
    fig = plt.figure(figsize=(7,5))
    # mpl.rcParams['axes.linewidth'] = 2
    # max_x = 8
    max_x = 1.2
    min_x = 0.
    # fig3 = plt.figure(figsize=(10,8))
    Amps = []
    Amps_err = []
    Ts = []
    Ts_err = []
    exps = []
    exps_err = []
    ax = fig.add_subplot(111)
    # ax3 = fig3.add_subplot(111)
    # p0 = [amplitude, decay_constant, exponent]
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, 
             x0, decay_constant,exponent)
    for aaa, dictms in enumerate(msmts_dict):
        #msmts_list = list(dictms.keys())
        msmts_list =[r'$|00\rangle+|11\rangle$' , r'$|01\rangle+|10\rangle$']
        # msmts_list =[r'$|00\rangle+|11\rangle$']
        for ii,msmt in enumerate(msmts_list):
            array = np.loadtxt(DBdir+dictms[msmt],skiprows=1)
            x.append(array[:,0])
            y.append(array[:,1])
            y_err.append(array[:,2])
            # print x
            # print y
            # print y_err
            # optimize.leastsq(fit_func,x,y,p0)
            p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, 
                 x0, decay_constant,exponent)
            fit_result = fit.fit1d(x[-1],y[-1], None, p0=p0, fitfunc=fitfunc, do_print=True, ret=True,fixed=fixed)
            
            Ts.append(fit_result['params_dict']['T'])
            Ts_err.append(fit_result['error_dict']['T'])
            Amps.append(fit_result['params_dict']['A'])
            Amps_err.append(fit_result['error_dict']['A'])
            if 4 in fixed:
                # ax.errorbar(x,y,fmt='o',yerr=y_err, label='N=' + str(N)+' T=' + '%.2f' % fit_result['params_dict']['T'] + '+-' + '%.2f' % fit_result['error_dict']['T']
                # +', A=' '%.2f' % fit_result['params_dict']['A'] + '+-' + '%.2f' % fit_result['error_dict']['A'],color=color[ii])
                ax.errorbar(x[-1],y[-1],fmt='o',yerr=y_err[-1], label=msmt,color=color[ii])
            else:
                exps.append(fit_result['params_dict']['n'])
                exps_err.append(fit_result['error_dict']['n'])
                ax.errorbar(x[-1],y[-1],fmt='o',yerr=y_err[-1], label=msmt,color=color[ii])
                # ax.errorbar(x[-1],y[-1],fmt='o',yerr=y_err[-1], label=msmt + ',  T=' + '%.2f' % fit_result['params_dict']['T'] + '+-' + '%.2f' % fit_result['error_dict']['T']
                # +', A=' '%.2f' % fit_result['params_dict']['A'] + '+-' + '%.2f' % fit_result['error_dict']['A'] +', n=' '%.2f' % fit_result['params_dict']['n'] + '+-' + '%.2f' % fit_result['error_dict']['n'],color=color[ii])
            if aaa == 0:
                ls = '-'
            else:
                ls = '--'
            plot.plot_fit1d(fit_result, np.linspace(-0.1,max_x,1001), ax=ax, plot_data=False,print_info=False,linestyle=ls,color=color[ii])
            
    # ax.set_xscale('log')
    ax.hlines([0.5],min_x,max_x,linestyles='dotted', linewidth = 2)
    ax.hlines([0.],min_x,max_x,linestyles='dotted', linewidth = 2)
    # plt.text(1, 0.8, r'$\left< XX \right>$', fontsize=30)
    ax.hlines([1.],min_x,max_x,linestyles='dotted', linewidth = 2)
    ax.set_xlim(min_x,max_x)
    ax.set_ylim(0.45,0.85)
    plt.xticks([0.0,0.5,1.0])
    plt.yticks([0.5,0.6,0.7,0.8],['0.0','0.2','0.4','0.6'])
    ax.set_xlabel('Free evolution time (s)',fontsize = 15)
    ax.set_ylabel(r'$\langle$XX$\rangle$',fontsize = 20)
    ax.tick_params(axis='x', which='major', labelsize=15)
    ax.tick_params(axis='y', which='major', labelsize=15)
    for axis in ['top','bottom','left','right']:
        ax.spines[axis].set_linewidth(2.)
    plt.legend(loc = 'upper right',fontsize = 20,numpoints = 1,frameon = False,columnspacing=0.5,handletextpad=0.0)

    # plt.savefig(r'/Users/'+os.getlogin()+r'/Dropbox/DFS36XX.pdf', bbox_inches='tight')
    #mpl.rcParams['axes.linewidth'] = 2
    plt.show()
Beispiel #7
0
def electron_DD_analysis(timestamp=None,
                         measurement_name=['adwindata'],
                         offset=0.5,
                         amplitude=0.5,
                         position=0,
                         T2=800,
                         power=2,
                         plot_fit=True,
                         do_print=False,
                         show_guess=False,
                         do_a_single_fit=False):
    ''' Function to analyze simple decoupling measurements. Loads the results and fits them to a simple exponential.
    Inputs:
    timestamp: list of timestamps in format in format yyyymmdd_hhmmss or hhmmss or None. (Added: List functionality. NK 20150320)
    measurement_name: list of measurement names
    Based on electron_T1_anal,
    '''

    if timestamp != None:
        if type(timestamp) == str:
            folder_list = [toolbox.data_from_time(timestamp)]
        else:
            folder_list = []
            for t in timestamp:
                folder_list.append(toolbox.data_from_time(t))
    else:
        folder_list = [toolbox.latest_data('Decoupling')]

    fit_results = []
    all_x = []
    all_y = []

    for ii, f in enumerate(folder_list):
        for k in range(0, len(measurement_name)):
            a = mbi.MBIAnalysis(f)
            a.get_sweep_pts()
            a.get_readout_results(name=measurement_name[k])
            a.get_electron_ROC()
            if ii == 0:
                ax = a.plot_results_vs_sweepparam(ret='ax')
            else:
                ax.errorbar(a.sweep_pts.reshape(-1)[:],
                            a.p0.reshape(-1)[:],
                            yerr=a.u_p0.reshape(-1)[:],
                            fmt='o')
            x = a.sweep_pts.reshape(-1)[:]
            y = a.p0.reshape(-1)[:]
            all_x.extend(x)
            all_y.extend(y)

            if not do_a_single_fit:

                p0, fitfunc, fitfunc_str = common.fit_general_exponential(
                    offset, amplitude, position, T2, power)

                #plot the initial guess
                if show_guess:
                    ax.plot(np.linspace(0, x[-1], 201),
                            fitfunc(np.linspace(0, x[-1], 201)),
                            ':',
                            lw=2)

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

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

    if do_a_single_fit:
        x = np.array(all_x)
        y = np.array(all_y)
        print x, np.shape(x)
        print y, np.shape(y)
        p0, fitfunc, fitfunc_str = common.fit_general_exponential(
            offset, amplitude, position, T2, power)

        #plot the initial guess
        if show_guess:
            ax.plot(np.linspace(0, x[-1], 201),
                    fitfunc(np.linspace(0, x[-1], 201)),
                    ':',
                    lw=2)

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

        ## 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_list[0], 'analyzed_result.pdf'),
                format='pdf')
    plt.savefig(os.path.join(folder_list[0], 'analyzed_result.png'),
                format='png')

    ## plot data and fit as function of tau
    #plt.figure()
    #plt.plot(np.linspace(0,x[-1],201), fit_result['fitfunc'](np.linspace(0,x[-1],201)), ':', lw=2)
    #plt.plot(x, y, '.', lw=2)

    return fit_results
def Carbon_T2_analysis_ms1(measurement_name = ['adwindata'], ssro_calib_timestamp =None, 
            offset = 0.5, 
            amplitude = 0.5,  
            decay_constant = 0.2, 
            x0=0,
            exponent = 1, 
            Addressed_carbon=5,
            plot_fit = True, do_print = True, show_guess = False):

    if Addressed_carbon == 1:
        timestamp_pos=['20141104_195135','20141104_203107','20141104_223132']
        timestamp_neg=['20141104_195949','20141104_212524','20141104_234927']
    elif Addressed_carbon == 5:
        timestamp_pos=['20150309_193904']
        timestamp_neg=['20150309_195337']
        # timestamp_pos=['20150102_193904']
        # timestamp_neg=['20150102_214323']
        #timestamp_pos=['20141105_003250','20141105_011316','20141105_031420']
        #timestamp_neg=['20141105_004136','20141105_020802','20141105_043221']
    elif Addressed_carbon == 2:
        timestamp_pos=['20141106_010748','20141106_014724','20141106_040245']
        timestamp_neg=['20141106_011609','20141106_024138','20141106_055052']

    if ssro_calib_timestamp == None: 
        ssro_calib_folder = toolbox.latest_data('SSRO')
    else:
        ssro_dstmp, ssro_tstmp = toolbox.verify_timestamp(ssro_calib_timestamp)
        ssro_calib_folder = toolbox.datadir + '/'+ssro_dstmp+'/'+ssro_tstmp+'_AdwinSSRO_SSROCalibration_111_1_sil18'
        print ssro_calib_folder


    ##accumulate data and average over positive and negative RO##

    cum_pts = 0

    for kk in range(len(timestamp_pos)):
        folder_pos = toolbox.data_from_time(timestamp_pos[kk])
        folder_neg = toolbox.data_from_time(timestamp_neg[kk])
        a = mbi.MBIAnalysis(folder_pos)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        a.get_electron_ROC(ssro_calib_folder)
        cum_pts += a.pts

        b = mbi.MBIAnalysis(folder_neg)
        b.get_sweep_pts()
        b.get_readout_results(name='adwindata')
        b.get_electron_ROC(ssro_calib_folder)

        if kk == 0:
            cum_sweep_pts = a.sweep_pts
            cum_p0 = (a.p0+(1-b.p0))/2.
            cum_u_p0 = np.sqrt(a.u_p0**2+b.u_p0**2)/2
        else:
            cum_sweep_pts = np.concatenate((cum_sweep_pts, a.sweep_pts))
            cum_p0 = np.concatenate((cum_p0, (a.p0+(1-b.p0))/2))
            cum_u_p0 = np.concatenate((cum_u_p0, np.sqrt(a.u_p0**2+b.u_p0**2)/2))
            print

    a.pts   = cum_pts
    a.sweep_pts = cum_sweep_pts
    a.p0    = cum_p0
    a.u_p0  = cum_u_p0


    ## accumulate data with negative RO


    
    #sort data by free evolution time.
    sorting_order=a.sweep_pts.argsort()
    a.sweep_pts.sort()
    a.p0=a.p0[sorting_order]
    a.u_p0=a.u_p0[sorting_order]


    ## generate plot of the raw data ##


    #uncomment this part to plot without error bars, but including obtained fit parameters.
    # fig = a.default_fig(figsize=(6,5))
    # ax = a.default_ax(fig)
    # ax.plot(a.sweep_pts, a.p0, 'bo',label='T1 of Carbon'+str(Addressed_carbon),lw=1.2)


    ax=a.plot_results_vs_sweepparam(ret='ax',figsize=figsize, ax=None, ylim=ylim)
    ## fit to a general exponential##

    fit_results = []

    x = a.sweep_pts.reshape(-1)[:]*2
    y = a.p0.reshape(-1)[:]
    y_err = a.u_p0.reshape(-1)[:]
    ax.plot(x,y)
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, x0, decay_constant,exponent)
    #p0, fitfunc, fitfunc_str = common.fit_line(0.5,-0.5/7.)

    #plot the initial guess

    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=[0,2])

    ## plot data and fit as function of total time

    if plot_fit == True:
        plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],1001), ax=ax, plot_data=False)

    fit_results.append(fit_result)

    filename= 'C13_T2_analysis_up_C'+str(Addressed_carbon)
    print 'plots are saved in ' + folder_pos

    #configure the plot
    plt.title('Sample_111_No1_C13_T2_up_C'+str(Addressed_carbon)+'el_state_1')
    plt.xlabel('Free evolution time (s)')
    plt.ylabel('Fidelity')
    plt.axis([a.sweep_pts[0],a.sweep_pts[a.pts-1],0.4,1])


    # plt.savefig(os.path.join(r'D:\measuring\data\Analyzed figures\Carbon Hahn', filename+'.pdf'),
    # format='pdf')
    # plt.savefig(os.path.join(r'D:\measuring\data\Analyzed figures\Carbon Hahn', filename+'.png'),
    # format='png')

    return x,y, y_err, fit_result
def Carbon_T2_analysis_ms0(measurement_name = ['adwindata'], ssro_calib_timestamp =None, 
            offset = 0.5, 
            amplitude = 0.5,  
            decay_constant = 0.2, 
            x0=0,
            exponent = 1, 
            Addressed_carbon=5,
            plot_fit = True, do_print = True, show_guess = False):
    ''' 
    Function to gather and analyze T1 measurements of a specific carbon.
    Addressed_carbon: selects the used timestamps and therefore the analyzed carbon
    measurement_name: list of measurement names
    Possible inputs for initial guesses: offset, amplitude, decay_constant,exponent
    '''





    ######################################
    #    carbon_init= up el_state=0      #
    ######################################


    if Addressed_carbon == 5:
        timestamp_pos=['20150315_215418']
        timestamp_neg=['20150315_225753']
        timestamp_pos=['20150317_103608']
        timestamp_neg=['20150317_105622']
    elif Addressed_carbon == 1:  
        timestamp_pos=['20150316_000112']
        timestamp_neg=['20150316_010415']
        timestamp_pos=['20150317_015434']
        timestamp_neg=['20150317_021428']
    elif Addressed_carbon == 2:
        timestamp_pos=['20150316_020808']
        timestamp_neg=['20150316_031102']
        timestamp_pos=['20150317_061458']
        timestamp_neg=['20150317_063658']
    if ssro_calib_timestamp == None: 
        ssro_calib_folder = toolbox.latest_data('SSRO')
    else:
        ssro_dstmp, ssro_tstmp = toolbox.verify_timestamp(ssro_calib_timestamp)
        ssro_calib_folder = toolbox.datadir + '/'+ssro_dstmp+'/'+ssro_tstmp+'_AdwinSSRO_SSROCalibration_111_1_sil18'
        print ssro_calib_folder


    ##accumulate data and average over positive and negative RO##

    cum_pts = 0

    for kk in range(len(timestamp_pos)):
        folder_pos = toolbox.data_from_time(timestamp_pos[kk])
        folder_neg = toolbox.data_from_time(timestamp_neg[kk])
        a = mbi.MBIAnalysis(folder_pos)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        timestamp_SSRO, ssro_calib_folder = toolbox.latest_data('AdwinSSRO', older_than = timestamp_pos[kk], return_timestamp = True)
        a.get_electron_ROC(ssro_calib_folder)
        cum_pts += a.pts

        b = mbi.MBIAnalysis(folder_neg)
        b.get_sweep_pts()
        b.get_readout_results(name='adwindata')
        timestamp_SSRO, ssro_calib_folder = toolbox.latest_data('AdwinSSRO', older_than = timestamp_neg[kk], return_timestamp = True)
        b.get_electron_ROC(ssro_calib_folder)

        if kk == 0:
            cum_sweep_pts = a.sweep_pts
            cum_p0 = (a.p0+(1-b.p0))/2.
            cum_u_p0 = np.sqrt(a.u_p0**2+b.u_p0**2)/2
        else:
            cum_sweep_pts = np.concatenate((cum_sweep_pts, a.sweep_pts))
            cum_p0 = np.concatenate((cum_p0, (a.p0+(1-b.p0))/2))
            cum_u_p0 = np.concatenate((cum_u_p0, np.sqrt(a.u_p0**2+b.u_p0**2)/2))

    a.pts   = cum_pts
    a.sweep_pts = cum_sweep_pts
    a.p0    = cum_p0
    a.u_p0  = cum_u_p0


    ## accumulate data with negative RO


    
    #sort data by free evolution time.
    sorting_order=a.sweep_pts.argsort()
    a.sweep_pts.sort()
    a.p0=a.p0[sorting_order]
    a.u_p0=a.u_p0[sorting_order]


    ## generate plot of the raw data ##


    #uncomment this part to plot without error bars, but including obtained fit parameters.
    # fig = a.default_fig(figsize=(6,5))
    # ax = a.default_ax(fig)
    # ax.plot(a.sweep_pts, a.p0, 'bo',label='T1 of Carbon'+str(Addressed_carbon),lw=1.2)


    ax=a.plot_results_vs_sweepparam(ret='ax',ax=None, 
                                    figsize=figsize, 
                                    ylim=(0.4,1.0)
                                    )


    ## fit to a general exponential##

    fit_results = []

    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]
    y_err = a.u_p0.reshape(-1)[:]
    ax.plot(x,y)
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, x0, decay_constant,exponent)
    #p0, fitfunc, fitfunc_str = common.fit_line(0.5,-0.5/7.)

    #plot the initial guess

    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=[0,2])

    ## plot data and fit as function of total time

    if plot_fit == True:
        plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],1001), ax=ax, plot_data=False)

    fit_results.append(fit_result)

    filename= 'C13_T2_analysis_up_C'+str(Addressed_carbon)
    print 'plots are saved in ' + folder_pos

    #configure the plot
    plt.title('Sample_111_No1_C13_T2_up_C'+str(Addressed_carbon)+'el_state_0')
    plt.xlabel('Free evolution time (s)')
    plt.ylabel('Fidelity')
    plt.axis([a.sweep_pts[0],a.sweep_pts[a.pts-1],0.4,1.])


    # plt.savefig(os.path.join(folder_pos, filename+'.pdf'),
    # format='pdf')
    # plt.savefig(os.path.join(folder_pos, filename+'.png'),
    # format='png')
    
    return x,y, y_err, fit_result
def plot_final_data(filename='final_data'):
    d = np.load('final_data.npz')
    x_list = d['x_list']
    y_list = d['y_list']
    e_list = d['e_list']

    fig = plt.figure(2, figsize=(30, 10))
    ax1 = fig.add_subplot(111)
    N = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 3072, 6144, 10240]

    for jj in range(0, len(x_list)):

        ##############  Fitting the data #########
        x = 1000 * np.array(x_list[jj]) / (2 * N[jj])
        y = np.array(y_list[jj])
        e = np.array(e_list[jj])

        x = x.reshape(-1)[:]
        y = y.reshape(-1)[:]
        e = e.reshape(-1)[:]

        #########################################################
        T2 = 1

        if jj == 3:
            x = np.delete(x, [
                28, 29, 30, 31, 32, 33, 34, 43, 44, 45, 46, 47, 48, 49, 50, 66,
                67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
                83, 84, 85, 86, 87, 88, 89, 96, 97, 98, 99, 100, 101, 102, 103,
                104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115,
                116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
                128, 129, 130
            ])
            y = np.delete(y, [
                28, 29, 30, 31, 32, 33, 34, 43, 44, 45, 46, 47, 48, 49, 50, 66,
                67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
                83, 84, 85, 86, 87, 88, 89, 96, 97, 98, 99, 100, 101, 102, 103,
                104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115,
                116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
                128, 129, 130
            ])
        if jj == 4:
            x = np.delete(x, [
                28, 29, 30, 31, 32, 33, 34, 43, 44, 45, 46, 47, 48, 49, 50, 66,
                67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
                83, 84, 85, 86, 87, 88, 89, 100, 101, 102, 103, 104, 105, 106,
                107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
                119, 120, 121, 122, 123, 124, 125, 126, 127
            ])
            y = np.delete(y, [
                28, 29, 30, 31, 32, 33, 34, 43, 44, 45, 46, 47, 48, 49, 50, 66,
                67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
                83, 84, 85, 86, 87, 88, 89, 100, 101, 102, 103, 104, 105, 106,
                107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
                119, 120, 121, 122, 123, 124, 125, 126, 127
            ])

        elif jj in range(5, len(x_list) - 2):
            x = np.delete(x, [
                25, 28, 29, 30, 31, 32, 33, 34, 43, 44, 45, 46, 47, 48, 49, 50,
                69, 70, 71, 72, 73, 74, 75, 76
            ])
            y = np.delete(y, [
                25, 28, 29, 30, 31, 32, 33, 34, 43, 44, 45, 46, 47, 48, 49, 50,
                69, 70, 71, 72, 73, 74, 75, 76
            ])
            T2 = 10

        elif jj in range(len(x_list) - 3, len(x_list) - 2):
            x = np.delete(x, [
                26, 27, 28, 29, 30, 31, 32, 41, 42, 43, 44, 45, 46, 47, 48, 67,
                68, 69, 70, 71, 72, 73, 74
            ])
            y = np.delete(y, [
                26, 27, 28, 29, 30, 31, 32, 41, 42, 43, 44, 45, 46, 47, 48, 67,
                68, 69, 70, 71, 72, 73, 74
            ])
            T2 = 10

        elif jj in range(len(x_list) - 2, len(x_list) - 1):
            x = np.delete(x, [3, 7, 8, 9, 11, 12, 13, 15, 26, 27, 28, 30, 31])
            y = np.delete(y, [3, 7, 8, 9, 11, 12, 13, 15, 26, 27, 28, 30, 31])
            T2 = 10

        elif jj in range(len(x_list) - 1, len(x_list)):
            x = np.delete(x, [3, 7, 8, 9])  #,10,12,13,14,26,27,28,30,31])
            y = np.delete(y, [3, 7, 8, 9])  #,10,12,13,14,26,27,28,30,31])
            T2 = 10

        ax1.errorbar(x.flatten(),
                     y.flatten(),
                     yerr=e[jj],
                     fmt=fmt_label[jj],
                     label=labels[jj],
                     color=color_list[jj])

        p0, fitfunc, fitfunc_str = common.fit_general_exponential(
            offset, amplitude, position, T2, power)

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

        # plot data and fit as function of total time
        plot_fit = True

        if plot_fit == True:
            plot.plot_fit1d(fit_result,
                            np.linspace(0,
                                        np.amax(x) + 400., 1001),
                            ax=ax1,
                            add_txt=False,
                            plot_data=False,
                            color=color_list[jj])

        fit_results.append(fit_result)
        T_list.append(fit_result['params_dict']['T'])

    ##################################
    ax1.set_xlabel('Total evolution time (ms)')
    ax1.set_xscale('log')
    ax1.set_xlim(1.e-2, 1.e5)
    ax1.grid()
    ax1.legend()

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

    del N[0:2]
    del T_list[0:2]
    del N[-1]
    del T_list[-1]

    N = list(np.array(N) / 1)
    #################### plot and fit scaling with N
    fig = plt.figure(3, figsize=(8, 6))
    ax2 = fig.add_subplot(111)
    ax2.plot(N, T_list, 'bo')

    B_guess = T_list[0] / 4
    n_guess = 0.78

    #A = fit.Parameter(A_guess, 'A')
    B = fit.Parameter(B_guess, 'B')
    n = fit.Parameter(n_guess, 'n')

    def fitfunc(x):
        return B() * x**n()

    print 'running fit'
    fit_result = fit.fit1d(N,
                           T_list,
                           None,
                           p0=[B, n],
                           fitfunc=fitfunc,
                           do_print=False,
                           ret=True,
                           fixed=[])

    #A0 = fit_result['params_dict']['A']
    B0 = fit_result['params_dict']['B']
    n0 = fit_result['params_dict']['n']

    # plotting the fitted function
    plot.plot_fit1d(fit_result,
                    np.linspace(min(N), max(N), 1000),
                    ax=ax2,
                    plot_data=True)
    ax2.set_xscale('log')
    ax2.set_yscale('log')
    ax2.set_xlabel('N')
    ax2.set_ylabel('coherence time (ms)')
    ax=a.plot_results_vs_sweepparam(ret='ax',ax=None, 
                                    figsize=figsize, 
                                    ylim=(0.4,1.0)
                                    )


    ## fit to a general exponential##

    fit_results = []

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

    ax.plot(x,y)
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, x0, decay_constant,exponent)
    #p0, fitfunc, fitfunc_str = common.fit_line(0.5,-0.5/7.)

    #plot the initial guess

    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=[0,2])

    ## plot data and fit as function of total time

    if plot_fit == True:
        plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],1001), ax=ax, plot_data=False)

    fit_results.append(fit_result)
Beispiel #12
0
def analyse_dataset(contains, **kw):
    """
    see the notebook purification/LT3/Espin_DD_w_switch.ipynb for example uses.
    """
    f_list = get_tstamps_dsets(contains, **kw)
    x_list, y_list, y_u_list = [], [], []

    print f_list

    for f_sub_list in f_list:
        x, y, y_u, a = compile_xy_values_of_datasets(f_sub_list, **kw)

        x_list.append(x)
        y_list.append(y)
        y_u_list.append(y_u)

    if kw.pop('plot_raw', True) and kw.get('do_plot', True):
        ax = a.default_ax(figsize=(7, 4))

        for x, y, y_u in zip(x_list, y_list, y_u_list):
            ax.errorbar(x, y, y_u, zorder=0, fmt='o', color='#d3d3d3')

    x_list, y_list, y_u_list = np.array(x_list), np.array(y_list), np.array(
        y_u_list)  ## conver tto array

    best_x, best_y, best_y_u = sort_for_best_signal(x_list, y_list, y_u_list,
                                                    **kw)
    ax.set_xlabel(a.sweep_name)
    ax.set_ylabel(r'$F(|0\rangle)$')
    ax.set_xlim([0, np.amax(best_x) * 1.05])

    # # To avoid dips in the analysis
    # for jj in range (1,2):
    #     index_list=[]
    #     for ii in range(1,len(best_x)-10):
    #         #if y[ii+2] > 0.65:
    #         for kk in range (ii+1, len(best_x)-1):
    #             if y[kk] > 1.05*y[ii] :
    #                 index_list.append(ii)
    #     best_x=np.delete(best_x,[index_list])
    #     best_y=np.delete(best_y,[index_list])
    #     best_y_u =np.delete(best_y_u,[index_list])

    ax.errorbar(best_x, best_y, best_y_u, zorder=5, fmt='bo')

    ########## time to fit the best results
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(
        0.5, 0.5, 0., 100., 2
    )  ## one could start to make cool guesses based on the data but i refrain
    fit_result = fit.fit1d(best_x,
                           best_y,
                           None,
                           p0=p0,
                           fitfunc=fitfunc,
                           do_print=True,
                           ret=True,
                           fixed=[0, 2])
    fit_result['all_x'] = x_list
    fit_result['all_y'] = y_list
    fit_result['all_y_u'] = y_u_list
    if kw.pop('do_plot', True):

        ax.set_xlabel(a.sweep_name)
        ax.set_ylabel(r'$F(|0\rangle)$')
        ax.set_xlim([0, np.amax(best_x) * 1.05])
        ax.errorbar(best_x, best_y, best_y_u, zorder=5, fmt='bo')

        plot.plot_fit1d(fit_result,
                        np.linspace(0,
                                    np.amax(best_x) * 1.05, 201),
                        ax=ax,
                        plot_data=False)
        plt.savefig(os.path.join(a.folder, 'analyzed_result.pdf'),
                    format='pdf')
        plt.savefig(os.path.join(a.folder, 'analyzed_result.png'),
                    format='png')
        plt.show()
        print 'plots are saved in'
        print a.folder

    if kw.pop('return_fit', False):
        fit_result['y_u'] = best_y_u
        return fit_result
Beispiel #13
0
def Carbon_T2_analysis_ms0(measurement_name=['adwindata'],
                           ssro_calib_timestamp=None,
                           offset=0.5,
                           amplitude=0.5,
                           decay_constant=0.2,
                           x0=0,
                           exponent=1,
                           Addressed_carbon=5,
                           plot_fit=True,
                           do_print=True,
                           show_guess=False):
    ''' 
    Function to gather and analyze T1 measurements of a specific carbon.
    Addressed_carbon: selects the used timestamps and therefore the analyzed carbon
    measurement_name: list of measurement names
    Possible inputs for initial guesses: offset, amplitude, decay_constant,exponent
    '''

    ######################################
    #    carbon_init= up el_state=0      #
    ######################################

    if Addressed_carbon == 5:
        timestamp_pos = ['20150315_215418']
        timestamp_neg = ['20150315_225753']
        timestamp_pos = ['20150317_103608']
        timestamp_neg = ['20150317_105622']
    elif Addressed_carbon == 1:
        timestamp_pos = ['20150316_000112']
        timestamp_neg = ['20150316_010415']
        timestamp_pos = ['20150317_015434']
        timestamp_neg = ['20150317_021428']
    elif Addressed_carbon == 2:
        timestamp_pos = ['20150316_020808']
        timestamp_neg = ['20150316_031102']
        timestamp_pos = ['20150317_061458']
        timestamp_neg = ['20150317_063658']
    if ssro_calib_timestamp == None:
        ssro_calib_folder = toolbox.latest_data('SSRO')
    else:
        ssro_dstmp, ssro_tstmp = toolbox.verify_timestamp(ssro_calib_timestamp)
        ssro_calib_folder = toolbox.datadir + '/' + ssro_dstmp + '/' + ssro_tstmp + '_AdwinSSRO_SSROCalibration_111_1_sil18'
        print ssro_calib_folder

    ##accumulate data and average over positive and negative RO##

    cum_pts = 0

    for kk in range(len(timestamp_pos)):
        folder_pos = toolbox.data_from_time(timestamp_pos[kk])
        folder_neg = toolbox.data_from_time(timestamp_neg[kk])
        a = mbi.MBIAnalysis(folder_pos)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        timestamp_SSRO, ssro_calib_folder = toolbox.latest_data(
            'AdwinSSRO', older_than=timestamp_pos[kk], return_timestamp=True)
        a.get_electron_ROC(ssro_calib_folder)
        cum_pts += a.pts

        b = mbi.MBIAnalysis(folder_neg)
        b.get_sweep_pts()
        b.get_readout_results(name='adwindata')
        timestamp_SSRO, ssro_calib_folder = toolbox.latest_data(
            'AdwinSSRO', older_than=timestamp_neg[kk], return_timestamp=True)
        b.get_electron_ROC(ssro_calib_folder)

        if kk == 0:
            cum_sweep_pts = a.sweep_pts
            cum_p0 = (a.p0 + (1 - b.p0)) / 2.
            cum_u_p0 = np.sqrt(a.u_p0**2 + b.u_p0**2) / 2
        else:
            cum_sweep_pts = np.concatenate((cum_sweep_pts, a.sweep_pts))
            cum_p0 = np.concatenate((cum_p0, (a.p0 + (1 - b.p0)) / 2))
            cum_u_p0 = np.concatenate(
                (cum_u_p0, np.sqrt(a.u_p0**2 + b.u_p0**2) / 2))

    a.pts = cum_pts
    a.sweep_pts = cum_sweep_pts
    a.p0 = cum_p0
    a.u_p0 = cum_u_p0

    ## accumulate data with negative RO

    #sort data by free evolution time.
    sorting_order = a.sweep_pts.argsort()
    a.sweep_pts.sort()
    a.p0 = a.p0[sorting_order]
    a.u_p0 = a.u_p0[sorting_order]

    ## generate plot of the raw data ##

    #uncomment this part to plot without error bars, but including obtained fit parameters.
    # fig = a.default_fig(figsize=(6,5))
    # ax = a.default_ax(fig)
    # ax.plot(a.sweep_pts, a.p0, 'bo',label='T1 of Carbon'+str(Addressed_carbon),lw=1.2)

    ax = a.plot_results_vs_sweepparam(ret='ax',
                                      ax=None,
                                      figsize=figsize,
                                      ylim=(0.4, 1.0))

    ## fit to a general exponential##

    fit_results = []

    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]
    y_err = a.u_p0.reshape(-1)[:]
    ax.plot(x, y)
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(
        offset, amplitude, x0, decay_constant, exponent)
    #p0, fitfunc, fitfunc_str = common.fit_line(0.5,-0.5/7.)

    #plot the initial guess

    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=[0, 2])

    ## plot data and fit as function of total time

    if plot_fit == True:
        plot.plot_fit1d(fit_result,
                        np.linspace(x[0], x[-1], 1001),
                        ax=ax,
                        plot_data=False)

    fit_results.append(fit_result)

    filename = 'C13_T2_analysis_up_C' + str(Addressed_carbon)
    print 'plots are saved in ' + folder_pos

    #configure the plot
    plt.title('Sample_111_No1_C13_T2_up_C' + str(Addressed_carbon) +
              'el_state_0')
    plt.xlabel('Free evolution time (s)')
    plt.ylabel('Fidelity')
    plt.axis([a.sweep_pts[0], a.sweep_pts[a.pts - 1], 0.4, 1.])

    # plt.savefig(os.path.join(folder_pos, filename+'.pdf'),
    # format='pdf')
    # plt.savefig(os.path.join(folder_pos, filename+'.png'),
    # format='png')

    return x, y, y_err, fit_result
def DD_scaling_mult_exp(msmtss,
    offset = 0.5, 
    x0 = 0,  
    amplitude = 0.4,  
    decay_constant = 1.5,
    fit_t1 = True,
    exponent = 1.75, fixed = [0,2,4]):
    plt.close('all')

    if fit_t1:
        T_1_list = [28.675811,32.567908]
        T_1_error_list = [3.271851,4.617016]
        n_1_list = [1.251100,0.950066]
        n_1_error_list = [0.254567,0.202308]

    Nlist = [1,4,8,16,32]
    color = ['m','b','g','orange','r']
    # color = plt.get_cmap('rainbow')(np.linspace(0, 1.0, len(Nlist)))
    print color
    # color[2]='g'

    x = np.zeros((8,len(Nlist)))
    y = np.zeros((8,len(Nlist)))
    y_err = np.zeros((8,len(Nlist)))
    fig = plt.figure(figsize=(8,6))
    mpl.rcParams['axes.linewidth'] = 2

    # fig3 = plt.figure(figsize=(10,8))
    
    ax = fig.add_subplot(111)
    # exponents = [1.25, 1.5, 1.75, 1.5]
    # exponents = [1.75]
    # ax3 = fig3.add_subplot(111)
    # p0 = [amplitude, decay_constant, exponent]
    msmst_exponents = [1.8142923125398551,1.7077567729840519]
    # msmsts_exponents = [1.7916010447987771,1.6792745887184537]
    # msmst_exponents = [4.]
    for iiii, msmts in enumerate(msmtss):
        x = np.zeros((8,len(Nlist)))
        y = np.zeros((8,len(Nlist)))
        y_err = np.zeros((8,len(Nlist)))
        # exponents = [1.25, 1.5, 1.75, 1.5]
        exponents = [msmst_exponents[iiii]]
        for exp_nr, exponent in enumerate(exponents):
            print 'NUMBER', exp_nr
            if True:
                fixed = [0, 2]
            else:
                fixed = [0, 2, 4]
            if fit_t1:
                fixed.extend([5,6])
            print fixed
            Amps = []
            Amps_err = []
            Ts = []
            Ts_err = []
            exps = []
            exps_err = []

            for ii,N in enumerate(Nlist):
                # print 'jaaaaaa', msmts
                array = np.loadtxt(DBdir+msmts[str(N)],skiprows=1)
                x[:,ii]=array[:,0]
                y[:,ii]=array[:,1]
                y_err[:,ii] = array[:,2]
                print exponent
                # optimize.leastsq(fit_func,x[:,ii],y[:,ii],p0)
                if fit_t1:
                    p0, fitfunc, fitfunc_str = fit_general_exponential_T1(offset, amplitude, 
                        x0, decay_constant,exponent,T_1_list[iiii],n_1_list[iiii])
                else:
                    p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, 
                     x0, decay_constant,exponent)
                fit_result = fit.fit1d(x[:,ii],y[:,ii], None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True,fixed=fixed)
                
                Ts.append(fit_result['params_dict']['T'])
                Ts_err.append(fit_result['error_dict']['T'])
                Amps.append(fit_result['params_dict']['A'])
                Amps_err.append(fit_result['error_dict']['A'])
                if 4 in fixed:
                    ax.errorbar(x[:,ii],y[:,ii],fmt='o',yerr=y_err[:,ii], label='N=' + str(N)+' T=' + '%.2f' % fit_result['params_dict']['T'] + '+-' + '%.2f' % fit_result['error_dict']['T']
                    +', A=' '%.2f' % fit_result['params_dict']['A'] + '+-' + '%.2f' % fit_result['error_dict']['A'],color=color[ii])
                else:
                    exps.append(fit_result['params_dict']['n'])
                    exps_err.append(fit_result['error_dict']['n'])
                    ax.errorbar(x[:,ii],y[:,ii],fmt='o',yerr=y_err[:,ii],label=str(N),color=color[ii])
                    # ax.errorbar(x[:,ii],y[:,ii],fmt='o',yerr=y_err[:,ii], label='N=' + str(N)+' T=' + '%.2f' % fit_result['params_dict']['T'] + '+-' + '%.2f' % fit_result['error_dict']['T']
                    # +', A=' '%.2f' % fit_result['params_dict']['A'] + '+-' + '%.2f' % fit_result['error_dict']['A'] +', n=' '%.2f' % fit_result['params_dict']['n'] + '+-' + '%.2f' % fit_result['error_dict']['n'],color=color[ii])
                plot.plot_fit1d(fit_result, np.linspace(0,8,1001), ax=ax, plot_data=False,print_info=False,color=color[ii])
                
            if exp_nr == len(exponents)-1 and iiii==0:
                min_x = 0
                max_x = 7.5
                mpl.rcParams['axes.linewidth'] = 2
                # ax.set_xscale('log')
                ax.set_xlim(min_x,max_x)
                ax.set_xlabel('Free evolution time (s)',fontsize = 15)
                ax.hlines([0.5],min_x,max_x,linestyles='dotted', linewidth = 2)
                ax.hlines([1],min_x,max_x,linestyles='dotted', linewidth = 2)
                ax.tick_params(axis='x', which='major', labelsize=15)
                ax.tick_params(axis='y', which='major', labelsize=15)
                ax.set_ylabel('Fidelity',fontsize = 15)
                ax.legend(loc='lower left')
                ax.set_ylim(0.42,1.08)
                # ax.set_xticklabels(['1','1','0.1','1','10'])
                plt.legend(loc = 'center right',fontsize = 15,ncol=1,numpoints = 1, scatterpoints = 1,frameon =False,columnspacing=0.5,handletextpad=0.0)
                plt.savefig(DBdir +'decoherenceplotsFree.pdf', bbox_inches='tight')


                # ax.set_xlim(0,8)
                # ax.set_xlabel('Free evolution time (s)',fontsize = 20)
                # ax.set_ylabel('Fidelity',fontsize = 20)
                # plt.legend()

            if exp_nr == 0 and iiii==0:
                fig3 = plt.figure(figsize=(8,6))
                ax3 = fig3.add_subplot(111)
            y_norm = np.zeros(np.shape(y))
            y_err_norm = np.zeros(np.shape(y))
            min_x = 10**(-1.5)
            max_x = 10**(1.2)
            xforplot = np.linspace(min_x,max_x,1001)
            for ii,N in enumerate(Nlist):
                y_norm[:,ii] = (y[:,ii]-0.5)/Amps[ii]
                y_err_norm[:,ii] = (y_err[:,ii])/Amps[ii]
                if 4 in fixed:
                    if False:
                        ax3.errorbar(x[:,ii],y_norm[:,ii],fmt='o',yerr=y_err_norm[:,ii], label='N=' + str(N)+' T=' + '%.2f' % Ts[ii] + '+-' + '%.2f' % Ts_err[ii]
                            +', A=' '%.2f' % Amps[ii] + '+-' + '%.2f' % Amps_err[ii],color=color[ii])
                    else:
                        ax3.errorbar(x[:,ii],y_norm[:,ii],fmt='o',yerr=y_err_norm[:,ii], label=str(N),color=color[ii])
                    ax3.plot(xforplot, np.exp(-xforplot**exponent/(Ts[ii]**exponent)),color=color[ii])
                else:
                    if False:
                        ax3.errorbar(x[:,ii],y_norm[:,ii],fmt='o',yerr=y_err_norm[:,ii], label='N=' + str(N)+' T=' + '%.2f' % Ts[ii] + '+-' + '%.2f' % Ts_err[ii]
                            +', A=' '%.2f' % Amps[ii] + '+-' + '%.2f' % Amps_err[ii] + ', exp=' '%.2f' % exps[ii] + '+-' + '%.2f' % exps_err[ii],color=color[ii])
                    else:
                        ax3.errorbar(x[:,ii],y_norm[:,ii],fmt='o',yerr=y_err_norm[:,ii], label=str(N),color=color[ii])
                    ax3.plot(xforplot, np.exp(-xforplot**exps[ii]/(Ts[ii]**exps[ii])),color=color[ii])



            logx = np.log10(Nlist)
            print 'y', Ts
            print 'yerror', Ts_err
            logy = np.log10(Ts)
            print 'logx', logx
            print 'logy', logy
            if exp_nr == 0 and iiii==0:
                mpl.rcParams['axes.linewidth'] = 2
                ax3.set_xscale('log')
                ax3.set_xlim(min_x,max_x)
                ax3.set_xlabel('Free evolution time (s)',fontsize = 15)
                ax3.hlines([0],min_x,max_x,linestyles='dotted', linewidth = 2)
                ax3.hlines([1],min_x,max_x,linestyles='dotted', linewidth = 2)
                ax3.tick_params(axis='x', which='major', labelsize=15)
                ax3.tick_params(axis='y', which='major', labelsize=15)
                ax3.set_ylabel('Normalized signal',fontsize = 15)
                ax3.legend(loc='lower left')
                ax3.set_ylim(-0.15,1.15)
                ax3.set_xticklabels(['1','1','0.1','1','10'])
                plt.legend(loc = 'center left',fontsize = 15,ncol=1,numpoints = 1,frameon = False,columnspacing=0.5,handletextpad=0.0)
                plt.savefig(DBdir +'decoherenceplots.pdf', bbox_inches='tight')

            def fit_func(x, a, b):
                return a*x + b
            params, covs = optimize.curve_fit(fit_func, logx, logy)
            print 'Fitting gives'
            print 'gamma =', params[0]
            print 'T_2 =  ', 10**(params[1])
            gamma = params[0]
            T_20 = 10**(params[1])
            gamma_err = np.sqrt(covs[0][0])
            T_20_err = np.sqrt(covs[1][1])*T_20
            print 'gamma_err = ', gamma_err 
            print 'T_20_err = ', T_20_err
            # print logx
            # print logy
            xmin = 10**-0.5

            print covs
            print 
            print params

            print covs[0][0]
            # print 10**(covs[0][1])
            # for a in range(len(Ts)):
            #     yerrp.append( abs(np.log(Ts[a]+Ts_err[a])-np.log(Ts[a])))
            #     yerrm.append( abs(np.log(Ts[a]-Ts_err[a])-np.log(Ts[a])))
            if exp_nr == 0 and iiii==0:
                fig2 = plt.figure(figsize=(4,6))
                # ax2 = fig2.add_subplot(211)
            ax2 = fig2.add_subplot(1, 1, 1)
            # for aa, N in enumerate(Nlist):
            #     ax2.errorbar(Nlist[aa],Ts[aa], yerr=Ts_err[aa], fmt='o',color=color[aa])
            color_2 = ['g','r']
            label = ['$^{13}$C$_1$','$^{13}$C$_2$']
            ax2.errorbar(Nlist,Ts, yerr=Ts_err, fmt='o',color=color_2[iiii],label=label[iiii])
            # if exp_nr == 0 and iiii==0:
            ax2.set_xscale('log')
            ax2.set_yscale('log')

            ax2.set_xlabel('Number of Pulses',fontsize = 15)
            ax2.set_ylabel('Coherence time (s)',fontsize = 15)
            if exp_nr == 0 and iiii==0:
                ax2.set_xlabel('Number of Pulses',fontsize = 15)
                ax2.tick_params(axis='x', which='major', labelsize=15)
                ax2.tick_params(axis='y', which='major', labelsize=15)
            else:
                ax2.tick_params(axis='x', which='major', labelsize=15)
                ax2.tick_params(axis='y', which='major', labelsize=15)
                plt.legend(loc = 'upper left',fontsize = 17,ncol=1,numpoints = 1,frameon = False,columnspacing=0.5,handletextpad=0.0)


            xforplot = np.linspace(xmin,ax2.get_xlim()[1],501)
            if False:
                if 4 in fixed:
                    ax2.plot(xforplot,10**(params[1])*xforplot**(params[0]),color=color_2[iiii],
                        label='exp= %.2f, gamma= %.3f +- %.3f, T_20 = %.2f +- %.2f' % (exponent, gamma, gamma_err, T_20, T_20_err))
                    
                    # ax2.plot(xforplot,10**(params[1])*xforplot**(params[0]), color =color[exp_nr] ,
                    #     label= 'exp=' + '%.2f' % exponent + ', gamma=' + '%.3f' % params[0] + '+-' + '%.4f' % covs[0][0])
                else:
                    ax2.plot(xforplot,10**(params[1])*xforplot**(params[0]),color=color_2[iiii],
                        label='exp= Free, gamma= %.3f +- %.3f, T_20 = %.2f +- %.2f' % (gamma, gamma_err, T_20, T_20_err))
            else:
                ax2.plot(xforplot,10**(params[1])*xforplot**(params[0]),color=color_2[iiii])
                # ax2.plot(xforplot,10**(params[1])*xforplot**(params[0]),color = color[exp_nr]  ,
                #     label= 'exp= free, gamma=' + '%.3f' % params[0] + '+-' + '%.4f' % covs[0][0])
            # 'T_2=' + '%.2f' % (10**(params[0][1])) + '+-' + '%.2f' % (10**(params[1][1])) 
        
            ax2.set_xlim(xmin, None)
            ax2.set_ylim(None,None)
            ax2.set_xticklabels(['1','1', '1', '10', '100'])
            ax2.set_yticklabels(['1','0.1','1','10'])
            plt.savefig(DBdir +'scalingC2C1expfixedAndT1.pdf', bbox_inches='tight')
    info_x = ax2.get_xlim()[0] + (ax2.get_xlim()[-1]-ax2.get_xlim()[0])*0.02
    info_y = ax2.get_ylim()[0] + (ax2.get_ylim()[-1]-ax2.get_ylim()[0])*0.02
    # ax2.text(info_x, info_y, '$T_2$'=, size='x-small',
    #                 color='k', ha='left', va='bottom',
    #                 bbox=dict(facecolor='white', alpha=0.5))
    
    # ax2.legend(loc='upper left', prop={'size':13})
    plt.show()
def DD_scaling(msmts,
    offset = 0.5, 
    x0 = 0,  
    amplitude = 0.2,  
    decay_constant = 1.2, 
    exponent = 1.7916010447987771, fixed = [0,2,4]):

    plt.close('all')
    exponent=1.8
    Nlist = [1,4,8,16,32]
    # Nlist = [128,256,512,1024,2048]
    color = ['r','g','b','m','k']
    x = np.zeros((8,len(Nlist)))
    y = np.zeros((8,len(Nlist)))
    y_err = np.zeros((8,len(Nlist)))
    fig = plt.figure(figsize=(10,8))
    # mpl.rcParams['axes.linewidth'] = 2
    # color = plt.get_cmap('rainbow')(np.linspace(0, 1.0, len(Nlist)))

    # fig3 = plt.figure(figsize=(10,8))
    Amps = []
    Amps_err = []
    Ts = []
    Ts_err = []
    exps = []
    exps_err = []
    ax = fig.add_subplot(111)
    # ax3 = fig3.add_subplot(111)
    # p0 = [amplitude, decay_constant, exponent]
    

    p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, 
             x0, decay_constant,exponent)
    for ii,N in enumerate(Nlist):
        array = np.loadtxt(DBdir+msmts[str(N)],skiprows=1)
        x[:,ii]=array[:,0]
        y[:,ii]=array[:,1]
        y_err[:,ii] = array[:,2]

        # optimize.leastsq(fit_func,x,y,p0)
        p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, 
             x0, decay_constant,exponent)
        fit_result = fit.fit1d(x[:,ii],y[:,ii], None, p0=p0, fitfunc=fitfunc, do_print=True, ret=True,fixed=fixed)
        
        Ts.append(fit_result['params_dict']['T'])
        Ts_err.append(fit_result['error_dict']['T'])
        Amps.append(fit_result['params_dict']['A'])
        Amps_err.append(fit_result['error_dict']['A'])
        if 4 in fixed:
            ax.errorbar(x[:,ii],y[:,ii],fmt='o',yerr=y_err[:,ii], label='N=' + str(N)+' T=' + '%.2f' % fit_result['params_dict']['T'] + '+-' + '%.2f' % fit_result['error_dict']['T']
            +', A=' '%.2f' % fit_result['params_dict']['A'] + '+-' + '%.2f' % fit_result['error_dict']['A'],color=color[ii])
        else:
            exps.append(fit_result['params_dict']['n'])
            exps_err.append(fit_result['error_dict']['n'])
            ax.errorbar(x[:,ii],y[:,ii],fmt='o',yerr=y_err[:,ii], label='N=' + str(N)+' T=' + '%.2f' % fit_result['params_dict']['T'] + '+-' + '%.2f' % fit_result['error_dict']['T']
            +', A=' '%.2f' % fit_result['params_dict']['A'] + '+-' + '%.2f' % fit_result['error_dict']['A'] +', n=' '%.2f' % fit_result['params_dict']['n'] + '+-' + '%.2f' % fit_result['error_dict']['n'],color=color[ii])
        plot.plot_fit1d(fit_result, np.linspace(0,8,1001), ax=ax, plot_data=False,print_info=False,color=color[ii])
        
    
    ax.hlines([0.5],0,8,linestyles='dotted', linewidth = 2)
    ax.set_xlim(0.5,8)
    ax.set_xlabel('Free evolution time (s)',fontsize = 25)
    ax.set_ylabel('Fidelity',fontsize = 20)
    ax.tick_params(axis='x', which='major', labelsize=20)
    ax.tick_params(axis='y', which='major', labelsize=20)
    # mpl.rcParams['axes.linewidth'] = 2
    plt.legend(prop={'size':15})


    fig3 = plt.figure(figsize=(9,6))
    ax3 = fig3.add_subplot(111)
    y_norm = np.zeros(np.shape(y))
    y_err_norm = np.zeros(np.shape(y))
    xforplot = np.linspace(0,40,1001)
    for ii,N in enumerate(Nlist):
        y_norm[:,ii] = (y[:,ii]-0.5)/Amps[ii]
        y_err_norm[:,ii] = (y_err[:,ii])/Amps[ii]
        # y_norm[:,ii] = y[:,ii]
        # y_err_norm[:,ii] = y_err[:,ii]
        if 4 in fixed:
            # ax3.errorbar(x[:,ii],y_norm[:,ii],fmt='o',yerr=y_err_norm[:,ii], label='N=' + str(N)+' T=' + '%.2f' % Ts[ii] + '+-' + '%.2f' % Ts_err[ii]
            #     +', A=' '%.2f' % Amps[ii] + '+-' + '%.2f' % Amps_err[ii],color=color[ii])
            if N>9:
                ax3.errorbar(x[:,ii],y_norm[:,ii],fmt='o',yerr=y_err_norm[:,ii], label='N=' + str(N), color=color[ii])
                ax3.plot(xforplot, np.exp(-xforplot**exponent/(Ts[ii]**exponent)),color=color[ii])
            else:
                ax3.errorbar(x[:,ii],y_norm[:,ii],fmt='o',yerr=y_err_norm[:,ii], label='N=' + str(N), color=color[ii])
                ax3.plot(xforplot, np.exp(-xforplot**exponent/(Ts[ii]**exponent)),color=color[ii]) 
            # ax3.plot(xforplot, 0.5+Amps[ii]*np.exp(-xforplot**exponent/(Ts[ii]**exponent)),color=color[ii])

        else:
            ax3.errorbar(x[:,ii],y_norm[:,ii],fmt='o',yerr=y_err_norm[:,ii], label='N=' + str(N)+' T=' + '%.2f' % Ts[ii] + '+-' + '%.2f' % Ts_err[ii]
                +', A=' '%.2f' % Amps[ii] + '+-' + '%.2f' % Amps_err[ii] + ', exp=' '%.2f' % exps[ii] + '+-' + '%.2f' % exps_err[ii],color=color[ii])
            ax3.plot(xforplot, np.exp(-xforplot**exps[ii]/(Ts[ii]**exps[ii])),color=color[ii])
            # ax3.plot(xforplot, 0.5+Amps[ii]*np.exp(-xforplot**exps[ii]/(Ts[ii]**exps[ii])),color=color[ii])

    logx = np.log10(Nlist)
    print 'y', Ts
    logy = np.log10(Ts)
    print 'logx', logx
    print 'logy', logy

    plt.legend(loc = 'center left', fontsize=18,frameon=False)
    ax3.set_xscale('log')
    ax3.set_xlim(np.min(x),40)
    ax3.hlines([1.],np.min(x),40,linestyles='dotted', linewidth = 2)
    ax3.hlines([0.],np.min(x),40,linestyles='dotted', linewidth = 2)
    ax3.set_yticks([0,0.5,1])
    ax3.set_xticks([0.1,1,10])
    for axis in ['top','bottom','left','right']:
        ax3.spines[axis].set_linewidth(2)
    ax3.set_xlabel('Free evolution time (s)',fontsize = 22)
    ax3.set_ylabel('Normalized Signal',fontsize = 22)
    ax3.tick_params(axis='x', which='major', labelsize=22)
    ax3.tick_params(axis='y', which='major', labelsize=22)
    # ax3.set_yticks([0.5,0.75,1])

    # ax3.legend(loc='lower left')
    def fit_func(x, a, b):
                return a*x + b
    
    params, covs = optimize.curve_fit(fit_func, logx, logy)
    print 'Fitting gives'
    print 'gamma =', params[0]
    print 'T_2 =  ', 10**(params[1])
    gamma = params[0]
    T_20 = 10**(params[1])
    gamma_err = np.sqrt(covs[0][0])
    T_20_err = np.sqrt(covs[1][1])*T_20


    def fit_func(x, a, b):
        return a*x + b
    params, covs = optimize.curve_fit(fit_func, logx, logy)
    print 'Fitting gives'
    print 'gamma =', params[0]
    print 'T_2 =  ', 10**(params[1])
    gamma = params[0]
    T_20 = 10**(params[1])
    gamma_err = np.sqrt(covs[0][0])
    T_20_err = np.sqrt(covs[1][1])*T_20
    # print logx
    # print logy
    
    # print 10**(covs[0][1])
    # for a in range(len(Ts)):
    #     yerrp.append( abs(np.log(Ts[a]+Ts_err[a])-np.log(Ts[a])))
    #     yerrm.append( abs(np.log(Ts[a]-Ts_err[a])-np.log(Ts[a])))
    
    fig2 = plt.figure(figsize=(8,6))
    ax2 = fig2.add_subplot(111)
    ax2.errorbar(Nlist,Ts, yerr=Ts_err, fmt='s',color='r')
    ax2.set_xscale('log')
    ax2.set_yscale('log',nonposy='clip')
    ax2.set_xlabel('Number of Pulses',fontsize = 20)
    ax2.set_ylabel('Coherence time (s)',fontsize = 20)

    xforplot = np.linspace(1,ax2.get_xlim()[1],501)
    #http://wiki.scipy.org/Cookbook/FittingData#head-5eba0779a34c07f5a596bbcf99dbc7886eac18e5
    ax2.plot(xforplot,10**(params[1])*xforplot**(params[0]),color='r',
                    label='exp= Free, gamma= %.3f +- %.3f, T_20 = %.2f +- %.2f' % (gamma, gamma_err, T_20, T_20_err))
    # 'T_2=' + '%.2f' % (10**(params[0][1])) + '+-' + '%.2f' % (10**(params[1][1])) 
    ax2.legend()
    info_x = ax2.get_xlim()[0] + (ax2.get_xlim()[-1]-ax2.get_xlim()[0])*0.02
    info_y = ax2.get_ylim()[0] + (ax2.get_ylim()[-1]-ax2.get_ylim()[0])*0.02
    # ax2.text(info_x, info_y, '$T_2$'=, size='x-small',
    #                 color='k', ha='left', va='bottom',
    #                 bbox=dict(facecolor='white', alpha=0.5))
    
    plt.show()
def DD_scaling_elec(msmts,
    offset = 0.5, 
    x0 = 0,  
    dip_std = 2.,
    amplitude = 0.5,  
    decay_constant = 1.2, 
    correct_dips = True,
    correct_dips2 = False,
    exponent = 4., fixed = [0]):

    plt.close('all')
    

    Nlist = [1,2,4,8,16,32,64,128,256,512,1024,2048]
    Nlist_1 = [1,2,4,8,16,32,64,128,256,512,1024,2048]
    # Nlist = [1]
    #Nlist = [1,32,1024]
    # decay_constants = [1.*x**0.77 for x in Nlist]
    color = plt.get_cmap('rainbow')(np.linspace(0, 1.0, len(Nlist_1)))
    # print color
    # color = ['b','g','r']

    # Nlist = [128,256,512,1024,2048,2049]
    # Nlist = [2048,2049]
    # Nlist = [2048]
    # color = ['r','g','b','m','k','r']
    
    
    fig = plt.figure(figsize=(7,6))
    # mpl.rcParams['axes.linewidth'] = 2
    min_x = 0.01
    max_x = 1000
    # fig3 = plt.figure(figsize=(10,8))
    Amps_Tot = []
    Amps_err_Tot = []
    Ts_Tot = []
    Ts_err_Tot = []
    exps_Tot = []
    exps_err_Tot = []


    ax = fig.add_subplot('111')
    # ax3 = fig3.add_subplot(111)
    # p0 = [amplitude, decay_constant, exponent]
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, 
             x0, decay_constant,exponent)
    x = []
    y = []
    y_err = []
    exponents = [3.]

    for ii,N in enumerate(Nlist):
        decay_constant = 1.*N**(0.77)
        p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, 
             x0, decay_constant,exponent)
        Amps = []
        Amps_err = []
        Ts = []
        Ts_err = []
        exps = []
        exps_err = []
        
        array = np.loadtxt(DBdir+msmts[str(N)],skiprows=1)
        
        
        sorting_order = array[:,0].argsort()
        array[:,0].sort()
        array[:,1]=array[:,1][sorting_order]
        array[:,2]=array[:,2][sorting_order]

        print array[:,1]
        print array[:,0]
        if correct_dips:
            x_old = array[:,0]
            y_old = array[:,1]
            y_err_old = array[:,2]
            x_new=[]
            y_new=[]
            y_err_new=[]
            for jj in range(len(x_old)-1):
                if all([ (y_old[jj] + dip_std*y_err_old[jj]) > value for value in y_old[jj+1::]]):
                    x_new.append(x_old[jj])
                    y_new.append(y_old[jj])
                    y_err_new.append(y_err_old[jj])
                else:
                    # print y_old[jj], y_old[jj+1]
                    pass
            # print len(x_new), len(y_new), len(y_err_new)
            # print x_new
            # print y_new
            # print y_err_new
            x.append(np.array(x_new))
            y.append(np.array(y_new))
            y_err.append(np.array(y_err_new))
        elif not correct_dips2:
            x.append(array[:,0])
            y.append(array[:,1])
            y_err.append(array[:,2])
        else:
            pass
        # if 'correct'

        for exp_nr, exponent in enumerate(exponents):
            # print 'NUMBER', exp_nr
            if exp_nr == len(exponents)-1 and True:
                fixed = [0,2]
            else:
                fixed = [0,1,2]
            
        
        # print x
        # print y
        # print y_err
        # optimize.leastsq(fit_func,x,y,p0)
            if correct_dips:
                fit_result = fit.fit1d(x[-1],y[-1], None, p0=p0, fitfunc=fitfunc, do_print=True, ret=True,fixed=fixed)
            else:
                fit_result = fit.fit1d(array[:,0],array[:,1], None, p0=p0, fitfunc=fitfunc, do_print=True, ret=True,fixed=fixed)
            


            if correct_dips2:
                xold = array[:,0]
                yold = array[:,1]
                yerr_old = array[:,2]
                print np.shape(xold), np.shape(yold), np.shape(yerr_old)
                counter=0
                iterator=True
                while iterator and (counter < 30):
                    print 'counter', counter
                    iterator=True
                    x_new=[]
                    y_new=[]
                    y_err_new=[]
                    for jj, xvalue in enumerate(xold):
                        # print '-------'
                        # print fit_result['fitfunc'](x)
                        # print (yold[jj] + dip_std*yerr_old[jj])
                        if (yold[jj] + dip_std*yerr_old[jj])> fit_result['fitfunc'](xvalue):   
                            x_new.append(xold[jj])
                            y_new.append(yold[jj])
                            y_err_new.append(yerr_old[jj])

                    if np.array_equal(xold,np.array(x_new)):
                        iterator = False

                    xold = np.array(x_new)
                    yold = np.array(y_new)
                    yerr_old = np.array(y_err_new)
                    counter +=1
                    print np.shape(xold), np.shape(yold), np.shape(yerr_old)
                    p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, 
                        x0, decay_constant,exponent)
                    fit_result = fit.fit1d(xold,yold, None, p0=p0, fitfunc=fitfunc, do_print=True, ret=True,fixed=fixed)
                print '---------------'
                print counter
                print '---------------'
                x.append(xold)
                y.append(yold)
                y_err.append(yerr_old)
            

            


            Ts.append(fit_result['params_dict']['T'])
            Ts_err.append(fit_result['error_dict']['T'])
            
            # Amps.append(fit_result['params_dict']['A'])
            # Amps_err.append(fit_result['error_dict']['A'])
            

            if 4 in fixed:
                # ax.errorbar(x,y,fmt='o',yerr=y_err, label='N=' + str(N)+' T=' + '%.2f' % fit_result['params_dict']['T'] + '+-' + '%.2f' % fit_result['error_dict']['T']
                # +', A=' '%.2f' % fit_result['params_dict']['A'] + '+-' + '%.2f' % fit_result['error_dict']['A'],color=color[ii])
                if N > 1000:
                    ax.errorbar(x[-1],y[-1],fmt='o',yerr=y_err[-1], label='N=' + str(N)+ ', T=' + un2str(fit_result['params_dict']['T'], fit_result['error_dict']['T']) ,color=color[ii])
                    # ax.errorbar(x[-1],y[-1],fmt='o',yerr=y_err[-1], label='N=' + str(N)+ ', T=' + un2str(fit_result['params_dict']['T'], fit_result['error_dict']['T']) + ', A=' + un2str(fit_result['params_dict']['A'], fit_result['error_dict']['A']),color=color[ii])
                else:
                    # ax.errorbar(x[-1],y[-1],fmt='o',yerr=y_err[-1], label='N=' + str(N)+ ',   T=' + un2str(fit_result['params_dict']['T'], fit_result['error_dict']['T']) + ', A=' + un2str(fit_result['params_dict']['A'], fit_result['error_dict']['A']),color=color[ii])
                    ax.errorbar(x[-1],y[-1],fmt='o',yerr=y_err[-1], label='N=' + str(N)+ ',   T=' + un2str(fit_result['params_dict']['T'], fit_result['error_dict']['T']),color=color[ii])
                print 'HELLO MOTO'
            else:
                exps.append(fit_result['params_dict']['n'])
                exps_err.append(fit_result['error_dict']['n'])
                label = 'N=' + str(N)+', T=' + un2str(fit_result['params_dict']['T'], fit_result['error_dict']['T']) \
                + ', A=' + un2str(fit_result['params_dict']['A'], fit_result['error_dict']['A']) +', n=' + un2str(fit_result['params_dict']['n'], fit_result['error_dict']['n'])
                label = str(N)
                ax.errorbar(x[-1],y[-1],fmt='o',yerr=y_err[-1], label=label,color=color[ii])
                # if ii == 1:
                #     ax.errorbar(x[-1],y[-1],fmt='o',yerr=y_err[-1], label='New msmt N=2048 T=' + un2str(fit_result['params_dict']['T'], fit_result['error_dict']['T'])
                #     +', n=' + un2str(fit_result['params_dict']['n'], fit_result['error_dict']['n']),color=color[ii])
                # else:
                #     ax.errorbar(x[-1],y[-1],fmt='o',yerr=y_err[-1], label='Old msmt N=2048 T=' + un2str(fit_result['params_dict']['T'], fit_result['error_dict']['T'])
                #     +', n=' + un2str(fit_result['params_dict']['n'], fit_result['error_dict']['n']),color=color[ii])
                
                # ax.errorbar(x[-1],y[-1],fmt='o',yerr=y_err[-1], label='N=' + str(N)+', T=' + un2str(fit_result['params_dict']['T'], fit_result['error_dict']['T'])
                #  +', n=' + un2str(fit_result['params_dict']['n'], fit_result['error_dict']['n']),color=color[ii])
            plot.plot_fit1d(fit_result, np.linspace(0.,max_x,10001), ax=ax, plot_data=False,print_info=False,color=color[ii])
            # plot.plot_fit1d(fit_result, np.linspace(0.,max_x,10001), ax=ax, plot_data=False,print_info=False,color='0.25')
        
        Amps_Tot.append(Amps)
        Amps_err_Tot.append(Amps_err)
        Ts_Tot.append(Ts)
        Ts_err_Tot.append(Ts_err)
        exps_Tot.append(exps)
        exps_err_Tot.append(exps_err)

    # print Amps_Tot
    Amps_Tot = list(map(list, zip(*Amps_Tot)))
    Amps_err_Tot = list(map(list, zip(*Amps_err_Tot)))
    Ts_Tot = list(map(list, zip(*Ts_Tot)))
    print Ts_Tot
    Ts_Tot = [[1./(1./x-1./10e3) for x in y] for y in Ts_Tot]

    Ts_err_Tot = list(map(list, zip(*Ts_err_Tot)))
    exps_Tot = list(map(list, zip(*exps_Tot)))
    exps_err_Tot = list(map(list, zip(*exps_err_Tot)))
    ax.set_xscale('log')
    #max_x=3
    ax.hlines([0.5],min_x,max_x,linestyles='dotted', linewidth = 2)

    ax.hlines([1.],min_x,max_x,linestyles='dotted', linewidth = 2)
    ax.set_xlim(min_x,max_x)
    ax.set_ylim(0.4,1.02)
    ax.set_xlabel('Free evolution time (ms)',fontsize = 20)
    ax.set_ylabel('Fidelity',fontsize = 20)
    ax.tick_params(axis='x', which='major', labelsize=20)
    ax.tick_params(axis='y', which='major', labelsize=20)
    # ax.set_xticks([0,1,2,3])
    ax.set_yticks([0.5,0.75,1])
    for axis in ['top','bottom','left','right']:
        ax.spines[axis].set_linewidth(2)
    # plt.legend(loc = 'center left',fontsize = 16, bbox_to_anchor=(1, 0.5))
    # plt.legend(loc = 'center left',fontsize = 15,ncol=2,numpoints = 1,frameon = False,columnspacing=0.5,handletextpad=0.0)
    plt.legend(loc = 'center left',fontsize = 15,ncol=2,numpoints = 1,frameon = False,columnspacing=0.5,handletextpad=0.0)
    
    plt.savefig(DBdir +'decoherence36dips.pdf', bbox_inches='tight')
    # plt.show()
    logx = np.log10(Nlist)
    def fit_func(x, a, b):
            return a*x + b

    # def fit_func(x, b):
    #         return (2./3.)*x + b

    for exp_nr, exponent in enumerate(exponents):
        if exp_nr == 0:
            fig3 = plt.figure(figsize=(4,6))
            ax3 = fig3.add_subplot(111)

            
    
        print Ts_Tot[exp_nr]
        # sdfklaj
        logy = np.log10(Ts_Tot[exp_nr])

        print 'logx', logx
        print 'logy', logy

        params, covs = optimize.curve_fit(fit_func, logx, logy)

        # print 'Fitting gives'
        # print 'gamma =', params[0]
        # print 'T_2 =  ', 10**(params[1])
        print params
        gamma = params[0]
        T_20 = 10**(params[1])
        print 'T20',T_20
        gamma_err = np.sqrt(covs[0][0])
        T_20_err = np.sqrt(covs[1][1])*T_20


        # print logx
        # print logy
        print covs
        print 
        print params

        print covs[0][0]
        # print 10**(covs[0][1])
        # for a in range(len(Ts)):
        #     yerrp.append( abs(np.log(Ts[a]+Ts_err[a])-np.log(Ts[a])))
        #     yerrm.append( abs(np.log(Ts[a]-Ts_err[a])-np.log(Ts[a])))
        if exp_nr == 0:
            fig2 = plt.figure(figsize=(4,6))
            ax2 = fig2.add_subplot(111)
        for aa, N in enumerate(Nlist):
            ax2.errorbar(Nlist[aa],Ts_Tot[exp_nr][aa], yerr=Ts_err_Tot[exp_nr][aa], fmt='o',color=color[aa])
        if exp_nr == 0:
            ax2.set_xscale('log')
            ax2.set_yscale('log')
            ax2.set_xlabel('Number of Pulses',fontsize = 15)
            ax2.set_ylabel('Coherence time (ms)',fontsize = 15)
            ax2.tick_params(axis='x', which='major', labelsize=15)
            ax2.tick_params(axis='y', which='major', labelsize=15)
        xforplot = np.linspace(0.5,ax2.get_xlim()[1],1001)

        xforplot = np.linspace(0.5,ax2.get_xlim()[1],1001)
    #http://wiki.scipy.org/Cookbook/FittingData#head-5eba0779a34c07f5a596bbcf99dbc7886eac18e5
        print 'T20',T_20
        print 'T20_error', T_20_err

        print 'gamma', gamma
        print 'gamma_err', gamma_err
        ax2.plot(xforplot,10**(params[1])*xforplot**(params[0]),color='0.25',
        label='gamma= %.2f +- %.4f, T_20 = %.2f +- %.4f' % (gamma, gamma_err, T_20, T_20_err))
        # if exp_nr == len(exponents)-1 and True:
        #     ax2.plot(xforplot,10**(params[1])*xforplot**(params[0]),color=color[exp_nr],
        #         label='exp= Free, gamma= %.3f +- %.3f, T_20 = %.2f +- %.2f' % (gamma, gamma_err, T_20, T_20_err))
            
        #     # ax2.plot(xforplot,10**(params[1])*xforplot**(params[0]), color =color[exp_nr] ,
        #     #     label= 'exp=' + '%.2f' % exponent + ', gamma=' + '%.3f' % params[0] + '+-' + '%.4f' % covs[0][0])
        # else:
        #     # ax2.plot(xforplot,10**(params[1])*xforplot**(params[0]),color=color[exp_nr],
        #     #     label='exp= %.2f, gamma= %.3f +- %.3f, T_20 = %.2f +- %.2f' % (exponent,gamma, gamma_err, T_20, T_20_err))
        #     ax2.plot(xforplot,10**(params[0])*xforplot**(2./3.),color=color[exp_nr],
        #         label='exp= %.2f, gamma=2/3, T_20 = %.2f +- %.2f' % (exponent, T_20, T_20_err))
        # 'T_2=' + '%.2f' % (10**(params[0][1])) + '+-' + '%.2f' % (10**(params[1][1])) 
    # plt.legend(loc='lower left', prop={'size':13})
    ax2.set_xlim(0.5*10.**(0),10.**4)
    ax2.set_ylim(10**(-0.5),10.**3.)
    for axis in ['top','bottom','left','right']:
        ax2.spines[axis].set_linewidth(2)
    plt.savefig(DBdir +'scaling.pdf', bbox_inches='tight')
    plt.show()
    else:
        cum_sweep_pts = np.concatenate((cum_sweep_pts, a.sweep_pts))
        cum_p0 = np.concatenate((cum_p0, a.p0))
        cum_u_p0 = np.concatenate((cum_u_p0, a.u_p0))

a.pts   = cum_pts
a.sweep_pts = cum_sweep_pts
a.p0    = cum_p0
a.u_p0  = cum_u_p0

ax = a.plot_results_vs_sweepparam(ret='ax')

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

p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, position, T2, power)

#plot the initial guess
if show_guess:
    ax.plot(np.linspace(0,x[-1],201), fitfunc(np.linspace(0,x[-1],201)), '-', lw=2)

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

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

print folder
plt.savefig(os.path.join(folder, 'combined_result.pdf'),
def FitSpinPumpTimes(fit_res_list, spin_pump_list, folder):
    """
    this function takes the fitted amplitudes for the population in ms=-1 and ms=0 and returns them as a plot.
    """

    spin_pump_list
    x = np.ones(len(spin_pump_list))
    #intialize array for ms=0
    y0 = np.ones(len(spin_pump_list))
    y0_u = np.ones(len(spin_pump_list))
    #intialize array for ms=-1
    y1 = np.ones(len(spin_pump_list))
    y1_u = np.ones(len(spin_pump_list))

    #extract relevant values from the fit results.
    for i, sp in enumerate(spin_pump_list):
        x[i] = sp
        fit_res = fit_res_list[i]
        y0[i] = np.absolute(fit_res['params_dict']['A'])
        y0_u[i] = np.absolute(fit_res['error'][1])
        y1[i] = np.absolute(fit_res['params_dict']['B'])
        y1_u[i] = np.absolute(fit_res['error'][4])

    print x, y0
    fig = plt.figure()
    ax = plt.subplot(111)
    #work around, because the function 'errorbar is a bit bugged...see various threads on stackexchange'
    plt.rc('lines', **{'linestyle': 'None'})
    plt.errorbar(x, y0, y0_u, color='blue', marker='o', fmt='')
    plt.errorbar(x, y1, y1_u, color='red', marker='o', fmt='')
    plt.axis([0, spin_pump_list[-1], 0, 1])

    p0, fitfunc, fitfunc_str = fit_decaying_cos(1 / 20., 0.1, 0.1, -90.,
                                                1. / 0.037, 1. / 0.037)

    #fit an exponential starting at 0 repumping time and an exponent of 1.
    fit_result = fit.fit1d(x,
                           y0,
                           None,
                           p0=p0,
                           fitfunc=fitfunc,
                           do_print=True,
                           ret=True,
                           print_info=False,
                           fixed=[])
    plot.plot_fit1d(fit_result,
                    np.linspace(0, x[-1], 1001),
                    ax=ax,
                    print_info=False,
                    plot_data=False,
                    linestyle='-b')

    p0, fitfunc, fitfunc_str = common.fit_general_exponential(
        0., 0.5, 0., 20., 1.)
    print fitfunc_str

    fit_result = fit.fit1d(x,
                           y1,
                           None,
                           p0=p0,
                           fitfunc=fitfunc,
                           do_print=True,
                           print_info=False,
                           ret=True,
                           fixed=[0, 2, 4])
    plot.plot_fit1d(fit_result,
                    np.linspace(0, x[-1], 1001),
                    ax=ax,
                    print_info=False,
                    plot_data=False,
                    linestyle='-r')

    #fit with a double exponential:
    p0, fitfunc, fitfunc_str = common.fit_double_exp_decay_with_offset(
        -0.2, 0.5, 5., 0.5, 20.)
    print fitfunc_str
    fit_result = fit.fit1d(x,
                           y1,
                           None,
                           p0=p0,
                           fitfunc=fitfunc,
                           do_print=True,
                           print_info=False,
                           ret=True,
                           fixed=[0])
    plot.plot_fit1d(fit_result,
                    np.linspace(0, x[-1], 1001),
                    ax=ax,
                    print_info=False,
                    plot_data=False,
                    linestyle='-g')

    plt.title(
        'Sample_111_No1_C13_C1_Ramsey_contrast_over_spinpumping_duration')
    plt.xlabel('Spin pumping duration (us)')
    plt.ylabel('Amplitude')
    plt.legend(['f_0', 'f_1'])

    plt.savefig(os.path.join(folder, 'SpinPumpData.pdf'), format='pdf')
    plt.savefig(os.path.join(folder, 'SpinPumpData.png'), format='png')
def Carbon_T2_analysis_ms1(measurement_name=['adwindata'],
                           ssro_calib_timestamp=None,
                           offset=0.5,
                           amplitude=0.5,
                           decay_constant=0.2,
                           x0=0,
                           exponent=1,
                           Addressed_carbon=5,
                           plot_fit=True,
                           do_print=True,
                           show_guess=False):

    if Addressed_carbon == 1:
        timestamp_pos = [
            '20141104_195135', '20141104_203107', '20141104_223132'
        ]
        timestamp_neg = [
            '20141104_195949', '20141104_212524', '20141104_234927'
        ]
    elif Addressed_carbon == 5:
        timestamp_pos = ['20150309_193904']
        timestamp_neg = ['20150309_195337']
        # timestamp_pos=['20150102_193904']
        # timestamp_neg=['20150102_214323']
        #timestamp_pos=['20141105_003250','20141105_011316','20141105_031420']
        #timestamp_neg=['20141105_004136','20141105_020802','20141105_043221']
    elif Addressed_carbon == 2:
        timestamp_pos = [
            '20141106_010748', '20141106_014724', '20141106_040245'
        ]
        timestamp_neg = [
            '20141106_011609', '20141106_024138', '20141106_055052'
        ]

    if ssro_calib_timestamp == None:
        ssro_calib_folder = toolbox.latest_data('SSRO')
    else:
        ssro_dstmp, ssro_tstmp = toolbox.verify_timestamp(ssro_calib_timestamp)
        ssro_calib_folder = toolbox.datadir + '/' + ssro_dstmp + '/' + ssro_tstmp + '_AdwinSSRO_SSROCalibration_111_1_sil18'
        print ssro_calib_folder

    ##accumulate data and average over positive and negative RO##

    cum_pts = 0

    for kk in range(len(timestamp_pos)):
        folder_pos = toolbox.data_from_time(timestamp_pos[kk])
        folder_neg = toolbox.data_from_time(timestamp_neg[kk])
        a = mbi.MBIAnalysis(folder_pos)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        a.get_electron_ROC(ssro_calib_folder)
        cum_pts += a.pts

        b = mbi.MBIAnalysis(folder_neg)
        b.get_sweep_pts()
        b.get_readout_results(name='adwindata')
        b.get_electron_ROC(ssro_calib_folder)

        if kk == 0:
            cum_sweep_pts = a.sweep_pts
            cum_p0 = (a.p0 + (1 - b.p0)) / 2.
            cum_u_p0 = np.sqrt(a.u_p0**2 + b.u_p0**2) / 2
        else:
            cum_sweep_pts = np.concatenate((cum_sweep_pts, a.sweep_pts))
            cum_p0 = np.concatenate((cum_p0, (a.p0 + (1 - b.p0)) / 2))
            cum_u_p0 = np.concatenate(
                (cum_u_p0, np.sqrt(a.u_p0**2 + b.u_p0**2) / 2))
            print

    a.pts = cum_pts
    a.sweep_pts = cum_sweep_pts
    a.p0 = cum_p0
    a.u_p0 = cum_u_p0

    ## accumulate data with negative RO

    #sort data by free evolution time.
    sorting_order = a.sweep_pts.argsort()
    a.sweep_pts.sort()
    a.p0 = a.p0[sorting_order]
    a.u_p0 = a.u_p0[sorting_order]

    ## generate plot of the raw data ##

    #uncomment this part to plot without error bars, but including obtained fit parameters.
    # fig = a.default_fig(figsize=(6,5))
    # ax = a.default_ax(fig)
    # ax.plot(a.sweep_pts, a.p0, 'bo',label='T1 of Carbon'+str(Addressed_carbon),lw=1.2)

    ax = a.plot_results_vs_sweepparam(ret='ax',
                                      figsize=figsize,
                                      ax=None,
                                      ylim=ylim)
    ## fit to a general exponential##

    fit_results = []

    x = a.sweep_pts.reshape(-1)[:] * 2
    y = a.p0.reshape(-1)[:]
    y_err = a.u_p0.reshape(-1)[:]
    ax.plot(x, y)
    p0, fitfunc, fitfunc_str = common.fit_general_exponential(
        offset, amplitude, x0, decay_constant, exponent)
    #p0, fitfunc, fitfunc_str = common.fit_line(0.5,-0.5/7.)

    #plot the initial guess

    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=[0, 2])

    ## plot data and fit as function of total time

    if plot_fit == True:
        plot.plot_fit1d(fit_result,
                        np.linspace(x[0], x[-1], 1001),
                        ax=ax,
                        plot_data=False)

    fit_results.append(fit_result)

    filename = 'C13_T2_analysis_up_C' + str(Addressed_carbon)
    print 'plots are saved in ' + folder_pos

    #configure the plot
    plt.title('Sample_111_No1_C13_T2_up_C' + str(Addressed_carbon) +
              'el_state_1')
    plt.xlabel('Free evolution time (s)')
    plt.ylabel('Fidelity')
    plt.axis([a.sweep_pts[0], a.sweep_pts[a.pts - 1], 0.4, 1])

    # plt.savefig(os.path.join(r'D:\measuring\data\Analyzed figures\Carbon Hahn', filename+'.pdf'),
    # format='pdf')
    # plt.savefig(os.path.join(r'D:\measuring\data\Analyzed figures\Carbon Hahn', filename+'.png'),
    # format='png')

    return x, y, y_err, fit_result
def electron_DD_analysis(timestamp=None, measurement_name = ['adwindata'], offset = 0.5, 
                        amplitude = 0.5, position =0, T2 = 800, 
                        power=2, plot_fit = True, do_print = False, 
                        show_guess = False):
    ''' Function to analyze simple decoupling measurements. Loads the results and fits them to a simple exponential.
    Inputs:
    timestamp: list of timestamps in format in format yyyymmdd_hhmmss or hhmmss or None. (Added: List functionality. NK 20150320)
    measurement_name: list of measurement names
    Based on electron_T1_anal,
    '''

    if timestamp != None:
        if type(timestamp)==str:
            folder_list=[toolbox.data_from_time(timestamp)]
        else:
            folder_list = []
            for t in timestamp:
                folder_list.append(toolbox.data_from_time(t))
    else:
        folder_list = [toolbox.latest_data('Decoupling')]

    fit_results = []
    for ii,f in enumerate(folder_list):
        for k in range(0,len(measurement_name)):
            a = mbi.MBIAnalysis(f)
            a.get_sweep_pts()
            a.get_readout_results(name=measurement_name[k])
            a.get_electron_ROC()
            if ii==0:
                ax = a.plot_results_vs_sweepparam(ret='ax')
            else:
                ax.errorbar(a.sweep_pts.reshape(-1)[:],a.p0.reshape(-1)[:],yerr=a.u_p0.reshape(-1)[:],fmt='o')
            x = a.sweep_pts.reshape(-1)[:]
            y = a.p0.reshape(-1)[:]

            p0, fitfunc, fitfunc_str = common.fit_general_exponential(offset, amplitude, position, T2, power)

            #plot the initial guess
            if show_guess:
                ax.plot(np.linspace(0,x[-1],201), fitfunc(np.linspace(0,x[-1],201)), ':', lw=2)

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

            ## 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_list[0], 'analyzed_result.pdf'),
    format='pdf')
    plt.savefig(os.path.join(folder_list[0], 'analyzed_result.png'),
    format='png')

            ## plot data and fit as function of tau
            #plt.figure()
            #plt.plot(np.linspace(0,x[-1],201), fit_result['fitfunc'](np.linspace(0,x[-1],201)), ':', lw=2)
            #plt.plot(x, y, '.', lw=2)




    return fit_results
Beispiel #21
0
    else:
        cum_sweep_pts = np.concatenate((cum_sweep_pts, a.sweep_pts))
        cum_p0 = np.concatenate((cum_p0, a.p0))
        cum_u_p0 = np.concatenate((cum_u_p0, a.u_p0))

a.pts = cum_pts
a.sweep_pts = cum_sweep_pts
a.p0 = cum_p0
a.u_p0 = cum_u_p0

ax = a.plot_results_vs_sweepparam(ret='ax')

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

p0, fitfunc, fitfunc_str = common.fit_general_exponential(
    offset, amplitude, position, T2, power)

#plot the initial guess
if show_guess:
    ax.plot(np.linspace(0, x[-1], 201),
            fitfunc(np.linspace(0, x[-1], 201)),
            '-',
            lw=2)

fit_result = fit.fit1d(x,
                       y,
                       None,
                       p0=p0,
                       fitfunc=fitfunc,
                       do_print=True,
                       ret=True,
Beispiel #22
0
def Carbon_T1(timestamp=None,
              measurement_name='adwindata',
              ssro_calib_timestamp=None,
              offset=0.5,
              x0=0,
              amplitude=0.5,
              decay_constant=200,
              exponent=2,
              plot_fit=False,
              do_print=False,
              fixed=[2],
              show_guess=True):
    ''' 
    Inputs:
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    List of parameters (order important for 'fixed') 
    offset, amplitude, decay_constant,exponent,frequency ,phase 
    '''
    figsize = (6, 4.7)

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

    if ssro_calib_timestamp == None:
        ssro_calib_folder = toolbox.latest_data('SSRO')
    else:
        ssro_dstmp, ssro_tstmp = toolbox.verify_timestamp(ssro_calib_timestamp)
        ssro_calib_folder = toolbox.datadir + '/' + ssro_dstmp + '/' + ssro_tstmp + '_AdwinSSRO_SSROCalibration_Hans_sil1'
        print ssro_calib_folder

    fit_results = []

    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC(ssro_calib_folder)
    # print a.result_corrected
    # print a.p0[:,0]
    # print a.sweep_pts
    # print a.labels
    # print a.u_p0[:,0]
    # print a.readouts
    ax = a.plot_results_vs_sweepparam(ret='ax',
                                      ax=None,
                                      figsize=figsize,
                                      ylim=(0.0, 1.0))

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

    p0, fitfunc, fitfunc_str = common.fit_general_exponential(
        offset, amplitude, x0, decay_constant, exponent)

    #plot the initial guess
    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=fixed)

    ## plot data and fit as function of total time
    if plot_fit == True:
        plot.plot_fit1d(fit_result,
                        np.linspace(x[0], x[-1], 1001),
                        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