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
Exemple #2
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
Exemple #3
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)
Exemple #4
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)
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.'
Exemple #6
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)
Exemple #7
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 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]
Exemple #9
0
def Zeno_get_2Q_values(timestamp=None,
                       folder=None,
                       folder_name='Zeno',
                       measurement_name=['adwindata'],
                       ssro_calib_timestamp=None):
    """
	Returns the relevant RO 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'

    if 'Evotime' in folder:
        c1ms0 = float(
            folder[114:])  ##assign the frequency from the folder name
    else:
        c1ms0 = float(folder[-8:])
    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, c1ms0, y, y_err
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 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]
Exemple #12
0
def get_debug_data(folder,folder_timestamp,RO_correct=True,ssro_calib_timestamp=None,tomo_bases="XXX"):
    a = CP.ConditionalParityAnalysis(folder)
    #a.get_sweep_pts()
    a.get_readout_results(name='adwindata', post_select = True, orientation_correct=True)
    orientation_b = a.orientations[1]
    if orientation_b == '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)
            if not os.path.exists(os.path.join(ssro_calib_folder,'analysis.hdf5')):
                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)

        #take the [0,0] part of the arrays right now; no sweep_pts
        p0_0,u_p0_0 = multiply_by*(a.p0_0[0,0]-0.5)*2,(2*a.u_p0_0[0,0]) 
        p0_1,u_p0_1 = multiply_by*(a.p0_1[0,0]-0.5)*2,(2*a.u_p0_1[0,0])

    else:
        p0_0,u_p0_0 = multiply_by*(a.normalized_ssro_0[0,0]-0.5)*2,(2*a.u_normalized_ssro_0[0,0])
        p0_1,u_p0_1 = multiply_by*(a.normalized_ssro_1[0,0]-0.5)*2,(2*a.u_normalized_ssro_1[0,0])
  
    p = (a.p0,a.p1)
    y = (p0_0,p0_1)
    y_avg = np.mean(y, axis=0)
    #print y_avg
    y_err = (u_p0_0,u_p0_1)

    return(p,y,y_err)
Exemple #13
0
def get_debug_data(folder,folder_timestamp,RO_correct=True,ssro_calib_timestamp=None,tomo_bases="XXX"):
    a = CP.ConditionalParityAnalysis(folder)
    #a.get_sweep_pts()
    a.get_readout_results(name='adwindata', post_select = True, orientation_correct=True)
    orientation_b = a.orientations[1]
    if orientation_b == '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)
            if not os.path.exists(os.path.join(ssro_calib_folder,'analysis.hdf5')):
                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)

        #take the [0,0] part of the arrays right now; no sweep_pts
        p0_0,u_p0_0 = multiply_by*(a.p0_0[0,0]-0.5)*2,(2*a.u_p0_0[0,0]) 
        p0_1,u_p0_1 = multiply_by*(a.p0_1[0,0]-0.5)*2,(2*a.u_p0_1[0,0])

    else:
        p0_0,u_p0_0 = multiply_by*(a.normalized_ssro_0[0,0]-0.5)*2,(2*a.u_normalized_ssro_0[0,0])
        p0_1,u_p0_1 = multiply_by*(a.normalized_ssro_1[0,0]-0.5)*2,(2*a.u_normalized_ssro_1[0,0])
  
    p = (a.p0,a.p1)
    y = (p0_0,p0_1)
    y_avg = np.mean(y, axis=0)
    #print y_avg
    y_err = (u_p0_0,u_p0_1)

    return(p,y,y_err)
def Carbon_phase_sweep(timestamp=None, measurement_name = ['adwindata'], ssro_calib_timestamp =None,
        frequency = 1, offset = 0.5, amplitude = 0.5,  phase =0, 
        fixed = [], 
        plot_fit = False, do_print = False, show_guess = True):
    ''' 
    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
    List of parameters (order important for 'fixed') 
    [freq, offset, Amplitude, phase] 
    '''

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

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


    fit_results = []
    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(ssro_calib_folder)
        ax = a.plot_results_vs_sweepparam(ret='ax')

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

        ax.plot(x,y)
        p0, fitfunc, fitfunc_str = common.fit_cos(frequency, offset, amplitude ,phase )



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

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

        print 'fitfunction: '+fitfunc_str

        ## plot data and fit as function of total time
        if plot_fit == True:
            plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax, plot_data=False)

        fit_results.append(fit_result)

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

    return fit_results
Exemple #15
0
def Carbon_T1(timestamp=None,
              measurement_name='adwindata',
              ssro_calib_timestamp=None,
              offset=0.5,
              x0=0,
              amplitude=0.5,
              decay_constant=200,
              exponent=2,
              plot_fit=False,
              do_print=False,
              fixed=[2],
              show_guess=True):
    ''' 
    Inputs:
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    List of parameters (order important for 'fixed') 
    offset, amplitude, decay_constant,exponent,frequency ,phase 
    '''
    figsize = (6, 4.7)

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

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

    fit_results = []

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

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

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

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

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

    ## plot data and fit as function of total time
    if plot_fit == True:
        plot.plot_fit1d(fit_result,
                        np.linspace(x[0], x[-1], 1001),
                        ax=ax,
                        plot_data=False)

    fit_results.append(fit_result)

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

    return fit_results
def Carbon_T1_analysis(measurement_name = ['adwindata'], ssro_calib_timestamp =None, 
            offset = 0.5, 
            amplitude = 0.5,  
            decay_constant = 0.1, 
            x0=0,
            exponent = 1, 
            Addressed_carbon=1,
            el_RO='positive',
            plot_fit = True, do_print = True, show_guess = False):
    ''' 
    Function to gather and analyze T1 measurements of a specific carbon.

    Addressed_carbon: selects the used timestamps and therefore the analyzed carbon

    measurement_name: list of measurement names

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

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



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


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

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


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

    cum_pts = 0

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

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

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


    ## accumulate data with negative RO


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


    ## generate plot of the raw data ##


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


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


    ## fit to a general exponential##

    fit_results = []

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

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

    #plot the initial guess

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

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

    ## plot data and fit as function of total time

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

    fit_results.append(fit_result)

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

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


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


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


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

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


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

    cum_pts = 0

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

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

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


    ## accumulate data with negative RO


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


    ## generate plot of the raw data ##


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


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

    fit_results = []

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

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

    #plot the initial guess

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

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

    ## plot data and fit as function of total time

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

    fit_results.append(fit_result)

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

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


    plt.savefig(os.path.join(folder, filename+'.pdf'),
    format='pdf')
    plt.savefig(os.path.join(folder, filename+'.png'),
    format='png')
def simple_plot_contrast(timestamps = [None,None], tag = '', measurement_name = ['adwindata'],folder_name ='Tomo',
        ssro_calib_timestamp =None, save = True,
        do_plot = True, return_data = False,
        guess_frq = 1/4000.,
        guess_amp = 1.5,
        guess_k = 0.,
        guess_phi = 0.,
        guess_o = 0.3):

    ### SSRO calibration
    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'

    if timestamps[0] == None: 
        folder_a = toolbox.latest_data(contains='positive' + tag)
        folder_b = toolbox.latest_data(contains='negative' + tag)
    elif len(timestamps)==1:        
        folder_b = toolbox.data_from_time(timestamps[0])      
        print folder_b
        folder_a = toolbox.latest_data(contains = 'pos', older_than = timestamps[0])   
        print folder_a
    else:
        folder_a = toolbox.data_from_time(timestamps[0])      
        folder_b = toolbox.data_from_time(timestamps[1])           
    
    a = mbi.MBIAnalysis(folder_a)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC(ssro_calib_folder)
    y_a= ((a.p0.reshape(-1)[:])-0.5)*2
    y_err_a = 2*a.u_p0.reshape(-1)[:] 


    b = mbi.MBIAnalysis(folder_b)
    b.get_sweep_pts()
    b.get_readout_results(name='adwindata')
    b.get_electron_ROC(ssro_calib_folder)
    y_b= ((b.p0.reshape(-1)[:])-0.5)*2
    y_err_b = 2*b.u_p0.reshape(-1)[:] 

    x = a.sweep_pts.reshape(-1)[:]
    # x = range(len(y_a)) 
    # ax = a.plot_results_vs_sweepparam(ret='ax', name = 'adwindata' )


    
    ### Combine data
    y = (y_a - y_b)/2.
    y_err =  1./2*(y_err_a**2 + y_err_b**2)**0.5 

    if x[-1] < x[0]:
        x = x[::-1]
        y = y[::-1]

    fig,ax = plt.subplots()

    o = fit.Parameter(guess_o, '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 = [A,o,f,phi]
    fitfunc_str = ''

    ax.errorbar(x,y,yerr = y_err, marker = 'o',ls = '')

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

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

    ax.set_title(folder_a)

    
    

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

    for i, y in enumerate(abs(y_fit)):
        if y == min(abs(y_fit)):
            x_opt = i


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

    plot.plot_fit1d(fit_result, np.linspace(0,x[-1],201), ax=ax,
           plot_data=False)

    ax.set_ylim([-1,1])

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

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

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


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

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

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

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

    ## plot data and fit as function of total time
    if plot_fit == True:
        plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],1001), ax=ax, plot_data=False)

    fit_results.append(fit_result)

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

    return fit_results
def OneQubitTomo(timestamp=None, measurement_name = ['adwindata'], ssro_calib_timestamp =None,
        frequency = [1,1,1], offset =[ 0.5,0.5,0.5], amplitude =[ 0.5,0.5,0.5],  phase =[0.5,0.5,0.5],
        fixed = [],
        plot_fit = False, do_print = False, show_guess = True):
    '''
    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
    List of parameters (order important for 'fixed')
    [freq, offset, Amplitude, phase]
    '''
    # timestampZ = '20141023_174418'
    # folderZ = toolbox.data_from_time(timestampZ)
    # timestampX = '20141023_173547'
    # folderX = toolbox.data_from_time(timestampX)
    # timestampY = '20141023_173918'
    # folderY = toolbox.data_from_time(timestampY)
    
    if timestamp != None:
        timestampZ = timestamp
        folderZ = toolbox.data_from_time(timestamp)
    else:
        timestampZ, folderZ   = toolbox.latest_data('CarbonR',return_timestamp =True)
    timestampY, folderY = toolbox.latest_data('CarbonR',older_than = timestampZ, return_timestamp =True)
    timestampX, folderX = toolbox.latest_data('CarbonR',older_than = timestampY, return_timestamp =True)
    folders = [folderX,folderY, folderZ]

    if ssro_calib_timestamp == None:
        ssro_calib_folder = toolbox.latest_data('SSRO',older_than = timestampX)
    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'

    order_of_bases = ['X', 'Y','Z']
    x = [None]*len(folders)
    y = [None]*len(folders)
    fit_result = [None]*len(folders)
    for i,folder in enumerate(folders):
        fit_results = []

        print '*'*60
        print order_of_bases[i] + ' Tomography'
        print 'folder %s' %folder


        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(ssro_calib_folder)
            if i ==0:
                ax = a.plot_results_vs_sweepparam(ret='ax',labels = order_of_bases[i])
                # a.plot_results_vs_sweepparam(ax=ax)
            else:
                a.plot_results_vs_sweepparam(ax=ax,labels = order_of_bases[i])
            x[i] = a.sweep_pts.reshape(-1)[:]
            y[i]= a.p0.reshape(-1)[:]


            print frequency[i]
            p0, fitfunc, fitfunc_str = common.fit_cos(frequency[i], offset[i], amplitude [i],phase[i] )
            try:
                fit_result[i] = fit.fit1d(x[i],y[i], None, p0=p0, fitfunc=fitfunc, do_print=do_print, ret=True,fixed=fixed)
                if plot_fit == True:
                    plot.plot_fit1d(fit_result[i], np.linspace(x[i][0],x[i][-1],201), ax=ax,
                            plot_data=False,print_info = False)
                fit.write_to_file(fit_result[i],folder,fitname = str(order_of_bases[i])+'-tomography')
            except:
                pass
            if show_guess:
                ax.plot(np.linspace(x[i][0],x[i][-1],201), fitfunc(np.linspace(x[i][0],x[i][-1],201)), ':', lw=2)


    print 'fitfunction: '+fitfunc_str
    if plot_fit ==True:
        ax.legend(('X data','X-fit','Y data','Y-fit','Z data','Z-fit'),fontsize='x-small')
    elif plot_fit == False:
        ax.legend(('X data','Y data','Z data'),fontsize='small')

    ## plot data and fit as function of total time

    fit_results.append(fit_result[i])

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

    return fit_results
def CosineSum_MBI_data(folder=None,
                       timestamp=[],
                       measurement_name=['adwindata'],
                       ssro_calib_folder=None,
                       ssro_calib_timestamp=None,
                       new_tsmp='20170612_230600',
                       old_tsmp='20170614_071700',
                       two_cos=True,
                       title='Cluster',
                       x_ticks=np.arange(0, 100, 5),
                       y_ticks=np.arange(0.2, 0.8, 0.1),
                       color='b',
                       c=1,
                       t=1,
                       frequency=[1, 1],
                       offset=0.5,
                       amplitude=[0.5, 0.5],
                       phase=[0, 0],
                       fixed=[],
                       plot_fit=False,
                       do_print=False,
                       show_guess=True,
                       xlim1=None,
                       xlim2=None):
    ''' 
    Function to analyze simple decoupling measurements. Loads the results and fits them to a simple exponential.
    Inputs:
    folder: allows to specify specific folder for the data(this overwrites the timestamp input)
    ssro_folder: allows to specify specific folder for ssro calib(this overwrites the ssro_timestamp input)
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    List of parameters (order important for 'fixed') 
    [freq, offset, Amplitude, phase] 
    '''
    timestamp = []
    plot_fit = True
    show_guess = False
    exponent = 2
    #two_cos=True
    fit_results = []

    cum_pts = 0
    cum_sweep_pts = np.empty(0)
    cum_p0 = np.empty(0)
    cu = np.empty(0)
    cu_u = np.empty(0)
    cum_u_p0 = np.empty(0)
    cum_tau_list = np.empty(0)

    # new_tsmp = '20170611_165140' ## newer than
    # old_tsmp = '20170611_235700' ## older than

    # new_tsmp = '20170612_005040' ## newer than
    # old_tsmp = '20170612_015800' ## older than

    # new_tsmp = '20170612_230600' ## newer than
    # old_tsmp = '20170614_071700' ## older than

    # new_tsmp = '20170616_190600' ## newer than
    # old_tsmp = '20170617_053700' ## older than

    # new_tsmp = '20170621_183900' ## newer than
    # old_tsmp = '20170621_185800' ## older than

    # new_tsmp = '20170719_161700' ## newer than
    # old_tsmp = '20170719_165500' ## older than

    # new_tsmp = '20170720_171400' ## newer than
    # old_tsmp = '20170720_181700' ## older than

    # new_tsmp = '20170720_182900' ## newer than
    # old_tsmp = '20170720_195700' ## older than

    search_string = 'Carbon'
    while toolbox.latest_data(contains=search_string,
                              return_timestamp=True,
                              older_than=old_tsmp,
                              newer_than=new_tsmp,
                              raise_exc=False) != False:
        old_tsmp, folder = toolbox.latest_data(contains=search_string,
                                               return_timestamp=True,
                                               older_than=old_tsmp,
                                               newer_than=new_tsmp,
                                               raise_exc=False)

        timestamp.append(old_tsmp)

    timestamp = timestamp[::-1]

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

    for kk in range(len(timestamp)):
        folder = toolbox.data_from_time(timestamp[kk])

        a = mbi.MBIAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        a.get_electron_ROC(ssro_calib_folder)
        cum_pts += a.pts
        # temperature = (a.g.attrs['temp']-100)/0.385
        # temperature_list.append(temperature)

        if kk == 0:
            cum_sweep_pts = a.sweep_pts
            cum_p0 = a.p0
            cum_u_p0 = a.u_p0
            #cum_tau_list = a.tau_list
        #elif kk in [5,10,15,21,26,31]:
        else:
            cum_sweep_pts = np.concatenate((cum_sweep_pts, a.sweep_pts))
            cum_p0 = np.concatenate((cum_p0, a.p0))
            cum_u_p0 = np.concatenate((cum_u_p0, a.u_p0))
            #cum_tau_list = np.concatenate((cum_tau_list, a.tau_list))

    a.pts = cum_pts
    a.sweep_pts = 1.0e3 * cum_sweep_pts
    a.p0 = cum_p0
    a.u_p0 = cum_u_p0

    #ax = a.plot_results_vs_sweepparam(ret='ax',fmt='o',color='brown',figsize=(46,12))
    e = a.u_p0
    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]

    # fig = plt.figure(1,figsize=(10,2))
    # ax2 = fig.add_subplot(111)

    # ax2.set_xlabel('Free evolution time (ms)')
    # ax2.set_ylabel('State Fidelity')

    #f = plt.figure(1,figsize=(60,2))
    #f,(ax1,ax2,ax3,ax4) = plt.subplots(1,4,sharey=True, facecolor='w',figsize=(10,3.5))

    fig = plt.figure(figsize=(9, 3.3))
    gs = gridspec.GridSpec(1, 4, width_ratios=[3, 3, 2, 1])
    ax1 = plt.subplot(gs[0])
    ax2 = plt.subplot(gs[1])
    ax3 = plt.subplot(gs[2])
    ax4 = plt.subplot(gs[3])

    ax1.errorbar(x.flatten(),
                 y.flatten(),
                 yerr=e,
                 fmt='o',
                 label='',
                 color=color,
                 lw=1,
                 markersize=3)
    ax2.errorbar(x.flatten(),
                 y.flatten(),
                 yerr=e,
                 fmt='o',
                 label='',
                 color=color,
                 lw=1,
                 markersize=3)
    ax3.errorbar(x.flatten(),
                 y.flatten(),
                 yerr=e,
                 fmt='o',
                 label='',
                 color=color,
                 lw=1,
                 markersize=3)
    ax4.errorbar(x.flatten(),
                 y.flatten(),
                 yerr=e,
                 fmt='o',
                 label='',
                 color=color,
                 lw=1,
                 markersize=3)

    fit_result = [None]

    #p0, fitfunc, fitfunc_str = common.fit_sum_2cos(offset,amplitude[0],frequency[0],phase[0],amplitude[1],frequency[1],phase[1])
    if two_cos == True:
        p0, fitfunc, fitfunc_str = common.fit_gaussian_decaying_2cos(
            offset, c, t, amplitude[0], frequency[0], phase[0], amplitude[1],
            frequency[1], phase[1])
    else:
        p0, fitfunc, fitfunc_str = common.fit_general_exponential_dec_cos(
            offset, amplitude[0], 0, t, exponent, frequency[0], phase[0])
    if show_guess:
        ax1.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=do_print,
                           ret=True,
                           fixed=fixed)
    if plot_fit == True:
        plot.plot_fit1d(fit_result,
                        np.linspace(x[0], x[-1], 8001),
                        ax=ax1,
                        color=color,
                        plot_data=False,
                        print_info=False,
                        lw=1.5)

        plot.plot_fit1d(fit_result,
                        np.linspace(x[0], x[-1], 8001),
                        ax=ax2,
                        color=color,
                        plot_data=False,
                        print_info=False,
                        lw=1.5)

        plot.plot_fit1d(fit_result,
                        np.linspace(x[0], x[-1], 8001),
                        ax=ax3,
                        color=color,
                        plot_data=False,
                        print_info=False,
                        lw=1.5)
        plot.plot_fit1d(fit_result,
                        np.linspace(x[0], x[-1], 8001),
                        ax=ax4,
                        color=color,
                        plot_data=False,
                        print_info=False,
                        lw=1.5)

    fit.write_to_file(fit_result, folder, fitname='Sum of cosine fit')

    ## plot data and fit as function of total time
    #plt.xticks(x_ticks)
    # plt.yticks(np.arange(min(y),(max(y)),0.1))
    #plt.yticks(y_ticks)
    ax1.set_xlim(0, 31)
    ax2.set_xlim(xlim1, xlim2)
    ax3.set_xlim(609, 631)
    ax4.set_xlim(910, 920)

    #ax2.set_ylim(0,1)

    #ax2.set_xlabel('Free evolution time (ms)')
    #ax2.set_ylabel('State Fidelity')
    d = .045  # how big to make the diagonal lines in axes coordinates
    # arguments to pass plot, just so we don't keep repeating them
    ax1.spines['right'].set_visible(False)
    ax2.spines['left'].set_visible(False)
    ax2.spines['right'].set_visible(False)
    ax3.spines['left'].set_visible(False)
    ax3.spines['right'].set_visible(False)
    ax1.yaxis.tick_left()
    ax1.tick_params(labelright='off')
    ax2.tick_params(labelleft='off')
    ax2.tick_params(labelright='off')
    ax3.tick_params(labelleft='off')
    ax3.tick_params(labelright='off')
    ax4.tick_params(labelleft='off')
    ax4.tick_params(labelright='off')
    #ax4.tick_params(labelbottom='off')
    #ax1.tick_params(labelbottom='off')
    #ax2.tick_params(labelbottom='off')
    #ax3.tick_params(labelbottom='off')

    ax4.spines['left'].set_visible(False)
    plt.sca(ax1)
    plt.xticks([10, 20, 30])
    plt.yticks([0.4, 0.5, 0.6, 0.7])
    plt.sca(ax2)
    plt.xticks([200, 210, 220, 230])
    plt.yticks([])
    plt.sca(ax3)
    plt.xticks([610, 620, 630])
    plt.yticks([])
    plt.sca(ax4)
    plt.xticks([910, 920])
    plt.yticks([])

    #plt.step(ax1,ax2,xticks=[10,20,30],yticks=[0.4,0.5,0.6,0.7])
    #ax4.yaxis.tick_right()
    #ax4.xaxis.tick_bottom()

    # kwargs = dict(transform=ax1.transAxes, color='k', clip_on=False)
    # ax1.plot((1-d,1+d), (-d,+d), **kwargs)
    # ax1.plot((1-d,1+d),(1-d,1+d), **kwargs)

    # kwargs.update(transform=ax2.transAxes)  # switch to the bottom axes
    # ax2.plot((-d,+d), (1-d,1+d), **kwargs)
    # ax2.plot((-d,+d), (-d,+d), **kwargs)
    # ax2.plot((1-d,1+d), (-d,+d), **kwargs)
    # ax2.plot((1-d,1+d),(1-d,1+d), **kwargs)

    # kwargs = dict(transform=ax3.transAxes, color='k', clip_on=False)
    # ax3.plot((-d,+d), (1-d,1+d), **kwargs)
    # ax3.plot((-d,+d), (-d,+d), **kwargs)
    # ax3.plot((1-d,1+d), (-d,+d), **kwargs)
    # ax3.plot((1-d,1+d),(1-d,1+d), **kwargs)

    # kwargs.update(transform=ax4.transAxes)  # switch to the bottom axes
    # ax4.plot((-d,+d), (1-d,1+d), **kwargs)
    # ax4.plot((-d,+d), (-d,+d), **kwargs)

    folder = 'C:\Users\TUD277931\Dropbox\TaminiauLab\Projects\Coherence in multi-qubit systems\Paper\Figures'
    plt.savefig(os.path.join(folder, title + '.pdf'),
                format='pdf',
                bbox_inches='tight',
                pad_inches=0.2,
                transparent=True)
def get_correlations(**kw):

    ### pull data
    ssro_calib_folder = kw.pop('ssro_calib_folder', None)
    ssro_calib_timestamp = kw.pop('ssro_calib_timestamp', None)
    search_string = kw.pop('search_string', 'el_13C_dm_')
    base_folder = kw.pop('base_folder', None)

    if ssro_calib_folder == None:
        if ssro_calib_timestamp == None:
            ssro_calib_folder = tb.latest_data('SSROCalibration')
        else:
            ssro_dstmp, ssro_tstmp = tb.verify_timestamp(ssro_calib_timestamp)
            ssro_calib_folder = tb.latest_data(
                contains=ssro_tstmp,
                older_than=str(int(ssro_dstmp) + 1) + '_' + ssro_tstmp,
                folder=base_folder)

    ### for basis assignment, see onenote 2016-08-24 or alternatively mathematica file E_13C_Bell_state.nb
    tomo_pulses_p = ['none', 'x', 'my']  ### used when looking for folders
    tomo_pulses_m = ['X', 'mx', 'y']  ### used when looking for folders

    f_list_pos_p, f_list_neg_p, f_list_pos_m, f_list_neg_m = [], [], [], []
    exp_values, exp_vals_u = np.array([]), np.array(
        []
    )  ### this will be a list with all combined expectation values such as XX or YZ
    sweep_pts = [
    ]  ### this will be a list of the bases associated expectation values

    ### carbon 1-qubit correlations
    c_x, c_y, c_z = 0., 0., 0.
    c_x_u, c_y_u, c_z_u = 0., 0., 0.

    ### this dictionary is used to translate the electron RO pulse into a measurement basis
    tomo_pulse_translation_dict = {
        'none': 'Z',
        'X': 'Z',
        'x': 'Y',
        'mx': 'Y',
        'y': 'X',
        'my': 'X'
    }

    for p, m in zip(tomo_pulses_p, tomo_pulses_m):
        f_list_pos_p.append(
            tb.latest_data(search_string + p + '_positive',
                           folder=base_folder,
                           return_timestamp=False,
                           **kw))
        f_list_neg_p.append(
            tb.latest_data(search_string + p + '_negative',
                           folder=base_folder,
                           return_timestamp=False,
                           **kw))
        f_list_pos_m.append(
            tb.latest_data(search_string + m + '_positive',
                           folder=base_folder,
                           return_timestamp=False,
                           **kw))
        f_list_neg_m.append(
            tb.latest_data(search_string + m + '_negative',
                           folder=base_folder,
                           return_timestamp=False,
                           **kw))

        #### now also calculate the measured contrast
        y_a, y_err_a = get_RO_results(f_list_pos_p[-1], ssro_calib_folder)
        y_b, y_err_b = get_RO_results(f_list_neg_p[-1], ssro_calib_folder)

        y_c, y_err_c = get_RO_results(f_list_pos_m[-1], ssro_calib_folder)
        y_d, y_err_d = get_RO_results(f_list_neg_m[-1], ssro_calib_folder)

        y_pos_electron = (y_a - y_b) / 2.
        y_pos_electron_u = 1. / 2 * (y_err_a**2 + y_err_b**2)**0.5
        y_neg_electron = (y_c - y_d) / 2.
        y_neg_electron_u = 1. / 2 * (y_err_c**2 + y_err_d**2)**0.5

        #### now do the final combination of results regarding the electron RO basis to get the combined expectation value
        y = (y_pos_electron - y_neg_electron) / 2.
        y_u = 1. / 2 * (y_pos_electron_u**2 + y_neg_electron_u**2)**0.5

        ### Combine data
        exp_values = np.append(exp_values, y)
        exp_vals_u = np.append(exp_vals_u, y_u)

        #### we also need to calculate the single qubit expectation values.
        #### easy for the electron spin. One simply adds the electron outcomes and divides by 2.
        #### for the nuclear spin one has to add up several RO bases and look at the correlations there
        #### (because experiments are not grouped by RO basis):
        exp_val_sum = (y_pos_electron + y_neg_electron) / 2.
        exp_val_sum_u = (y_pos_electron_u**2 + y_neg_electron_u**2) / 4.

        ### update the running average of the nuclear spin expectation values:
        c_x, c_y, c_z = c_x + exp_val_sum[0] / 3., c_y + exp_val_sum[
            1] / 3., c_z + exp_val_sum[2] / 3.
        c_x_u, c_y_u, c_z_u = c_x_u + exp_val_sum_u[
            0] / 9., c_y_u + exp_val_sum_u[1] / 9., c_z_u + exp_val_sum_u[
                2] / 9.

        ### add the electron values
        y_electron = np.sum(exp_val_sum) / 3.
        y_electron_u = np.sum(exp_val_sum_u / 9.)**0.5
        exp_values = np.append(exp_values, y_electron)
        exp_vals_u = np.append(exp_vals_u, y_electron_u)

        ### write up the combined analysis bases:
        a = mbi.MBIAnalysis(f_list_pos_p[-1])
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        e_base = np.array([tomo_pulse_translation_dict[p]] * 4)
        c_base = a.adgrp.attrs['Tomography Bases'].flatten()
        comb_base = np.core.defchararray.add(
            e_base, np.append(c_base, 'I')
        )  ### add identity to 13C bases as this is evaluated on the fly
        sweep_pts = np.append(sweep_pts, comb_base)

    ### the nuclear spin single qubit correlations have been esimated in a running average (transposed correlations)
    ### and are now added to the results (square root still needs to be taken for the uncertainties)
    sweep_pts = np.append(sweep_pts, ['IX', 'IY', 'IZ'])
    exp_values = np.append(exp_values, np.array([c_x, c_y, c_z]))
    print 'Nuclear spin correlations', c_x, c_y, c_z
    print sweep_pts
    print np.round(exp_values, 2)

    exp_vals_u = np.append(
        exp_vals_u, np.array([np.sqrt(c_x_u),
                              np.sqrt(c_y_u),
                              np.sqrt(c_z_u)]))

    return f_list_pos_p[0], sweep_pts, exp_values, exp_vals_u
def Carbon_Ramsey_Crosstalk(timestamp=None,
                            measurement_name=['adwindata'],
                            ssro_calib_timestamp=None,
                            frequency=1,
                            offset=0.5,
                            x0=0,
                            amplitude=0.5,
                            decay_constant=200,
                            phase=0,
                            exponent=2,
                            plot_fit=False,
                            do_print=False,
                            fixed=[2, 3, 4],
                            show_guess=True,
                            return_phase=False,
                            return_freq=False,
                            return_results=True,
                            return_amp=False,
                            close_plot=False,
                            title=None):
    ''' 
    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
    List of parameters (order important for 'fixed') 
    offset, amplitude, decay_constant,exponent,frequency ,phase 
    '''

    if timestamp != None:
        folder_a = toolbox.data_from_time(timestamp)
    else:
        folder_a, timestamp = toolbox.latest_data('Crosstalk',
                                                  return_timestamp=True)

    folder_b = toolbox.latest_data('Crosstalk', older_than=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'
        print ssro_calib_folder

    fit_results = []
    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

        fig = a.default_fig(figsize=(7.5, 5))
        ax2 = a.default_ax(fig)
        ax2.axhspan(0, 1, fill=False, ls='dotted')
        ax2.set_ylim(-1, 1)
        ax2.errorbar(x, RO_data, RO_data_u)

        p0, fitfunc, fitfunc_str = common.fit_general_exponential_dec_cos(
            offset, amplitude, x0, decay_constant, exponent, frequency, phase)

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

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

        print 'fitfunction: ' + fitfunc_str

        ## plot data and fit as function of total time
        if plot_fit == True:
            plot.plot_fit1d(fit_result,
                            np.linspace(x[0], x[-1], 1001),
                            ax=ax2,
                            plot_data=False)

        fit_results.append(fit_result)
        if title == None:
            title = 'analyzed_result'
        plt.savefig(os.path.join(folder_a, title + '.pdf'), format='pdf')
        plt.savefig(os.path.join(folder_a, title + '.png'), format='png')
        if close_plot == True:
            plt.close()

        if return_freq == True:
            f0 = fit_result['params_dict']['f']
            u_f0 = fit_result['error_dict']['f']
            return f0, u_f0

        if return_phase == True:
            phi0 = fit_result['params_dict']['phi']
            u_phi0 = fit_result['error_dict']['phi']
            Amp = fit_result['params_dict']['A']
            if return_amp == True:
                return phi0, u_phi0, Amp
            else:
                return phi0, u_phi0

    if return_results == True:
        return fit_results
Exemple #23
0
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.'
Exemple #24
0
def BarPlotTomoContrast(timestamps=[None, None],
                        tag='',
                        measurement_name=['adwindata'],
                        folder_name='Tomo',
                        ssro_calib_timestamp=None,
                        save=True,
                        plot_fit=True,
                        return_data=False):
    '''
	Function that makes a bar plot with errorbars of MBI type data that has been measured with a positive
	and negative RO.
	'''

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

    if timestamps[0] == None:
        folder_a = toolbox.latest_data(contains='positive' + tag)
        folder_b = toolbox.latest_data(contains='negative' + tag)
    elif len(timestamps) == 1:
        folder_b = toolbox.data_from_time(timestamps[0])
        folder_a = toolbox.latest_data(contains='positive',
                                       older_than=timestamps[0])
    else:
        folder_a = toolbox.data_from_time(timestamps[0])
        folder_b = toolbox.data_from_time(timestamps[1])

    a = mbi.MBIAnalysis(folder_a)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC(ssro_calib_folder)
    y_a = ((a.p0.reshape(-1)[:]) - 0.5) * 2
    y_err_a = 2 * a.u_p0.reshape(-1)[:]

    b = mbi.MBIAnalysis(folder_b)
    b.get_sweep_pts()
    b.get_readout_results(name='adwindata')
    b.get_electron_ROC(ssro_calib_folder)
    y_b = ((b.p0.reshape(-1)[:]) - 0.5) * 2
    y_err_b = 2 * b.u_p0.reshape(-1)[:]

    x_labels = a.sweep_pts.reshape(-1)[:]
    x = range(len(y_a))

    y = (y_a - y_b) / 2.
    y_err = 1. / 2 * (y_err_a**2 + y_err_b**2)**0.5

    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.set_xticklabels(x_labels.tolist())
        ax.set_ylim(-1.1, 1.1)
        ax.set_title(str(folder_a) + '/' + str(timestamps[0]))
        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_a, 'tomo.png'))
            fig.savefig(os.path.join(folder_a, 'tomo.pdf'))
        except:
            print 'Figure has not been saved.'

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

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

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


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

    cum_pts = 0

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

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

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

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


    ## accumulate data with negative RO


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


    ## generate plot of the raw data ##


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


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

    fit_results = []

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

    #plot the initial guess

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

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

    ## plot data and fit as function of total time

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

    fit_results.append(fit_result)

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

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


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

    return x,y, y_err, fit_result
def Carbon_Ramsey_mult_msmts(timestamp=None, measurement_name = ['adwindata'], ssro_calib_timestamp =None,
            frequency = 1, 
            offset = 0.5, 
            x0 = 0,  
            amplitude = 0.5,  
            decay_constant = 200, 
            phase =0, 
            exponent = 2, 
            plot_fit = False, do_print = False, fixed = [2], show_guess = True,
            return_phase = False,
            return_freq = False,
            return_amp = False,
            return_results = True,
            close_plot = False,
            partstr = 'part',
            contains=[],
            title = 'Carbon'):
    ''' 
    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
    List of parameters (order important for 'fixed') 
    offset, amplitude, decay_constant,exponent,frequency ,phase 
    '''

    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        folder = toolbox.latest_data(title)
        if partstr in folder:
            numberstart = folder.find(partstr)+len(partstr)
            numberofparts = int(folder[numberstart:len(folder)])
            basis_str = folder[folder.rfind('\\')+7:numberstart]
        else:
            numberofparts = 1

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

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

    fit_results = []
    #for kk in range(numberofparts):
    for kk,cnts in enumerate(contains):    
        '''
        if partstr in folder:
            folder = toolbox.latest_data(basis_str+str(kk+1))
        else:
            folder = toolbox.latest_data(basis_str)
        '''
        folder = toolbox.latest_data(cnts)    
        a = mbi.MBIAnalysis(folder)
        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')

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

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

    sorting_order=a.sweep_pts.argsort()
    a.sweep_pts.sort()
    a.p0=a.p0[sorting_order]
    a.u_p0=a.u_p0[sorting_order]

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

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

    ax.plot(x,y)

    p0, fitfunc, fitfunc_str = common.fit_general_exponential_dec_cos(offset, amplitude, 
            x0, decay_constant,exponent,frequency ,phase )

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

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

    ## plot data and fit as function of total time
    if plot_fit == True:
        plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],1001), ax=ax, plot_data=False)

    fit_results.append(fit_result)
    if title == None:
        title = 'analyzed_result'
    plt.savefig(os.path.join(folder, title + '.pdf'),
    format='pdf')
    plt.savefig(os.path.join(folder, title + '.png'),
    format='png')
    if close_plot == True:
        plt.close()

    if return_freq == True:
        f0 = fit_result['params_dict']['f']
        u_f0 = fit_result['error_dict']['f']
        return f0, u_f0

    if return_phase == True and return_amp == False:
        phi0 = fit_result['params_dict']['phi']
        u_phi0 = fit_result['error_dict']['phi']
        return phi0, u_phi0

    if return_phase == True and return_amp == True:
        phi0 = fit_result['params_dict']['phi']
        u_phi0 = fit_result['error_dict']['phi']
        A = fit_result['params_dict']['A']
        u_A = fit_result['error_dict']['A']
        return phi0, u_phi0, A, u_A

    if return_results == True:
        return fit_results
Exemple #27
0
def get_data(folder,folder_timestamp,RO_correct=True,ssro_calib_timestamp=None,tomo_bases='XXX',get_title=False, return_orientations=False, **kw):
    evaluate_both = kw.pop('evaluate_both',False)

    a = CP.ConditionalParityAnalysis(folder)
    #a.get_sweep_pts()
    a.get_readout_results(name='adwindata', post_select_GHZ = True)
    if a.orientations[3] == 'negative':
        multiply_by = -1
    else:
        multiply_by = 1

    print a.orientations

    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_GHZ = True)
        #take the [0,0] part of the arrays; there are no sweep_pts
        p0_000,u_p0_000 = multiply_by*(a.p0_000[0,0]-0.5)*2,(2*a.u_p0_000[0,0]) 
        p0_001,u_p0_001 = multiply_by*(a.p0_001[0,0]-0.5)*2,(2*a.u_p0_001[0,0])
        p0_010,u_p0_010 = multiply_by*(a.p0_010[0,0]-0.5)*2,(2*a.u_p0_010[0,0])
        p0_011,u_p0_011 = multiply_by*(a.p0_011[0,0]-0.5)*2,(2*a.u_p0_011[0,0])
        p0_100,u_p0_100 = multiply_by*(a.p0_100[0,0]-0.5)*2,(2*a.u_p0_100[0,0])
        p0_101,u_p0_101 = multiply_by*(a.p0_101[0,0]-0.5)*2,(2*a.u_p0_101[0,0])
        p0_110,u_p0_110 = multiply_by*(a.p0_110[0,0]-0.5)*2,(2*a.u_p0_110[0,0])
        p0_111,u_p0_111 = multiply_by*(a.p0_111[0,0]-0.5)*2,(2*a.u_p0_111[0,0])
        print "probablity with ROC", a.p0_000[0,0]
        print "exp  with ROC",p0_000, u_p0_000

    if evaluate_both:
    #else:
        p0_000,u_p0_000 = multiply_by*(a.normalized_ssro_000[0,0]-0.5)*2,(2*a.u_normalized_ssro_000[0,0])
        p0_001,u_p0_001 = multiply_by*(a.normalized_ssro_001[0,0]-0.5)*2,(2*a.u_normalized_ssro_001[0,0])
        p0_010,u_p0_010 = multiply_by*(a.normalized_ssro_010[0,0]-0.5)*2,(2*a.u_normalized_ssro_010[0,0])
        p0_011,u_p0_011 = multiply_by*(a.normalized_ssro_011[0,0]-0.5)*2,(2*a.u_normalized_ssro_011[0,0])
        p0_100,u_p0_100 = multiply_by*(a.normalized_ssro_100[0,0]-0.5)*2,(2*a.u_normalized_ssro_100[0,0])
        p0_101,u_p0_101 = multiply_by*(a.normalized_ssro_101[0,0]-0.5)*2,(2*a.u_normalized_ssro_101[0,0])
        p0_110,u_p0_110 = multiply_by*(a.normalized_ssro_110[0,0]-0.5)*2,(2*a.u_normalized_ssro_110[0,0])
        p0_111,u_p0_111 = multiply_by*(a.normalized_ssro_111[0,0]-0.5)*2,(2*a.u_normalized_ssro_111[0,0])
        print "prob without ROC", a.normalized_ssro_000[0,0]
        print "exp without ROC",p0_000, u_p0_000
        print "WARNING WARNING REMOVE THIS STATEMENT. REMOVE EVALUATE_BOTH OPTION"

    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)
        d_list_name = "".join(aa for aa in a.d_list)
        title = a_list_name+' '+b_list_name+' '+c_list_name+' '+d_list_name
    else:
        title=''

    p = (a.p000[0,0],a.p001[0,0],a.p010[0,0],a.p011[0,0],a.p100[0,0],a.p101[0,0],a.p110[0,0],a.p111[0,0])
    y = (p0_000,p0_001,p0_010,p0_011,p0_100,p0_101,p0_110,p0_111)
    y_err = (u_p0_000,u_p0_001,u_p0_010,u_p0_011,u_p0_100,u_p0_101,u_p0_110,u_p0_111)

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

    return(p,y,y_err,title)
Exemple #28
0
def CosineSum_MBI_data(folder=None,
                       timestamp=[],
                       measurement_name=['adwindata'],
                       ssro_calib_folder=None,
                       ssro_calib_timestamp=None,
                       new_tsmp='20170612_230600',
                       old_tsmp='20170614_071700',
                       two_cos=True,
                       title='Cluster',
                       x_ticks=np.arange(0, 100, 5),
                       y_ticks=np.arange(0.2, 0.8, 0.1),
                       color='b',
                       c=1,
                       t=1,
                       frequency=[1, 1],
                       offset=0.5,
                       amplitude=[0.5, 0.5],
                       phase=[0, 0],
                       fixed=[],
                       plot_fit=False,
                       do_print=False,
                       show_guess=True,
                       xlim=None):
    ''' 
    Function to analyze simple decoupling measurements. Loads the results and fits them to a simple exponential.
    Inputs:
    folder: allows to specify specific folder for the data(this overwrites the timestamp input)
    ssro_folder: allows to specify specific folder for ssro calib(this overwrites the ssro_timestamp input)
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    List of parameters (order important for 'fixed') 
    [freq, offset, Amplitude, phase] 
    '''
    timestamp = []
    plot_fit = True
    show_guess = False
    exponent = 2
    #two_cos=True
    fit_results = []

    cum_pts = 0
    cum_sweep_pts = np.empty(0)
    cum_p0 = np.empty(0)
    cu = np.empty(0)
    cu_u = np.empty(0)
    cum_u_p0 = np.empty(0)
    cum_tau_list = np.empty(0)

    # new_tsmp = '20170611_165140' ## newer than
    # old_tsmp = '20170611_235700' ## older than

    # new_tsmp = '20170612_005040' ## newer than
    # old_tsmp = '20170612_015800' ## older than

    # new_tsmp = '20170612_230600' ## newer than
    # old_tsmp = '20170614_071700' ## older than

    # new_tsmp = '20170616_190600' ## newer than
    # old_tsmp = '20170617_053700' ## older than

    # new_tsmp = '20170621_183900' ## newer than
    # old_tsmp = '20170621_185800' ## older than

    # new_tsmp = '20170719_161700' ## newer than
    # old_tsmp = '20170719_165500' ## older than

    # new_tsmp = '20170720_171400' ## newer than
    # old_tsmp = '20170720_181700' ## older than

    # new_tsmp = '20170720_182900' ## newer than
    # old_tsmp = '20170720_195700' ## older than

    search_string = 'Carbon'
    while toolbox.latest_data(contains=search_string,
                              return_timestamp=True,
                              older_than=old_tsmp,
                              newer_than=new_tsmp,
                              raise_exc=False) != False:
        old_tsmp, folder = toolbox.latest_data(contains=search_string,
                                               return_timestamp=True,
                                               older_than=old_tsmp,
                                               newer_than=new_tsmp,
                                               raise_exc=False)

        timestamp.append(old_tsmp)

    timestamp = timestamp[::-1]

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

    for kk in range(len(timestamp)):
        folder = toolbox.data_from_time(timestamp[kk])

        a = mbi.MBIAnalysis(folder)
        a.get_sweep_pts()
        a.get_readout_results(name='adwindata')
        a.get_electron_ROC(ssro_calib_folder)
        cum_pts += a.pts
        # temperature = (a.g.attrs['temp']-100)/0.385
        # temperature_list.append(temperature)

        if kk == 0:
            cum_sweep_pts = a.sweep_pts
            cum_p0 = a.p0
            cum_u_p0 = a.u_p0
            #cum_tau_list = a.tau_list
        #elif kk in [5,10,15,21,26,31]:
        else:
            cum_sweep_pts = np.concatenate((cum_sweep_pts, a.sweep_pts))
            cum_p0 = np.concatenate((cum_p0, a.p0))
            cum_u_p0 = np.concatenate((cum_u_p0, a.u_p0))
            #cum_tau_list = np.concatenate((cum_tau_list, a.tau_list))

    a.pts = cum_pts
    a.sweep_pts = 1.0e3 * cum_sweep_pts
    a.p0 = cum_p0
    a.u_p0 = cum_u_p0

    #ax = a.plot_results_vs_sweepparam(ret='ax',fmt='o',color='brown',figsize=(46,12))
    e = a.u_p0
    x = a.sweep_pts.reshape(-1)[:]
    y = a.p0.reshape(-1)[:]

    fig = plt.figure(1, figsize=(4, 1.5))
    ax2 = fig.add_subplot(111)
    ax2.errorbar(x.flatten(),
                 y.flatten(),
                 yerr=e,
                 fmt='o',
                 label='',
                 color=color,
                 lw=1,
                 markersize=3)
    ax2.set_xlabel('Free evolution time (ms)')
    ax2.set_ylabel('State Fidelity')

    fit_result = [None]

    #p0, fitfunc, fitfunc_str = common.fit_sum_2cos(offset,amplitude[0],frequency[0],phase[0],amplitude[1],frequency[1],phase[1])
    if two_cos == True:
        p0, fitfunc, fitfunc_str = common.fit_gaussian_decaying_2cos(
            offset, c, t, amplitude[0], frequency[0], phase[0], amplitude[1],
            frequency[1], phase[1])
    else:
        p0, fitfunc, fitfunc_str = common.fit_general_exponential_dec_cos(
            offset, amplitude[0], 0, t, exponent, frequency[0], phase[0])
    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=do_print,
                           ret=True,
                           fixed=fixed)
    if plot_fit == True:
        plot.plot_fit1d(fit_result,
                        np.linspace(x[0], x[-1], 8001),
                        ax=ax2,
                        color=color,
                        plot_data=False,
                        print_info=False,
                        lw=1.5)

    fit.write_to_file(fit_result, folder, fitname='Sum of cosine fit')

    ## plot data and fit as function of total time
    plt.xticks(x_ticks)
    # plt.yticks(np.arange(min(y),(max(y)),0.1))
    plt.yticks(y_ticks)
    ax2.set_xlim(0, xlim)
    #ax2.set_ylim(0,1)

    #ax2.set_xlabel('Free evolution time (ms)')
    #ax2.set_ylabel('State Fidelity')

    folder = 'C:\Users\TUD277931\Dropbox\TaminiauLab\Projects\Coherence in multi-qubit systems\Paper\Figures\Fig 3'
    plt.savefig(os.path.join(folder, title + '.pdf'),
                format='pdf',
                bbox_inches='tight',
                pad_inches=0.2,
                transparent=True)
def BarPlotTomo_QEC(timestamp = None, measurement_name = ['adwindata'],folder_name ='Tomo',
        plot_post_select = False,
        ssro_calib_timestamp = None, save = True,
        do_plots = False, title =None ,fontsize = 10, post_select_QEC = False) :
    '''
    Function that makes a bar plot with errorbars of MBI type data
    '''
    plt.rc('font', size=fontsize)
    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 = CP.ConditionalParityAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata',post_select_QEC = False)
    a.get_electron_ROC(ssro_calib_folder)

    x_labels = a.sweep_pts.reshape(-1)

    ''' all data '''

    c0,u_c0 = a.convert_fidelity_to_contrast(a.p0,a.u_p0)
    x = range(len(c0))

    if do_plots ==True:
        fig,ax = plt.subplots()
        ax.bar(x,c0,yerr=u_c0,align ='center',ecolor = 'k' )
        ax.set_xticks(x)
        if title == None:
            ax.set_title(str(folder)+'/'+str(timestamp))
        else:
            ax.set_title(title)
        print x_labels
        ax.set_xticklabels(x_labels.tolist())
        ax.set_ylim(-1,1)
        ax.hlines([-1,0,1],x[0]-1,x[-1]+1,linestyles='dotted')

        try:
            fig.savefig(os.path.join(folder,'tomo.png'))
            fig.savefig(os.path.join(folder, title+'.pdf'),
                    format='pdf',bbox_inches='tight')
        except:
            print 'Figure A has not been saved.'

    ''' postselected data '''

    a = CP.ConditionalParityAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata',post_select_QEC = True)
    a.get_electron_ROC(ssro_calib_folder, post_select_QEC = True)
            
    c0_00,u_c0_00 =  a.convert_fidelity_to_contrast(a.p0_00,a.u_p0_00)
    c0_01,u_c0_01 =  a.convert_fidelity_to_contrast(a.p0_01,a.u_p0_01)
    c0_10,u_c0_10 =  a.convert_fidelity_to_contrast(a.p0_10,a.u_p0_10)
    c0_11,u_c0_11 =  a.convert_fidelity_to_contrast(a.p0_11,a.u_p0_11)

    x = range(len(c0_00))

    if do_plots == True and plot_post_select == True:
        fig_00,ax_00 = plt.subplots()
        rects = ax_00.bar(x,c0_00,yerr=u_c0_00,align ='center',ecolor = 'k' )
        # ax_00.bar(x,a.p0_00,yerr = u_c0_00,align = 'center',ecolor = 'k')
        ax_00.set_xticks(x)
        if title == None:
            ax_00.set_title(str(folder)+'/'+str(timestamp)+'0')
        else:
            ax_00.set_title(str(title)+'0')

        ax_00.set_xticklabels(x_labels.tolist())
        # ax_00.set_ylim(-1,1)
        ax_00.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(c0_00[ii],2)) +'('+ str(int(round(u_c0_00[ii]*100))) +')',
                    ha='center', va='bottom')
        autolabel(rects)

        fig_01,ax_01 = plt.subplots()
        rects = ax_01.bar(x,c0_01,yerr=u_c0_01,align ='center',ecolor = 'k' )
        ax_01.set_xticks(x)
        if title == None:
            ax_01.set_title(str(folder)+'/'+str(timestamp)+'1')
        else:
            ax_01.set_title(str(title)+'1')
        ax_01.set_xticklabels(x_labels.tolist())
        # ax_01.set_ylim(-1,1)
        ax_01.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(c0_01[ii],2)) +'('+ str(int(round(u_c0_01[ii]*100))) +')',
                    ha='center', va='bottom')
        autolabel(rects)

        fig_10,ax_10 = plt.subplots()
        rects = ax_10.bar(x,c0_10,yerr=u_c0_10,align ='center',ecolor = 'k' )
        # ax_10.bar(x,a.p0_10,yerr = u_c0_10,align = 'center',ecolor = 'k')
        ax_10.set_xticks(x)
        if title == None:
            ax_10.set_title(str(folder)+'/'+str(timestamp)+'0')
        else:
            ax_10.set_title(str(title)+'0')

        ax_10.set_xticklabels(x_labels.tolist())
        # ax_10.set_ylim(-1,1)
        ax_10.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(c0_10[ii],2)) +'('+ str(int(round(u_c0_10[ii]*100))) +')',
                    ha='center', va='bottom')
        autolabel(rects)

        fig_11,ax_11 = plt.subplots()
        rects = ax_11.bar(x,c0_11,yerr=u_c0_11,align ='center',ecolor = 'k' )
        ax_11.set_xticks(x)
        if title == None:
            ax_11.set_title(str(folder)+'/'+str(timestamp)+'1')
        else:
            ax_11.set_title(str(title)+'1')
        ax_11.set_xticklabels(x_labels.tolist())
        # ax_11.set_ylim(-1,1)
        ax_11.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(c0_11[ii],2)) +'('+ str(int(round(u_c0_11[ii]*100))) +')',
                    ha='center', va='bottom')
        autolabel(rects)



        try:
            fig_00.savefig(os.path.join(folder, str(title)+'0.pdf'),
                    format='pdf',bbox_inches='tight')

            fig_01.savefig(os.path.join(folder, str(title)+'1.pdf'),
                    format='pdf',bbox_inches='tight')
            fig_10.savefig(os.path.join(folder, str(title)+'0.pdf'),
                    format='pdf',bbox_inches='tight')

            fig_11.savefig(os.path.join(folder, str(title)+'1.pdf'),
                    format='pdf',bbox_inches='tight')
        except:
            print 'Figure B has not been saved.'

    return x, c0, u_c0, c0_00, u_c0_00, c0_01, u_c0_01, c0_10, u_c0_10, c0_11, u_c0_11, x_labels, folder
def Carbon_Ramsey(timestamp=None, carbon=None, transition=None, measurement_name = ['adwindata'], ssro_calib_timestamp =None,
            frequency = 1, 
            offset = 0.5, 
            x0 = 0,  
            amplitude = 0.5,  
            decay_constant = 200, 
            phase =0, 
            exponent = 2, 
            plot_fit = False, do_print = False, fixed = [2], show_guess = True,
            return_phase = False,
            return_freq = False,
            return_amp = False,
            return_results = True,
            close_plot = False,
            color='b',
            title = 'Carbon',
            x_ticks=np.arange(0,100,5),
            y_ticks=np.arange(0.2,0.8,0.1)):
    ''' 
    Function to analyze simple decoupling measurements. Loads the results and fits them to a simple exponential.
    Inputs:
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    List of parameters (order important for 'fixed') 
    offset, amplitude, decay_constant,exponent,frequency ,phase 
    '''

    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    elif carbon != None:
        folder = toolbox.latest_data(contains='C'+str(carbon)+'_ms'+str(transition))
    else:
        folder = toolbox.latest_data(title)

    print folder

    if ssro_calib_timestamp == None: 
        ssro_calib_folder = toolbox.latest_data('SSROCalibration')

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


    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(ssro_calib_folder)
        
        x = 1.0e3*a.sweep_pts.reshape(-1)[:]
        y = a.p0.reshape(-1)[:]
        e= a.u_p0
        
        # fig = plt.figure(1,figsize=(4,1.5))
        fig = plt.figure(1,figsize=(8,3))

        ax2 = fig.add_subplot(111)
        ax2.errorbar(x.flatten(),y.flatten(),yerr=e,fmt='o',label='',color=color,markersize=4,lw=1)
        ax2.set_xlabel('Free evolution time (ms)')
        ax2.set_ylabel('State Fidelity')

        print min(y)
        print max(y)
        #plt.xticks(x_ticks)
        # plt.yticks(np.arange(min(y),(max(y)),0.1))
        #plt.yticks(y_ticks)

        #ax2.set_ylim(min(y)-0.03,max(y)+0.07)
        
        p0, fitfunc, fitfunc_str = common.fit_general_exponential_dec_cos(offset, amplitude, 
                x0, decay_constant,exponent,frequency ,phase )

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

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

        print 'fitfunction: '+fitfunc_str

        ## plot data and fit as function of total time
        if plot_fit == True:
            plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],1001), ax=ax2, add_txt = False, color=color, plot_data=False,lw=1.5)

        

        fit_results.append(fit_result)
        if title == None:
            title = 'analyzed_result'
        
        folder='C:\Users\TUD277931\Dropbox\TaminiauLab\Projects\Coherence in multi-qubit systems\Paper\Figures\Fig 3'
        plt.savefig(os.path.join(folder, title + '.pdf'),
        format='pdf',bbox_inches='tight',pad_inches=0.2,transparent=True)

        if close_plot == True:
            plt.close()

    #     plt.savefig('C:\Users\TUD277931\Dropbox\TaminiauLab\Projects\Coherence in multi-qubit systems\Paper\Figures\Fig 1\T1_sum_log.pdf',
    # format='pdf',bbox_inches='tight',pad_inches=0.2,transparent=True)

        # for item in fit_result['params_dict']:
        #     print item
        # return fit_result
        #print folder

        if return_freq == True:
            f0 = fit_result['params_dict']['f']
            u_f0 = fit_result['error_dict']['f']
            return f0, u_f0

        if return_phase == True and return_amp == False:
            phi0 = fit_result['params_dict']['phi']
            u_phi0 = fit_result['error_dict']['phi']
            return phi0, u_phi0

        if return_phase == True and return_amp == True:
            phi0 = fit_result['params_dict']['phi']
            u_phi0 = fit_result['error_dict']['phi']
            A = fit_result['params_dict']['A']
            u_A = fit_result['error_dict']['A']
            return phi0, u_phi0, A, u_A

        if return_amp == True:
            A = fit_result['params_dict']['A']
            u_A = fit_result['error_dict']['A']
            return A, u_A

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

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

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

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

    cum_pts = 0

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

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

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

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

    ## accumulate data with negative RO

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

    ## generate plot of the raw data ##

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

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

    ## fit to a general exponential##

    fit_results = []

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

    #plot the initial guess

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

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

    ## plot data and fit as function of total time

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

    fit_results.append(fit_result)

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

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

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

    return x, y, y_err, fit_result
def BarPlotTomoContrast(timestamps = [None,None], tag = '', measurement_name = ['adwindata'],folder_name ='Tomo',
        ssro_calib_timestamp =None, save = True,
        plot_fit = True, return_data = False) :
    '''
    Function that makes a bar plot with errorbars of MBI type data that has been measured with a positive
    and negative RO.
    '''

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


    if timestamps[0] == None: 
        folder_a = toolbox.latest_data(contains='positive' + tag)
        folder_b = toolbox.latest_data(contains='negative' + tag)
    elif len(timestamps)==1:        
        folder_b = toolbox.data_from_time(timestamps[0])      
        print folder_b
        folder_a = toolbox.latest_data(contains = 'pos', older_than = timestamps[0])   
        print folder_a
    else:
        folder_a = toolbox.data_from_time(timestamps[0])      
        folder_b = toolbox.data_from_time(timestamps[1])           
    
    a = mbi.MBIAnalysis(folder_a)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC(ssro_calib_folder)
    y_a= ((a.p0.reshape(-1)[:])-0.5)*2
    y_err_a = 2*a.u_p0.reshape(-1)[:] 


    b = mbi.MBIAnalysis(folder_b)
    b.get_sweep_pts()
    b.get_readout_results(name='adwindata')
    b.get_electron_ROC(ssro_calib_folder)
    y_b= ((b.p0.reshape(-1)[:])-0.5)*2
    y_err_b = 2*b.u_p0.reshape(-1)[:] 

    x_labels = a.sweep_pts.reshape(-1)[:]
    x = range(len(y_a)) 


    
    ### Combine data
    y = (y_a - y_b)/2.
    y_err =  1./2*(y_err_a**2 + y_err_b**2)**0.5 
    
    print tag
    print y
    print y_err
    # print folder_a
    # print folder_b

    # print y_a
    # print y_b
    # print y


    ### Fidelities
    # F_ZZ  = (1 + y[2] + y[5] + y[14])/4
    # F_ZmZ     = (1 + y[2] - y[5] - y[14])/4
    # F_ent     = (1 + y[0] -y[4] -y[8])/4
    # F_ent     = (1 + y[0] +y[1] +y[2])/4
    # print 'Fidelity with ZZ  = ' + str(F_ZZ)
    # print 'Fidelity with ZmZ  = ' + str(F_ZmZ)
    # print 'Fidelity with ent = ' + str(F_ent)

    # print 'XY = ' +str( (y[0]**2 + y[1]**2)**0.5)

    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.set_xticklabels(x_labels.tolist())
        ax.set_ylim(-1.1,1.1)
        print 'test'
        print folder_a
        ax.set_title(str(folder_a)+'/'+str(timestamps[0]))
        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_a,'tomo.png'))
        except:
            print 'Figure has not been saved.'

    if return_data == True:
        return x_labels, x, y, y_err
Exemple #33
0
def CosineSum_MBI_data(folder=None,timestamp=None, measurement_name = ['adwindata'],ssro_calib_folder=None, ssro_calib_timestamp =None,
        frequency = [1,1], offset =0.5, amplitude =[ 0.5,0.5],  phase =[0,0], 
        fixed = [], 
        plot_fit = False, do_print = False, show_guess = True,xlim=None):
    ''' 
    Function to analyze simple decoupling measurements. Loads the results and fits them to a simple exponential.
    Inputs:
    folder: allows to specify specific folder for the data(this overwrites the timestamp input)
    ssro_folder: allows to specify specific folder for ssro calib(this overwrites the ssro_timestamp input)
    timestamp: in format yyyymmdd_hhmmss or hhmmss or None.
    measurement_name: list of measurement names
    List of parameters (order important for 'fixed') 
    [freq, offset, Amplitude, phase] 
    '''

    if folder== None:
        if timestamp == None:
            timestamp, folder   = toolbox.latest_data('CarbonR',return_timestamp =True)
        else: 
            folder = toolbox.data_from_time(timestamp) 

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

    a = mbi.MBIAnalysis(folder)
    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= a.p0.reshape(-1)[:]




    p0, fitfunc, fitfunc_str = common.fit_sum_2cos(offset,amplitude[0],frequency[0],phase[0],amplitude[1],frequency[1],phase[1]) 
    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=do_print, ret=True,fixed=fixed)
    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.write_to_file(fit_result,folder,fitname = 'Sum of cosine fit') 


    ## plot data and fit as function of total time

    plt.savefig(os.path.join(folder, 'CosineSumFit.pdf'),
    format='pdf')
    plt.savefig(os.path.join(folder, 'CosineSumFit.png'),
    format='png')
    return fitfunc,ax,a,fit_result
Exemple #34
0
def fit_ramsey(title=None, timestamp = None, ssro_calib_timestamp = None, ax = None,do_fit = False, Rmbi_guess=0.9, theta_guess= 1.5705, phi_guess=1.5705, show_guess = False):


    """
    fit Rmbi**2Cos(theta)**2 + Rmbi**2Sin(theta)**2(cos(x+phi)+sin(x+phi)
    """
    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        folder = toolbox.latest_data(title)

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

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

    fig, ax = plt.subplots(1,1, figsize=(4.5,4))
    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC()    

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

    y= ((a.p0.reshape(-1))-0.5)*2
    x = np.linspace(0,720,len(y))

    y_err = a.u_p0.reshape(-1)[:]


    Rmbi = fit.Parameter(Rmbi_guess, 'Rmbi')
    theta = fit.Parameter(theta_guess, 'theta')
    phi = fit.Parameter(phi_guess, 'phi')
    
    p0 = [Rmbi,theta, phi]

    fitfunc_str = 'Rmbi^2 * Cos(theta)^2 + Rmbi^2 * Sin(theta)^2 * (Cos(x+phi)+Sin(x+phi)'

    ax.errorbar(x,y,yerr=y_err)

    def fitfunc(x) : 
        # return (Rmbi()*np.cos(theta()+np.pi*x/180.)+0*phi())
        return (Rmbi()**2)*(np.cos(theta()*np.pi/180.)**2 + np.sin(theta()*np.pi/180.)**2 * (np.cos(x*np.pi/180.+np.pi*phi()/180.)+np.sin(x*np.pi/180.+np.pi*phi()/180.)))

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

    if do_fit == True:
        fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc,
            fitfunc_str=fitfunc_str, do_print=True, ret=True,fixed = [])

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

    ax.set_title(folder)
    ax.set_ylabel('Contrast')
    ax.set_xlabel('Phase')

    ax.set_ylim([-1.1,1.1])
    # print 'fitted minimal fidelity {0:.3f} +- {1:.3f}'.format((1-fit['params'][0]),fit['error'][0])
    # print 'Fitted minimum at {0:.3f} +- {1:.3f}'.format((fit['params'][2]),fit['error'][2])
Exemple #35
0
def fit_ramsey(title=None,
               timestamp=None,
               ssro_calib_timestamp=None,
               ax=None,
               do_fit=False,
               Rmbi_guess=0.9,
               theta_guess=1.5705,
               phi_guess=1.5705,
               show_guess=False):
    """
    fit Rmbi**2Cos(theta)**2 + Rmbi**2Sin(theta)**2(cos(x+phi)+sin(x+phi)
    """
    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        folder = toolbox.latest_data(title)

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

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

    fig, ax = plt.subplots(1, 1, figsize=(4.5, 4))
    a = mbi.MBIAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC()

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

    y = ((a.p0.reshape(-1)) - 0.5) * 2
    x = np.linspace(0, 720, len(y))

    y_err = a.u_p0.reshape(-1)[:]

    Rmbi = fit.Parameter(Rmbi_guess, 'Rmbi')
    theta = fit.Parameter(theta_guess, 'theta')
    phi = fit.Parameter(phi_guess, 'phi')

    p0 = [Rmbi, theta, phi]

    fitfunc_str = 'Rmbi^2 * Cos(theta)^2 + Rmbi^2 * Sin(theta)^2 * (Cos(x+phi)+Sin(x+phi)'

    ax.errorbar(x, y, yerr=y_err)

    def fitfunc(x):
        # return (Rmbi()*np.cos(theta()+np.pi*x/180.)+0*phi())
        return (Rmbi()**
                2) * (np.cos(theta() * np.pi / 180.)**2 +
                      np.sin(theta() * np.pi / 180.)**2 *
                      (np.cos(x * np.pi / 180. + np.pi * phi() / 180.) +
                       np.sin(x * np.pi / 180. + np.pi * phi() / 180.)))

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

    if do_fit == True:
        fit_result = fit.fit1d(x,
                               y,
                               None,
                               p0=p0,
                               fitfunc=fitfunc,
                               fitfunc_str=fitfunc_str,
                               do_print=True,
                               ret=True,
                               fixed=[])

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

    ax.set_title(folder)
    ax.set_ylabel('Contrast')
    ax.set_xlabel('Phase')

    ax.set_ylim([-1.1, 1.1])
from analysis.lib.tools import toolbox
from analysis.lib.fitting import fit, esr
from analysis.lib.tools import plot
from analysis.lib.math import error

### settings
timestamp = '20150613_093117'#'20150609_231010' ### one can use this timestamp as starting point.
ssro_calib_timestamp = '20150610_174113'
analysis_length = 38
average_data = True
analysis_type = 'double_lorentz' #### possibilities 'peseudo-voigt' 'gauss' 'lorentz' 'double_gauss', 'double_lorentz'

show_guess = False


ssro_dstmp, ssro_tstmp = toolbox.verify_timestamp(ssro_calib_timestamp)
ssro_calib_folder = toolbox.datadir + '/'+ssro_dstmp+'/'+ssro_tstmp+'_AdwinSSRO_SSROCalibration_111_1_sil18'

folder_list = []

if timestamp == None:
    timestamp = '20800101_101010' ## some future date... only younger data is considered.

for i in range(analysis_length):
    timestamp, folder = toolbox.latest_data(contains='DESR',
                                        return_timestamp =True,
                                        older_than=timestamp,
                                        raise_exc=False)
    folder_list.append(folder)

# print folder_list
def Sweep_repetitions(older_than = None,
		folder_name ='Memory_NoOf_Repetitions_',
		carbon = '2',
		ssro_calib_timestamp =None, 
		plot_result= True) :

	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


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

	folder_dict['res'] = np.sqrt(npY**2+npX**2)
	folder_dict['res_u'] = np.sqrt((npX*npX_u)**2+(npY*npY_u)**2)/np.sqrt((npX**2+npY**2))

	if folder_name == 'Memory_Sweep_repump_time_':
		plot_label = 'average repump time'
		
	elif folder_name == 'Memory_NoOf_Repetitions_':
		plot_label = 'Number of repetitions'

	elif folder_name == 'Memory_Sweep_repump_duration':
		plot_label = 'repump duration'

	elif folder_name == 'Memory_sweep_timing_':
		x_labels = np.array(x_labels)*1e6
		plot_label = 'Waiting time (us)'

	else:
		plot_label = folder_name
		

	if plot_result:
		fig = plt.figure()
		ax = plt.subplot()
		plt.errorbar(x_labels,folder_dict['res'],folder_dict['res_u'],marker='o',label='C'+carbon)


		plt.xlabel(plot_label)
		plt.ylabel('Bloch vector length')
		plt.title('Dephasing for C'+carbon)
		plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
		plt.savefig(os.path.join(folder_dict[t][0],'CarbonDephasing.pdf'),format='pdf')
		plt.savefig(os.path.join(folder_dict[t][0],'CarbonDephasing.png'),format='png')
		plt.show()
		plt.close('all')

	else:
		return np.array(x_labels), np.array(folder_dict['res']),np.array(folder_dict['res_u']),folder_dict[t][0]
def simple_plot_contrast(timestamps = [None,None], tag = '', measurement_name = ['adwindata'],folder_name ='Tomo',
		ssro_calib_timestamp =None, save = True,
		do_plot = True, return_data = False) :
	'''
	Function that makes a bar plot with errorbars of MBI type data that has been measured with a positive
	and negative RO.
	'''

	### SSRO calibration
	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'

	if timestamps[0] == None: 
		folder_a = toolbox.latest_data(contains='positive' + tag)
		folder_b = toolbox.latest_data(contains='negative' + tag)
	elif len(timestamps)==1:		
		folder_b = toolbox.data_from_time(timestamps[0])      
		print folder_b
		folder_a = toolbox.latest_data(contains = 'pos', older_than = timestamps[0])   
		print folder_a
	else:
		folder_a = toolbox.data_from_time(timestamps[0])      
		folder_b = toolbox.data_from_time(timestamps[1])     	   
 	
	a = mbi.MBIAnalysis(folder_a)
	a.get_sweep_pts()
	a.get_readout_results(name='adwindata')
	a.get_electron_ROC(ssro_calib_folder)
	y_a= ((a.p0.reshape(-1)[:])-0.5)*2
	y_err_a = 2*a.u_p0.reshape(-1)[:] 


	b = mbi.MBIAnalysis(folder_b)
	b.get_sweep_pts()
	b.get_readout_results(name='adwindata')
	b.get_electron_ROC(ssro_calib_folder)
	y_b= ((b.p0.reshape(-1)[:])-0.5)*2
	y_err_b = 2*b.u_p0.reshape(-1)[:] 

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


	
	### Combine data
	y = (y_a - y_b)/2.
	y_err =  1./2*(y_err_a**2 + y_err_b**2)**0.5 
	if do_plot == True:
		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)
		print folder_a
		ax.set_title(str(folder_a)+'/'+str(timestamps[0]))
		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_a,'simple_plot_contrast.png'))
		except:
		    print 'Figure has not been saved.'

	if return_data == True:
		return  x, y, y_err
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]
Exemple #40
0
def Carbon_T1_analysis(measurement_name=['adwindata'],
                       ssro_calib_timestamp=None,
                       offset=0.5,
                       amplitude=0.5,
                       decay_constant=0.04,
                       x0=0,
                       exponent=1,
                       Addressed_carbon=1,
                       plot_fit=True,
                       do_print=False,
                       show_guess=False,
                       el_state='both'):
    ''' 
    Function to gather and analyze T1 measurements of a specific carbon.

    Addressed_carbon: selects the used timestamps and therefore the analyzed carbon

    measurement_name: list of measurement names

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

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

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

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

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

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

        cum_pts = 0

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

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

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

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

        ## accumulate data with negative RO

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

        ## generate plot of the raw data ##

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

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

        ## fit to a general exponential##

        fit_results = []

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

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

        #plot the initial guess

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

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

        ## plot data and fit as function of total time

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

        fit_results.append(fit_result)

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

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

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

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

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

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

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

        cum_pts = 0

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

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

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

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

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

        print a.p0
        ## accumulate data with negative RO

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

        ## generate plot of the raw data ##

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

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

        fit_results = []

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

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

        #plot the initial guess

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

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

        ## plot data and fit as function of total time

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

        fit_results.append(fit_result)

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

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

        plt.savefig(os.path.join(folder_pos, filename + '.pdf'), format='pdf')
        plt.savefig(os.path.join(folder_pos, filename + '.png'), format='png')
def Sweep_repetitions(older_than=None,
                      folder_name='Memory_NoOf_Repetitions_',
                      carbon='2',
                      ssro_calib_timestamp=None,
                      plot_result=True):

    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

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

    folder_dict['res'] = np.sqrt(npY**2 + npX**2)
    folder_dict['res_u'] = np.sqrt((npX * npX_u)**2 +
                                   (npY * npY_u)**2) / np.sqrt(
                                       (npX**2 + npY**2))

    if folder_name == 'Memory_Sweep_repump_time_':
        plot_label = 'average repump time'

    elif folder_name == 'Memory_NoOf_Repetitions_':
        plot_label = 'Number of repetitions'

    elif folder_name == 'Memory_Sweep_repump_duration':
        plot_label = 'repump duration'

    elif folder_name == 'Memory_sweep_timing_':
        x_labels = np.array(x_labels) * 1e6
        plot_label = 'Waiting time (us)'

    else:
        plot_label = folder_name

    if plot_result:
        fig = plt.figure()
        ax = plt.subplot()
        plt.errorbar(x_labels,
                     folder_dict['res'],
                     folder_dict['res_u'],
                     marker='o',
                     label='C' + carbon)

        plt.xlabel(plot_label)
        plt.ylabel('Bloch vector length')
        plt.title('Dephasing for C' + carbon)
        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
        plt.savefig(os.path.join(folder_dict[t][0], 'CarbonDephasing.pdf'),
                    format='pdf')
        plt.savefig(os.path.join(folder_dict[t][0], 'CarbonDephasing.png'),
                    format='png')
        plt.show()
        plt.close('all')

    else:
        return np.array(x_labels), np.array(folder_dict['res']), np.array(
            folder_dict['res_u']), folder_dict[t][0]
Exemple #42
0
def simple_plot_contrast(timestamps=[None, None],
                         tag='',
                         measurement_name=['adwindata'],
                         folder_name='Tomo',
                         ssro_calib_timestamp=None,
                         save=True,
                         do_plot=True,
                         return_data=False):
    '''
	Function that makes a bar plot with errorbars of MBI type data that has been measured with a positive
	and negative RO.
	'''

    ### SSRO calibration
    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'

    if timestamps[0] == None:
        folder_a = toolbox.latest_data(contains='positive' + tag)
        folder_b = toolbox.latest_data(contains='negative' + tag)
    elif len(timestamps) == 1:
        folder_b = toolbox.data_from_time(timestamps[0])
        print folder_b
        folder_a = toolbox.latest_data(contains='pos',
                                       older_than=timestamps[0])
        print folder_a
    else:
        folder_a = toolbox.data_from_time(timestamps[0])
        folder_b = toolbox.data_from_time(timestamps[1])

    a = mbi.MBIAnalysis(folder_a)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC(ssro_calib_folder)
    y_a = ((a.p0.reshape(-1)[:]) - 0.5) * 2
    y_err_a = 2 * a.u_p0.reshape(-1)[:]

    b = mbi.MBIAnalysis(folder_b)
    b.get_sweep_pts()
    b.get_readout_results(name='adwindata')
    b.get_electron_ROC(ssro_calib_folder)
    y_b = ((b.p0.reshape(-1)[:]) - 0.5) * 2
    y_err_b = 2 * b.u_p0.reshape(-1)[:]

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

    ### Combine data
    y = (y_a - y_b) / 2.
    y_err = 1. / 2 * (y_err_a**2 + y_err_b**2)**0.5
    if do_plot == True:
        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)
        print folder_a
        ax.set_title(str(folder_a) + '/' + str(timestamps[0]))
        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_a, 'simple_plot_contrast.png'))
        except:
            print 'Figure has not been saved.'

    if return_data == True:
        return x, y, y_err
def Carbon_Ramsey_mult_msmts(timestamp=None,
                             measurement_name=['adwindata'],
                             ssro_calib_timestamp=None,
                             frequency=1,
                             offset=0.5,
                             x0=0,
                             amplitude=0.5,
                             decay_constant=200,
                             phase=0,
                             exponent=2,
                             plot_fit=False,
                             do_print=False,
                             fixed=[2],
                             show_guess=True,
                             return_phase=False,
                             return_freq=False,
                             return_amp=False,
                             return_results=True,
                             close_plot=False,
                             partstr='part',
                             contains=[],
                             title='Carbon'):
    ''' 
    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
    List of parameters (order important for 'fixed') 
    offset, amplitude, decay_constant,exponent,frequency ,phase 
    '''

    if timestamp != None:
        folder = toolbox.data_from_time(timestamp)
    else:
        folder = toolbox.latest_data(title)
        if partstr in folder:
            numberstart = folder.find(partstr) + len(partstr)
            numberofparts = int(folder[numberstart:len(folder)])
            basis_str = folder[folder.rfind('\\') + 7:numberstart]
        else:
            numberofparts = 1

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

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

    fit_results = []
    #for kk in range(numberofparts):
    for kk, cnts in enumerate(contains):
        '''
        if partstr in folder:
            folder = toolbox.latest_data(basis_str+str(kk+1))
        else:
            folder = toolbox.latest_data(basis_str)
        '''
        folder = toolbox.latest_data(cnts)
        a = mbi.MBIAnalysis(folder)
        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')

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

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

    sorting_order = a.sweep_pts.argsort()
    a.sweep_pts.sort()
    a.p0 = a.p0[sorting_order]
    a.u_p0 = a.u_p0[sorting_order]

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

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

    ax.plot(x, y)

    p0, fitfunc, fitfunc_str = common.fit_general_exponential_dec_cos(
        offset, amplitude, x0, decay_constant, exponent, frequency, phase)

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

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

    ## plot data and fit as function of total time
    if plot_fit == True:
        plot.plot_fit1d(fit_result,
                        np.linspace(x[0], x[-1], 1001),
                        ax=ax,
                        plot_data=False)

    fit_results.append(fit_result)
    if title == None:
        title = 'analyzed_result'
    plt.savefig(os.path.join(folder, title + '.pdf'), format='pdf')
    plt.savefig(os.path.join(folder, title + '.png'), format='png')
    if close_plot == True:
        plt.close()

    if return_freq == True:
        f0 = fit_result['params_dict']['f']
        u_f0 = fit_result['error_dict']['f']
        return f0, u_f0

    if return_phase == True and return_amp == False:
        phi0 = fit_result['params_dict']['phi']
        u_phi0 = fit_result['error_dict']['phi']
        return phi0, u_phi0

    if return_phase == True and return_amp == True:
        phi0 = fit_result['params_dict']['phi']
        u_phi0 = fit_result['error_dict']['phi']
        A = fit_result['params_dict']['A']
        u_A = fit_result['error_dict']['A']
        return phi0, u_phi0, A, u_A

    if return_results == True:
        return fit_results
def Carbon_Ramsey(timestamp=None, measurement_name = ['adwindata'], ssro_calib_timestamp =None,
            frequency = 1, 
            offset = 0.5, 
            x0 = 0,  
            amplitude = 0.5,  
            decay_constant = 200, 
            phase =0, 
            exponent = 2, 
            plot_fit = False, do_print = False, fixed = [2], show_guess = True,
            return_phase = False,
            return_freq = False,
            return_amp = False,
            return_results = True,
            close_plot = False,
            title = 'Carbon'):
    ''' 
    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
    List of parameters (order important for 'fixed') 
    offset, amplitude, decay_constant,exponent,frequency ,phase 
    '''

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

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

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


    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(ssro_calib_folder)
        ax = a.plot_results_vs_sweepparam(ret='ax')

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

        ax.plot(x,y)
        p0, fitfunc, fitfunc_str = common.fit_general_exponential_dec_cos(offset, amplitude, 
                x0, decay_constant,exponent,frequency ,phase )

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

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

        print 'fitfunction: '+fitfunc_str

        ## plot data and fit as function of total time
        if plot_fit == True:
            plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],1001), ax=ax, plot_data=False)

        fit_results.append(fit_result)
        if title == None:
            title = 'analyzed_result'
        plt.savefig(os.path.join(folder, title + '.pdf'),
        format='pdf')
        plt.savefig(os.path.join(folder, title + '.png'),
        format='png')
        if close_plot == True:
            plt.close()

        # for item in fit_result['params_dict']:
        #     print item

        if return_freq == True:
            f0 = fit_result['params_dict']['f']
            u_f0 = fit_result['error_dict']['f']
            return f0, u_f0

        if return_phase == True and return_amp == False:
            phi0 = fit_result['params_dict']['phi']
            u_phi0 = fit_result['error_dict']['phi']
            return phi0, u_phi0

        if return_phase == True and return_amp == True:
            phi0 = fit_result['params_dict']['phi']
            u_phi0 = fit_result['error_dict']['phi']
            A = fit_result['params_dict']['A']
            u_A = fit_result['error_dict']['A']
            return phi0, u_phi0, A, u_A

        if return_amp == True:
            A = fit_result['params_dict']['A']
            u_A = fit_result['error_dict']['A']
            return A, u_A

    if return_results == True:
        return fit_results
Exemple #45
0
def QEC_analysis(timestamp=None, measurement_name = ['adwindata'], ssro_calib_timestamp =None,
            frequency = 1, 
            offset = 0.5, 
            x0 = 0,  
            amplitude = 0.5,  
            decay_constant = 200, 
            phase =0, 
            exponent = 2, 
            plot_fit = False, do_print = False, fixed = [2], show_guess = True,
            return_phase = False,
            return_freq = False,
            return_results = True,
            close_plot = False,
            title = None):
    ''' 
    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
    List of parameters (order important for 'fixed') 
    offset, amplitude, decay_constant,exponent,frequency ,phase 
    '''

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

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


    fit_results = []
    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(ssro_calib_folder)
        ax = a.plot_results_vs_sweepparam(ret='ax')

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

        ax.plot(x,y)
        p0, fitfunc, fitfunc_str = common.fit_general_exponential_dec_cos(offset, amplitude, 
                x0, decay_constant,exponent,frequency ,phase )

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

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

        print 'fitfunction: '+fitfunc_str

        ## plot data and fit as function of total time
        if plot_fit == True:
            plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],1001), ax=ax, plot_data=False)

        fit_results.append(fit_result)
        if title == None:
            title = 'analyzed_result'
        plt.savefig(os.path.join(folder, title + '.pdf'),
        format='pdf')
        plt.savefig(os.path.join(folder, title + '.png'),
        format='png')
        if close_plot == True:
            plt.close()

        if return_freq == True:
            f0 = fit_result['params_dict']['f']
            u_f0 = fit_result['error_dict']['f']
            return f0, u_f0

        if return_phase == True:
            phi0 = fit_result['params_dict']['phi']
            u_phi0 = fit_result['error_dict']['phi']
            return phi0, u_phi0

    if return_results == True:
        return fit_results
def Carbon_Ramsey_Crosstalk(timestamp=None, measurement_name = ['adwindata'], ssro_calib_timestamp =None,
            frequency = 1, 
            offset = 0.5, 
            x0 = 0,  
            amplitude = 0.5,  
            decay_constant = 200, 
            phase =0, 
            exponent = 2, 
            plot_fit = False, do_print = False, fixed = [2,3,4], show_guess = True,
            return_phase = False,
            return_freq = False,
            return_results = True,
            return_amp = False,
            close_plot = False,
            title = None):
    ''' 
    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
    List of parameters (order important for 'fixed') 
    offset, amplitude, decay_constant,exponent,frequency ,phase 
    '''

    if timestamp != None:
        folder_a = toolbox.data_from_time(timestamp)
    else:
        folder_a, timestamp = toolbox.latest_data('Crosstalk', return_timestamp = True)
        
    folder_b =  toolbox.latest_data('Crosstalk',older_than = 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'
        print ssro_calib_folder

    fit_results = []
    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

        fig = a.default_fig(figsize=(7.5,5))
        ax2 = a.default_ax(fig)
        ax2.axhspan(0,1,fill=False,ls='dotted')
        ax2.set_ylim(-1,1)
        ax2.errorbar(x,RO_data,RO_data_u)

        p0, fitfunc, fitfunc_str = common.fit_general_exponential_dec_cos(offset, amplitude, 
        x0, decay_constant,exponent,frequency ,phase )

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

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

        print 'fitfunction: '+fitfunc_str

        ## plot data and fit as function of total time
        if plot_fit == True:
            plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],1001), ax=ax2, plot_data=False)

        fit_results.append(fit_result)
        if title == None:
            title = 'analyzed_result'
        plt.savefig(os.path.join(folder_a, title + '.pdf'),
        format='pdf')
        plt.savefig(os.path.join(folder_a, title + '.png'),
        format='png')
        if close_plot == True:
            plt.close()

        if return_freq == True:
            f0 = fit_result['params_dict']['f']
            u_f0 = fit_result['error_dict']['f']
            return f0, u_f0

        if return_phase == True:
            phi0 = fit_result['params_dict']['phi']
            u_phi0 = fit_result['error_dict']['phi']
            Amp = fit_result['params_dict']['A']
            if return_amp == True:    
                return phi0, u_phi0, Amp
            else:
                return phi0, u_phi0

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





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


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


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

    cum_pts = 0

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

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

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

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


    ## accumulate data with negative RO


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


    ## generate plot of the raw data ##


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


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


    ## fit to a general exponential##

    fit_results = []

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

    #plot the initial guess

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

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

    ## plot data and fit as function of total time

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

    fit_results.append(fit_result)

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

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


    # plt.savefig(os.path.join(folder_pos, filename+'.pdf'),
    # format='pdf')
    # plt.savefig(os.path.join(folder_pos, filename+'.png'),
    # format='png')
    
    return x,y, y_err, fit_result
Exemple #48
0
def simple_plot_contrast(timestamps=[None, None],
                         tag='',
                         measurement_name=['adwindata'],
                         folder_name='Tomo',
                         ssro_calib_timestamp=None,
                         save=True,
                         do_plot=True,
                         return_data=False,
                         guess_frq=1 / 4000.,
                         guess_amp=1.5,
                         guess_k=0.,
                         guess_phi=0.,
                         guess_o=0.3):

    ### SSRO calibration
    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'

    if timestamps[0] == None:
        folder_a = toolbox.latest_data(contains='positive' + tag)
        folder_b = toolbox.latest_data(contains='negative' + tag)
    elif len(timestamps) == 1:
        folder_b = toolbox.data_from_time(timestamps[0])
        print folder_b
        folder_a = toolbox.latest_data(contains='pos',
                                       older_than=timestamps[0])
        print folder_a
    else:
        folder_a = toolbox.data_from_time(timestamps[0])
        folder_b = toolbox.data_from_time(timestamps[1])

    a = mbi.MBIAnalysis(folder_a)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata')
    a.get_electron_ROC(ssro_calib_folder)
    y_a = ((a.p0.reshape(-1)[:]) - 0.5) * 2
    y_err_a = 2 * a.u_p0.reshape(-1)[:]

    b = mbi.MBIAnalysis(folder_b)
    b.get_sweep_pts()
    b.get_readout_results(name='adwindata')
    b.get_electron_ROC(ssro_calib_folder)
    y_b = ((b.p0.reshape(-1)[:]) - 0.5) * 2
    y_err_b = 2 * b.u_p0.reshape(-1)[:]

    x = a.sweep_pts.reshape(-1)[:]
    # x = range(len(y_a))
    # ax = a.plot_results_vs_sweepparam(ret='ax', name = 'adwindata' )

    ### Combine data
    y = (y_a - y_b) / 2.
    y_err = 1. / 2 * (y_err_a**2 + y_err_b**2)**0.5

    if x[-1] < x[0]:
        x = x[::-1]
        y = y[::-1]

    fig, ax = plt.subplots()

    o = fit.Parameter(guess_o, '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 = [A, o, f, phi]
    fitfunc_str = ''

    ax.errorbar(x, y, yerr=y_err, marker='o', ls='')

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

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

    ax.set_title(folder_a)

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

    for i, y in enumerate(abs(y_fit)):
        if y == min(abs(y_fit)):
            x_opt = i

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

    plot.plot_fit1d(fit_result,
                    np.linspace(0, x[-1], 201),
                    ax=ax,
                    plot_data=False)

    ax.set_ylim([-1, 1])

    plt.savefig(os.path.join(folder_a, 'mbi_erabi_analysis.pdf'), format='pdf')
    plt.savefig(os.path.join(folder_a, 'mbi_erabi_analysis.png'), format='png')
Exemple #49
0
def get_data(folder,folder_timestamp,RO_correct=True,ssro_calib_timestamp=None,tomo_bases='XXX',get_title=False, return_orientations=False, **kw):
    evaluate_both = kw.pop('evaluate_both',False)

    a = CP.ConditionalParityAnalysis(folder)
    #a.get_sweep_pts()
    a.get_readout_results(name='adwindata', post_select_GHZ = True)

    if a.orientations[3] == 'negative':
        multiply_by = -1
    else:
        multiply_by = 1

    print a.orientations

    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_GHZ = True)
        #take the [0,0] part of the arrays; there are no sweep_pts
        p0_000,u_p0_000 = multiply_by*(a.p0_000[0,0]-0.5)*2,(2*a.u_p0_000[0,0]) 
        p0_001,u_p0_001 = multiply_by*(a.p0_001[0,0]-0.5)*2,(2*a.u_p0_001[0,0])
        p0_010,u_p0_010 = multiply_by*(a.p0_010[0,0]-0.5)*2,(2*a.u_p0_010[0,0])
        p0_011,u_p0_011 = multiply_by*(a.p0_011[0,0]-0.5)*2,(2*a.u_p0_011[0,0])
        p0_100,u_p0_100 = multiply_by*(a.p0_100[0,0]-0.5)*2,(2*a.u_p0_100[0,0])
        p0_101,u_p0_101 = multiply_by*(a.p0_101[0,0]-0.5)*2,(2*a.u_p0_101[0,0])
        p0_110,u_p0_110 = multiply_by*(a.p0_110[0,0]-0.5)*2,(2*a.u_p0_110[0,0])
        p0_111,u_p0_111 = multiply_by*(a.p0_111[0,0]-0.5)*2,(2*a.u_p0_111[0,0])
        print "probablity with ROC", a.p0_000[0,0]
        print "exp  with ROC",p0_000, u_p0_000

    if evaluate_both:
    #else:
        p0_000,u_p0_000 = multiply_by*(a.normalized_ssro_000[0,0]-0.5)*2,(2*a.u_normalized_ssro_000[0,0])
        p0_001,u_p0_001 = multiply_by*(a.normalized_ssro_001[0,0]-0.5)*2,(2*a.u_normalized_ssro_001[0,0])
        p0_010,u_p0_010 = multiply_by*(a.normalized_ssro_010[0,0]-0.5)*2,(2*a.u_normalized_ssro_010[0,0])
        p0_011,u_p0_011 = multiply_by*(a.normalized_ssro_011[0,0]-0.5)*2,(2*a.u_normalized_ssro_011[0,0])
        p0_100,u_p0_100 = multiply_by*(a.normalized_ssro_100[0,0]-0.5)*2,(2*a.u_normalized_ssro_100[0,0])
        p0_101,u_p0_101 = multiply_by*(a.normalized_ssro_101[0,0]-0.5)*2,(2*a.u_normalized_ssro_101[0,0])
        p0_110,u_p0_110 = multiply_by*(a.normalized_ssro_110[0,0]-0.5)*2,(2*a.u_normalized_ssro_110[0,0])
        p0_111,u_p0_111 = multiply_by*(a.normalized_ssro_111[0,0]-0.5)*2,(2*a.u_normalized_ssro_111[0,0])
        print "prob without ROC", a.normalized_ssro_000[0,0]
        print "exp without ROC",p0_000, u_p0_000
        print "WARNING WARNING REMOVE THIS STATEMENT. REMOVE EVALUATE_BOTH OPTION"

    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)
        d_list_name = "".join(aa for aa in a.d_list)
        title = a_list_name+' '+b_list_name+' '+c_list_name+' '+d_list_name
    else:
        title=''

    p = (a.p000[0,0],a.p001[0,0],a.p010[0,0],a.p011[0,0],a.p100[0,0],a.p101[0,0],a.p110[0,0],a.p111[0,0])
    y = (p0_000,p0_001,p0_010,p0_011,p0_100,p0_101,p0_110,p0_111)
    y_err = (u_p0_000,u_p0_001,u_p0_010,u_p0_011,u_p0_100,u_p0_101,u_p0_110,u_p0_111)

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

    return(p,y,y_err,title)
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_T2_analysis_ms1(measurement_name=['adwindata'],
                           ssro_calib_timestamp=None,
                           offset=0.5,
                           amplitude=0.5,
                           decay_constant=0.2,
                           x0=0,
                           exponent=1,
                           Addressed_carbon=5,
                           plot_fit=True,
                           do_print=True,
                           show_guess=False):

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

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

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

    cum_pts = 0

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

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

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

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

    ## accumulate data with negative RO

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

    ## generate plot of the raw data ##

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

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

    fit_results = []

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

    #plot the initial guess

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

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

    ## plot data and fit as function of total time

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

    fit_results.append(fit_result)

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

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

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

    return x, y, y_err, fit_result
        timestamp_pos=['20150316_020808']
        timestamp_neg=['20150316_031102']
        timestamp_pos=['20150317_061458']
        timestamp_neg=['20150317_063658']
=======
        timestamp_pos=['20150102_185838']
        timestamp_neg=['20150102_191030']


    else:
        print "Carbon not measured"

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


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

    cum_pts = 0

    for kk in range(len(timestamp_pos)):
        folder_pos = toolbox.data_from_time(timestamp_pos[kk])
        folder_neg = toolbox.data_from_time(timestamp_neg[kk])
        print folder_pos
        print folder_neg
        a = mbi.MBIAnalysis(folder_pos)
        a.get_sweep_pts()
def BarPlotTomo_QEC(timestamp=None,
                    measurement_name=['adwindata'],
                    folder_name='Tomo',
                    plot_post_select=False,
                    ssro_calib_timestamp=None,
                    save=True,
                    do_plots=False,
                    title=None,
                    fontsize=10,
                    post_select_QEC=False):
    '''
    Function that makes a bar plot with errorbars of MBI type data
    '''
    plt.rc('font', size=fontsize)
    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 = CP.ConditionalParityAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata', post_select_QEC=False)
    a.get_electron_ROC(ssro_calib_folder)

    x_labels = a.sweep_pts.reshape(-1)
    ''' all data '''

    c0, u_c0 = a.convert_fidelity_to_contrast(a.p0, a.u_p0)
    x = range(len(c0))

    if do_plots == True:
        fig, ax = plt.subplots()
        ax.bar(x, c0, yerr=u_c0, align='center', ecolor='k')
        ax.set_xticks(x)
        if title == None:
            ax.set_title(str(folder) + '/' + str(timestamp))
        else:
            ax.set_title(title)
        print x_labels
        ax.set_xticklabels(x_labels.tolist())
        ax.set_ylim(-1, 1)
        ax.hlines([-1, 0, 1], x[0] - 1, x[-1] + 1, linestyles='dotted')

        try:
            fig.savefig(os.path.join(folder, 'tomo.png'))
            fig.savefig(os.path.join(folder, title + '.pdf'),
                        format='pdf',
                        bbox_inches='tight')
        except:
            print 'Figure A has not been saved.'
    ''' postselected data '''

    a = CP.ConditionalParityAnalysis(folder)
    a.get_sweep_pts()
    a.get_readout_results(name='adwindata', post_select_QEC=True)
    a.get_electron_ROC(ssro_calib_folder, post_select_QEC=True)

    c0_00, u_c0_00 = a.convert_fidelity_to_contrast(a.p0_00, a.u_p0_00)
    c0_01, u_c0_01 = a.convert_fidelity_to_contrast(a.p0_01, a.u_p0_01)
    c0_10, u_c0_10 = a.convert_fidelity_to_contrast(a.p0_10, a.u_p0_10)
    c0_11, u_c0_11 = a.convert_fidelity_to_contrast(a.p0_11, a.u_p0_11)

    x = range(len(c0_00))

    if do_plots == True and plot_post_select == True:
        fig_00, ax_00 = plt.subplots()
        rects = ax_00.bar(x, c0_00, yerr=u_c0_00, align='center', ecolor='k')
        # ax_00.bar(x,a.p0_00,yerr = u_c0_00,align = 'center',ecolor = 'k')
        ax_00.set_xticks(x)
        if title == None:
            ax_00.set_title(str(folder) + '/' + str(timestamp) + '0')
        else:
            ax_00.set_title(str(title) + '0')

        ax_00.set_xticklabels(x_labels.tolist())
        # ax_00.set_ylim(-1,1)
        ax_00.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(c0_00[ii], 2)) + '(' +
                         str(int(round(u_c0_00[ii] * 100))) + ')',
                         ha='center',
                         va='bottom')

        autolabel(rects)

        fig_01, ax_01 = plt.subplots()
        rects = ax_01.bar(x, c0_01, yerr=u_c0_01, align='center', ecolor='k')
        ax_01.set_xticks(x)
        if title == None:
            ax_01.set_title(str(folder) + '/' + str(timestamp) + '1')
        else:
            ax_01.set_title(str(title) + '1')
        ax_01.set_xticklabels(x_labels.tolist())
        # ax_01.set_ylim(-1,1)
        ax_01.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(c0_01[ii], 2)) + '(' +
                         str(int(round(u_c0_01[ii] * 100))) + ')',
                         ha='center',
                         va='bottom')

        autolabel(rects)

        fig_10, ax_10 = plt.subplots()
        rects = ax_10.bar(x, c0_10, yerr=u_c0_10, align='center', ecolor='k')
        # ax_10.bar(x,a.p0_10,yerr = u_c0_10,align = 'center',ecolor = 'k')
        ax_10.set_xticks(x)
        if title == None:
            ax_10.set_title(str(folder) + '/' + str(timestamp) + '0')
        else:
            ax_10.set_title(str(title) + '0')

        ax_10.set_xticklabels(x_labels.tolist())
        # ax_10.set_ylim(-1,1)
        ax_10.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(c0_10[ii], 2)) + '(' +
                         str(int(round(u_c0_10[ii] * 100))) + ')',
                         ha='center',
                         va='bottom')

        autolabel(rects)

        fig_11, ax_11 = plt.subplots()
        rects = ax_11.bar(x, c0_11, yerr=u_c0_11, align='center', ecolor='k')
        ax_11.set_xticks(x)
        if title == None:
            ax_11.set_title(str(folder) + '/' + str(timestamp) + '1')
        else:
            ax_11.set_title(str(title) + '1')
        ax_11.set_xticklabels(x_labels.tolist())
        # ax_11.set_ylim(-1,1)
        ax_11.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(c0_11[ii], 2)) + '(' +
                         str(int(round(u_c0_11[ii] * 100))) + ')',
                         ha='center',
                         va='bottom')

        autolabel(rects)

        try:
            fig_00.savefig(os.path.join(folder,
                                        str(title) + '0.pdf'),
                           format='pdf',
                           bbox_inches='tight')

            fig_01.savefig(os.path.join(folder,
                                        str(title) + '1.pdf'),
                           format='pdf',
                           bbox_inches='tight')
            fig_10.savefig(os.path.join(folder,
                                        str(title) + '0.pdf'),
                           format='pdf',
                           bbox_inches='tight')

            fig_11.savefig(os.path.join(folder,
                                        str(title) + '1.pdf'),
                           format='pdf',
                           bbox_inches='tight')
        except:
            print 'Figure B has not been saved.'

    return x, c0, u_c0, c0_00, u_c0_00, c0_01, u_c0_01, c0_10, u_c0_10, c0_11, u_c0_11, x_labels, folder