Пример #1
0
	def perform_phenom_fit(self,key,plotting = False, ax = None):

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

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

		ii = self.find_index(key[0])

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

		fixed =[1]

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

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

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

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

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

		# print 'uncertainty ', p1_u;
		if len(key) == 1:
			self.pickle_dict[key[0]]['fit'] = fit_result
		else:
			self.pickle_dict[key[0]][key[1]]['fit'] = fit_result
Пример #2
0
def average_repump_time(contains='', do_fit=False, **kw):
    '''
    gets data from a folder whose name contains the contains variable.
    Does or does not fit the data with a gaussian function
    '''

    ### kw for fitting

    fit_offset = kw.pop('fit_offset', 0)
    fit_amplitude = kw.pop('fit_amplitude', 1)
    fit_x0 = kw.pop('fit_x0', None)
    fit_sigma = kw.pop('fit_sigma', 0.2)
    fixed = kw.pop('fixed', [])
    show_guess = kw.pop('show_guess', False)

    ### folder choice
    if contains == '':
        contains = 'Sweep_Repump_time'
    elif len(contains) == 2:
        contains = 'Sweep_Repump_time' + contains
    elif len(contains) == 1:
        contains = 'Sweep_Repump_time_' + contains

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

    if '_Z' in f:
        x, y, y_u = get_pos_neg_data(a, adwindata_str='Z_', **kw)
        ylabel = 'Z'
    else:
        x, y1, y1_u = get_pos_neg_data(a, adwindata_str='X_', **kw)
        x2, y2, y2_u = get_pos_neg_data(a, adwindata_str='Y_', **kw)
        y, y_u = quadratic_addition(y1, y2, y1_u, y2_u)
        # y=y1
        # y_u = y1_u
        ylabel = 'Bloch vector length'

    ### create a plot
    xlabel = a.g.attrs['sweep_name']
    x = a.g.attrs['sweep_pts']  # could potentially be commented out?
    title = kw.pop("title", "avg repump time")
    fig, ax = create_plot(f, xlabel=xlabel, ylabel=ylabel, title=title)

    if fit_x0 is None:
        max_idx = np.argmax(y)
        fit_x0 = x[max_idx]

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

    ### fitting if you feel like it
    if do_fit:

        p0, fitfunc, fitfunc_str = common.fit_gauss(fit_offset, fit_amplitude,
                                                    fit_x0, fit_sigma)

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

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

        try:
            fit_result['carbon_id'] = a.g.attrs['carbons'][0]
        except:
            pass

    ## save and close plot. We are done.
    save_and_close_plot(f)

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

    if kw.get('ret', False):
        return fit_result
Пример #3
0
	def perform_semi_pheno_model_fit(self,key, plotting = False, ax = None, xlim = None):

		if len(key) == 1:
			data = self.pickle_dict[key[0]]
		elif self.use_averaged:
			data = self.pickle_dict[key[0]]['state_dict_averaged'][key[1]]
		else:
			data = self.pickle_dict[key[0]][key[1]]

		evotime = data[timetrace_keylist[0]]
		fid = data[timetrace_keylist[1]]
		fid_u = data[timetrace_keylist[2]]


		if xlim != None:
			last_plot_point = xlim[-1]
		else:
			last_plot_point = evotime[-1]
		### find the position in the data dictionary
		i = self.find_index(key[0])

		# print 'this is the ', key

		if key[0] == '0' or key[0] == 'single_qubit' or key[0] == '00':
			t = 8.25
			p0, fitfunc, fitfunc_str = common.fit_gauss(self.fit_offset, 0.43, 0., t)
			fixed = [0,1]

			if self.process_fidelities:
				fixed = [1]

			if self.contrast:
				p0, fitfunc, fitfunc_str = common.fit_gauss(0, 0.43, 0., t)
				
			
			fit_result = fit.fit1d(evotime,fid, None, p0=p0, fitfunc=fitfunc, do_print=True, ret=True,fixed=fixed)

			if plotting:
				plot.plot_fit1d(fit_result, np.linspace(0.0,200,1001), ax=ax,color = color_list[i], plot_data=False,add_txt = False, lw = fit_lw)
			if key[0] == 'single_qubit':
				label_begin = '1Q'
			else: label_begin = key[0]

			self.results.append(label_begin + ' : T = ' + str(round(abs(fit_result['params'][-1]),2)) + ' +- ' + str(round(abs(fit_result['error'][-1]),2)))

			if key[0] == '0' or key[0] == '00':
				self.t = fit_result['params_dict']['sigma'] ### use t for the following fits with multiple measurements.
				self.A = fit_result['params_dict']['A']
				if self.process_fidelities:
					self.fit_offset = fit_result['params_dict']['a']


		else:
			if '0' not in self.pickle_dict.keys(): ### in exceptional cases there might be no 0 measurements reference
				self.t = 8.25

			if not self.process_fidelities and not self.contrast: ### logical decision for state fidelities.
				fit_result, result_string = ZAnalysis.fit_pheno_State_decay(key[0],ax,self.A*2,evotime,fid, t = self.t)

			elif self.process_fidelities:
				fit_result, result_string = ZAnalysis.fit_pheno_process_decay(key[0],ax,self.A,evotime,fid,'2',offset0 = self.fit_offset, t = self.t)

			elif self.contrast:
				fit_result, result_string = ZAnalysis.fit_pheno_State_decay(key[0],ax,self.A,evotime,fid,t = self.t,contrast = self.contrast)

			if plotting:
				plot.plot_fit1d(fit_result, np.linspace(0.0,200,1001), ax=ax, plot_data=False,color = color_list[i],add_txt = False, lw = fit_lw)
			
			# print fit_result['params_dict']
			result_string = str(round(abs(fit_result['params_dict']['t']),2)) + ' +- ' + str(round(fit_result['error_dict']['t'],2))
			self.results.append(key[0]+' : T = ' + result_string)

		# print 'uncertainty ', p1_u;
		if len(key) == 1:
			self.pickle_dict[key[0]]['fit'] = fit_result
		elif self.use_averaged:
			self.pickle_dict[key[0]]['state_dict_averaged'][key[1]]['fit'] = fit_result
		else:
			self.pickle_dict[key[0]][key[1]]['fit'] = fit_result
Пример #4
0
    def fit_gaussian(self, ax=None, ret_ax=False, **kw):
        """
        function that fits a gaussian, and returns the FWHM (not sigma).
        x and y can be given as input, ad well as all the parameter guesses.
        """
        y = kw.pop('y', self.y_data)
        x = kw.pop('x', self.frq_data)
        g_sigma = kw.pop('g_sigma', 10)
        plot_title = kw.pop('plot_title', '')
        plot_fit = kw.pop('plot_fit', False)
        save_plot = kw.pop('save_plot', True)
        fixed = kw.pop('fixed', [])
        label = kw.pop('label', '')
        g_a = np.nanmean(y)
        g_A = max(y) - g_a
        g_x0 = x[np.argmax(y)]

        p0, fitfunc, fitfunc_str = common.fit_gauss(g_a, g_A, g_x0, g_sigma)
        fit_result = fit.fit1d(x,
                               y,
                               None,
                               p0=p0,
                               fitfunc=fitfunc,
                               do_print=False,
                               ret=True,
                               fixed=fixed)
        if 'sigma' not in fit_result['params_dict']:
            print 'WARNING: COULD NOT FIT sigma'
            return 0, 10, 0

        sigma = np.abs(fit_result['params_dict']['sigma'])
        u_sigma = np.abs(fit_result['error_dict']['sigma'])
        x0 = fit_result['params_dict']['x0']
        FWHM = 2 * math.sqrt(2 * math.log(2)) * sigma
        u_FWHM = 2 * math.sqrt(2 * math.log(2)) * u_sigma

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

            if ret_ax:
                return FWHM, u_FWHM, ax

            plt.show(ax.get_figure())
            plt.close(ax.get_figure())

        return FWHM, u_FWHM, x0
Пример #5
0
            # V = V[0:len(V):10]
            # y = y[0:len(y):10]
            '''
			Start fitting
			'''

            offset = 0.00
            amplitude = max_value
            x0 = V[max_index]
            exponent = 1
            decay_constant = 3
            sigma = 0.0004
            gamma = 0.5

            if fitting_method == 'gauss':
                p0, fitfunc, fitfunc_str = common.fit_gauss(
                    offset, amplitude, x0, sigma)
            elif fitting_method == 'exp':
                p0, fitfunc, fitfunc_str = common.fit_general_exponential(
                    offset, amplitude, x0, decay_constant, exponent)
            elif fitting_method == 'lorentz':
                p0, fitfunc, fitfunc_str = common.fit_lorentz(
                    offset, amplitude, x0, gamma)

            fit_result = fit.fit1d(V,
                                   y,
                                   None,
                                   p0=p0,
                                   fitfunc=fitfunc,
                                   do_print=True,
                                   ret=True,
                                   fixed=fixed)
Пример #6
0
def return_phase_stab(contains, start_rep_no=3,mode='only_meas',**kw):
    base_folder_lt4 = analysis_params.data_settings['base_folder_lt4']
    folder = os.path.join(base_folder_lt4,contains)
    filename_str = kw.pop('filename_str','XsweepY')
    measfiles=tb.latest_data(contains = filename_str,folder =folder,return_all=True)

    x0s = []
    sigmas = []
    for measfile in measfiles:
        a = ppq.purifyPQAnalysis(measfile, hdf5_mode='r')

        # general params
        delay_stable = np.float(a.g.attrs['count_int_time_stab'])
        delay_meas = np.float(a.g.attrs['count_int_time_meas'])
    

        if mode == 'only_meas':
        
            sample_counts_1 = a.g['adwindata']['sampling_counts_1'].value
            sample_counts_2 = a.g['adwindata']['sampling_counts_2'].value
            sample_counts_1 = sample_counts_1[start_rep_no:]
            sample_counts_2 = sample_counts_2[start_rep_no:]

        
            delay = delay_meas
          
            v_1 = sample_counts_1
            v_2 = sample_counts_2
            t = np.arange(0, (len(v_1)*delay/1000), (float(delay)/1000))



        elif mode == 'only_stab':

            pid_counts_1 = a.g['adwindata']['pid_counts_1'].value
            pid_counts_2 = a.g['adwindata']['pid_counts_2'].value
            pid_counts_1 = pid_counts_1[start_rep_no:]
            pid_counts_2 = pid_counts_2[start_rep_no:]

            delay = delay_stable
          
            v_1 = pid_counts_1
            v_2 = pid_counts_2
            t = np.arange(0, (len(v_1)*delay/1000), (float(delay)/1000))
            
        g_0 = a.g.attrs['Phase_Msmt_g_0']
        visibility = a.g.attrs['Phase_Msmt_Vis']
       
        cosvals = [2*(float(n0)/(float(n0)+float(n1)*g_0)-0.5)*visibility for n0,n1 in zip(v_1,v_2)]
        cosvals = [cosval if np.abs(cosval) < 1 else (1.0 * np.sign(cosval)) for cosval in cosvals]
        angle = 180*np.arccos(cosvals)/np.pi

        hist, bins = np.histogram(angle,bins= 100,normed = True)
        width = np.diff(bins)
        center = (bins[:-1] + bins[1:]) / 2
        

        g_a = 0.0
        g_x0 = 90
        g_sigma = 45
        g_A = 1/(np.sqrt(2 * np.pi) * g_sigma)

        p0, fitfunc,fitfunc_str = common.fit_gauss(g_a, g_A, g_x0, g_sigma)
        fit_result = fit.fit1d(center,hist, None, p0=p0, fitfunc=fitfunc,
                             ret=True,fixed=[])

        x0s.append(fit_result['params_dict']['x0'])
        sigmas.append(fit_result['params_dict']['sigma'])
    return x0s, sigmas
Пример #7
0
def analyze_phase(contains, mode, plot_zoomed = [], start_rep_no = 1,**kw):
    # Import
    lt3_analysis = kw.pop('lt3_analysis', False)

    if not(lt3_analysis):
        measfile= tb.latest_data(contains)
    else:
        base_folder_lt4 = analysis_params.data_settings['base_folder_lt4']
        folder = os.path.join(base_folder_lt4,contains)
        filename_str = kw.pop('filename_str','XsweepY')
        measfile=tb.latest_data(contains = filename_str,folder =folder,return_all=False)

    a = ppq.purifyPQAnalysis(measfile, hdf5_mode='r')

    # general params
    

    delay_stable = np.float(a.g.attrs['count_int_time_stab'])
    delay_meas = np.float(a.g.attrs['count_int_time_meas'])
    pid_cycles = a.g.attrs['pid_points_to_store']
    if a.g.attrs['do_post_ent_phase_msmt'] and mode == 'do_only_meas':
        sample_cycles = 1
        max_repetitions = a.g['adwindata']['completed_reps'].value
    else:
        sample_cycles = a.g.attrs['sample_points']
        max_repetitions = a.g['adwindata']['store_index_stab'].value/a.g.attrs['pid_points_to_store']

    

    g_0 = a.g.attrs['Phase_Msmt_g_0']
    visibility = a.g.attrs['Phase_Msmt_Vis']

    
   
    if mode == 'only_meas':
    
        sample_counts_1 = a.g['adwindata']['sampling_counts_1'].value
        sample_counts_2 = a.g['adwindata']['sampling_counts_2'].value
        sample_counts_1 = sample_counts_1[(start_rep_no - 1)*sample_cycles:]
        sample_counts_2 = sample_counts_2[(start_rep_no - 1)*sample_cycles:]

    
        delay = delay_meas
        total_cycles = sample_cycles

        v_1 = sample_counts_1
        v_2 = sample_counts_2
        t = np.arange(0, (len(v_1)*delay/1000), (float(delay)/1000))



    elif mode == 'only_stab':

        pid_counts_1 = a.g['adwindata']['pid_counts_1'].value
        pid_counts_2 = a.g['adwindata']['pid_counts_2'].value
        pid_counts_1 = pid_counts_1[(start_rep_no - 1)*pid_cycles:]
        pid_counts_2 = pid_counts_2[(start_rep_no - 1)*pid_cycles:]

        delay = delay_stable
        total_cycles = pid_cycles

        v_1 = pid_counts_1
        v_2 = pid_counts_2
        t = np.arange(0, (len(v_1)*delay/1000), (float(delay)/1000))



    else:
        pid_counts_1 = a.g['adwindata']['pid_counts_1'].value
        pid_counts_2 = a.g['adwindata']['pid_counts_2'].value
        sample_counts_1 = a.g['adwindata']['sampling_counts_1'].value
        sample_counts_2 = a.g['adwindata']['sampling_counts_2'].value
        sample_counts_1 = sample_counts_1[(start_rep_no - 1)*sample_cycles:]
        sample_counts_2 = sample_counts_2[(start_rep_no - 1)*sample_cycles:]
        pid_counts_1 = pid_counts_1[(start_rep_no - 1)*pid_cycles:]
        pid_counts_2 = pid_counts_2[(start_rep_no - 1)*pid_cycles:]

        v_1 = []
        v_2 = []
        t = []
        angle = []

        for i in xrange(len(pid_counts_1)/pid_cycles):
            
            v_1.extend(pid_counts_1[i*pid_cycles:((i+1)*pid_cycles)])
            v_2.extend(pid_counts_2[i*pid_cycles:((i+1)*pid_cycles)])
            if len(t) == 0:
                t.extend(delay_stable * (1 + np.arange(pid_cycles)))
            else:
                t.extend(t[-1] + delay_stable * (1 + np.arange(pid_cycles)))

            v_1.extend(sample_counts_1[i*sample_cycles:((i+1)*sample_cycles)])
            v_2.extend(sample_counts_2[i*sample_cycles:((i+1)*sample_cycles)])
            if len(t) == 0:
                t.extend(delay_meas * (1 + np.arange(sample_cycles)))
            else:
                t.extend(t[-1] + delay_meas * (1 + np.arange(sample_cycles)))
        t = np.array(t)
        total_cycles = pid_cycles + sample_cycles

    cosvals = [2*(float(n0)/(float(n0)+float(n1)*g_0)-0.5)*visibility for n0,n1 in zip(v_1,v_2)]
    cosvals = [cosval if np.abs(cosval) < 1 else (1.0 * np.sign(cosval)) for cosval in cosvals]
    angle = 180*np.arccos(cosvals)/np.pi

   


    # counts
    fig = plt.figure(figsize=(17,6))
    ax = plt.subplot(211)
    plt.plot(t, v_1, 'b')
    plt.title('Counts ZPL detector 1 {0}'.format(a.folder))
    ax.set_xlabel('elapsed time (ms)')
    ax.set_ylabel('counts')
    ax2 = plt.subplot(212)
    plt.plot(t, v_2, 'b')
    plt.title('Counts ZPL detector 2 {0}'.format(a.folder))
    ax2.set_xlabel('elapsed time (ms)')
    ax2.set_ylabel('counts')
    plt.tight_layout()  
    fig.savefig(os.path.join(a.folder, 'trace_counts.png'))

    if len(plot_zoomed):
        
        fig = plt.figure(figsize=(17,6))
        ax = plt.subplot(111)
        plt.plot(t[total_cycles*plot_zoomed[0]:total_cycles*plot_zoomed[1]], angle[total_cycles*plot_zoomed[0]:total_cycles*plot_zoomed[1]])
        plt.title('Zoomed trace {0}'.format(a.folder))
        ax.set_xlabel('elapsed time (milliseconds)')
        ax.set_ylabel('Phase')
        plt.tight_layout()
        fig.savefig(os.path.join(a.folder, 'trace_zoomed.png'))

    # phase
    fig = plt.figure(figsize=(17,6))
    ax = plt.subplot(111)
    plt.plot(t, angle, 'r')
    plt.title('Phase of ZPL photons {0}'.format(a.folder))
    plt.ylim([0,180])
    ax.set_xlabel('elapsed time (ms)')
    ax.set_ylabel('angle ($^o$)')
    fig.savefig(os.path.join(a.folder, 'trace_angle.png'))


    # fft

    if mode == 'only_meas' or mode == 'only_stab':

        yf = np.abs(scipy.fftpack.fft(angle))
        xf = np.linspace(0, 1.0/(2*delay*1e-6), len(angle)/2)

        fig, ax = plt.subplots()
        ymax = 1.2*np.max(yf[15:-15])
        plt.ylim([0,ymax])
        ax.plot(xf[:len(yf)], yf[:len(yf)/2])
        xlim = plt.xlim()
        if (xlim[1]>1000):
            plt.xlim(0,1000)
        plt.title('FFT {0}'.format(a.folder))
        ax.set_xlabel('frequency (Hz)')
        ax.set_ylabel('Amplitude (a.u.)')
        fig.savefig(os.path.join(a.folder, 'fft.png'))

    # histogram
    fig = plt.figure()
    ax = plt.subplot(111)
    hist, bins = np.histogram(angle,bins= 100,normed = True)
    width = np.diff(bins)
    center = (bins[:-1] + bins[1:]) / 2
    ax.bar(center, hist, align='center', width=width)
    g_a = 0.0
    g_x0 = 90
    g_sigma = 45
    g_A = 1/(np.sqrt(2 * np.pi) * g_sigma)

    p0, fitfunc,fitfunc_str = common.fit_gauss(g_a, g_A, g_x0, g_sigma)
    fit_result = fit.fit1d(center,hist, None, p0=p0, fitfunc=fitfunc,
                         ret=True,fixed=[])
    plot.plot_fit1d(fit_result, np.linspace(center[0],center[-1],201), ax=ax, 
                        plot_data=False,print_info = True)

    ax.set_xlabel('Phase')
    fig.savefig(os.path.join(a.folder, 'histogram.png'))
    if len(fit_result['params_dict']):
        print 'x0, sigma ', fit_result['params_dict']['x0'] , fit_result['params_dict']['sigma'] 

    # standard dev
    fig = plt.figure()
    ax = plt.subplot(111)
    angle_reshape = (np.reshape(angle,[total_cycles,-1]))
    binsize = 1.0
    var_array = np.zeros([int(np.floor(total_cycles/binsize)),1])
    for x in range(int(np.floor(total_cycles/binsize))):
        var_array[x] = np.sqrt(np.var(angle_reshape[binsize*x:binsize*(x+1),:]))


    plt.plot(binsize*t[0:(int(np.floor(total_cycles/binsize)))], var_array)
    plt.title('Standard deviation of Phase {0}'.format(a.folder))
    ax.set_xlabel('time (ms)')
    ax.set_ylabel('std dev ($^o$)')