示例#1
0
def compile_xy_values_of_datasets(f_list, ssro_tstamp='112128', **kw):
    """
    besides returning all msmt values this function also returns 
    one data object in case one wants to review msmt params.
    """

    if ssro_tstamp == None:
        ssro_calib_folder = tb.latest_data('SSROCalib')
    else:
        ssro_dstmp, ssro_tstmp = tb.verify_timestamp(ssro_tstamp)
        ssro_calib_folder = tb.latest_data(ssro_tstmp)

    x = []
    y = []
    y_u = []
    for f in f_list:
        a = mbi.MBIAnalysis(f)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        a.get_electron_ROC(ssro_calib_folder)

        x.extend(a.sweep_pts.reshape(-1))
        y.extend(a.p0.reshape(-1))
        y_u.extend(a.u_p0.reshape(-1))

    return x, y, y_u, a
def analyse_pi_pulse(**kw):
    '''
    Perform a parabolic fit of the data to extract the optimal voltage for the pi pulse.
    '''
    timestamp = kw.pop('timestamp', None)
    do_print = kw.pop('do_print', False)

    x0_guess = kw.pop('x0_guess', 0.6)
    a_guess = kw.pop('a_guess', 12)
    of_guess = kw.pop('of_guess', 0.9)

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

    fig, ax = plt.subplots(1, 1, figsize=(4.5, 4))
    fit_result = calibration_tools.fit_parabolic(
        folder,
        x0_guess=x0_guess,
        a_guess=a_guess,
        of_guess=of_guess,
        ax=ax,
        do_print=do_print)  #, info_xy=(x0_guess,0.5))
    calibration_tools.plot_result(folder, ax=ax, ret=True)
    #ax.set_ylim(0.,0.4)

    plt.savefig(os.path.join(folder, 'pi_pulse_calibration_analysis_fit.png'))

    return fit_result
示例#3
0
    def find_tstamps_of_day(self,
                            ts_list,
                            day_string,
                            analysis_folder='throw exception',
                            newest_tstamp='235959',
                            oldest_tstamp='000000'):
        latest_t = day_string + newest_tstamp  # where in the day do you want to begin? 235959 mean: take the whole day
        newer_than = day_string + oldest_tstamp
        while tb.latest_data('XX',
                             older_than=latest_t,
                             folder=analysis_folder,
                             newer_than=newer_than,
                             return_timestamp=True,
                             raise_exc=False) != False:
            latest_t, f = tb.latest_data('XX',
                                         older_than=latest_t,
                                         folder=analysis_folder,
                                         newer_than=newer_than,
                                         return_timestamp=True,
                                         raise_exc=False)
            ### debug statement that prints the full timestamp and the relevant identifier.
            # print latest_t[8:],latest_t

            ### append found timestamp to list of timestamps
            ts_list.append(latest_t[8:])

        return ts_list
示例#4
0
    def get_electron_ROC(self, **kw):
        ssro_calib_folder = kw.pop('ssro_calib_folder', None)
        if ssro_calib_folder is None:
            ssro_calib_folder = toolbox.latest_data('SSROCalibration')
        # print ssro_calib_folder
        if ssro_calib_folder == '':
            ssro_calib_folder = toolbox.latest_data('SSROCalibration')

        self.p0 = np.zeros(self.normalized_ssro.shape)
        self.u_p0 = np.zeros(self.normalized_ssro.shape)

        ro_duration = self.g.attrs['SSRO_duration']
        roc = error.SingleQubitROC()

        # Decide between ssro calib via MW Initialisation or some other method
        # At the time of writing only MWInit and full las0r SSRO exist ~SK 2016
        if 'MWInit' in ssro_calib_folder:
            el_state = self.adgrp.attrs['electron_transition']
            # print 'MWInit, el_state: ' + str(el_state)

            roc.F0, roc.u_F0, roc.F1, roc.u_F1 = \
                ssro.get_SSRO_MWInit_calibration(ssro_calib_folder,
                        ro_duration,el_state)

        else:
            roc.F0, roc.u_F0, roc.F1, roc.u_F1 = \
                ssro.get_SSRO_calibration(ssro_calib_folder,
                        ro_duration)

        p0, u_p0 = roc.num_eval(self.normalized_ssro, self.u_normalized_ssro)

        self.p0 = p0
        self.u_p0 = u_p0

        self.result_corrected = True
def Zeno_2Q_proc_list(starts=[],
						stops=[]):
	fid=[]
	fid_u=[]
	evotime=[]
	if len(starts)==0:
		print 'nothing to do here'

	else:
		fig=plt.figure()
		ax=plt.subplot()
		for i in range(len(starts)):
			evotime,fid,fid_u = Zeno_2Q_proc_fidelity_decay(timestamp_start=starts[i],
									timestamp_stop=stops[i],
									plot_results=False)
			plt.errorbar(evotime,fid,fid_u,marker='o')
		

		plt.xlabel('Free evolution time (s)')
		plt.ylabel('2 qubit average fidelity')
		plt.title('Timestamps_start_'+str(starts[0])+'_stop_'+str(stops[-1]))

		print toolbox.latest_data('Zeno',older_than=starts[-1])
		plt.savefig(os.path.join(toolbox.latest_data('Zeno',older_than=starts[-1]),'ZenoTwoQAvgDecays_combined.pdf'),format='pdf')
		plt.savefig(os.path.join(toolbox.latest_data('Zeno',older_than=starts[-1]),'ZenoTwoQAvgDecays_combined.png'),format='png')
		plt.close('all')
def Zeno_get_2Q_values(timestamp=None, folder=None,folder_name='Zeno',
						measurement_name = ['adwindata'], 
						ssro_calib_timestamp ='20150128_080328'):
	"""
	Returns the relevant 2qubit values for a given timestamp.
	"""
	if timestamp == None and folder==None:
	    timestamp, folder   = toolbox.latest_data(folder_name,return_timestamp =True)
	elif timestamp ==None and folder!=None: 
		pass
	else:
	    folder = toolbox.data_from_time(timestamp) 

	if folder != None and timestamp == None:
		d,t = toolbox.get_date_time_string_from_folder(folder)
		timestamp = toolbox.timestamp_from_datetime(t)
	### SSRO calibration
	if ssro_calib_timestamp == None:
	    ssro_calib_folder = toolbox.latest_data('SSRO',older_than=timestamp)
	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'

	a = mbi.MBIAnalysis(folder)
	a.get_sweep_pts()
	a.get_readout_results(name='adwindata')
	a.get_electron_ROC(ssro_calib_folder)

	x_labels = a.sweep_pts.reshape(-1)
	y= ((a.p0.reshape(-1))-0.5)*2
	y_err = 2*a.u_p0.reshape(-1)

	return x_labels,y,y_err
示例#7
0
def get_lt_fps(fps_bs, lt3_folder, lt4_folder):
    max_measurement_delay = datetime.timedelta(minutes=2, seconds=10)
    fps_lt3 = []
    fps_lt4 = []
    for fp_bs in fps_bs:
        if not 'Bell_BS' in fp_bs:
            raise Exception('File' + fp_bs + ' not a BS file?')
        bs_m_folder = os.path.split(fp_bs)[0]
        bs_m_time = tb.get_datetime_from_folder(bs_m_folder)
        bs_m_name = tb.get_measurement_name_from_folder(bs_m_folder)[8:]
        min_timestamp = tb.timestamp_from_datetime(bs_m_time -
                                                   max_measurement_delay)
        max_timestamp = tb.timestamp_from_datetime(bs_m_time +
                                                   max_measurement_delay)

        lt3_m_folder = tb.latest_data(contains=bs_m_name,
                                      folder=lt3_folder,
                                      older_than=max_timestamp,
                                      newer_than=min_timestamp)
        fps_lt3.append(tb.get_msmt_fp(lt3_m_folder))
        lt4_m_folder = tb.latest_data(contains=bs_m_name,
                                      folder=lt4_folder,
                                      older_than=max_timestamp,
                                      newer_than=min_timestamp)
        fps_lt4.append(tb.get_msmt_fp(lt4_m_folder))

    return fps_lt3, fps_lt4
def analyse_pi_pulse(**kw):
    '''
    Perform a parabolic fit of the data to extract the optimal voltage for the pi pulse.
    '''
    timestamp     = kw.pop('timestamp', None)
    do_print      = kw.pop('do_print', False)

    x0_guess      = kw.pop('x0_guess', 0.6)
    a_guess       = kw.pop('a_guess', 12)
    of_guess      = kw.pop('of_guess', 0.9)

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


    fig, ax = plt.subplots(1,1, figsize=(4.5,4))
    fit_result=calibration_tools.fit_parabolic(folder, x0_guess=x0_guess,a_guess=a_guess,of_guess=of_guess, ax=ax, do_print = do_print)#, info_xy=(x0_guess,0.5))
    calibration_tools.plot_result(folder, ax=ax, ret=True)
    #ax.set_ylim(0.,0.4)

    plt.savefig(os.path.join(folder, 'pi_pulse_calibration_analysis_fit.png'))

    return fit_result
示例#9
0
def Zeno_2Q_proc_list(starts=[], stops=[]):
    fid = []
    fid_u = []
    evotime = []
    if len(starts) == 0:
        print 'nothing to do here'

    else:
        fig = plt.figure()
        ax = plt.subplot()
        for i in range(len(starts)):
            evotime, fid, fid_u = Zeno_2Q_proc_fidelity_decay(
                timestamp_start=starts[i],
                timestamp_stop=stops[i],
                plot_results=False)
            plt.errorbar(evotime, fid, fid_u, marker='o')

        plt.xlabel('Free evolution time (s)')
        plt.ylabel('2 qubit average fidelity')
        plt.title('Timestamps_start_' + str(starts[0]) + '_stop_' +
                  str(stops[-1]))

        print toolbox.latest_data('Zeno', older_than=starts[-1])
        plt.savefig(os.path.join(
            toolbox.latest_data('Zeno', older_than=starts[-1]),
            'ZenoTwoQAvgDecays_combined.pdf'),
                    format='pdf')
        plt.savefig(os.path.join(
            toolbox.latest_data('Zeno', older_than=starts[-1]),
            'ZenoTwoQAvgDecays_combined.png'),
                    format='png')
        plt.close('all')
示例#10
0
def save_DD_data():  
    from analysis.lib.m2.ssro import mbi; reload(mbi)
    base_folder_lt3 = analysis_params.data_settings['base_folder_lt3']
    lt3_folder = os.path.join(base_folder_lt3,'DDCalib')
    lt3_ssro_folder = os.path.join(base_folder_lt3,'SSROs')
    base_folder_lt4 = analysis_params.data_settings['base_folder_lt4']
    lt4_folder = os.path.join(base_folder_lt4,'DDCalib')
    lt4_ssro_folder = os.path.join(base_folder_lt4,'SSROs')

    file_b = tb.latest_data(contains = 'sweep_decoupling',folder= lt3_folder)
    file_a = tb.latest_data(contains = 'sweep_decoupling',folder =lt4_folder)
    ssro_b  = tb.latest_data(contains = 'SSROCalib', folder = lt3_ssro_folder)
    ssro_a  = tb.latest_data(contains = 'SSROCalib',  folder = lt4_ssro_folder)
    print file_b
    a = mbi.MBIAnalysis(file_b)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata',CR_after_check = True)
    a.get_electron_ROC(ssro_b)
    a.save('ssro_results')
   
    a = mbi.MBIAnalysis(file_a)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata',CR_after_check = True)
    a.get_electron_ROC(ssro_a)
    a.save('ssro_results')
示例#11
0
def make_folder_dict(pre_fix_name='Memory_NoOf_Repetitions_',**kw):
	'''
	combine all tomography data of a desired dataset, based on a
	name : string that uniquely defines the measurement you want to get
	tomo_list: list of strings containing the readout basis
	carbon: string defining the carbon Number
	older_than: string 'yyyymmdd_hhmmss' to exlude all data after this time
	ssro_calib_timestamp: string with timestamp if you want to use specific ssro calib
	'''

	tomo_list = kw.pop('tomo_list',['X','Y'])
	carbon = kw.pop('carbon','1')
	older_than = kw.pop('older_than',None)
	ssro_calib_timestamp = kw.pop('ssro_calib_timestamp',None)
	post_fix_name = kw.pop('post_fix_name','')

	folder_dict={}
	
	for t in tomo_list:
		folder_dict[t]={}
		folder_dict[t]['folders']=[]
		for ro in ['positive','negative']:
			search_string = pre_fix_name+ro+'_Tomo_'+t+'_'+'C'+carbon+post_fix_name
			f=toolbox.latest_data(contains = search_string,older_than = older_than,raise_exc = False)
			folder_dict[t]['folders'].append(f)

		if ssro_calib_timestamp == None: 
		    ssro_calib_folder = toolbox.latest_data('SSRO')
		else:
			ssro_calib_folder = toolbox.latest_data(contains=ssro_calib_timestamp+'_AdwinSSRO_SSROCalibration')
		folder_dict[t]['ssro_calib_folder']=ssro_calib_folder

	return folder_dict
示例#12
0
    def verify_tstamp_lists(self, lt3_t_list, lt4_t_list, date):

        print len(lt3_t_list), len(lt4_t_list)
        if len(lt3_t_list) != len(lt4_t_list):
            print 't_lt3 , t_lt4'
            for lt3_t, lt4_t in zip(lt3_t_list, lt4_t_list):
                print lt3_t, lt4_t
            raise Exception(
                'The length of the time stamp lists is unequal. Clean out the data folders on each computer t3_0,t4_0: ',
                lt3_t_list[0], lt4_t_list[0])

        clean_t_list_lt3, clean_t_list_lt4 = [], []

        ### check for contents
        newer_than = date + '_000000'
        for t_lt3, t_lt4 in zip(lt3_t_list, lt4_t_list):

            f_lt3 = tb.latest_data(t_lt3,
                                   folder=self.lt3_folder,
                                   newer_than=newer_than)
            f_lt4 = tb.latest_data(t_lt4,
                                   folder=self.lt4_folder,
                                   newer_than=newer_than)

            ## get file path and open file
            Datafile_lt3 = h5py.File(
                f_lt3 + f_lt3[len(self.lt3_folder) + 9:] + '.hdf5', 'r')
            Datafile_lt4 = h5py.File(
                f_lt4 + f_lt4[len(self.lt4_folder) + 9:] + '.hdf5', 'r')

            if (not u'PQ_hist' in Datafile_lt4.keys()
                ):  ### did we actually detect any clicks what so ever?
                continue

            ### we exploit the fact that .keys is ordered according to what is saved last.
            ### --> adwin data is saved last: therefore if the last key contains pq --> no adwin data

            if ('PQ' in Datafile_lt3.keys()[-1]) or (len(Datafile_lt4.keys()) <
                                                     2):
                continue

            ### check if there are adwin ssro events and if they have the same length for both files

            ssros_lt3 = Datafile_lt3[Datafile_lt3.keys()
                                     [-1]]['adwindata']['ssro_results'].value
            ssros_lt4 = Datafile_lt4[Datafile_lt4.keys()
                                     [0]]['adwindata']['ssro_results'].value

            if (len(ssros_lt4) == len(ssros_lt3)) and (len(ssros_lt3) != 0):
                ### timestamp contains valuable information, add to clean lists
                clean_t_list_lt3.append(t_lt3)
                clean_t_list_lt4.append(t_lt4)

        ### return clean timestamp lists

        return clean_t_list_lt3, clean_t_list_lt4
示例#13
0
def gate_sweep_analysis(carbon, **kw):
	"""
	gets data, plots it and prints the gate parameters for maximum bloch vector length.
	"""
	older_than = kw.pop('older_than',None)
	newer_than = kw.pop('newer_than',None)
	ssro_tstamp = kw.pop('ssro_tstamp',None)
	
	uncond_data = kw.pop('uncond_data',False)

	return_data = kw.pop('return_data',False)
	plot_fidelity = kw.pop('plot_fidelity',False)
	gate_time = kw.pop('gate_time',False)
	line_fidelity = kw.pop('line_fidelity',False)

	#finding how many taus there are: nr. folders/nr. of parts
	if uncond_data == False:
		search_string = 'Sweep_carbon_Gate__C'+str(carbon)+ '_positive_tau'
	else:
		search_string = 'Sweep_uncond_carbon_Gate__C'+str(carbon)+ '_positive_tau'
		
	entire_folder_list = toolbox.latest_data(contains = search_string, older_than=older_than, newer_than=newer_than, return_all = True)[::-1]
	nr_of_parts = len(toolbox.latest_data(contains = search_string + '0', older_than=older_than, newer_than=newer_than, return_all = True)[::-1])
	nr_of_taus = len(entire_folder_list)/nr_of_parts

	tau_nrs 	= kw.pop('tau_nrs', range(nr_of_taus))
	for t in tau_nrs:			
		gates,x,y,x_u,y_u,folder_pos, gate_values = get_raw_data_all_parts(carbon,older_than = older_than,
			newer_than = newer_than, ssro_tstamp = ssro_tstamp, uncond_data = uncond_data, tau_nr = t, **kw)
		
		b,b_u = get_bloch_length(x,y,x_u,y_u)

		best_b = np.amax(b)
		best_b_ind = np.argmax(b)

		#### get the top 5 gates and return their configurations
		idx = (-b).argsort()[:5]
		for i in idx:
			print 'Gate %i: Blochvec. length of: %f at %s'%(i,b[i],gates[i])
		# print 'best gate configuration at: ', gates[best_b_ind]
		# print 'bloch vector length: ', best_b

		if plot_fidelity:
			bar_plot_fidelity(gates,gate_values,b,b_u)

		if gate_time:
			plot_gate_time([gates],[gate_values],[b],[b_u])

		if line_fidelity:
			line_plot_fidelity([gates],gate_values,[b],[b_u])

		if return_data:
			return gates,gate_values,b,b_u
			print 'data returned'

	print 'Analysis complete, have a nice day!'
def get_raw_data(carbon,**kw):
	"""
	extracts the data for one carbon from a positive and negative file.
	returns arrays for the contrast along x, y and the respective uncertainties.
	"""
	older_than = kw.pop('older_than',None)
	ssro_tstamp = kw.pop('ssro_tstamp',None)

	if ssro_tstamp == None:
		ssro_calib_folder = toolbox.latest_data(contains = 'SSRO')
		print ssro_calib_folder

	search_string_pos = 'Sweep_carbon_Gate__C'+str(carbon)+'_positive'
	search_string_neg = 'Sweep_carbon_Gate__C'+str(carbon)+'_negative'

	folder_pos = toolbox.latest_data(contains = search_string_pos, older_than=older_than)
	folder_neg = toolbox.latest_data(contains = search_string_neg, older_than=older_than)

	a = mbi.MBIAnalysis(folder_pos)
	a.get_sweep_pts()
	a.get_readout_results(name='adwindata')
	a.get_electron_ROC(ssro_calib_folder = ssro_calib_folder)

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

	print a.p0
	print b.p0
	a.p0 = 2*a.p0-1; a.u_p0 = 2*a.u_p0
	b.p0 = 2*b.p0-1; b.u_p0 = 2*b.u_p0

	###combine positive & negative:

	a.p0 = (a.p0 - b.p0)/2
	a.u_p0 = ((a.u_p0**2 + b.u_p0**2)**0.5)/2


	x_arr,x_u_arr = np.array([]),np.array([])
	y_arr,y_u_arr = np.array([]),np.array([])
	gates = np.array([]) ### used parameters

	### sort into X and y lists.
	for (pt,val,val_u) in zip(a.sweep_pts.reshape(-1),a.p0.reshape(-1),a.u_p0.reshape(-1)):
		if 'X' in pt:
			x_arr = np.append(x_arr,val)
			x_u_arr = np.append(x_u_arr,val_u)
			gates = np.append(gates,'N = '+str(pt[2:4])+',\ntau = '+str(pt[5:]))
		elif 'Y' in pt:
			y_arr = np.append(y_arr,val)
			y_u_arr = np.append(y_u_arr,val_u)


	return gates,x_arr,y_arr,x_u_arr,y_u_arr,folder_pos
def Carbon_Ramsey_Crosstalk_no_fit(older_than=None, crosstalk = None,measurement_name = ['adwindata'], 
    ssro_calib_folder =None,title = None):
    ''' 
    Function to analyze 
    Crosstalk is for example ['1to2', '1to5', '2to1', '2to5', '5to2', '5to1'] 
    '''
    #1to5_RO_X

    if crosstalk == None:
        crosstalk = ['1to2', '1to5', '2to1', '2to5', '5to2', '5to1'] 

    for kk in crosstalk:
        
        folder_a = toolbox.latest_data(kk + '_RO_X', older_than = older_than)
        folder_b = toolbox.latest_data(kk + '_RO_Y', older_than = older_than)  

        if ssro_calib_folder == None: 
            ssro_calib_folder = toolbox.latest_data('SSRO')

        for k in range(0,len(measurement_name)):
            a = mbi.MBIAnalysis(folder_a)
            a.get_sweep_pts()
            a.get_readout_results(name='adwindata')
            a.get_electron_ROC(ssro_calib_folder)
            # ax = a.plot_results_vs_sweepparam(ret='ax')

            X_RO_data = 2*(a.p0.reshape(-1)[:])-1
            X_RO_data_u = 2*(a.u_p0.reshape(-1)[:])

            a = mbi.MBIAnalysis(folder_b)
            a.get_sweep_pts()
            a.get_readout_results(name='adwindata')
            a.get_electron_ROC(ssro_calib_folder)
            # ax = a.plot_results_vs_sweepparam(ret='ax')

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

            Y_RO_data = 2*(a.p0.reshape(-1)[:])-1
            Y_RO_data_u = 2*(a.u_p0.reshape(-1)[:])

            RO_data     = (X_RO_data**2 + Y_RO_data**2)**0.5
            RO_data_u   = (1./(X_RO_data**2 + Y_RO_data**2)*(X_RO_data**2 * X_RO_data_u**2 + Y_RO_data**2 *Y_RO_data_u**2))**0.5
            
            x_ticks = a.sweep_pts.reshape(-1)
            x = range(len(RO_data))

            fig = a.default_fig(figsize=(7.5,5))
            ax2 = a.default_ax(fig)
            ax2.axhspan(0,RO_data[0],fill=False)
            ax2.axhspan(RO_data[0]-RO_data_u[0],RO_data[0]+RO_data_u[0],fill=False,ls='dotted')
            ax2.set_ylim(0,2*np.max(RO_data))
            ax2.set_xlim(x[1]-1, x[-1]+1)
            ax2.errorbar(x[1:],RO_data[1:],RO_data_u[1:])
            ax2.xaxis.set_ticks( x[1:] )
            ax2.set_xticklabels(x_ticks, rotation=90)
def BarPlotTomo(timestamp = None, measurement_name = ['adwindata'],folder_name ='Tomo',
		ssro_calib_timestamp =None, save = True,
		plot_fit = True) :
	'''
	Function that makes a bar plot with errorbars of MBI type data 
	'''
	if timestamp == None:
	    timestamp, folder   = toolbox.latest_data(folder_name,return_timestamp =True)
	else: 
	    folder = toolbox.data_from_time(timestamp) 

	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'

	a = mbi.MBIAnalysis(folder)
	a.get_sweep_pts()
	a.get_readout_results(name='adwindata')
	a.get_electron_ROC(ssro_calib_folder)

	x_labels = a.sweep_pts.reshape(-1)
	y= ((a.p0.reshape(-1))-0.5)*2
	x = range(len(y)) 
	y_err = 2*a.u_p0.reshape(-1)

	if plot_fit ==True: 
		fig,ax = plt.subplots() 
		rects = ax.bar(x,y,yerr=y_err,align ='center',ecolor = 'k' )
		ax.set_xticks(x)
		# ax.title = timestamp
		# print x_labels
		ax.set_xticklabels(x_labels.tolist())
		ax.set_ylim(-1.1,1.1)
		ax.set_title(str(folder)+'/'+str(timestamp))
		# ax.grid()
		ax.hlines([-1,0,1],x[0]-1,x[-1]+1,linestyles='dotted')


			# print values on bar plot
	def autolabel(rects):
	    for ii,rect in enumerate(rects):
	        height = rect.get_height()
	        plt.text(rect.get_x()+rect.get_width()/2., 1.02*height, str(round(y[ii],2)) +'('+ str(int(round(y_err[ii]*100))) +')',
	            ha='center', va='bottom')
	autolabel(rects)

	if save and ax != None:
		try:
		    fig.savefig(
		        os.path.join(folder,'tomo.png'))
		except:
		    print 'Figure has not been saved.'
示例#17
0
def get_pos_neg_data(a,
                     adwindata_str='',
                     ro_array=['positive', 'negative'],
                     **kw):
    '''
    Input: a : a data object of the class MBIAnalysis
    averages positive and negative data
    returns the sweep points, measured contrast and uncertainty
    '''

    ### get SSRO
    ssro_calib_folder = kw.pop('ssro_calib_folder', None)
    if ssro_calib_folder is None:
        use_preceding_ssro_calib = kw.pop('use_preceding_ssro_calib', False)
        if use_preceding_ssro_calib:
            kw['older_than'] = a.timestamp.replace('/', '')
            ssro_calib_folder = toolbox.latest_data('SSROCalib', **kw)
        else:
            ssro_calib_timestamp = kw.pop('ssro_calib_timestamp', None)

            if ssro_calib_timestamp == None:
                ssro_calib_folder = toolbox.latest_data(
                    'SSROCalib', **kw)  # , older_than = older_than)
            else:
                ssro_dstmp, ssro_tstmp = toolbox.verify_timestamp(
                    ssro_calib_timestamp)
                ssro_calib_folder = toolbox.data_from_time(
                    ssro_calib_timestamp)

    # if adwindata_str == '':
    #   return

    ##acquire pos_neg data
    for i, ro in enumerate(ro_array):
        a.get_sweep_pts()
        a.get_readout_results(name=adwindata_str + ro,
                              CR_after_check=CR_after_check,
                              **kw)
        a.get_electron_ROC(ssro_calib_folder, **kw)

        x_labels = a.sweep_pts
        if i == 0:
            res = ((a.p0.reshape(-1)) - 0.5) * 2
            res_u = 2 * a.u_p0.reshape(-1)

        else:
            y = ((a.p0.reshape(-1)) - 0.5) * 2  # Contrast
            y_u = 2 * a.u_p0.reshape(-1)  # contrast
            res = [y0 / 2 - y[ii] / 2 for ii, y0 in enumerate(res)]
            res_u = [
                np.sqrt(y0**2 + y_u[ii]**2) / 2 for ii, y0 in enumerate(res_u)
            ]

    return np.array(x_labels), np.array(res), np.array(res_u)
示例#18
0
def get_temperature(older_than, newer_than):

    x = np.array([])
    y = np.array([])

    while toolbox.latest_data(contains='temp_monitor',
                              older_than=older_than,
                              newer_than=newer_than,
                              raise_exc=False) != False:
        ## Find the data folder
        timestamp, folder = toolbox.latest_data(contains='temp_monitor',
                                                older_than=older_than,
                                                newer_than=newer_than,
                                                return_timestamp=True)

        ## convert timestamp to Epoch time (absolute time)
        Time_temp1 = datetime.datetime(int(timestamp[:4]), int(timestamp[4:6]),
                                       int(timestamp[6:8]),
                                       int(timestamp[8:10]),
                                       int(timestamp[10:12]),
                                       int(timestamp[12:14]), 0)
        Time_temp1 = datetime.datetime.timetuple(Time_temp1)
        Epoch_timestamp = calendar.timegm(Time_temp1)  # in seconds

        ## get the data
        filename = toolbox.measurement_filename(folder, ext='dat')
        data = np.loadtxt(filename, skiprows=16)

        # convert time data to Epoch time
        time_data = data[:, 0] * 3600 + Epoch_timestamp
        temperature_data = (data[:, 1] - 100) / 0.385

        # Filter out fluke measurements
        indices_flukes = [i for i, j in enumerate(temperature_data) if j < 10]
        time_data = np.delete(time_data, indices_flukes)
        temperature_data = np.delete(temperature_data, indices_flukes)

        x = np.concatenate(
            (x, time_data))  # Time after beginning of measurement [sec]
        y = np.concatenate((y, temperature_data))

        older_than = str(int(timestamp) - 1)

    ## Ordering in time:
    sort_indices = np.argsort(x)
    x = np.array(x)[sort_indices]
    y = np.array(y)[sort_indices]

    print 'folder = ' + folder

    return x, y, folder
def gate_sweep_analysis(carbon, **kw):
	"""
	gets data, plots it and prints the gate parameters for maximum bloch vector length.
	"""

	older_than = kw.pop('older_than',None)
	newer_than = kw.pop('newer_than',None)
	ssro_tstamp = kw.pop('ssro_tstamp',None)
	

	return_data = kw.pop('return_data',False)
	plot_fidelity = kw.pop('plot_fidelity',False)
	gate_time = kw.pop('gate_time',False)
	line_fidelity = kw.pop('line_fidelity',False)

	#finding how many taus there are: nr. folders/nr. of parts
	search_string = 'Sweep_carbon_Gate__C'+str(carbon)+ '_positive_tau'
	entire_folder_list = toolbox.latest_data(contains = search_string, older_than=older_than, newer_than=newer_than, return_all = True)[::-1]
	search_string += '0'
	nr_of_parts = len(toolbox.latest_data(contains = search_string, older_than=older_than, newer_than=newer_than, return_all = True)[::-1])
	nr_of_taus = len(entire_folder_list)/nr_of_parts
	print nr_of_parts
	print nr_of_taus
	tau_nrs 	= kw.pop('tau_nrs', range(nr_of_taus))

	for t in tau_nrs:			
		gates,x,y,x_u,y_u,folder_pos, gate_values = get_raw_data_all_parts(carbon,older_than = older_than,
			newer_than = newer_than, ssro_tstamp = ssro_tstamp, tau_nr = t, **kw)
		
		b,b_u = get_bloch_length(x,y,x_u,y_u)

		best_b = np.amax(b)
		best_b_ind = np.argmax(b)

		print 'best gate configuration at: ', gates[best_b_ind]
		print 'bloch vector length: ', best_b

		if plot_fidelity:
			bar_plot_fidelity(gates,gate_values,b,b_u)

		if gate_time:
			plot_gate_time([gates],[gate_values],[b],[b_u])

		if line_fidelity:
			line_plot_fidelity([gates],gate_values,[b],[b_u])

		if return_data:
			return gates,gate_values,b,b_u
			print 'data returned'

	print 'Analysis complete, have a nice day!'
示例#20
0
def Zeno_2Q_proc_fidelity_decay(timestamp_start=None,
									timestamp_stop=None,
									folder_name='Zeno',plot_results=True):
	"""
	Plots the process fidelity for a 2-qubit state as a function of time
	"""
	state_list=['X','mX','Y','mY','Z','mZ']

	evo_time_arr=[]
	fid_arr=[]
	fid_u_arr=[]

	#get individual state fidelities
	for state in state_list:
		evo_time,fid,fid_u=Zeno_2Q_state_fidelity_decay( timestamp_start=timestamp_start,
										timestamp_stop=timestamp_stop,
										state=state,plot_results=False)
		fid_arr.append(fid);fid_u_arr.append(fid_u)

	#calculate average state fidelity
	avg_fid=np.zeros(len(fid_arr[0]))
	avg_fid_u=np.zeros(len(fid_u_arr[0]))
	for i in range(len(fid_arr[0])):
		for ii in range(len(fid_arr)):
			avg_fid[i]= avg_fid[i] + fid_arr[ii][i]/len(fid_arr)
			avg_fid_u[i]= avg_fid_u[i] + fid_u_arr[ii][i]**2/36
		avg_fid_u[i]=avg_fid_u[i]**0.5


	if plot_results==True:
		fig=plt.figure()
		ax=plt.subplot()

		plt.errorbar(evo_time,avg_fid,avg_fid_u,color='blue',marker='o')
		plt.xlabel('Free evolution time (s)')
		plt.ylabel('2 qubit average fidelity')
		plt.title('Timestamps_start_'+str(timestamp_start)+'_stop_'+str(timestamp_stop))

		print toolbox.latest_data('Zeno',older_than=timestamp_start)
		plt.savefig(os.path.join(toolbox.latest_data('Zeno',older_than=timestamp_start),'ZenoTwoQAvgDecay.pdf'),format='pdf')
		plt.savefig(os.path.join(toolbox.latest_data('Zeno',older_than=timestamp_start),'ZenoTwoQAvgDecay.png'),format='png')

		fig=plt.figure()
		ax=plt.subplot()

		for i,state in enumerate(state_list):
			plt.errorbar(evo_time,fid_arr[i],fid_u_arr[i],marker='o', label=state)

		plt.xlabel('Free evolution time (s)')
		plt.ylabel('2 qubit state fidelity')
		plt.title('Timestamps_start_'+str(timestamp_start)+'_stop_'+str(timestamp_stop))
		plt.legend()

		print toolbox.latest_data('Zeno',older_than=timestamp_start)
		plt.savefig(os.path.join(toolbox.latest_data('Zeno',older_than=timestamp_start),'ZenoTwoQStateFidelities.pdf'),format='pdf')
		plt.savefig(os.path.join(toolbox.latest_data('Zeno',older_than=timestamp_start),'ZenoTwoQStateFidelities.png'),format='png')
		plt.close('all')

	else:
		return evo_time,avg_fid,avg_fid_u
示例#21
0
def load_calibration(timestamp=''):
    if (timestamp == ''):
        folder_name = toolbox.latest_data(contains='laser_calib')
    else:
        folder_name = toolbox.latest_data(contains=timestamp)

    all_files = [f for f in os.listdir(folder_name) if timestamp in f]
    file_name = [f for f in all_files if '.hdf5' in f]

    f = h5py.File(os.path.join(folder_name, file_name[0]), 'r')
    ls_grp = f['/calibration']
    V = ls_grp['V'].value
    freq = ls_grp['freq_GHz'].value
    return V, freq
示例#22
0
    def get_N_ROC(self, P_min1=1, u_P_min1=0, P_0=1, u_P_0=0,
            F0_RO_pulse=1, u_F0_RO_pulse=0,
            F1_RO_pulse=1, u_F1_RO_pulse=0,
            ssro_calib_folder=None):

        if ssro_calib_folder == None:
            ssro_calib_folder = toolbox.latest_data('SSRO')

        self.p0 = np.zeros(self.normalized_ssro.shape)
        self.u_p0 = np.zeros(self.normalized_ssro.shape)

        ro_durations = self.g.attrs['E_RO_durations']
        roc = Nspin_correction.NuclearSpinROC()
        roc.P_min1 = P_min1
        roc.u_P_min1 = u_P_min1
        roc.P_0 = P_0
        roc.u_P_0 = u_P_0

        roc.F0_RO_pulse = F0_RO_pulse
        roc.u_F0_RO_pulse = u_F0_RO_pulse
        roc.F1_RO_pulse = F1_RO_pulse
        roc.u_F1_RO_pulse = u_F1_RO_pulse

        for i in range(len(self.normalized_ssro[0])):
            roc.F0_ssro, roc.u_F0_ssro, roc.F1_ssro, roc.u_F1_ssro = \
                ssro.get_SSRO_calibration(ssro_calib_folder,
                        ro_durations[i])

            p0, u_p0 = roc.num_evaluation(self.normalized_ssro[:,i],
                    self.u_normalized_ssro[:,i])

            self.p0[:,i] = p0
            self.u_p0[:,i] = u_p0

        self.result_corrected = True
def plot_desr(do_save=False):
    folder=r'M:\tnw\ns\qt\Diamond\Projects\Magnetometry with adaptive measurements\Data\raw_data\20141014\130500_PulsarDarkESR_FM_Gretel_sil10'

    ssro_calib_folder = toolbox.latest_data(contains='AdwinSSRO_SSROCalibration')
    print ssro_calib_folder
    
    a = sequence.SequenceAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results('ssro')
    a.get_electron_ROC(ssro_calib_folder=ssro_calib_folder)

    x = a.sweep_pts # convert to MHz
    y = a.p0.reshape(-1)[:]
    # ax.plot(x,y)
    fig2 = plt.figure(figsize=(2,1.25))
    fig2.clf()
    ax2 = fig2.add_subplot(111) 
    #a.plot_result_vs_sweepparam(ret=True, name='ssro',ax=ax2)
    ax2.set_xlim([-3,3])
    ax2.set_ylim(0.5,1)
    ax2.yaxis.set_ticks([0.5,0.75,1])
    #ax2.xaxis.set_ticks([0.5,0.75,1])
    guess_x0= 2.845334
    guess_offset = 1
    guess_Nsplit = 2.18e-3
    guess_sigma = 0.0001

    guess_A_min1 = 0.4
    guess_A_plus1 = 0.25
    guess_A_0 = 0.3
 

    A_min1 = fit.Parameter(guess_A_min1, 'A_min1')
    A_plus1 = fit.Parameter(guess_A_plus1, 'A_plus1')
    A_0 = fit.Parameter(guess_A_0, 'A_0')
    o = fit.Parameter(guess_offset, 'o')
    x0 = fit.Parameter(guess_x0, 'x0')
    sigma = fit.Parameter(guess_sigma, 'sigma')
    Nsplit = fit.Parameter(guess_Nsplit, 'Nsplit')
    def fitfunc(x):

        return o() - np.abs(A_min1())*np.exp(-((x-(x0()-Nsplit()))/sigma())**2) \
                - np.abs(A_plus1())*np.exp(-((x-(x0()+Nsplit()))/sigma())**2) \
                - np.abs(A_0())*np.exp(-((x-x0())/sigma())**2) \
    

    print x
    fit_result = fit.fit1d(x, y, None, p0 = [A_min1, A_plus1, A_0, sigma, o, x0, Nsplit],
        fitfunc = fitfunc, do_print=True, ret=True, fixed=[])  
    print fitfunc(x)
    x_fit=np.linspace(a.sweep_pts[0],a.sweep_pts[-1],2001)
    y_fit=fit_result['fitfunc'](x_fit)
    
    
    ax2.plot(1e3*(x_fit-2.845334),y_fit,color='Grey',linewidth=2)
    ax2.errorbar(1e3*(a.sweep_pts-2.845334),a.p0,yerr=a.u_p0,color=colors[3],fmt='o')
    ax2.set_ylabel('P($m_s =0$)')
    ax2.set_xlabel('Pulse detuning (MHz)')
    if do_save:
        fig2.savefig(r'M:\tnw\ns\qt\Diamond\Projects\Magnetometry with adaptive measurements\Data\analyzed data\desr.pdf', bbox_inches='tight')
示例#24
0
文件: mbi.py 项目: zaguros/analysis
    def get_N_ROC(self, P_min1=1, u_P_min1=0, P_0=1, u_P_0=0,
            F0_RO_pulse=1, u_F0_RO_pulse=0,
            F1_RO_pulse=1, u_F1_RO_pulse=0,
            ssro_calib_folder=None):

        if ssro_calib_folder == None:
            ssro_calib_folder = toolbox.latest_data('SSRO')

        self.p0 = np.zeros(self.normalized_ssro.shape)
        self.u_p0 = np.zeros(self.normalized_ssro.shape)

        ro_durations = self.g.attrs['E_RO_durations']
        roc = Nspin_correction.NuclearSpinROC()
        roc.P_min1 = P_min1
        roc.u_P_min1 = u_P_min1
        roc.P_0 = P_0
        roc.u_P_0 = u_P_0

        roc.F0_RO_pulse = F0_RO_pulse
        roc.u_F0_RO_pulse = u_F0_RO_pulse
        roc.F1_RO_pulse = F1_RO_pulse
        roc.u_F1_RO_pulse = u_F1_RO_pulse

        for i in range(len(self.normalized_ssro[0])):
            roc.F0_ssro, roc.u_F0_ssro, roc.F1_ssro, roc.u_F1_ssro = \
                ssro.get_SSRO_calibration(ssro_calib_folder,
                        ro_durations[i])

            p0, u_p0 = roc.num_evaluation(self.normalized_ssro[:,i],
                    self.u_normalized_ssro[:,i])

            self.p0[:,i] = p0
            self.u_p0[:,i] = u_p0

        self.result_corrected = True
示例#25
0
def plot_single(contains='', ind=0, fit=False, plot_range=None, **kw):

    title = kw.pop('title', None)

    folder = toolbox.latest_data(contains)

    filename = toolbox.measurement_filename(folder, ext='dat')

    V, f, c, i, st = np.loadtxt(filename, unpack=True)

    fig = plt.figure()
    ax = plt.subplot(111)

    fltr = i == ind  #(dd[:,2]<(y+0.05)) & (dd[:,2]>(j-0.05)) #
    xx = f[np.where(fltr)]
    zz = c[np.where(fltr)]

    ax.plot(xx, zz)

    if fit:
        X = np.arange(np.min(xx), np.max(xx), 0.005)
        fitfunc = fit_laserscan(xx, zz)
        ax.plot(X, fitfunc['fitfunc'](X))

    if plot_range != None:
        ax.set_xlim(plot_range)

    ax.set_ylabel('Counts')
    ax.set_xlabel('Laser frequency [GHz]')

    if title != None:
        plt.title(title + ' ' + os.path.split(filename)[1])
    else:
        plt.title(os.path.split(filename)[1])
示例#26
0
def fast_ssro_calib(folder='',
                    name='ssro',
                    cr=True,
                    RO_length_ns=3500,
                    plot_sweep_index='max'):
    print folder
    if folder == '':
        folder = toolbox.latest_data('FastSSRO')
    a = FastSSROAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name)
    if cr:
        a.get_cr_results(name)
        plt.close('all')

    a.get_sweep_idxs(noof_syncs_per_sweep_pt=1)
    a.get_fastssro_results(channel=0, pq_binsize_ns=1.0, hist_binsize_ns=100)
    swp_idx = a.plot_fidelity_cpsh_vs_sweep(RO_length_ns=RO_length_ns,
                                            ret='max_sweep_index')
    if plot_sweep_index != 'max':
        swp_idx = plot_sweep_index
    a.ssro_plots(sweep_index=swp_idx,
                 RO_length_ns=RO_length_ns,
                 plot_points=500)
    #a.plot_histogram(channel=0)
    a.finish()
def analyze_dark_esr(folder, ax=None, **kw):
    if ax == None:
        fig, ax = plt.subplots(1,1)
    ssro_calib_folder = toolbox.latest_data(contains='AdwinSSRO_SSROCalibration')

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

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

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


    fit_result = fit.fit1d(x, y, esr.fit_ESR_gauss, guess_offset,
            guess_amplitude, guess_width, guess_ctr,
            # (2, guess_splitN),
             #(2, guess_splitC),
            # (2, guess_splitB),
            #(3, guess_splitN),
            do_print=True, ret=True, fixed=[])
    
    plot.plot_fit1d(fit_result, np.linspace(min(x), max(x), 1000), ax=ax, plot_data=False, **kw)
       
    ax.set_xlabel('MW frq (GHz)')
    ax.set_ylabel(r'fidelity wrt. $|0\rangle$')
    ax.set_title(a.timestamp+'\n'+a.measurementstring)
    plt.savefig(os.path.join(folder, 'darkesr_analysis.png'),
            format='png')
    return fit_result
示例#28
0
def analyze_data(timestamp,
                 output=False):  #,	guess_frq = 1 / 20e9, 	guess_amp = 0.5):

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

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

    print folder

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

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

    # plt.ylim([0,0.052])
    x = a.sweep_pts
    y = a.p0

    if output:
        return folder, x, y
示例#29
0
def plot_debug_GHZ_data(plot=True, save = True,tomo_bases="ZZI",plot_single=True,extra_tag='',return_data=False):
    p = np.zeros([4,2])
    y = np.zeros([4,2])
    y_err = np.zeros([4,2])

    x_labels = ('1', '-1')
    data_labels = ['pp','pn','np','nn']

    for k,label in enumerate(data_labels):
        timestamp,folder = toolbox.latest_data(contains=extra_tag+'tomo'+tomo_bases+'_'+label,return_timestamp=True)
        print folder
        p[k],y[k],y_err[k] = get_debug_data(folder,timestamp,RO_correct=True,tomo_bases=tomo_bases)
        if plot_single:
            do_plot(folder,timestamp,'GHZ_debug_results',p[k],y[k],y_err[k],x_labels,range(len(y[k])),show_plot=False,tomo_bases=tomo_bases)
        try:
            oldest_timestamp
        except NameError:
            oldest_timestamp=timestamp
        oldest_timestamp=min(oldest_timestamp,timestamp)

    p_avg = np.mean(p, axis = 0)
    y_avg = np.mean(y, axis = 0)
    #y_err_avg = np.mean(y_err, axis = 0)
    y_err_avg = np.divide(np.sqrt(np.sum((y_err**2),axis=0)),len(data_labels))

    x = range(len(y_avg)) 

    do_plot(folder,timestamp,'GHZ_debug_results_all_orientations',p_avg,y_avg,y_err_avg,x_labels,x,tomo_bases=tomo_bases)

    if return_data == True:
        return(folder,oldest_timestamp,p_avg,y_avg,y_err_avg,title)
示例#30
0
def plot_debug_GHZ_data(show_plot=True, save = True,tomo_bases="ZZI",plot_single=True,extra_tag='',return_data=False,older_than=None):
    p = np.zeros([4,2])
    y = np.zeros([4,2])
    y_err = np.zeros([4,2])

    x_labels = ('1', '-1')
    data_labels = ['pp','pn','np','nn']

    for k,label in enumerate(data_labels):
        timestamp,folder = toolbox.latest_data(contains=extra_tag+'tomo_'+tomo_bases+'_'+label,return_timestamp=True,older_than=older_than)
        # print folder
        p[k],y[k],y_err[k] = get_debug_data(folder,timestamp,RO_correct=True,tomo_bases=tomo_bases)
        if plot_single:
            do_plot(folder,timestamp,'GHZ_debug_results',p[k],y[k],y_err[k],x_labels,range(len(y[k])),show_plot=False,tomo_bases=tomo_bases)
        try:
            oldest_timestamp
        except NameError:
            oldest_timestamp=timestamp
        oldest_timestamp=min(oldest_timestamp,timestamp)

    p_avg = np.mean(p, axis = 0)
    y_avg = np.mean(y, axis = 0)
    #y_err_avg = np.mean(y_err, axis = 0)
    y_err_avg = np.divide(np.sqrt(np.sum((y_err**2),axis=0)),len(data_labels))

    x = range(len(y_avg)) 
    if show_plot:
        do_plot(folder,timestamp,'GHZ_debug_results_all_orientations',p_avg,y_avg,y_err_avg,x_labels,x,tomo_bases=tomo_bases)

    if return_data == True:
        return(folder,oldest_timestamp,p_avg,y_avg,y_err_avg,title)
示例#31
0
def load_latest_dm_mirror_surf(folder=None):
    from analysis.lib.tools import toolbox as tb
    lf = tb.latest_data(contains='DM_sweep_curve', folder=folder)
    fn = tb.get_measurement_name_from_folder(lf)
    dn, tn = tb.get_date_time_string_from_folder(lf)
    qt.instruments['DM'].load_mirror_surf(
        os.path.join(lf, tn + '_' + fn + '_msurf.npz'))
def load_mult_dat_tag(tag,older_than, number_of_msmts, ssro_calib_folder='',start = 3.0, pts = 51, step_size = 10e-3):
   cum_pts = 0
   for kk in range(number_of_msmts):
       folder = toolbox.latest_data(contains = tag, older_than = older_than,folder = 'd:\measuring\data')
       a = mbi.MBIAnalysis(folder)
       a.get_sweep_pts()
       a.get_readout_results(name='measurement' + str(kk))
       a.get_electron_ROC(ssro_calib_folder=ssro_calib_folder)
       cum_pts += a.pts

       if kk == 0:
           cum_sweep_pts = np.linspace(start, start+(pts-1)*step_size,pts)
           cum_p0 = a.p0
           cum_u_p0 = a.u_p0
       else:
           cum_sweep_pts = np.concatenate((cum_sweep_pts, np.linspace(start+kk*(pts-1)*step_size, start+(pts-1)*step_size+kk*(pts-1)*step_size, 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

   return a, folder
def analyze_data(timestamp, output = False):   #,	guess_frq = 1 / 20e9, 	guess_amp = 0.5):

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

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

	print folder


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


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

	# plt.ylim([0,0.052])
	x = a.sweep_pts
	y = a.p0

	if output:
		return folder, x, y
示例#34
0
def analyse_delay_feedback_phase_error(contains='', name='ssro', **kw):
    if contains == '':
        contains = 'fb_delayline'

    ### acquire data
    f = toolbox.latest_data(contains, **kw)
    a = PurificationDelayFBAnalysis(f)

    x, y, y_u = a.get_phase_errors(name=name, **kw)

    label = kw.pop('label', None)

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

    plt.axhline(y=0.0)

    xlabel = a.g.attrs['sweep_name']
    ylabel = "phase error after feedback"

    plt.xlabel(xlabel)
    plt.ylabel(ylabel)

    if kw.get('ret_data', False):
        return x, y, y_u
示例#35
0
def get_CR_histos(
    contains='',
    timestamp=None,
):
    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        folder = toolbox.latest_data(contains)

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

    before, after = a.get_CR_before_after()

    fig = plt.figure()
    ax = plt.subplot()
    ax.hist(before,
            abs(max(before) - min(before) + 1),
            normed=True,
            label='before')
    ax.hist(after,
            abs(max(after) - min(after) + 1),
            normed=True,
            label='after')
    ax.set_title(a.default_plot_title)
    ax.set_xlabel('counts during CR check')
    ax.set_ylabel('probability')
    plt.legend()

    plt.show()
    plt.close('all')
示例#36
0
def phase_offset_after_LDE(contains='', **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 = 'phase_offset_after_LDE'

    # older_than = kw.get('older_than',None) automatically handled by kws
    ### acquire data
    f = toolbox.latest_data(contains, **kw)
    a = mbi.MBIAnalysis(f)
    print 'this is the timestamp ', get_tstamp_from_folder(f)

    ro_array = ['positive', 'negative']
    x, y, y_u = get_pos_neg_data(a, adwindata_str='', ro_array=ro_array, **kw)
    y = np.round(y, decimals=2)
    y_u = np.round(y_u, decimals=2)
    # print el,x,y,y_u ### for debugging

    data = [0, 0, 0]
    ### put output string together
    for jj, res, res_u in zip(range(3), y, y_u):
        data[jj] = cp.deepcopy(str(res) + " +/- " + str(res_u))

    row_format = "{:>18}" * (len(x))

    headline_format = "{:>18}" * len(x)
    print headline_format.format(*x)
    print "-------------------------------------------------------------------------"
    print row_format.format(*data)
示例#37
0
def get_data_timestamps(older_than, nr_of_repetitions, carbon = 'C1'):

    ### Initialize data lists
    data_types = [carbon+'_noInit', carbon+'_down', carbon+'_up',
                  '_down_'+carbon+'_neg', '_down_'+carbon+'_pos', '_up_'+carbon+'_neg', '_up_'+carbon+'_pos',
                  '_no_'+carbon+'_neg', '_no_'+carbon+'_pos']
    timestamps = {}
    folders    = {}

    for kk in range(len(data_types)):
        temp_time   = [0]*nr_of_repetitions
        temp_folder = [0]*nr_of_repetitions
        temp_older_than = older_than

        for ii in range(nr_of_repetitions):
            temp_time[ii], temp_folder[ii] = toolbox.latest_data(contains = data_types[kk], older_than = temp_older_than, return_timestamp = True)
            temp_older_than = temp_time[ii]

        if data_types[kk][0:5] == '_down':
            timestamps[data_types[kk][1:5]+data_types[kk][8:12]]  = temp_time
            folders[data_types[kk][1:5]+data_types[kk][8:12]]     = temp_folder
        elif data_types[kk][0:3] == '_up':
            timestamps[data_types[kk][1:3]+data_types[kk][6:10]]  = temp_time
            folders[data_types[kk][1:3]+data_types[kk][6:10]]     = temp_folder
        elif data_types[kk][0:3] == '_no':
            timestamps[data_types[kk][1:3]+data_types[kk][6:10]]  = temp_time
            folders[data_types[kk][1:3]+data_types[kk][6:10]]     = temp_folder
        else:
            timestamps[data_types[kk][3:]] = temp_time
            folders[data_types[kk][3:]]    = temp_folder

    return timestamps, folders
示例#38
0
def analyze_single_instance(label='adptv_estimation_det',
                            compare_to_simulations=True):

    f = toolbox.latest_data(contains=label)
    s = magnetometry.RamseySequence_Exp(folder=f)
    s.set_exp_pars(T2=96e-6, fid0=0.87, fid1=1 - .975)
    print f
    s.load_exp_data()
    s.CR_after_postselection()
    s.convert_to_dict()
    #print 'phases dict'
    #print s.phases_dict
    s.print_results()

    #B_dict, index_dict = s.B_vs_index()

    #beta, prob, err, mB, sB = s.mean_square_error(do_plot=True, save_plot=True)
    if compare_to_simulations:
        beta_sim, p_sim, ave_exp, err_sim, a, b = s.compare_to_simulations(
            show_plot=True, verbose=True, do_save=True, plot_log=True)
    else:
        beta_sim, p_sim, ave_exp, err_sim, a, b = s.mean_square_error(
            show_plot=True, save_plot=True, do_plot=True)

    #s.analyse_ramsey()
    return beta_sim, p_sim, ave_exp, err_sim, a, b
示例#39
0
def check_adwin_realtime_record_pk(label, newer_than=False):

    f, axarr = plt.subplots(2, sharex=True, figsize=(10, 10))
    for n in [1]:
        for m in [1, 2, 3, 4]:
            dir0, daydir, m_dirs = toolbox.latest_data(
                contains=label + '_test_pk_(n=' + str(n) + '_m=' + str(m) +
                ')',
                return_all=True,
                newer_than=newer_than)

            for i in m_dirs:
                f = os.path.join(dir0, daydir, i)
                exp = magnetometry.RamseySequence_Exp(folder=f)
                exp.load_exp_data()
                #exp.check_realtime_phases()
                x = np.arange(2**exp.N + 1)
                axarr[0].plot(exp.real_pk_adwin, ':k')
                axarr[1].plot(exp.imag_pk_adwin, ':k')
                axarr[0].plot(exp.real_pk_adwin,
                              'o',
                              label=str(n) + '_' + str(m))
                axarr[1].plot(exp.imag_pk_adwin,
                              'o',
                              label=str(n) + '_' + str(m))

    axarr[0].set_title('real part')
    axarr[1].set_title('imaginary part')
    plt.xlim([0, 17])
    plt.legend()
    plt.show()
def analyze_data(timestamp, output = False):   #,	guess_frq = 1 / 20e9, 	guess_amp = 0.5):

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

	print folder

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

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

	# plt.ylim([0,0.052])
	x = a.sweep_pts
	y = a.p0

	if output:
		return x, y, ax
	else:
		return ax
示例#41
0
def load_mult_dat(tau, number_of_msmts, N_steps=4,ssro_calib_folder=''):
  cum_pts = 0
  for kk in range(number_of_msmts):
    folder = toolbox.latest_data(contains=str(tau), older_than='140424')
    # print folder
    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='measurement'+ str(kk))
    a.get_electron_ROC(ssro_calib_folder=ssro_calib_folder)
    cum_pts += a.pts
       
    pts         = 11
    N_start    = (kk+0)     * (pts-1)*N_steps 
    N_end      = (kk+1+0) * (pts-1)*N_steps
    N_list     = np.linspace(N_start, N_end, pts)

    if kk == 0:
        cum_sweep_pts = np.linspace(N_start, N_end, 11)#a.sweep_pts
        cum_p0 = a.p0
        cum_u_p0 = a.u_p0
    else:
        cum_sweep_pts = np.concatenate((cum_sweep_pts, np.linspace(N_start,N_end,11)))
        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

  return a, folder
def fit_exp(x,
            y,
            guess_a,
            guess_A,
            guess_tau,
            fixed=[],
            show_fit=True,
            save=True,
            timestamp='',
            **kw):
    '''
	Fit single exponential to T1 data
	'''

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

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

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

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

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

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

    if save:
        plt.savefig(os.path.join(folder, 'Calibrate_Pi_analysis_fit.png'))
    return fit_result
def analyze_data(timestamp,
                 output=False):  #,	guess_frq = 1 / 20e9, 	guess_amp = 0.5):

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

    print folder

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

    # print a.p0

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

    # plt.ylim([0,0.052])
    x = a.sweep_pts
    y = a.p0

    if output:
        return x, y, ax
    else:
        return ax
示例#44
0
def fingerprint_loop(older_than=None,
                     newer_than=None,
                     contains='',
                     number=0,
                     filename='loop'):
    fig = figure(number, figsize=(10, 5))
    ax = fig.add_subplot(111)
    histdata_1521 = []
    histdata_1531 = []
    # ssro_calib_folders = ['d:\\measuring\\data\\20140504\\070533_AdwinSSRO_SSROCalibration_Hans_sil1']

    ## Data location ##
    while toolbox.latest_data(contains=contains,
                              older_than=older_than,
                              newer_than=newer_than,
                              raise_exc=False) != False:
        timestamp, folder = toolbox.latest_data(contains=contains,
                                                older_than=older_than,
                                                newer_than=newer_than,
                                                return_timestamp=True)
        ssro_calib_folder = toolbox.latest_data(
            contains='AdwinSSRO_SSROCalibration', older_than='20140502193810')
        ## Data location ##
        a = mbi.MBIAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        a.get_electron_ROC(ssro_calib_folder)

        # ############
        # ## Plotting ###
        # # ############
        #     print folder
        x = a.sweep_pts.reshape(-1)[:]
        y = a.p0.reshape(-1)[:]
        y_error = a.u_p0.reshape(-1)[:]
        # ax.errorbar(x,y,y_error)
        older_than = str(int(timestamp) - 1)

        idx_1521 = np.argmin(abs(x - 15.21))
        idx_1531 = np.argmin(abs(x - 15.31))

        if y[idx_1521] < 0.8:
            histdata_1521.append(y[idx_1521])
            histdata_1531.append(y[idx_1531])
            ax.errorbar(x, y, y_error)
        print y_error
示例#45
0
def analyze_nmr_single(timestamp = None,center_guess = False, ax=None, ret=None,min_dip_depth = 0.85 , **kw):

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


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

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

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



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

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

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

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

        return (f0-2.8)*1e3, u_f0*1e3
示例#46
0
def simple_plot(timestamp=None,
                measurement_name=['adwindata'],
                folder_name='CarbonPiCal',
                ssro_calib_timestamp=None,
                save=True,
                plot_fit=True):
    '''
	Function that makes a bar plot with errorbars of MBI type data 
	'''
    if timestamp == None:
        timestamp, folder = toolbox.latest_data(folder_name,
                                                return_timestamp=True)
    else:
        folder = toolbox.data_from_time(timestamp)

    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

    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC(ssro_calib_folder)

    x_labels = a.sweep_pts.reshape(-1)
    y = ((a.p0.reshape(-1)) - 0.5) * 2
    x = range(len(y))
    y_err = 2 * a.u_p0.reshape(-1)

    fig, ax = plt.subplots()
    rects = ax.errorbar(x, y, yerr=y_err)
    ax.set_xticks(x)
    ax.set_xticklabels(x_labels.tolist(), rotation=90)
    ax.set_ylim(-1.1, 1.1)
    ax.set_title(str(folder) + '/' + str(timestamp))
    ax.hlines([-1, 0, 1], x[0] - 1, x[-1] + 1, linestyles='dotted')

    if save and ax != None:
        try:
            fig.savefig(os.path.join(folder, 'simple_plot.png'))
        except:
            print 'Figure has not been saved.'
def analyse_Ramsey(folder='',
                   T2=3e3,
                   Ampl=-1. / 3,
                   detuning=3e-3,
                   hf_N=2.17e-3,
                   *arg):

    timestamp = kw.pop(timestamp, None)

    guess_tau = T2
    guess_a = 0.5
    guess_A = Ampl

    guess_hf_N = hf_N
    guess_det = detuning
    guess_hf_C = hf_C

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

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

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

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

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

    plt.savefig(os.path.join(folder, 'electronramsey_analysis.pdf'),
                format='pdf')
def Carbon_control_sweep_N_zoom(timestamp=None, measurement_name = ['adwindata'], 
            A = [0.5, 0.5],
            fitfunc_type = 'single', plot_fit = False, do_print = False, show_guess = True,
            yaxis = [-0.05,1.05]):
    ''' Function to analyze data for optimization of the number of pulses for a controlled C13 gate. 
    '''
    
    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        folder = toolbox.latest_data('Decoupling')

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

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

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

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

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

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

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

	ssro_calib_timestamp = kw.pop('ssro_calib_timestamp',None)
	older_than = kw.pop('older_than',None)

	data_dict = {
	'folders' : [],
	'sweep_pts': [],
	'res' : [],
	'res_u' : []
	}


	for ro in ['positive','negative']:
		search_string = ro+name
		data_dict['folders'].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
	for i,f in enumerate(data_dict['folders']):
		a = mbi.MBIAnalysis(f)
		a.get_sweep_pts()
		a.get_readout_results(name='adwindata')
		a.get_electron_ROC(ssro_calib_folder)

		

		x_labels = a.sweep_pts.reshape(-1)
		if i == 0:
			data_dict['res'] = ((a.p0.reshape(-1))-0.5)*2
			data_dict['res_u'] = 2*a.u_p0.reshape(-1)
		else:
			y = ((a.p0.reshape(-1))-0.5)*2
			y_u = 2*a.u_p0.reshape(-1)
			data_dict['res'] = [y0/2-y[ii]/2 for ii,y0 in enumerate(data_dict['res'])]
			data_dict['res_u'] = [np.sqrt(y0**2+y_u[ii]**2)/2 for ii,y0 in enumerate(data_dict['res_u'])]


	return x_labels,data_dict['res'],data_dict['res_u'],data_dict['folders'][0]
示例#50
0
def simple_plot(timestamp = None, measurement_name = ['adwindata'],folder_name ='CarbonPiCal',
		ssro_calib_timestamp =None, save = True,
		plot_fit = True) :
	'''
	Function that makes a bar plot with errorbars of MBI type data 
	'''
	if timestamp == None:
	    timestamp, folder   = toolbox.latest_data(folder_name,return_timestamp =True)
	else: 
	    folder = toolbox.data_from_time(timestamp) 

	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


	a = mbi.MBIAnalysis(folder)
	a.get_sweep_pts()
	a.get_readout_results(name='adwindata')
	a.get_electron_ROC(ssro_calib_folder)

	x_labels = a.sweep_pts.reshape(-1)
	y= ((a.p0.reshape(-1))-0.5)*2
	x = range(len(y)) 
	y_err = 2*a.u_p0.reshape(-1)

	fig,ax = plt.subplots() 
	rects = ax.errorbar(x,y,yerr=y_err)
	ax.set_xticks(x)
	ax.set_xticklabels(x_labels.tolist())
	ax.set_ylim(-1.1,1.1)
	ax.set_title(str(folder)+'/'+str(timestamp))
	ax.hlines([-1,0,1],x[0]-1,x[-1]+1,linestyles='dotted')

	if save and ax != None:
		try:
		    fig.savefig(
		        os.path.join(folder,'simple_plot.png'))
		except:
		    print 'Figure has not been saved.'
def single_repetition_evolution(label='adptv_estimation_det'):
	f = toolbox.latest_data(contains=label)
	s = magnetometry.RamseySequence_Exp (folder = f)
	s.set_exp_pars (T2=96e-6, fid0=0.87, fid1=1-.975)
	#print f
	s.load_exp_data()
	s.convert_to_dict()
	s.CR_after_postselection()
	#beta, prob = s.analysis_dict (phase = curr_phase, msmnt_results = curr_msmnt, times = np.rint(self.msmnt_times))
	return s
示例#52
0
def get_lt_fps(fps_bs, lt3_folder, lt4_folder):
    max_measurement_delay = datetime.timedelta(minutes=2,seconds=10)
    fps_lt3 = []
    fps_lt4 = []
    for fp_bs in fps_bs:
        if not 'Bell_BS' in fp_bs:
            raise Exception('File'+ fp_bs+' not a BS file?')
        bs_m_folder = os.path.split(fp_bs)[0] 
        bs_m_time = tb.get_datetime_from_folder(bs_m_folder)
        bs_m_name = tb.get_measurement_name_from_folder(bs_m_folder)[8:]
        min_timestamp = tb.timestamp_from_datetime(bs_m_time - max_measurement_delay)
        max_timestamp = tb.timestamp_from_datetime(bs_m_time + max_measurement_delay)
        
        lt3_m_folder = tb.latest_data(contains = bs_m_name, folder = lt3_folder, older_than = max_timestamp, newer_than = min_timestamp)
        fps_lt3.append(tb.get_msmt_fp(lt3_m_folder))
        lt4_m_folder = tb.latest_data(contains = bs_m_name, folder = lt4_folder, older_than = max_timestamp, newer_than = min_timestamp)
        fps_lt4.append(tb.get_msmt_fp(lt4_m_folder))

    return fps_lt3, fps_lt4
def analyse_Rabi(guess_frq = 2., guess_amp = 0.2, guess_of = 0.1, **kw) :

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

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


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

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

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

    x = a.sweep_pts
    y = a.p0

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

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

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

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

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

    return fit_result
示例#54
0
    def get_magnetometry_phase_calibration(self, name='',ssro_calib_folder=''):

        self.result_corrected = False
        adwingrp = self.adwingrp(name)        
        self.reps = adwingrp['completed_reps'].value-1
        RO_clicks = adwingrp['RO_data'].value
        phase = adwingrp['set_phase'].value
        times=self.g.attrs['ramsey_time']

        phase_values = np.unique(phase)
        self.ssro_results = np.zeros(len(phase_values))

        
        for j in phase_values:
            self.ssro_results [np.min(np.where(phase==j))] = np.sum(RO_clicks[np.where(phase==j)])
            
        if len(self.ssro_results)==1:
            self.sweep_pts = self.g.attrs['sweep_pts']
            phase=np.array(list(np.arange(len(self.sweep_pts)))*int((self.reps+1)/float(len(self.sweep_pts))))
       
            phase_values = np.unique(phase)
            self.ssro_results = np.zeros(len(phase_values))
            
            for j in phase_values:

                self.ssro_results [np.min(np.where(phase==j))] = np.sum(RO_clicks[np.where(phase==j)])

        #self.sweep_pts = times
        #print 'len phases',len(phases)
        #print phases
        #print phase_values

        self.normalized_ssro = self.ssro_results*len(self.ssro_results)/(float(self.reps))
        self.u_normalized_ssro = (self.normalized_ssro*(1.-self.normalized_ssro)/(float(self.reps)))**0.5  #this is quite ugly, maybe replace?

        
        if ssro_calib_folder == '':
                ssro_calib_folder = toolbox.latest_data('SSROCalibration')
                print ssro_calib_folder
        self.p0 = self.normalized_ssro
        self.u_p0 = self.u_normalized_ssro
        
        ro_duration = self.g.attrs['SSRO_duration']
        roc = error.SingleQubitROC()
        roc.F0, roc.u_F0, roc.F1, roc.u_F1 = \
            ssro.get_SSRO_calibration(ssro_calib_folder, 
                    ro_duration)
        p0, u_p0 = roc.num_eval(self.normalized_ssro,
                self.u_normalized_ssro)
            
        self.p0 = p0
        self.u_p0 = u_p0
        
        self.result_corrected = True
        return self.p0,self.u_p0
示例#55
0
def get_3mmt_data(folder,folder_timestamp,RO_correct=True,ssro_calib_timestamp=None,tomo_bases='XXX',get_title=False,return_orientations=False):
    a = CP.ConditionalParityAnalysis(folder)
    #a.get_sweep_pts()
    a.get_readout_results(name='adwindata', post_select_QEC = True,orientation_correct=True)
    orientations = a.orientations
    orientation_c = a.orientations[2]
    if orientation_c == 'negative':
        multiply_by = -1
    else:
        multiply_by = 1
    #print(a.orientations,multiply_by)

    if RO_correct == True:
        if ssro_calib_timestamp == None: 
            ssro_calib_folder = toolbox.latest_data('SSRO',older_than=folder_timestamp)
            analysis_file=os.path.join(ssro_calib_folder,'analysis.hdf5')
            if not os.path.exists(analysis_file):
                ssro.ssrocalib(ssro_calib_folder)
        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'#GHZ_'+tomo_bases
        
        #print ssro_calib_folder
        a.get_electron_ROC(ssro_calib_folder = ssro_calib_folder, post_select_QEC = True)

        #take the [0,0] part of the arrays right now; no sweep_pts
        p0_00,u_p0_00 = multiply_by*(a.p0_00[0,0]-0.5)*2,(2*a.u_p0_00[0,0]) 
        p0_01,u_p0_01 = multiply_by*(a.p0_01[0,0]-0.5)*2,(2*a.u_p0_01[0,0])
        p0_10,u_p0_10 = multiply_by*(a.p0_10[0,0]-0.5)*2,(2*a.u_p0_10[0,0])
        p0_11,u_p0_11 = multiply_by*(a.p0_11[0,0]-0.5)*2,(2*a.u_p0_11[0,0])

    else:
        p0_00,u_p0_00 = multiply_by*(a.normalized_ssro_00[0,0]-0.5)*2,(2*a.u_normalized_ssro_00[0,0])
        p0_01,u_p0_01 = multiply_by*(a.normalized_ssro_01[0,0]-0.5)*2,(2*a.u_normalized_ssro_01[0,0])
        p0_10,u_p0_10 = multiply_by*(a.normalized_ssro_10[0,0]-0.5)*2,(2*a.u_normalized_ssro_10[0,0])
        p0_11,u_p0_11 = multiply_by*(a.normalized_ssro_11[0,0]-0.5)*2,(2*a.u_normalized_ssro_11[0,0])

    if get_title:
        a_list_name = "".join(aa for aa in a.a_list)
        b_list_name = "".join(aa for aa in a.b_list)
        c_list_name = "".join(aa for aa in a.c_list)
        title = a_list_name+' '+b_list_name+' '+c_list_name
    else:
        title=''

    p = (a.p00[0,0],a.p01[0,0],a.p10[0,0],a.p11[0,0])
    y = (p0_00,p0_01,p0_10,p0_11)
    y_avg = np.mean(y, axis=0)
    #print y_avg
    y_err = (u_p0_00,u_p0_01,u_p0_10,u_p0_11)

    if return_orientations:
        return(p,y,y_err,title,orientations)

    return(p,y,y_err,title)
示例#56
0
def plot_singlerun_GHZ_data(timestamp=None, plot=True, save = True):
    if timestamp == None:
        timestamp, folder   = toolbox.latest_data(folder_name,return_timestamp =True)
    else: 
        folder = toolbox.data_from_time(timestamp) 

    p,y,y_err = get_data(folder,timestamp,RO_correct=True)

    x_labels = ('1,1,1', '1,1,-1' , '1,-1,1', '1,-1,-1','-1,1,1', '-1,1,-1' , '-1,-1,1', '-1,-1,-1')
    x = range(len(y)) 

    do_plot(folder,timestamp,'GHZ_results',p,y,y_err,x_labels,x)
示例#57
0
def analyse_pulse_calibration(angle='_pi_1'):
    ### parameters
    timestamp = None
    if angle == '_pi_1':
        guess_x0 = 0.38
    elif angle == '_pi_o':
        guess_x0 = 0.24
    elif angle == '_pi_p1':
        guess_x0 = 0.67   
        angle='_pi_1'     
    else:
        guess_x0=0.5
    msmt_type = 'mbi'


    guess_of = 0.973
    guess_a = 0.

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

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

        x = a.sweep_pts
        y = a.p0

    elif msmt_type == 'mbi':
        a = mbi.MBIAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        a.get_electron_ROC()
        ax = a.plot_results_vs_sweepparam(name='adwindata', ret='ax')
        ax.set_ylim(-0.1,1)

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

    else:
        raise Exception('Unknown msmt type')

    res = funcs.calibrate_pulse_amplitude(x, y, ax, guess_x0, guess_of, guess_a)
    plt.savefig(os.path.join(folder, 'pulse_calibration.pdf'),
            format='pdf')
    plt.savefig(os.path.join(folder, 'pulse_calibration.png'),
            format='png')
def get_data(name_contains, input_timestamp = None, input_id = None, ssro_calib_folder = ''):
	'''
	Retrieves msmt data for a SINGLE loop in SimpleDecoupling, i.e. 'tot' = 1.
	Inputs: 
	- String containing an element of the file name
	- (Optional): timestamp. Default is latest data 

	Returns:
	- 'x': array with sweeped parameter values
	- 'y': array with msmt outcomes (corrected for SSRO fidelity)
	- 'yerr': array with msmt errors
	- 'folder': path of data file
	- (optional)'timestamp': timestamp corresponding to data. Returned by default unless a timestamp is specified
	- (optional) 'ssro_calib_folder': path of the corresponding ssro calibration file. If '', latest calibration is used 
	'''

	if input_timestamp != None:
		folder = toolbox.data_from_time(input_timestamp)
	else:
		timestamp, folder = toolbox.latest_data(name_contains, return_timestamp = True)
	a = mbi.MBIAnalysis(folder)

	#print 'DATA FOLDER & SSRO FOLDER:'
	#print folder

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


	# Retrieve data & reshape
	if input_id != None:
		name = 'measurement'+ str(input_id)
		adwingrp = a.adwingrp(name = name)
		a.adgrp = adwingrp
		sweep = a.adgrp.attrs['sweep_pts']
		x = sweep.reshape(-1)[:]
		a.get_readout_results(name = name)
		a.get_electron_ROC(ssro_calib_folder = ssro_calib_folder)
		y = a.p0.reshape(-1)[:]
		yerr = a.u_p0.reshape(-1)[:]
	else:
		a.get_sweep_pts()
		a.get_readout_results(name='measurement0')
		a.get_electron_ROC(ssro_calib_folder = ssro_calib_folder)
		x = a.sweep_pts.reshape(-1)[:]
		y = a.p0.reshape(-1)[:]
		yerr = a.u_p0.reshape(-1)[:]


	if input_timestamp != None: 
		return x, y, yerr, folder
	else:
		return x, y, yerr, folder, timestamp