Пример #1
0
def sweep_N_analysis(tau,N_steps,plot_fit = False, do_print = True, show_guess = False):


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

    total_pts = 320/N_steps+1
    pts_per_run=11

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

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

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


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

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

    fit_results.append(fit_result)

    plt.savefig(os.path.join(folder, 'analyzed_result.pdf'),
    format='pdf')
    plt.savefig(os.path.join(folder, 'analyzed_result.png'),
    format='png')
Пример #2
0
def Osci_period(carbon='1', older_than=None, ssro_calib_timestamp=None, **kw):

    fit_results = kw.pop('fit_results', True)
    folder_name = kw.pop('folder_name', 'Memory_NoOf_Repetitions_')

    ### fit parameters
    freq = kw.pop('freq', 1 / 170.)
    offset = kw.pop('offfset', 0.)
    decay = kw.pop('decay', 200)
    fixed = kw.pop('fixed', [1])
    print folder_name

    folder_dict = {
        'X': [],
        'Y': [],
        'resX': [],
        'resX_u': [],
        'resY': [],
        'resY_u': [],
        'sweep_pts': [],
        'res': [],
        'res_u': []
    }

    ### search data

    for ro in ['positive', 'negative']:
        for t in ['X', 'Y']:
            search_string = folder_name + ro + '_Tomo_' + t + '_' + 'C' + carbon
            folder_dict[t].append(
                toolbox.latest_data(contains=search_string,
                                    older_than=older_than,
                                    raise_exc=False))

    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_sil8'
        # print ssro_calib_folder

        ### extract data
    x_labels, npX, npY, npX_u, npY_u = get_dephasing_data(
        folder_dict, ssro_calib_folder)

    fig = plt.figure()
    ax = plt.subplot()
    for y, y_u, jj in zip([npX, npY], [npX_u, npY_u], range(2)):
        if fit_results:
            A0 = max(y)
            phi0 = 0
            p0, fitfunc, fitfunc_str = common.fit_decaying_cos(
                freq, offset, A0, phi0, decay)

            # fixed = [1]

            fit_result = fit.fit1d(x_labels,
                                   y,
                                   None,
                                   p0=p0,
                                   fitfunc=fitfunc,
                                   do_print=True,
                                   ret=True,
                                   fixed=fixed)
            plot.plot_fit1d(fit_result,
                            np.linspace(x_labels[0], x_labels[-1], 1001),
                            ax=ax,
                            color=color_list[jj],
                            plot_data=False,
                            add_txt=False,
                            lw=2)

        plt.errorbar(x_labels,
                     y,
                     y_u,
                     marker='o',
                     color=color_list[jj],
                     label='C' + carbon + ['X', 'Y'][jj])

    ## define folder for data saving
    folder = folder_dict[t][0]

    plt.xlabel('Repump repetitions')
    plt.ylabel('Contrast')
    plt.title(get_tstamp_from_folder(folder) + ' Dephasing for C' + carbon)
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    plt.savefig(os.path.join(folder, 'CarbonDephasing_osci.pdf'), format='pdf')
    plt.savefig(os.path.join(folder, 'CarbonDephasing_osci.png'), format='png')
    plt.show()
    plt.close('all')
    print 'Results are saved in ', folder[18:18 + 15]
def Carbon_Ramsey(timestamp=None, measurement_name = ['adwindata'], 
            frequency = [1], amplitude = [0.5],  decay_constant = [200],phase =[0], offset = 0.5, 
            fitfunc_type = 'single', plot_fit = False, do_print = False, show_guess = True, fitexp = None):
    ''' 
    Inputs:
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    '''
    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        folder = toolbox.latest_data('CarbonRamsey')

    fit_results = []
    for k in range(0,len(measurement_name)):
        a = mbi.MBIAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        a.get_electron_ROC()
        a.sweep_pts = a.sweep_pts*1e6
        ax = a.plot_results_vs_sweepparam(ret='ax')
        ax.set_ylim(-0.05,1.05)

        ax.set_xlim(-0.05,40)

        x = a.sweep_pts.reshape(-1)[:]
        y = a.p0.reshape(-1)[:]
        print fitexp
        print
        print 
        if len(frequency) == 1:
            if fitexp == 'Gaussian':
                p0, fitfunc, fitfunc_str = common.fit_gaussian_decaying_cos(frequency[0], offset, amplitude[0], phase[0], decay_constant[0])
                print 'ok'
            else:
                p0, fitfunc, fitfunc_str = common.fit_decaying_cos(frequency[0], offset, amplitude[0], phase[0], decay_constant[0])
            #plot the initial guess
            print 'no'
            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=[4])
        elif len(frequency) == 2:
            print 'yes'
            p0, fitfunc, fitfunc_str = common.fit_double_decaying_cos(frequency[0], amplitude[0], phase[0], decay_constant[0], frequency[1], amplitude[1], phase[1], decay_constant[1], offset)
            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=[2,3,6,7])
           
            ### Also plot the individual curves
            
            # p0_0, fitfunc_0, fitfunc_str_0 = common.fit_double_decaying_cos(fit_result['params'][0], 0, phase[0], fit_result['params'][2], fit_result['params'][3], fit_result['params'][4], phase[1], fit_result['params'][5])
            # ax.plot(np.linspace(0,x[-1],201), fitfunc_0(np.linspace(0,x[-1],201)), 'b-', lw=1)
            # p0_1, fitfunc_1, fitfunc_str_1 = common.fit_double_decaying_cos(fit_result['params'][0], fit_result['params'][1], phase[0], fit_result['params'][2], fit_result['params'][3],0, phase[1], fit_result['params'][5])
            # ax.plot(np.linspace(0,x[-1],201), fitfunc_1(np.linspace(0,x[-1],201)), 'm-', lw=1)



        ## plot fit
        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)
        ax.set_xlabel('Free evolution time (us)')

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

        # freq = fit_results[0]['params_dict']['f1']
        # period = 1/freq 
        # print 'Period is %s pulses ' %(period)
        # N_pi = round(period*.5/2)*2.0 
        # N_pi2 = round(period/2*.25)*2.0
        # print 'Pi pulse: %s pulses' %N_pi
        # print 'Pi2 pulse: %s pulses' %N_pi2
    return fit_results

### PLEASE DO NOT DO THESE KIND OF THINGS BELOW!!!! ### THIS IS A MODULE WITH FUNCTIONS THAT ARE GENERALLY USED
### DO NO ADD DATA HERE< BUT IMPORT THIS FUNCTION IF YOU NEED IT


######################### RAMSEY T2* ##############################################

# Carbon_Ramsey(timestamp='20140519135216', measurement_name = ['adwindata'], 
#             frequency = [575], amplitude = [0.5],  decay_constant = [0.009],phase =[0], 
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')

# Carbon_Ramsey(timestamp='20140519183105', measurement_name = ['adwindata'], 
#             frequency = [575], amplitude = [0.5],  decay_constant = [0.007],phase =[0], 
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')

# Carbon_Ramsey(timestamp='20140520134826', measurement_name = ['adwindata'], 
#             frequency = [205], amplitude = [0.5],  decay_constant = [0.007],phase =[0], 
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')

######################## RAMSEY 2 freq ##############################################

# Carbon_Ramsey(timestamp='20140521164658', measurement_name = ['adwindata'], 
#             frequency = [338e-3,14e-3], amplitude = [1,1],  decay_constant = [0.009e6,0.009e6],phase =[0,0], 
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False)

# Carbon_Ramsey(timestamp='20140521165249', measurement_name = ['adwindata'], 
#             frequency = [305e-3,16e-3], amplitude = [1,1],  decay_constant = [0.009e6,0.009e6],phase =[0,0], 
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False)

# Carbon_Ramsey(timestamp='20140521170735', measurement_name = ['adwindata'], 
#             frequency = [350e-3,27e-3], amplitude = [1,1],  decay_constant = [0.009e6,0.009e6],phase =[0,0], 
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False)

# Carbon_Ramsey(timestamp='20140521162939', measurement_name = ['adwindata'], 
#             frequency = [344e-3,19e-3], amplitude = [1,1],  decay_constant = [0.009e6,0.009e6],phase =[0,0], 
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False)

# ######################### RAMSEY simple ##############################################

# Carbon_Ramsey(timestamp='20140507114220', measurement_name = ['adwindata'], 
#             frequency = [350e-3], amplitude = [-0.5],  decay_constant = [900e6],phase =[0], 
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')

# Carbon_Ramsey(timestamp='20140507124543', measurement_name = ['adwindata'], 
#             frequency = [350e-3], amplitude = [-0.5],  decay_constant = [900e6],phase =[0], 
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')

# Carbon_Ramsey(timestamp='20140507151219', measurement_name = ['adwindata'], 
#             frequency = [350e-3], amplitude = [-0.5],  decay_constant = [900e6],phase =[0], 
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')

# Carbon_Ramsey(timestamp='20140429141113', measurement_name = ['adwindata'], 
#             frequency = [350e-3], amplitude = [-0.5],  decay_constant = [900e6],phase =[0], 
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')
Пример #4
0
def calibrate_LDE_phase(contains='', do_fit=False, **kw):
    '''
    gets data from a folder whose name contains the contains variable.
    Does or does not fit the data with a gaussian function
    '''

    ### folder choice
    if contains == '':
        contains = 'LDE_phase_calibration'

    # tomography
    tomo = kw.pop('tomo_basis', 'X')
    # return fit
    ret = kw.get('ret', False)
    # for fitting
    freq = kw.pop('freq', None)
    decay = kw.pop('decay', 50)
    phi0 = kw.pop('phi0', 0)
    offset = kw.pop('offset', 0)
    A0 = kw.pop('A0', None)
    show_plot = kw.pop('show_plot', True)

    fixed = kw.pop('fixed', [1])
    show_guess = kw.pop('show_guess', False)

    # older_than = kw.get('older_than',None) automatically handled by kws
    ### acquire data
    if 'folder' in kw:
        f = kw.pop('folder')
    else:
        f = toolbox.latest_data(contains, **kw)
    a = mbi.MBIAnalysis(f)

    if freq is None:
        try:
            freq = a.g.attrs['phase_detuning'] / 360.0
        except:
            freq = 1. / 12.  # voll auf die zwoelf.

    ro_array = ['positive', 'negative']
    # print ro_array
    if tomo == '':
        adwindata_str = tomo
    else:
        adwindata_str = tomo + '_'
    x, y, y_u = get_pos_neg_data(a,
                                 adwindata_str=adwindata_str,
                                 ro_array=ro_array,
                                 **kw)
    ylabel = tomo

    ### create a plot
    xlabel = a.g.attrs['sweep_name']
    x = a.g.attrs['sweep_pts']  # could potentially be commented out?
    fig, ax = create_plot(f,
                          xlabel=xlabel,
                          ylabel=ylabel,
                          title='Acquired phase')

    ## plot data
    plot_data(x, y, y_u=y_u)

    ### fitting if you feel like it / still needs implementation
    if do_fit:
        if A0 is None:
            A0 = max(y)

        p0, fitfunc, fitfunc_str = common.fit_decaying_cos(
            freq, offset, A0, phi0, decay)

        if show_guess:
            # print decay
            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,
                               VERBOSE=True,
                               fixed=fixed)

        plot.plot_fit1d(fit_result,
                        np.linspace(x[0], x[-1], 1001),
                        ax=ax,
                        color='r',
                        plot_data=False,
                        add_txt=True,
                        lw=2)

        p_dict = fit_result['params_dict']
        e_dict = fit_result['error_dict']

        if 'carbons' in a.g.attrs:
            fit_result['carbon_id'] = a.g.attrs['carbons'][0]
        elif 'dps_carbons' in a.g.attrs:
            fit_result['carbon_id'] = a.g.attrs['dps_carbons'][0]
        elif 'carbon' in a.g.attrs:
            fit_result['carbon_id'] = a.g.attrs['carbon']
        else:
            fit_result['carbon_id'] = None

        if p_dict['A'] < 0:
            p_dict['phi'] = p_dict['phi'] + 180
            p_dict['A'] = p_dict['A'] * (-1)

        try:
            detuning = a.g.attrs['phase_detuning']
            fit_result['detuning'] = detuning
            fit_result['acq_phase_per_rep'] = 360 * (p_dict['f']) - detuning
            fit_result['u_acq_phase_per_rep'] = 360 * (e_dict['f'])
            print 'This is the phase detuning', detuning
            print 'Acquired phase per repetition (compensating for phase_detuning=) {:3.3f} +/- {:3.3f}'.format(
                round(fit_result['acq_phase_per_rep'], 3),
                round(fit_result['u_acq_phase_per_rep'], 3))
            print 'phase offset ', round(p_dict['phi'], 3)
        except:
            print 'no phase detuning found'
            ## save and close plot. We are done.

    save_and_close_plot(f, show=show_plot)

    if kw.get('ret', False):
        return fit_result

    if kw.get('ret_data', False):
        return x, y, y_u

    if kw.get('ret_fit_data', False):
        return fit_result, x, y, y_u

    if kw.get('ret_data_fit', False):
        return x, y, y_u, fit_result
Пример #5
0
def Osci_period(carbon = '1',older_than = None,ssro_calib_timestamp = None,**kw):

	fit_results = kw.pop('fit_results',True)
	folder_name = kw.pop('folder_name','Memory_NoOf_Repetitions_')

	### fit parameters
	freq = kw.pop('freq',1/170.)
	offset = kw.pop('offfset',0.)
	decay = kw.pop('decay',200)
	fixed = kw.pop('fixed',[1])
	print folder_name



	folder_dict = {
	'X' : [],
	'Y' : [],
	'resX' : [],
	'resX_u' : [],
	'resY' : [],
	'resY_u': [],
	'sweep_pts': [],
	'res' : [],
	'res_u' : []
	}

	### search data

	for ro in ['positive','negative']:
		for t in ['X','Y']:
			search_string = folder_name+ro+'_Tomo_'+t+'_'+'C'+carbon
			folder_dict[t].append(toolbox.latest_data(contains = search_string,older_than = older_than,raise_exc = False))
	
	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_sil8'
		# print ssro_calib_folder

		### extract data
	x_labels,npX,npY,npX_u,npY_u = get_dephasing_data(folder_dict,ssro_calib_folder)


	fig = plt.figure()
	ax = plt.subplot()
	for y,y_u,jj in zip([npX,npY],[npX_u,npY_u],range(2)):
		if fit_results:
			A0 = max(y)
			phi0 = 0
			p0,fitfunc,fitfunc_str = common.fit_decaying_cos(freq,offset,A0,phi0,decay)

			# fixed = [1]

			fit_result = fit.fit1d(x_labels,y,None,p0 = p0, fitfunc = fitfunc, do_print = True, ret = True, fixed = fixed)
			plot.plot_fit1d(fit_result, np.linspace(x_labels[0],x_labels[-1],1001), ax=ax,color = color_list[jj], plot_data=False,add_txt = False, lw = 2)

		plt.errorbar(x_labels,y,y_u,marker='o',color = color_list[jj],label='C'+carbon+['X','Y'][jj])

	## define folder for data saving
	folder = folder_dict[t][0]

	plt.xlabel('Repump repetitions')
	plt.ylabel('Contrast')
	plt.title(get_tstamp_from_folder(folder) + ' Dephasing for C'+carbon)
	plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
	plt.savefig(os.path.join(folder,'CarbonDephasing_osci.pdf'),format='pdf')
	plt.savefig(os.path.join(folder,'CarbonDephasing_osci.png'),format='png')
	plt.show()
	plt.close('all')
	print 'Results are saved in ', folder[18:18+15]
def Carbon_control_sweep_N_zoomtau(tau_array=None,
                                   timestamp_array=None,
                                   measurement_name=['adwindata'],
                                   frequency=[1],
                                   amplitude=[0.5],
                                   decay_constant=[200],
                                   phase=[0],
                                   offset=0.5,
                                   fitfunc_type='single',
                                   plot_fit=False,
                                   plot_data=False,
                                   do_print=False,
                                   show_guess=True,
                                   yaxis=[-0.5, 1.05],
                                   fixed=[2, 6]):
    """
    Goal: find the optimal tau for carbon control.
    Fits a series of dynamicaldecopuling_sweepN measurements and plots the amplitudes as a function of tau.
    Input (one of two):
    - tau_array: array with tau values used in the measurements (takes last data with that tau value in its name)
    - TO DO: timestamp_array: array with timestamps to be used
    """

    fit_results = []

    if tau_array != None:
        nr_of_msmts = len(tau_array)
        fitted_values = np.zeros(
            [nr_of_msmts, 6]
        )  # first column = tau, next 5 columns = [frq, offset, amplitude, phase, decay constant] ([f, a, A, phi, t])
        fitted_errors = np.zeros([nr_of_msmts, 6])

        for counter, tau in enumerate(tau_array):
            timestamp, folder = toolbox.latest_data('tau_%s' %
                                                    str(format(tau, '.3f')),
                                                    return_timestamp=True)
            print "folder for tau = %s: %s" % (tau, folder)
            a = mbi.MBIAnalysis(folder)
            a.get_sweep_pts()
            a.get_readout_results(name='adwindata')
            a.get_electron_ROC()
            if plot_data:
                ax = a.plot_results_vs_sweepparam(ret='ax')
                ax.set_ylim(yaxis)

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

            if len(frequency) == 1:

                p0, fitfunc, fitfunc_str = common.fit_decaying_cos(
                    frequency[0], offset, amplitude[0], phase[0],
                    decay_constant[0])
                #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=fixed)

                ## plot fit
            if plot_fit == True:
                plot.plot_fit1d(fit_result,
                                np.linspace(0, x[-1], 201),
                                ax=ax,
                                plot_data=False,
                                print_info=True)
                plt.savefig(os.path.join(folder, 'analyzed_result.pdf'),
                            format='pdf')
                plt.savefig(os.path.join(folder, 'analyzed_result.png'),
                            format='png')

            fit_results.append(fit_result)

            # store fitted values
            fitted_values[counter, 0] = tau
            fitted_errors[counter, 0] = tau

            parameter_names = ['f', 'a', 'A',
                               't']  # NOTE: PHI IS ASSUMED FIXED!
            for k in range(len(parameter_names)):

                parameter = parameter_names[k]

                fitted_values[counter,
                              k] = fit_result['params_dict'][parameter]
                fitted_errors[counter, k] = fit_result['error_dict'][parameter]

                # print 'tau = %s: parameter %s has value %s +- %s' % (tau, parameter, fit_result['params_dict'][parameter], fit_result['error_dict'][parameter])

        plt.figure()

        plt.errorbar(tau_array,
                     fitted_values[:, 2],
                     yerr=fitted_errors[:, 2],
                     fmt='-o')
        plt.xlabel('tau (us)')
        plt.ylabel('Fitted amplitude')
        plt.title(timestamp)

        plt.savefig(
            os.path.join(
                folder,
                'SimpleDecoupling_sweepN_tau=[%s-%s]_FittedAmplitudes.png' %
                (np.amin(tau_array), np.amax(tau_array))))
        print 'FIGURE SAVED IN FOLDER: ', folder

    return fit_results, fitted_values, fitted_errors
def Carbon_control_sweep_N(timestamp=None,
                           contains=None,
                           ssro_calib_folder=None,
                           measurement_name=['adwindata'],
                           frequency=[1],
                           amplitude=[0.5],
                           decay_constant=[200],
                           phase=[0],
                           offset=0.5,
                           fitfunc_type='single',
                           plot_fit=False,
                           do_print=False,
                           show_guess=True,
                           yaxis=[-0.5, 1.05],
                           fixed=[2, 6],
                           plot_nice=False):
    ''' Function to analyze simple decoupling measurements. Loads the results and fits them to a simple exponential.
    Inputs:
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    '''
    # offset = 0.5
    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        if contains != None:
            folder = toolbox.latest_data(contains)
        else:
            folder = toolbox.latest_data('Decoupling')

    fit_results = []
    for k in range(0, len(measurement_name)):
        a = mbi.MBIAnalysis(folder)

        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        if ssro_calib_folder != None:
            a.get_electron_ROC(ssro_calib_folder=ssro_calib_folder)
        else:
            a.get_electron_ROC()
        ax = a.plot_results_vs_sweepparam(ret='ax')
        ax.set_ylim(yaxis)

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

        if len(frequency) == 1:

            p0, fitfunc, fitfunc_str = common.fit_decaying_cos(
                frequency[0], offset, amplitude[0], phase[0],
                decay_constant[0])
            #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=fixed)
        elif len(frequency) == 2:
            p0, fitfunc, fitfunc_str = common.fit_double_decaying_cos(
                frequency[0], amplitude[0], phase[0], decay_constant[0],
                frequency[1], amplitude[1], phase[1], decay_constant[1],
                offset)
            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)

            ## Also plot the individual curves

            p0_0, fitfunc_0, fitfunc_str_0 = common.fit_double_decaying_cos(
                fit_result['params'][0], 0, phase[0], fit_result['params'][2],
                fit_result['params'][3], fit_result['params'][4], phase[1],
                fit_result['params'][5], fit_result['params'][6])
            ax.plot(np.linspace(0, x[-1], 201),
                    fitfunc_0(np.linspace(0, x[-1], 201)),
                    'r-',
                    lw=1,
                    alpha=0.5)
            p0_1, fitfunc_1, fitfunc_str_1 = common.fit_double_decaying_cos(
                fit_result['params'][0], fit_result['params'][1], phase[0],
                fit_result['params'][2], fit_result['params'][3], 0, phase[1],
                fit_result['params'][5], fit_result['params'][6])
            ax.plot(np.linspace(0, x[-1], 201),
                    fitfunc_1(np.linspace(0, x[-1], 201)),
                    'm-',
                    lw=1,
                    alpha=0.5)

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

        y_fit = fit_result['fitfunc'](np.arange(0, 60, 1))

        for i, j in enumerate(abs(y_fit - 0.5)):
            if j == min(abs(y_fit - 0.5)):
                x_opt = i

        ax.text(5, 0.9, 'pulses for pi/2: ' + str(x_opt))

        fit_results.append(fit_result)
        print folder
        plt.savefig(os.path.join(folder, 'analyzed_result.pdf'), format='pdf')
        plt.savefig(os.path.join(folder, 'analyzed_result.png'), format='png')
        fit_result['tau'] = a.g.attrs['tau_list'][0]
        # freq = fit_results[0]['params_dict']['f1']
        # period = 1/freq
        # print 'Period is %s pulses ' %(period)
        # # N_pi = round(period*.5/2)*2.0
        # N_pi2 = round(period/2*.25)*2.0
        # # print 'Pi pulse: %s pulses' %N_pi
        # print 'Pi2 pulse: %s pulses' %N_pi2

        if plot_nice:
            fig, ax = plt.subplots(figsize=(7, 5))
            ax2 = ax.twiny()
            one_cnot = 1 / (4 * fit_result['params_dict']['f'])
            print 'one cnot'
            print one_cnot

            ax.errorbar(x, y, yerr=y_err, marker='o', ls='', color='b')
            ax.plot(np.linspace(x[0], x[-1], 10000),
                    fit_result['fitfunc'](np.linspace(x[0], x[-1], 10000)),
                    lw=2,
                    color='b')
            ax.set_xlim(x[0] - 3, x[-1] + 3)
            ax.set_yticks([0, 0.5, 1])
            ax.set_ylim(0, 1)
            ax.set_xlabel('Number of pulses (N)')
            ax.set_ylabel(r'$F(|0\rangle)$')
            print np.arange(0, 250, one_cnot)
            ax2.set_xticks(np.arange(0, 250, one_cnot))
            ax2.set_xticklabels(np.arange(0, 8, 1))
            ax2.set_xlabel('Number of gates')
            plt.savefig(os.path.join(folder, 'nice_result.pdf'), format='pdf')
            plt.savefig(os.path.join(folder, 'nice_result.png'), format='png')
    return fit_result
def Carbon_control_sweep_N_zoomtau(tau_array = None, timestamp_array = None, measurement_name = ['adwindata'], 
            frequency = [1], amplitude = [0.5],  decay_constant = [200],phase =[0], offset = 0.5,
            fitfunc_type = 'single', plot_fit = False, plot_data = False, do_print = False, show_guess = True,
            yaxis = [-0.5,1.05], fixed=[2,6]):
    """
    Goal: find the optimal tau for carbon control.
    Fits a series of dynamicaldecopuling_sweepN measurements and plots the amplitudes as a function of tau.
    Input (one of two):
    - tau_array: array with tau values used in the measurements (takes last data with that tau value in its name)
    - TO DO: timestamp_array: array with timestamps to be used
    """

    fit_results = []

    if tau_array != None:
        nr_of_msmts = len(tau_array) 
        fitted_values = np.zeros([nr_of_msmts, 6]) # first column = tau, next 5 columns = [frq, offset, amplitude, phase, decay constant] ([f, a, A, phi, t])
        fitted_errors = np.zeros([nr_of_msmts, 6])

        for counter, tau in enumerate(tau_array):
            timestamp, folder = toolbox.latest_data('tau_%s' % str(format(tau, '.3f')), return_timestamp = True)
            print "folder for tau = %s: %s" % (tau, folder)
            a = mbi.MBIAnalysis(folder)
            a.get_sweep_pts()
            a.get_readout_results(name='adwindata')
            a.get_electron_ROC()
            if plot_data:
                ax = a.plot_results_vs_sweepparam(ret='ax')
                ax.set_ylim(yaxis)

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

            if len(frequency) == 1:

                p0, fitfunc, fitfunc_str = common.fit_decaying_cos(frequency[0], offset, amplitude[0], phase[0], decay_constant[0])
                #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=fixed)

                ## plot fit
            if plot_fit == True:
                plot.plot_fit1d(fit_result, np.linspace(0,x[-1],201), ax=ax, plot_data=False,print_info = True)
                plt.savefig(os.path.join(folder, 'analyzed_result.pdf'),
                format='pdf')
                plt.savefig(os.path.join(folder, 'analyzed_result.png'),
                format='png')

            fit_results.append(fit_result)

            # store fitted values
            fitted_values[counter, 0] = tau
            fitted_errors[counter, 0] = tau

            parameter_names = ['f', 'a', 'A', 't'] # NOTE: PHI IS ASSUMED FIXED!
            for k in range(len(parameter_names)):

                parameter = parameter_names[k]

                fitted_values[counter, k] = fit_result['params_dict'][parameter]
                fitted_errors[counter, k] = fit_result['error_dict'][parameter]

                # print 'tau = %s: parameter %s has value %s +- %s' % (tau, parameter, fit_result['params_dict'][parameter], fit_result['error_dict'][parameter])

        plt.figure()


        plt.errorbar(tau_array, fitted_values[:,2], yerr = fitted_errors[:,2], fmt = '-o')
        plt.xlabel('tau (us)')
        plt.ylabel('Fitted amplitude')
        plt.title(timestamp)

        plt.savefig(os.path.join(folder, 'SimpleDecoupling_sweepN_tau=[%s-%s]_FittedAmplitudes.png' % (np.amin(tau_array), np.amax(tau_array)) ) )
        print 'FIGURE SAVED IN FOLDER: ', folder

    return fit_results, fitted_values, fitted_errors
def Carbon_control_sweep_N(timestamp=None,contains=None, ssro_calib_folder = None, measurement_name = ['adwindata'], 
    frequency = [1], amplitude = [0.5],  decay_constant = [200],phase =[0], offset = 0.5,
    fitfunc_type = 'single', plot_fit = False, do_print = False, show_guess = True,
    yaxis = [-0.5,1.05], fixed=[2,6],plot_nice = False):
    ''' Function to analyze simple decoupling measurements. Loads the results and fits them to a simple exponential.
    Inputs:
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    '''
    # offset = 0.5
    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        if contains!=None:
            folder=toolbox.latest_data(contains)
        else:
            folder = toolbox.latest_data('Decoupling')

    fit_results = []
    for k in range(0,len(measurement_name)):
        a = mbi.MBIAnalysis(folder)

        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        if ssro_calib_folder != None:
            a.get_electron_ROC(ssro_calib_folder = ssro_calib_folder)
        else:
            a.get_electron_ROC()
        ax = a.plot_results_vs_sweepparam(ret='ax')
        ax.set_ylim(yaxis)

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

        if len(frequency) == 1:

            p0, fitfunc, fitfunc_str = common.fit_decaying_cos(frequency[0], offset, amplitude[0], phase[0], decay_constant[0])
            #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=fixed)
        elif len(frequency) == 2:
            p0, fitfunc, fitfunc_str = common.fit_double_decaying_cos(frequency[0], amplitude[0], phase[0], 
                            decay_constant[0], frequency[1], amplitude[1], phase[1], decay_constant[1],offset)
            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)
           
            ## Also plot the individual curves
            
            p0_0, fitfunc_0, fitfunc_str_0 = common.fit_double_decaying_cos(fit_result['params'][0], 0, phase[0], fit_result['params'][2], fit_result['params'][3], fit_result['params'][4], phase[1], fit_result['params'][5], fit_result['params'][6])
            ax.plot(np.linspace(0,x[-1],201), fitfunc_0(np.linspace(0,x[-1],201)), 'r-', lw=1,alpha=0.5)
            p0_1, fitfunc_1, fitfunc_str_1 = common.fit_double_decaying_cos(fit_result['params'][0], fit_result['params'][1], phase[0], fit_result['params'][2], fit_result['params'][3],0, phase[1], fit_result['params'][5], fit_result['params'][6])
            ax.plot(np.linspace(0,x[-1],201), fitfunc_1(np.linspace(0,x[-1],201)), 'm-', lw=1,alpha=0.5)

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


        y_fit = fit_result['fitfunc'](np.arange(0,60,1))

        for i, j in enumerate(abs(y_fit-0.5)):
            if j == min(abs(y_fit-0.5)):
                x_opt = i


        ax.text(5,0.9,'pulses for pi/2: ' +str(x_opt))

        fit_results.append(fit_result)
        print folder
        plt.savefig(os.path.join(folder, 'analyzed_result.pdf'),
        format='pdf')
        plt.savefig(os.path.join(folder, 'analyzed_result.png'),
        format='png')
        fit_result['tau']=a.g.attrs['tau_list'][0]
        # freq = fit_results[0]['params_dict']['f1']
        # period = 1/freq 
        # print 'Period is %s pulses ' %(period)
        # # N_pi = round(period*.5/2)*2.0 
        # N_pi2 = round(period/2*.25)*2.0
        # # print 'Pi pulse: %s pulses' %N_pi
        # print 'Pi2 pulse: %s pulses' %N_pi2

        if plot_nice:
            fig,ax = plt.subplots(figsize = (7,5)) 
            ax2 = ax.twiny()
            one_cnot = 1/(4*fit_result['params_dict']['f'])
            print 'one cnot'
            print one_cnot

            ax.errorbar(x,y,yerr=y_err,marker = 'o',ls = '',color = 'b')
            ax.plot(np.linspace(x[0],x[-1],10000),fit_result['fitfunc'](np.linspace(x[0],x[-1],10000)),lw = 2, color = 'b')
            ax.set_xlim(x[0]-3,x[-1]+3)
            ax.set_yticks([0,0.5,1])
            ax.set_ylim(0,1)
            ax.set_xlabel('Number of pulses (N)')
            ax.set_ylabel(r'$F(|0\rangle)$')
            print np.arange(0,250,one_cnot)
            ax2.set_xticks(np.arange(0,250,one_cnot))
            ax2.set_xticklabels(np.arange(0,8,1))
            ax2.set_xlabel('Number of gates')
            plt.savefig(os.path.join(folder, 'nice_result.pdf'),
            format='pdf')
            plt.savefig(os.path.join(folder, 'nice_result.png'),
            format='png')            
    return fit_result
def Carbon_Ramsey(timestamp=None,
                  measurement_name=['adwindata'],
                  frequency=[1],
                  amplitude=[0.5],
                  decay_constant=[200],
                  phase=[0],
                  offset=0.5,
                  fitfunc_type='single',
                  plot_fit=False,
                  do_print=False,
                  show_guess=True,
                  fitexp=None):
    ''' 
    Inputs:
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    '''
    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        folder = toolbox.latest_data('CarbonRamsey')

    fit_results = []
    for k in range(0, len(measurement_name)):
        a = mbi.MBIAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        a.get_electron_ROC()
        a.sweep_pts = a.sweep_pts * 1e6
        ax = a.plot_results_vs_sweepparam(ret='ax')
        ax.set_ylim(-0.05, 1.05)

        ax.set_xlim(-0.05, 40)

        x = a.sweep_pts.reshape(-1)[:]
        y = a.p0.reshape(-1)[:]
        print fitexp
        print
        print
        if len(frequency) == 1:
            if fitexp == 'Gaussian':
                p0, fitfunc, fitfunc_str = common.fit_gaussian_decaying_cos(
                    frequency[0], offset, amplitude[0], phase[0],
                    decay_constant[0])
                print 'ok'
            else:
                p0, fitfunc, fitfunc_str = common.fit_decaying_cos(
                    frequency[0], offset, amplitude[0], phase[0],
                    decay_constant[0])
            #plot the initial guess
            print 'no'
            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=[4])
        elif len(frequency) == 2:
            print 'yes'
            p0, fitfunc, fitfunc_str = common.fit_double_decaying_cos(
                frequency[0], amplitude[0], phase[0], decay_constant[0],
                frequency[1], amplitude[1], phase[1], decay_constant[1],
                offset)
            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=[2, 3, 6, 7])

            ### Also plot the individual curves

            # p0_0, fitfunc_0, fitfunc_str_0 = common.fit_double_decaying_cos(fit_result['params'][0], 0, phase[0], fit_result['params'][2], fit_result['params'][3], fit_result['params'][4], phase[1], fit_result['params'][5])
            # ax.plot(np.linspace(0,x[-1],201), fitfunc_0(np.linspace(0,x[-1],201)), 'b-', lw=1)
            # p0_1, fitfunc_1, fitfunc_str_1 = common.fit_double_decaying_cos(fit_result['params'][0], fit_result['params'][1], phase[0], fit_result['params'][2], fit_result['params'][3],0, phase[1], fit_result['params'][5])
            # ax.plot(np.linspace(0,x[-1],201), fitfunc_1(np.linspace(0,x[-1],201)), 'm-', lw=1)

        ## plot fit
        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)
        ax.set_xlabel('Free evolution time (us)')

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

        # freq = fit_results[0]['params_dict']['f1']
        # period = 1/freq
        # print 'Period is %s pulses ' %(period)
        # N_pi = round(period*.5/2)*2.0
        # N_pi2 = round(period/2*.25)*2.0
        # print 'Pi pulse: %s pulses' %N_pi
        # print 'Pi2 pulse: %s pulses' %N_pi2
    return fit_results


### PLEASE DO NOT DO THESE KIND OF THINGS BELOW!!!! ### THIS IS A MODULE WITH FUNCTIONS THAT ARE GENERALLY USED
### DO NO ADD DATA HERE< BUT IMPORT THIS FUNCTION IF YOU NEED IT

######################### RAMSEY T2* ##############################################

# Carbon_Ramsey(timestamp='20140519135216', measurement_name = ['adwindata'],
#             frequency = [575], amplitude = [0.5],  decay_constant = [0.009],phase =[0],
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')

# Carbon_Ramsey(timestamp='20140519183105', measurement_name = ['adwindata'],
#             frequency = [575], amplitude = [0.5],  decay_constant = [0.007],phase =[0],
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')

# Carbon_Ramsey(timestamp='20140520134826', measurement_name = ['adwindata'],
#             frequency = [205], amplitude = [0.5],  decay_constant = [0.007],phase =[0],
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')

######################## RAMSEY 2 freq ##############################################

# Carbon_Ramsey(timestamp='20140521164658', measurement_name = ['adwindata'],
#             frequency = [338e-3,14e-3], amplitude = [1,1],  decay_constant = [0.009e6,0.009e6],phase =[0,0],
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False)

# Carbon_Ramsey(timestamp='20140521165249', measurement_name = ['adwindata'],
#             frequency = [305e-3,16e-3], amplitude = [1,1],  decay_constant = [0.009e6,0.009e6],phase =[0,0],
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False)

# Carbon_Ramsey(timestamp='20140521170735', measurement_name = ['adwindata'],
#             frequency = [350e-3,27e-3], amplitude = [1,1],  decay_constant = [0.009e6,0.009e6],phase =[0,0],
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False)

# Carbon_Ramsey(timestamp='20140521162939', measurement_name = ['adwindata'],
#             frequency = [344e-3,19e-3], amplitude = [1,1],  decay_constant = [0.009e6,0.009e6],phase =[0,0],
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False)

# ######################### RAMSEY simple ##############################################

# Carbon_Ramsey(timestamp='20140507114220', measurement_name = ['adwindata'],
#             frequency = [350e-3], amplitude = [-0.5],  decay_constant = [900e6],phase =[0],
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')

# Carbon_Ramsey(timestamp='20140507124543', measurement_name = ['adwindata'],
#             frequency = [350e-3], amplitude = [-0.5],  decay_constant = [900e6],phase =[0],
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')

# Carbon_Ramsey(timestamp='20140507151219', measurement_name = ['adwindata'],
#             frequency = [350e-3], amplitude = [-0.5],  decay_constant = [900e6],phase =[0],
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')

# Carbon_Ramsey(timestamp='20140429141113', measurement_name = ['adwindata'],
#             frequency = [350e-3], amplitude = [-0.5],  decay_constant = [900e6],phase =[0],
#             fitfunc_type = 'single', plot_fit = True, do_print = False, show_guess = False,fitexp='Gaussian')