def analyze_SP_RO(sp_file, params,folder='',plot=True,save=True,do_print=False,ret = False,name='spin_pumping.png'):
    '''
    Function to plot and fit a single SP or RO curve. 
    

    sp_file     string      (part of) the filename that contains data of interest
    folder      string      folder that contains the data
    '''     
    
    if folder == '':
        folder = os.getcwd()

    v = load(folder+'\\'+sp_file)
    Ex_RO_power = params['Ex_RO_amplitude']
    A_RO_power = params['Ex_RO_amplitude']
    Ex_SP_power = params['Ex_SP_amplitude']
    A_SP_power = params['A_SP_amplitude']

    if 'Spin_RO' in sp_file:
        sp_counts = sum(v['counts'],axis=0)
        title = 'RO Powers: Ex = ' + str(Ex_RO_power*1E9) + 'nW, A = ' + str(A_RO_power*1E9) + 'nW'
    else:
        sp_counts = v['counts']
        title = 'SP Powers: Ex = ' + str(Ex_SP_power*1E9) + 'nW, A = ' + str(A_SP_power*1E9) + 'nW'
        
    
    sp_time = v['time']
    v.close()

    offset_guess = sp_counts[len(sp_counts)-1]
    init_amp_guess = max(sp_counts)
    firstpoint=int(find_nearest(sp_counts,init_amp_guess))

    decay_guess = 10

    if plot:
        figure4 = plt.figure(4)
        plt.clf()

    fit_result=fit.fit1d(sp_time[firstpoint:len(sp_counts)-1]/1E3, sp_counts[firstpoint:len(sp_counts)-1], common.fit_exp_decay_with_offset, 
            offset_guess, init_amp_guess, decay_guess,
            do_plot = plot, do_print = do_print, newfig = False, ret=True,
            plot_fitparams_xy = (0.5,0.5))
    
    if plot:
       
        plt.plot(sp_time/1E3,sp_counts,'sg')
        plt.xlabel('Time ($\mu$s)')
        plt.ylabel('Integrated counts')
        plt.title(title)
        plt.ylim(ymax=max(sp_counts)*1.2)
        plt.text(0.01*(max(sp_time/1E3)+min(sp_time/1E3)),1.15*max(sp_counts),folder+sp_file,fontsize='x-small')
    
        if save:
            figure4.savefig(folder+'\\'+name+'.png')

    if ret:
        return fit_result
Пример #2
0
    def calibrate(self, steps): # calibration values in uW
        rng = arange(0,steps)
        x = zeros(steps,dtype = float)
        y = zeros(steps,dtype = float)
        
        self.apply_voltage(0)
        self._ins_pm.set_wavelength(self._wavelength*1e9)
        time.sleep(2)
        bg = self._ins_pm.get_power()

        print 'background power: %.4f uW' % (bg*1e6)

        time.sleep(2)

        V_max = self.get_V_max()
        V_min = self.get_V_min()
        
        if V_max + V_min < 0: rng=flipud(rng)
        
        for a in rng:
            x[a] = a*(V_max-V_min)/float(steps-1)+V_min
            self.apply_voltage(x[a])
            time.sleep(1)
            y[a] = self._ins_pm.get_power() - bg
            
            print 'measured power at %.2f V: %.4f uW' % \
                    (a*(V_max-V_min)/float(steps-1)+V_min, y[a]*1e6)
        
        #x= x*(V_max-V_min)/float(steps-1)+V_min 
        a, xc, k = copysign(max(y), V_max + V_min), copysign(.5, V_max + V_min), copysign(5., V_max + V_min)
        fitres = fit.fit1d(x,y, common.fit_AOM_powerdependence, 
                a, xc, k, do_print=True, do_plot=False, ret=True)
     
        fd = zeros(len(x))        
        if type(fitres) != type(False):
            p1 = fitres['params_dict']
            self.set_cal_a(p1['a'])
            self.set_cal_xc(p1['xc'])
            self.set_cal_k(p1['k'])
            fd = fitres['fitdata']
        else:
            print 'could not fit calibration curve!'
        
        dat = qt.Data(name= 'aom_calibration_'+self._name+'_'+\
                self._cur_controller)
        dat.add_coordinate('Voltage [V]')
        dat.add_value('Power [W]')
        dat.add_value('fit')
        dat.create_file()
        plt = qt.Plot2D(dat, 'rO', name='aom calibration', coorddim=0, valdim=1, 
                clear=True)
        plt.add_data(dat, coorddim=0, valdim=2)
        dat.add_data_point(x,y,fd)
        dat.close_file()
        plt.save_png(dat.get_filepath()+'png')

        self.save_cfg()
        print (self._name+' calibration finished')
def plot_esr(datapath,
             fit_data=True,
             save=True,
             f_dip=2.828E9,
             msplusone=False,
             Zsplitting=35e6):
    plt.close('all')
    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)

    for k in files:
        if '.npz' in k:
            data_file = k

    data = np.load(datapath + '\\' + data_file)

    mw_freq = data['freq']
    counts = data['counts']
    data.close()

    f_dip_guess = f_dip
    offset_guess = counts.max()
    dip_depth_guess = offset_guess - counts.min()
    width_guess = 5e-3

    if msplusone:
        noof_dips = 2
        dip_separation = Zsplitting
    else:
        noof_dips = 1
        dip_separation = 0

    if fit_data:
        figure2 = plt.figure(2)
        figure2.clf()
        fit_res = fit.fit1d(mw_freq / 1E9,
                            counts,
                            common.fit_gauss,
                            offset_guess,
                            dip_depth_guess,
                            f_dip_guess / 1E9,
                            width_guess,
                            do_plot=True,
                            do_print=True,
                            newfig=False)

    print fit_res
    plt.plot(mw_freq / 1E9, counts, '-k')
    plt.xlabel('MW frequency (GHz)')
    plt.ylabel('Integrated counts')
    plt.title('MW frequency sweep')
    #, power = '+num2str(mwpower,0)+' dBm)
    #plt.text(0.1*(mw_max_freq+mw_min_freq),max(counts_during_readout),datapath)
    if save:
        figure2.savefig(datapath + '\\esr_data.png')
    def calibrate(self, steps): # calibration values in uW
        x = arange(0,steps)
        y = zeros(steps,dtype = float)
        
        self.apply_voltage(0)
        ins_pm.set_wavelength(self._wavelength*1e9)
        time.sleep(2)
        bg = ins_pm.get_power()

        print 'background power: %.4f uW' % (bg*1e6)

        time.sleep(2)

        V_max = self.get_V_max()
        
        for a in x:
            self.apply_voltage(a*V_max/(steps-1))
            time.sleep(1)
            y[a] = ins_pm.get_power() - bg
            
            print 'measured power at %.2f V: %.4f uW' % \
                    (a/float(steps-1)*V_max, y[a]*1e6)
        
        x = x/float(steps-1)*V_max    
        a, xc, k = max(y), .5, 5.
        fitres = fit.fit1d(x,y, common.fit_AOM_powerdependence, 
                a, xc, k, do_print=True, do_plot=False, ret=True)
     
        fd = zeros(len(x))        
        if type(fitres) != type(False):
            p1 = fitres['params_dict']
            self.set_cal_a(p1['a'])
            self.set_cal_xc(p1['xc'])
            self.set_cal_k(p1['k'])
            fd = fitres['fitdata']
        else:
            print 'could not fit calibration curve!'
        
        
        dat = qt.Data(name='aom_calibration_'+self._name+'_'+\
                self._cur_controller)
        dat.add_coordinate('Voltage [V]')
        dat.add_value('Power [W]')
        dat.add_value('fit')
        dat.create_file()
        plt = qt.Plot2D(dat, 'rO', name='aom calibration', coorddim=0, valdim=1, 
                clear=True)
        plt.add_data(dat, coorddim=0, valdim=2)
        dat.add_data_point(x,y,fd)
        dat.close_file()
        
        self.save_cfg()
        print (self._name+' calibration finished')
Пример #5
0
def spin_flip_time_vs_MW_freq(folder='', x_axis_par='par_MW_freq'):
    
    if folder == '':
        folder = os.getcwd()
    
    print get_param_column(os.path.join(folder,'SSRO_preselect-0_parameters.dat'),'par_cr_threshold')

    allfiles = os.listdir(folder)
    rofiles = [f for f in allfiles if ('_ro_countrate' in f and '.dat' in f)]
 
    x_axis = []
    spin_flip_time = []
    
    for f in rofiles:
        fn, ext = os.path.splitext(f)
        print fn
        idx = int(fn[fn.find('SSRO_preselect-')+15:fn.find('_ro_countrate')])
        basepath = os.path.join(folder, PREFIX+'-'+str(idx))
        parfile = basepath+'_'+PARAMS_SUFFIX+'.dat'  
        x_axis.append(loadtxt(parfile)[get_param_column(parfile,x_axis_par)]/1.0e9) #MW freq in GHz
        
        ro_data= loadtxt(f)
        
        t = ro_data[:,0]/1000 #time in us
        y = ro_data[:,1] #cnts
        #a : offset ~ 0, A : Amplitude, tau : spin_flip_time ~ 20 us
        a, A, tau = 0, max(y), 20
        
        #debug: CHECKING TODO
        print idx
        print 't', t
        print 'y' , y 
        #break


        
        fitres = fit.fit1d(t,y, common.fit_exp_decay_with_offset, \
                a, A, tau, do_print=True, do_plot=False, ret=True)

        if type(fitres) != type(False):
            p1 = fitres['params_dict']
            spin_flip_time.append(p1['tau'])
        else:    
            print 'could not fit exponential curve for file index ', idx 

    fig = plt.figure()
    plt.plot(x_axis, spin_flip_time, 'ro', label='spin flip time vs MW freq')
    plt.xlabel('MW frequqncy [GHz]')
    plt.ylabel('spin flip time [ns]')
    plt.legend()
def plot_esr(datapath, fit_data = True, save = True, f_dip = 2.828E9,msplusone=False,Zsplitting=35e6):
    plt.close('all')
    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)
    
    for k in files:
        if '.npz' in k:
            data_file = k


    data = np.load(datapath+'\\'+data_file)

    mw_freq = data['freq']
    counts = data['counts']
    data.close()

    f_dip_guess=f_dip
    offset_guess = counts.max()
    dip_depth_guess = offset_guess - counts.min()
    width_guess = 5e-3
    

    if msplusone:
        noof_dips = 2
        dip_separation = Zsplitting
    else:
        noof_dips = 1
        dip_separation=0

    if fit_data:
        figure2 = plt.figure(2)
        figure2.clf()
        fit_res=fit.fit1d(mw_freq/1E9, counts, common.fit_gauss, 
            offset_guess, dip_depth_guess, f_dip_guess/1E9,width_guess,
            do_plot = True, do_print = True, newfig = False)
    
    
    print fit_res
    plt.plot(mw_freq/1E9,counts, '-k')
    plt.xlabel('MW frequency (GHz)')
    plt.ylabel('Integrated counts')
    plt.title('MW frequency sweep')
#, power = '+num2str(mwpower,0)+' dBm)
    #plt.text(0.1*(mw_max_freq+mw_min_freq),max(counts_during_readout),datapath)
    if save:
        figure2.savefig(datapath+'\\esr_data.png')
Пример #7
0
def rabi_calibration(datapath,fit_data = True, save = True,close_fig=True,new_fig=True):

    """ 
    Fits results from a spin_control data using a FFT. 
    Datapath should be a folder that contains the actual measurement results,
    so for example: datapath = 'D:\data\yyyymmdd\hhmmss_spin_control_suffix'
    Flag fit_data if data should be fit.
    Flag save if data should be saved (in the data directory)

    """

    print 'Analyzing spin control data...'

    # Create directories for saving figures and saving processed data:
    if not os.path.exists(os.path.join(datapath,'figures')):
        os.makedirs(os.path.join(datapath,'figures'))
    if not os.path.exists(os.path.join(datapath,'processed_data')): 
        os.makedirs(os.path.join(datapath,'processed_data'))

    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)
    
    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath+'\\'+stats_params_file)
    f_drive = e['mw_drive_freq']
    mwpower = e['mw_power']
    mw_min_len = e['min_sweep_par']
    mw_max_len = e['max_sweep_par']
    name=e['sweep_par_name']
    noof_datapoints = e['noof_datapoints']
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################
    
    g = np.load(datapath+'\\'+spin_ro_file)
    raw_counts = g['counts']
    SSRO_raw = g['SSRO_counts']
    repetitions = g['sweep_axis']
    t = g['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size/float(noof_datapoints)

    idx = 0
    counts_during_readout = np.zeros(noof_datapoints)
    mw_len = np.linspace(mw_min_len,mw_max_len,noof_datapoints)
    counts_during_readout = np.sum(raw_counts, axis = 1)

    SSRO = np.zeros(noof_datapoints)
    SSRO = np.sum(SSRO_raw, axis = 1)

    #########################################
    ############ FITTING ####################
    #########################################
    
    if fit_data:
        FFT = np.fft.fft(SSRO)
        N = int(noof_datapoints)
        timestep = (mw_max_len-mw_min_len)/float(noof_datapoints-1)
        freq = np.fft.fftfreq(N,d = timestep)

        #Remove offset:
        FFT[freq == 0] = 0

        plot1 = qt.Plot2D(freq*1E3, abs(FFT), 'sb',name='FFT',clear=True)
        plot1.set_xlabel('Frequency (MHz)')
        plot1.set_ylabel('Amplitude')
        plot1.set_plottitle('FFT (offset removed)')
        plot1.set_title('FFT')

        if save:
            plot1.save_png(os.path.join(datapath, 'figures', 'fft_signal_rabi.png'))

        freq_guess = freq[find_nearest(abs(FFT),abs(FFT).max())]
        amp_guess = (SSRO.max()+SSRO.min())/2.0
        offset_guess = SSRO.min()+(SSRO.max()+\
                SSRO.min())/2.0
        phase_guess = 0

        #print 'frequency guess = ',freq_guess

        fit_result = fit.fit1d(mw_len, SSRO, rabi.fit_rabi_simple, 
                freq_guess, amp_guess, offset_guess, phase_guess,
                do_plot = False, ret = True)
        print fit_result
        f = fit_result['params_dict']['f']
        a = fit_result['params_dict']['a']
        A = fit_result['params_dict']['A']
        phi = fit_result['params_dict']['phi']
        x = np.linspace(mw_min_len, mw_max_len, 501)

        fit_curve = a + A*np.cos(2*np.pi*(f*x + phi/360))

        pi_pulse_len = 0.5*1/f
        pi_2_pulse_len = 0.5*pi_pulse_len


    name= spin_ro_file[:len(spin_ro_file)-16]
    if new_fig:
        plot2 = qt.Plot2D(mw_len, SSRO, 'sk',
                title=name, name='MWCal',clear=True)
        plot2.add(x,fit_curve, '-r',title='fit '+name)
    else:
        plot2 = qt.plots['Cal']
        plot2.add(mw_len, SSRO, 'xk',title=name)
        plot2.add(x,fit_curve, '-r',title='fit '+name)
    plot2.set_xlabel(name)
    plot2.set_ylabel('SSRO (not corrected)')
    plot2.set_plottitle(str(name) + ' , driving f ='+num2str(f_drive/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm'+datapath)
    
    #plot2.text(0.1*(mw_max_len+mw_min_len),max(SSRO),datapath)
    if save:
        plot2.save_png(os.path.join(datapath,'figures', 'histogram_integrated'))
    g.close()
    plot1.clear()
    plot1.quit()
    if close_fig:
        plot2.clear()
        plot2.quit()

    if save:
        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: MW length (ns)\tCol1: SSRO\n'
        col_vals = str()
        for k in np.arange(noof_datapoints):
            col_vals += num2str(mw_len[k],2)+'\t'+num2str(SSRO[k],0)+'\n'
        fo = open(os.path.join(datapath, 'processed_data', 'mw_pi_calibration_SSRO.dat'), "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()
    
    if 'len' in name:
        minimum = pi_pulse_len
        
    else:
        minimum=x[find_nearest(fit_curve,fit_curve.min())]
    
    rabi_dict={"minimum":minimum,"Amplitude":A,"offset":a, "freq":f,"lowest_meas_value":SSRO.min()}
    return rabi_dict
Пример #8
0
data = load('Rabi-0_SpinReadout.npz')

j = 0
time = []
counts = []

for i in data['MW burst time']:
    time.append(i)
    print j
    counts.append(sum(data['counts'][j]))
    j = j + 1

amp = (max(counts) - min(counts)) / 2.
offset = (max(counts) + min(counts)) / 2.
freq = 0.001
decay = 500.

plt.plot(time, counts, 'o')
fit_result = fit.fit1d(np.array(time),
                       np.array(counts),
                       rabi.fit_rabi_damped_exp,
                       freq,
                       amp,
                       offset,
                       decay,
                       do_plot=True,
                       ret=True)
plt.show()
plt.savefig('rabi_fitted.png')
def plot_SE(datapath, fid=(0.82,0.9),fiderr=(0.01,0.01),fit_data = True, exp_guess=2.8, save = True):

    plt.close('all')
    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)
    
    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath+'\\'+stats_params_file)
    f_drive = e['mw_drive_freq']
    mwpower = e['mw_power']
    tau_max = e['tau_max']
    tau_min = e['tau_min']
    #frabi = e['frabi']
    frabi=11.

    noof_datapoints = e['noof_datapoints']
    noof_reps = e['completed_repetitions']
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################
    
    f = np.load(datapath+'\\'+spin_ro_file)
    raw_counts = f['counts']
    SSRO_counts = f['SSRO_counts']
    repetitions = f['sweep_axis']
    t = f['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size/float(noof_datapoints)

    idx = 0
    counts_during_readout = zeros(noof_datapoints)
    tau_free_evol = linspace(tau_min,tau_max,noof_datapoints)*2e-3
    counts_during_readout = sum(raw_counts, axis = 1)
    SSRO_readout = sum(SSRO_counts, axis = 1)/float(noof_reps)
    SSRO_readout_corr = zeros(len(SSRO_readout))
    readout_error = zeros(len(SSRO_readout))

    for i in arange(len(SSRO_readout)):
        ms0_events = SSRO_readout[i]*noof_reps
        ms1_events = noof_reps*(1-SSRO_readout[i])
        corr = SSRO_correct(array([ms1_events,ms0_events]),F0=fid[0],F1=fid[1],F0err=fiderr[0],F1err=fiderr[1])
        SSRO_readout_corr[i]=corr[0][0]
        readout_error[i] = corr[1][0] 

    #########################################
    ############ FITTING ####################
    #########################################
    #FIXME: write nice fitting routine for SE
    
    figure2 = plt.figure(2)
        

    plt.plot(tau_free_evol,counts_during_readout, 'sk')
    plt.xlabel('Free evolution time [us]')
    plt.ylabel('Integrated counts')
    plt.title('Spin Echo, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, frabi = '+num2str(frabi,0)+' MHz')
    plt.text(0.1*(max(tau_free_evol)+min(tau_free_evol)),max(counts_during_readout),datapath)
    if save:
        figure2.savefig(datapath+'\\histogram_integrated.png')

    figure4 = plt.figure(4)
  
    plt.plot(tau_free_evol,SSRO_readout, 'sk')
    plt.xlabel('Free evolution time [us]')
    plt.ylabel('Fraction of events >0 counts')
    plt.title('Spin Echo SSRO cor, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, frabi = '+num2str(frabi,0)+' MHz')
    plt.text(0.1*(max(tau_free_evol)+min(tau_free_evol)),max(SSRO_readout),datapath)
    if save:
        figure4.savefig(datapath+'\\SSRO_readout.png')    

    figure6 = plt.figure(6)
        
    if fit_data:
        tau_guess = 530
        offset_guess = SSRO_readout_corr.min()
        amp_guess=SSRO_readout_corr.max()-offset_guess

        print tau_guess
        print offset_guess
        print amp_guess
        print tau_guess
        print exp_guess
        print tau_free_evol

        fitresult=fit.fit1d(tau_free_evol, SSRO_readout_corr, 
                SE.fit_echo, tau_guess, amp_guess,offset_guess, 
                exp_guess, do_plot = True, do_print = True, newfig = False)
        print fitresult
    plt.errorbar(tau_free_evol,SSRO_readout_corr,fmt='sk',yerr=readout_error)
    plt.xlabel('Free evolution time [us]')
    plt.ylabel('P ms=0')
    plt.title('Spin Echo SSRO cor, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, frabi = '+num2str(frabi,0)+' MHz')
    plt.text(0.1*(max(tau_free_evol)+min(tau_free_evol)),max(SSRO_readout_corr),datapath)
    if save:
        figure6.savefig(datapath+'\\SSRO_readout_corr.png')  


    x = 6.0
    y = 8.0

    figure3 = plt.figure(figsize=(x,y))
    plt.pcolor(raw_counts, cmap = 'hot', antialiased=False)
    plt.xlabel('Readout time (us)')
    plt.ylabel('MW repetition number')
    plt.title('Total histogram, integrated over repetitions')
    plt.colorbar()
    if save:
        figure3.savefig(datapath+'\\histogram_counts_2d.png')

    f.close()
    

    ###########################################
    ######## SPIN PUMPING #####################
    ###########################################
    v = np.load(datapath+'\\'+sp_file)
    sp_counts = v['counts']
    sp_time = v['time']

    offset_guess = sp_counts[len(sp_counts)-1]
    init_amp_guess = sp_counts[2]
    decay_guess = 10

    figure5 = plt.figure(5)
    fit.fit1d(sp_time/1E3, sp_counts, common.fit_exp_decay_with_offset, 
            offset_guess, init_amp_guess, decay_guess,
            do_plot = True, do_print = True, newfig = False,
            plot_fitparams_xy = (0.5,0.5))
    
    plt.plot(sp_time/1E3,sp_counts,'sg')
    plt.xlabel('Time ($\mu$s)')
    plt.ylabel('Integrated counts')
    plt.title('Spin pumping')
    v.close()
    if save:
        figure5.savefig(datapath+'\\spin_pumping.png')

        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: Interpulse delay (ns)\tCol1: Integrated counts\tCol2: SSRO corr\n'
        col_vals = str()
        for k in arange(noof_datapoints):
            col_vals += num2str(tau_free_evol[k],2)+'\t'+num2str(counts_during_readout[k],0)+'\t'+num2str(SSRO_readout_corr[k],2)+'\n'
        fo = open(datapath+'\\integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    return True
def plot_ramsey(datapath, fit_data = True, save = True):

    plt.close('all')
    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)
    
    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath+'\\'+stats_params_file)
    f_drive = e['mw_drive_freq']
    detuning = e['detuning']
    mwpower = e['mw_power']
    tau_max = e['tau_min']
    tau_min = e['tau_max']
    #pi_2_duration = e['pi_2_duration']
    pi_2_duration=25
    noof_datapoints = e['noof_datapoints']
    noof_reps = e['completed_repetitions']
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################
    
    f = np.load(datapath+'\\'+spin_ro_file)
    raw_counts = f['counts']
    SSRO_counts = f['SSRO_counts']
    repetitions = f['sweep_axis']
    t = f['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size/float(noof_datapoints)

    idx = 0
    counts_during_readout = zeros(noof_datapoints)
    tau = linspace(tau_min,tau_max,noof_datapoints)
    counts_during_readout = sum(raw_counts, axis = 1)
    SSRO_readout = sum(SSRO_counts, axis = 1)/float(noof_reps)
    #########################################
    ############ FITTING ####################
    #########################################
    print fit_data
    if fit_data:
        FFT = fft.fft(counts_during_readout)
        N = int(noof_datapoints)
        timestep = (mw_max_len-mw_min_len)/float(noof_datapoints-1)
        freq = fft.fftfreq(N,d = timestep)

        #Remove offset:
        FFT[freq == 0] = 0

        figure1 = plt.figure(1)
        plt.bar(freq*1E3,abs(FFT), width = 0.4*1E3*(freq[1]-freq[0]), align = 'center')
        plt.xlabel('Frequency (MHz)')
        plt.ylabel('Amplitude')
        plt.title('FFT (offset removed)')
        
        if save:
            figure1.savefig(datapath+'\\fft_signal_rabi.png')

        offset_guess = counts_during_readout.min()+(counts_during_readout.max()+\
                counts_during_readout.min())/2.0
        tau_guess = 1000
        
        #modulations:
        mod_freq_guess = freq[find_nearest(abs(FFT),abs(FFT).max())]
        mod_amp_guess = (counts_during_readout.max()+counts_during_readout.min())/2.0
        mod_phase_guess = 0

        print 'modulation frequency guess = ',freq_guess 
        print 'modulation amplitude guess = ',mod_amp_guess

    figure2 = plt.figure(2)
        
    if fit_data:
        tau_guess = 200
        fit.fit1d(tau, counts_during_readout, 
                ramsey.fit_ramsey_gaussian_decay, 
                tau_guess, offset_guess, 
                (mod_freq_guess,mod_amp_guess,mod_phase_guess),
                do_plot = True, do_print = True, newfig = False)
    print SSRO_readout
    plt.plot(tau,SSRO_readout, 'sk')
    plt.xlabel('\Delta t$ (ns)')
    plt.ylabel('Integrated counts')
    plt.title('Ramsey, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm,\n Detuning = '+\
            num2str(detuning/1E6,0)+' MHz, $\pi/2$ length = '+\
            num2str(pi_2_duration,0)+' ns')
    plt.text(0.1*(tau_max+tau_min),max(counts_during_readout),datapath)
    if save:
        figure2.savefig(datapath+'\\histogram_integrated.png')

    x = 6.0
    y = 8.0

    figure3 = plt.figure(figsize=(x,y))
    plt.pcolor(raw_counts, cmap = 'hot', antialiased=False)
    plt.xlabel('Readout time (us)')
    plt.ylabel('MW repetition number')
    plt.title('Total histogram, integrated over repetitions')
    plt.colorbar()
    if save:
        figure3.savefig(datapath+'\\histogram_counts_2d.png')

    f.close()
    

    ###########################################
    ######## SPIN PUMPING #####################
    ###########################################
    v = np.load(datapath+'\\'+sp_file)
    sp_counts = v['counts']
    sp_time = v['time']

    offset_guess = sp_counts[len(sp_counts)-1]
    init_amp_guess = sp_counts[2]
    decay_guess = 10

    figure4 = plt.figure(4)
    fit.fit1d(sp_time/1E3, sp_counts, common.fit_exp_decay_with_offset, 
            offset_guess, init_amp_guess, decay_guess,
            do_plot = True, do_print = True, newfig = False,
            plot_fitparams_xy = (0.5,0.5))
    
    plt.plot(sp_time/1E3,sp_counts,'sg')
    plt.xlabel('Time ($\mu$s)')
    plt.ylabel('Integrated counts')
    plt.title('Spin pumping')
    v.close()
    if save:
        figure4.savefig(datapath+'\\spin_pumping.png')

        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: Interpulse delay (ns)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in arange(noof_datapoints):
            col_vals += num2str(tau[k],2)+'\t'+num2str(counts_during_readout[k],0)+'\n'
        fo = open(datapath+'\\integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    return True
def plot_Pulse_cal_time(datapath, fit_data=True, save=True):

    plt.close('all')
    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)

    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath + '\\' + stats_params_file)
    f_drive = e['mw_drive_freq']
    mwpower = e['mw_power']
    min_amp = e['min_pulse_amp']
    max_amp = e['max_pulse_amp']
    min_time = e['min_time']
    max_time = e['max_time']
    noof_datapoints = e['noof_datapoints']
    noof_reps = e['completed_repetitions']
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################

    f = np.load(datapath + '\\' + spin_ro_file)
    raw_counts = f['counts']
    repetitions = f['sweep_axis']
    SSRO_counts = f['SSRO_counts']
    t = f['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size / float(noof_datapoints)

    idx = 0
    counts_during_readout = zeros(noof_datapoints)
    delay_time = linspace(min_time, max_time, noof_datapoints)
    amp = linspace(min_amp, max_amp, noof_datapoints)
    counts_during_readout = sum(raw_counts, axis=1)
    SSRO_readout = sum(SSRO_counts, axis=1) / float(noof_reps)

    #########################################
    ############ FITTING ####################
    #########################################

    #FIXME to be implemented
    figure2 = plt.figure(2)
    plt.plot(delay_time, SSRO_readout, 'sk')
    plt.xlabel('time between CORPSE pulses [ns]')
    plt.ylabel('P ms=0')
    plt.title('MW length sweep, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm')
    #plt.text(0.1*(mw_max_len+mw_min_len),max(counts_during_readout),datapath)
    if save:
        figure2.savefig(datapath + '\\histogram_integrated.png')

    x = 6.0
    y = 8.0

    figure3 = plt.figure(figsize=(x, y))
    plt.pcolor(raw_counts, cmap='hot', antialiased=False)
    plt.xlabel('Readout time (us)')
    plt.ylabel('MW repetition number')
    plt.title('Total histogram, integrated over repetitions')
    plt.colorbar()
    if save:
        figure3.savefig(datapath + '\\histogram_counts_2d.png')

    f.close()

    ###########################################
    ######## SPIN PUMPING #####################
    ###########################################
    v = np.load(datapath + '\\' + sp_file)
    sp_counts = v['counts']
    sp_time = v['time']

    offset_guess = sp_counts[len(sp_counts) - 1]
    init_amp_guess = sp_counts[2]
    decay_guess = 10

    figure4 = plt.figure(4)
    fit.fit1d(sp_time / 1E3,
              sp_counts,
              common.fit_exp_decay_with_offset,
              offset_guess,
              init_amp_guess,
              decay_guess,
              do_plot=True,
              do_print=True,
              newfig=False,
              plot_fitparams_xy=(0.5, 0.5))

    plt.plot(sp_time / 1E3, sp_counts, 'sg')
    plt.xlabel('Time ($\mu$s)')
    plt.ylabel('Integrated counts')
    plt.title('Spin pumping')
    v.close()
    if save:
        figure4.savefig(datapath + '\\spin_pumping.png')

        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#' + time.ctime() + '\n'
        col_names = '#Col0: MW length (ns)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in arange(noof_datapoints):
            col_vals += num2str(amp[k], 2) + '\t' + num2str(
                counts_during_readout[k], 0) + '\n'
        fo = open(datapath + '\\integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    return True
def autoanalyze_single_ssro(rodata,
                            spdata,
                            crdata,
                            save_basepath,
                            binsize=0.131072,
                            reps=1e4,
                            ms=0,
                            closefigs=True,
                            stop=0,
                            firstbin=0):
    """
    Analyzes a single SSRO measurement (can do both ms=0/+-1).
    creates an overview plot over the measurement results, and a plot
    of the measurement fidelity vs the measurement time.
    saves the fidelities and errors vs ro time.

    """

    if stop == 0:
        stop = rodata['time'][-1] / 1e3
        sp_stop = spdata['time'][-1] / 1e3
    #print rodata['time'][-1]/1e3
    print 'stop = ', stop
    lastbin = int(stop / binsize)
    print 'lastbin = ', lastbin
    print 'binsize = ', binsize
    t0 = time.time()
    ts = timestamp()

    rocounts = rodata['counts']  #.transpose()
    spcounts = spdata['counts']
    info = ''  # will be populated with information that is written to a file
    info = """Analyze SSRO measurement:

Measurement settings:
=====================

repetitions: %d
binsize [us]: %f
stop analysis [us]: %f
    -> last bin: %d

Measurement results:
====================

""" % (reps, binsize, stop, lastbin)

    annotation = 'repetitions: %d' % reps

    cpsh_vs_ROtime = """# columns:
# - time
# - counts per shot
"""

    cnts_vs_SPtime = """# columns:
# - time
# - counts
"""

    fig1 = plt.figure(figsize=(16, 12))

    ### histogram for photon counts per shot (cpsh)
    cpsh = sum(rocounts[:, firstbin:lastbin], axis=1)  # sum over all columns

    ax = plt.subplot(221)
    plt.hist(cpsh, max(cpsh) + 1, align='mid', label='counts')
    plt.xlabel('counts/shot')
    plt.ylabel('occurrences')
    plt.title('counts per shot, m_s = %d' % ms)

    mean_cpsh = sum(cpsh) / float(reps)
    annotation += "\nmean c.p.sh. = %.2f" % (mean_cpsh)
    info += "\nmean c.p.sh. = %.2f" % (mean_cpsh)

    pzero = len(where(cpsh == 0)[0]) / float(reps)
    annotation += "\np(0 counts) = %.2f" % (pzero)
    info += "\np(0 counts) = %.2f" % (pzero)

    plt.figtext(0.45,
                0.85,
                annotation,
                horizontalalignment='right',
                verticalalignment='top')

    ### spin relaxation during readout
    ro_time = rodata['time'][:lastbin]  # create time axis [us]
    ro_countrate = sum(rocounts[:, :lastbin], axis=0) / (binsize * 1e-6 * reps
                                                         )  # [Hz]
    sp_time = spdata['time']
    sp_countrate = spcounts / (binsize * 1e-6 * reps)  # [Hz]

    savetxt(save_basepath + '_ro_countrate.dat',
            array([ro_time, ro_countrate]).transpose())
    savetxt(save_basepath + '_sp_countrate.dat',
            array([sp_time, sp_countrate]).transpose())
    #array([sp_time, sp_countrate]).transpose())

    ax = plt.subplot(222)
    # ax.set_yscale('log')
    plt.plot(ro_time, ro_countrate, 'o')
    plt.xlabel('RO time [ns]')
    plt.ylabel('counts [Hz]')
    plt.title('spin relaxation during readout')

    ### spin pumping data

    # convert counts to Hz
    sp = array([j / (binsize * 1e-6 * reps) for j in spdata['counts']])
    ax = plt.subplot(223)
    if False and len(spdata['counts']) > 2:
        offset_guess = spdata['counts'][len(spdata['counts']) - 1]
        init_amp_guess = spdata['counts'][2]
        decay_guess = 10

        fit_result = fit.fit1d(spdata['time'][2:len(spdata['counts']) - 1] /
                               1E3,
                               spdata['counts'][2:len(spdata['counts']) - 1],
                               common.fit_exp_decay_with_offset,
                               offset_guess,
                               init_amp_guess,
                               decay_guess,
                               do_plot=True,
                               do_print=True,
                               newfig=False,
                               ret=True,
                               plot_fitparams_xy=(0.5, 0.5))

    # ax.set_yscale('log')
    # NOTE: spin pumping starts at 1 us, that is the first datapoint
    # that is retrieved from the adwin. Fit might not be displayed properly
    # anymore now...
    plt.plot(spdata['time'] + 1E3, sp, 'o')
    plt.xlabel('spin pumping time [ns]')
    plt.ylabel('counts [Hz]')
    plt.title('spin relaxation during pumping')

    ### charge readout
    ax = plt.subplot(224)
    cr = crdata['counts']
    plt.hist(cr, abs(max(cr) - min(cr) + 1), label='cr')
    #### plt.hist(cr[:,2], abs(max(cr[:,2])-min(cr[:,2]))+1, label='cr2')
    plt.xlabel('counts')
    plt.ylabel('occurences')
    plt.title('charge readout statistics')
    # plt.legend()

    ### fidelity analysis
    fid_dat = zeros((0, 3))

    for i in range(1, lastbin):
        t = i * binsize

        # d: hist of counts, c: counts per shot
        d = sum(rocounts[:, :i], axis=1)
        c = sum(d) / float(reps)

        cpsh_vs_ROtime += '%f\t%f\n' % (t, c)

        # we get the fidelity from the probability to get zero counts in a
        # shot
        pzero = len(where(d == 0)[0]) / float(reps)
        pzero_err = sqrt(pzero * (1 - pzero) / reps)
        fid = 1 - pzero if ms == 0 else pzero  # fidelity calc. depends on ms
        fid_dat = vstack((fid_dat, array([[t, fid, pzero_err]])))

    fig2 = plt.figure()
    plt.errorbar(fid_dat[:, 0], fid_dat[:, 1], fmt='o', yerr=fid_dat[:, 2])
    plt.xlabel('RO time [us]')
    plt.ylabel('ms = %d RO fidelity' % ms)
    plt.title('SSRO fidelity')

    ### saving
    infofile = open(save_basepath + '_autoanalysis.txt', 'w')
    infofile.write(info)
    infofile.close()

    # fidelities
    savez(os.path.join(save_basepath + '_fid_vs_ROtime'),
          time=fid_dat[:, 0],
          fid=fid_dat[:, 1],
          fid_error=fid_dat[:, 2])
    savetxt(os.path.join(save_basepath + '_fid_vs_ROtime.dat'), fid_dat)

    # counts per shot
    f = open(save_basepath + '_cpsh_vs_ROtime.dat', 'w')
    f.write(cpsh_vs_ROtime)
    f.close()

    fig1.savefig(save_basepath + '_autoanalysis.pdf', format='pdf')
    fig2.savefig(save_basepath + '_fid_vs_ROtime.pdf', format='pdf')

    totaltime = time.time() - t0
    print 'autoanalysis took %.2f seconds' % totaltime

    if closefigs:
        fig1.clf()
        fig2.clf()
        plt.close('all')
def plot_esmw(datapath, fit_data=True, save=True):
    plt.close('all')

    suffix = 'esmw'

    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)

    e = np.load(datapath + '\\' + suffix + '-1_statics_and_parameters.npz')
    f_drive = e['mw_drive_freq']
    mwpower = e['mw_power']
    mw_min_freq = e['min_esmw_freq']
    mw_max_freq = e['max_esmw_freq']
    noof_datapoints = e['noof_datapoints']
    e.close()

    spin_ro_file = list()
    sp_file = list()

    for idx in arange(noof_datapoints):
        for k in files:
            if k == suffix + '-' + num2str(idx, 0) + '_Spin_RO.npz':
                spin_ro_file.append(k)
            if k == suffix + '-' + num2str(idx, 0) + '_SP_histogram.npz':
                sp_file.append(k)

    ###########################################
    ######## SPIN RO  #########################
    ###########################################

    mw_freq = linspace(mw_min_freq, mw_max_freq, noof_datapoints)
    fit_par = []
    for idx in arange(noof_datapoints):
        f = np.load(datapath + '\\' + spin_ro_file[idx])
        raw_counts = f['counts']
        repetitions = f['sweep_axis']
        t = f['time']

        tot_size = len(repetitions)
        reps_per_point = tot_size / float(noof_datapoints)

        counts_during_readout = sum(raw_counts, axis=0)
        ro_time = arange(0, shape(raw_counts)[1])
        figure1 = plt.figure(1)

        offset_guess = counts_during_readout.min()
        init_amp_guess = counts_during_readout.max()
        decay_guess = 10

        if fit_data:
            fit_result, p = fit.fit1d(ro_time[arange(4,
                                                     len(ro_time) - 1)],
                                      counts_during_readout[arange(
                                          4,
                                          len(ro_time) - 1)],
                                      common.fit_exp_decay_with_offset,
                                      offset_guess,
                                      init_amp_guess,
                                      decay_guess,
                                      do_plot=True,
                                      do_print=True,
                                      newfig=False,
                                      plot_fitparams_xy=(0.5, 0.5),
                                      ret=True)
            if fit_result != False:
                fit_par.append(fit_result['params'][2])
            else:
                fit_par.append(0)
        plt.plot(ro_time, counts_during_readout, 'or')
        plt.xlabel('Read-out duration ($\mu$s)')
        plt.ylabel('Integrated counts')
        plt.title('Read-out with MW, driving $f$ ='+num2str(f_drive/1E6,1)+\
                ' MHz, power = '+num2str(mwpower,0)+' dBm')
        if save:
            figure1.savefig(datapath + '\\histogram_integrated' +
                            num2str(idx, 0) + '.png')
        plt.clf()

        x = 6.0
        y = 8.0

        figure2 = plt.figure(figsize=(x, y))
        plt.pcolor(raw_counts, cmap='hot', antialiased=False)
        plt.xlabel('Readout time (us)')
        plt.ylabel('MW repetition number')
        plt.title('Total histogram, integrated over repetitions')
        plt.colorbar()
        if save:
            figure2.savefig(datapath + '\\histogram_counts_2d' +
                            num2str(idx, 0) + '.png')
        plt.clf()

        f.close()

        ###########################################
        ######## SPIN PUMPING #####################
        ###########################################
        v = np.load(datapath + '\\' + sp_file[idx])
        sp_counts = v['counts']
        sp_time = v['time']

        offset_guess = sp_counts[len(sp_counts) - 1]
        init_amp_guess = sp_counts[2]
        decay_guess = 10

        figure3 = plt.figure(3)
        if fit_data:
            fit.fit1d(sp_time / 1E3,
                      sp_counts,
                      common.fit_exp_decay_with_offset,
                      offset_guess,
                      init_amp_guess,
                      decay_guess,
                      do_plot=True,
                      do_print=True,
                      newfig=False,
                      plot_fitparams_xy=(0.5, 0.5))

        plt.plot(sp_time / 1E3, sp_counts, 'sg')
        plt.xlabel('Time ($\mu$s)')
        plt.ylabel('Integrated counts')
        plt.title('Spin pumping')
        v.close()
        if save:
            figure3.savefig(datapath + '\\spin_pumping' + num2str(idx, 0) +
                            '.png')
        plt.clf()

    if save:
        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#' + time.ctime() + '\n'
        col_names = '#Col0: MW Freq (ns)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in arange(len(mw_freq)):
            col_vals += num2str(mw_freq[k], 4) + '\t' + num2str(
                counts_during_readout[k], 0) + '\n'
        fo = open(datapath + '\\integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    if fit_data:
        plt.close('all')
        print len(mw_freq)
        print len(fit_par)
        figure4 = plt.figure(4)
        plt.plot(mw_freq / 1E6, fit_par, '-r')
        plt.xlabel('MW frequency (MHz)')
        plt.ylabel('Decay constant')

        if save:
            figure4.savefig(datapath + '\\decay_constant_vs_mw_freq.png')
        plt.clf()

    return fit_par
def plot_SE(datapath,
            fid=(0.82, 0.9),
            fiderr=(0.01, 0.01),
            fit_data=True,
            exp_guess=2.8,
            save=True):

    plt.close('all')
    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)

    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath + '\\' + stats_params_file)
    f_drive = e['mw_drive_freq']
    mwpower = e['mw_power']
    tau_max = e['tau_max']
    tau_min = e['tau_min']
    #frabi = e['frabi']
    frabi = 11.

    noof_datapoints = e['noof_datapoints']
    noof_reps = e['completed_repetitions']
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################

    f = np.load(datapath + '\\' + spin_ro_file)
    raw_counts = f['counts']
    SSRO_counts = f['SSRO_counts']
    repetitions = f['sweep_axis']
    t = f['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size / float(noof_datapoints)

    idx = 0
    counts_during_readout = zeros(noof_datapoints)
    tau_free_evol = linspace(tau_min, tau_max, noof_datapoints) * 2e-3
    counts_during_readout = sum(raw_counts, axis=1)
    SSRO_readout = sum(SSRO_counts, axis=1) / float(noof_reps)
    SSRO_readout_corr = zeros(len(SSRO_readout))
    readout_error = zeros(len(SSRO_readout))

    for i in arange(len(SSRO_readout)):
        ms0_events = SSRO_readout[i] * noof_reps
        ms1_events = noof_reps * (1 - SSRO_readout[i])
        corr = SSRO_correct(array([ms1_events, ms0_events]),
                            F0=fid[0],
                            F1=fid[1],
                            F0err=fiderr[0],
                            F1err=fiderr[1])
        SSRO_readout_corr[i] = corr[0][0]
        readout_error[i] = corr[1][0]

    #########################################
    ############ FITTING ####################
    #########################################
    #FIXME: write nice fitting routine for SE

    figure2 = plt.figure(2)

    plt.plot(tau_free_evol, counts_during_readout, 'sk')
    plt.xlabel('Free evolution time [us]')
    plt.ylabel('Integrated counts')
    plt.title('Spin Echo, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, frabi = '+num2str(frabi,0)+' MHz')
    plt.text(0.1 * (max(tau_free_evol) + min(tau_free_evol)),
             max(counts_during_readout), datapath)
    if save:
        figure2.savefig(datapath + '\\histogram_integrated.png')

    figure4 = plt.figure(4)

    plt.plot(tau_free_evol, SSRO_readout, 'sk')
    plt.xlabel('Free evolution time [us]')
    plt.ylabel('Fraction of events >0 counts')
    plt.title('Spin Echo SSRO cor, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, frabi = '+num2str(frabi,0)+' MHz')
    plt.text(0.1 * (max(tau_free_evol) + min(tau_free_evol)),
             max(SSRO_readout), datapath)
    if save:
        figure4.savefig(datapath + '\\SSRO_readout.png')

    figure6 = plt.figure(6)

    if fit_data:
        tau_guess = 530
        offset_guess = SSRO_readout_corr.min()
        amp_guess = SSRO_readout_corr.max() - offset_guess

        print tau_guess
        print offset_guess
        print amp_guess
        print tau_guess
        print exp_guess
        print tau_free_evol

        fitresult = fit.fit1d(tau_free_evol,
                              SSRO_readout_corr,
                              SE.fit_echo,
                              tau_guess,
                              amp_guess,
                              offset_guess,
                              exp_guess,
                              do_plot=True,
                              do_print=True,
                              newfig=False)
        print fitresult
    plt.errorbar(tau_free_evol,
                 SSRO_readout_corr,
                 fmt='sk',
                 yerr=readout_error)
    plt.xlabel('Free evolution time [us]')
    plt.ylabel('P ms=0')
    plt.title('Spin Echo SSRO cor, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, frabi = '+num2str(frabi,0)+' MHz')
    plt.text(0.1 * (max(tau_free_evol) + min(tau_free_evol)),
             max(SSRO_readout_corr), datapath)
    if save:
        figure6.savefig(datapath + '\\SSRO_readout_corr.png')

    x = 6.0
    y = 8.0

    figure3 = plt.figure(figsize=(x, y))
    plt.pcolor(raw_counts, cmap='hot', antialiased=False)
    plt.xlabel('Readout time (us)')
    plt.ylabel('MW repetition number')
    plt.title('Total histogram, integrated over repetitions')
    plt.colorbar()
    if save:
        figure3.savefig(datapath + '\\histogram_counts_2d.png')

    f.close()

    ###########################################
    ######## SPIN PUMPING #####################
    ###########################################
    v = np.load(datapath + '\\' + sp_file)
    sp_counts = v['counts']
    sp_time = v['time']

    offset_guess = sp_counts[len(sp_counts) - 1]
    init_amp_guess = sp_counts[2]
    decay_guess = 10

    figure5 = plt.figure(5)
    fit.fit1d(sp_time / 1E3,
              sp_counts,
              common.fit_exp_decay_with_offset,
              offset_guess,
              init_amp_guess,
              decay_guess,
              do_plot=True,
              do_print=True,
              newfig=False,
              plot_fitparams_xy=(0.5, 0.5))

    plt.plot(sp_time / 1E3, sp_counts, 'sg')
    plt.xlabel('Time ($\mu$s)')
    plt.ylabel('Integrated counts')
    plt.title('Spin pumping')
    v.close()
    if save:
        figure5.savefig(datapath + '\\spin_pumping.png')

        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#' + time.ctime() + '\n'
        col_names = '#Col0: Interpulse delay (ns)\tCol1: Integrated counts\tCol2: SSRO corr\n'
        col_vals = str()
        for k in arange(noof_datapoints):
            col_vals += num2str(tau_free_evol[k], 2) + '\t' + num2str(
                counts_during_readout[k], 0) + '\t' + num2str(
                    SSRO_readout_corr[k], 2) + '\n'
        fo = open(datapath + '\\integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    return True
def plot_rabi(datapath, fit_data=True, with_detuning=False, save=True):

    plt.close('all')
    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)

    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath + '\\' + stats_params_file)
    f_drive = e['mw_drive_freq']
    mwpower = e['mw_power']
    mw_min_len = e['min_mw_length']
    mw_max_len = e['max_mw_length']
    noof_datapoints = e['noof_datapoints']
    noof_reps = e['completed_repetitions']
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################

    f = np.load(datapath + '\\' + spin_ro_file)
    raw_counts = f['counts']
    SSRO_counts = f['SSRO_counts']
    repetitions = f['sweep_axis']
    t = f['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size / float(noof_datapoints)

    idx = 0
    counts_during_readout = zeros(noof_datapoints)
    mw_len = linspace(mw_min_len, mw_max_len, noof_datapoints)
    counts_during_readout = sum(raw_counts, axis=1)
    SSRO_readout = sum(SSRO_counts, axis=1) / float(noof_reps)

    #########################################
    ############ FITTING ####################
    #########################################

    if fit_data:
        FFT = fft.fft(SSRO_readout)
        N = int(noof_datapoints)
        timestep = (mw_max_len - mw_min_len) / float(noof_datapoints - 1)
        freq = fft.fftfreq(N, d=timestep)

        #Remove offset:
        FFT[freq == 0] = 0

        figure1 = plt.figure(1)
        plt.bar(freq * 1E3,
                abs(FFT),
                width=0.4 * 1E3 * (freq[1] - freq[0]),
                align='center')
        plt.xlabel('Frequency (MHz)')
        plt.ylabel('Amplitude')
        plt.title('FFT (offset removed)')

        if save:
            figure1.savefig(datapath + '\\fft_signal_rabi.png')

        freq_guess = freq[find_nearest(abs(FFT), abs(FFT).max())]
        amp_guess = (counts_during_readout.max() +
                     counts_during_readout.min()) / 2.0
        offset_guess = counts_during_readout.min()+(counts_during_readout.max()+\
                counts_during_readout.min())/2.0
        phase_guess = 0

    figure3 = plt.figure(3)
    plt.clf()
    ax1 = figure3.add_subplot(111)

    if fit_data and with_detuning:
        tau_guess = 200
        fit.fit1d(mw_len,
                  counts_during_readout,
                  rabi.fit_rabi_multiple_detunings,
                  amp_guess,
                  offset_guess,
                  freq_guess,
                  tau_guess, (0, 0), (2.2E-3, 0), (2 * 2.2E-3, 0),
                  do_plot=True,
                  do_print=True,
                  newfig=False)
    elif fit_data:
        [fit_result, p] = fit.fit1d(mw_len,
                                    counts_during_readout,
                                    rabi.fit_rabi_simple,
                                    freq_guess,
                                    amp_guess,
                                    offset_guess,
                                    phase_guess,
                                    do_plot=True,
                                    do_print=True,
                                    newfig=False,
                                    ret=True)

        #pi_pulse_len = 0.5*1/fit_result['params_dict']['f']
        #pi_2_pulse_len = 0.5*pi_pulse_len

        #print 'pi pulse length = ', pi_pulse_len
        #print 'pi/2 pulse length = ',pi_2_pulse_len

    #ax2 = figure2.add_subplot(111, sharex=ax1, frameon=False)
    #ax2.plot(mw_len,counts_during_readout, 'sk')

    plt.xlabel('MW length (ns)')
    plt.ylabel('Integrated counts')
    plt.title('MW length sweep, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm')
    plt.text(0.1 * (mw_max_len + mw_min_len), max(counts_during_readout),
             datapath)
    if save:
        figure3.savefig(datapath + '\\histogram_integrated.png')

    figure2 = plt.figure(2)
    plt.clf()
    ax1 = figure2.add_subplot(111)
    #plt.plot(mw_len,SSRO_readout, 'sk')

    if fit_data and with_detuning:
        tau_guess = 200
        fit.fit1d(mw_len,
                  SSRO_readout,
                  rabi.fit_rabi_multiple_detunings,
                  amp_guess,
                  offset_guess,
                  freq_guess,
                  tau_guess, (0, 0), (2.2E-3, 0), (2 * 2.2E-3, 0),
                  do_plot=True,
                  do_print=True,
                  newfig=False)
    elif fit_data:
        [fit_result, p] = fit.fit1d(mw_len,
                                    SSRO_readout,
                                    rabi.fit_rabi_simple,
                                    freq_guess,
                                    amp_guess,
                                    offset_guess,
                                    phase_guess,
                                    do_plot=True,
                                    do_print=True,
                                    newfig=False,
                                    ret=True)

        pi_pulse_len = 0.5 * 1 / fit_result['params_dict']['f']
        pi_2_pulse_len = 0.5 * pi_pulse_len

        print 'pi pulse length = ', pi_pulse_len
        print 'pi/2 pulse length = ', pi_2_pulse_len

    #ax2 = figure2.add_subplot(111, sharex=ax1, frameon=False)
    #ax2.plot(mw_len,counts_during_readout, 'sk')
    plt.ylim([0, 1])
    plt.xlabel('MW length (ns)')
    plt.ylabel('P($m_s=0$)')
    plt.title('MW length sweep, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm')
    plt.text(0.1 * (mw_max_len + mw_min_len), max(counts_during_readout),
             datapath)
    if save:
        figure2.savefig(datapath + '\\histogram_integrated_SSRO.png')

    x = 6.0
    y = 8.0

    figure4 = plt.figure(figsize=(x, y))
    plt.pcolor(raw_counts, cmap='hot', antialiased=False)
    plt.xlabel('Readout time (us)')
    plt.ylabel('MW repetition number')
    plt.title('Total histogram, integrated over repetitions')
    plt.colorbar()
    if save:
        figure4.savefig(datapath + '\\histogram_counts_2d.png')

    f.close()

    ###########################################
    ######## SPIN PUMPING #####################
    ###########################################
    v = np.load(datapath + '\\' + sp_file)
    sp_counts = v['counts']
    sp_time = v['time']

    offset_guess = sp_counts[len(sp_counts) - 1]
    init_amp_guess = sp_counts[2]
    decay_guess = 10

    figure5 = plt.figure()
    fit.fit1d(sp_time / 1E3,
              sp_counts,
              common.fit_exp_decay_with_offset,
              offset_guess,
              init_amp_guess,
              decay_guess,
              do_plot=True,
              do_print=True,
              newfig=False,
              plot_fitparams_xy=(0.5, 0.5))

    plt.plot(sp_time / 1E3, sp_counts, 'sg')
    plt.xlabel('Time ($\mu$s)')
    plt.ylabel('Integrated counts')
    plt.title('Spin pumping')
    v.close()
    if save:
        figure5.savefig(datapath + '\\spin_pumping.png')

        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#' + time.ctime() + '\n'
        col_names = '#Col0: MW length (ns)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in arange(noof_datapoints):
            col_vals += num2str(mw_len[k], 2) + '\t' + num2str(
                counts_during_readout[k], 0) + '\n'
        fo = open(datapath + '\\integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    return True
def plot_ramsey(datapath, fit_data=True, save=True):

    plt.close('all')
    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)

    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath + '\\' + stats_params_file)
    f_drive = e['mw_drive_freq']
    detuning = e['detuning']
    mwpower = e['mw_power']
    tau_max = e['tau_min']
    tau_min = e['tau_max']
    #pi_2_duration = e['pi_2_duration']
    pi_2_duration = 25
    noof_datapoints = e['noof_datapoints']
    noof_reps = e['completed_repetitions']
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################

    f = np.load(datapath + '\\' + spin_ro_file)
    raw_counts = f['counts']
    SSRO_counts = f['SSRO_counts']
    repetitions = f['sweep_axis']
    t = f['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size / float(noof_datapoints)

    idx = 0
    counts_during_readout = zeros(noof_datapoints)
    tau = linspace(tau_min, tau_max, noof_datapoints)
    counts_during_readout = sum(raw_counts, axis=1)
    SSRO_readout = sum(SSRO_counts, axis=1) / float(noof_reps)
    #########################################
    ############ FITTING ####################
    #########################################
    print fit_data
    if fit_data:
        FFT = fft.fft(counts_during_readout)
        N = int(noof_datapoints)
        timestep = (mw_max_len - mw_min_len) / float(noof_datapoints - 1)
        freq = fft.fftfreq(N, d=timestep)

        #Remove offset:
        FFT[freq == 0] = 0

        figure1 = plt.figure(1)
        plt.bar(freq * 1E3,
                abs(FFT),
                width=0.4 * 1E3 * (freq[1] - freq[0]),
                align='center')
        plt.xlabel('Frequency (MHz)')
        plt.ylabel('Amplitude')
        plt.title('FFT (offset removed)')

        if save:
            figure1.savefig(datapath + '\\fft_signal_rabi.png')

        offset_guess = counts_during_readout.min()+(counts_during_readout.max()+\
                counts_during_readout.min())/2.0
        tau_guess = 1000

        #modulations:
        mod_freq_guess = freq[find_nearest(abs(FFT), abs(FFT).max())]
        mod_amp_guess = (counts_during_readout.max() +
                         counts_during_readout.min()) / 2.0
        mod_phase_guess = 0

        print 'modulation frequency guess = ', freq_guess
        print 'modulation amplitude guess = ', mod_amp_guess

    figure2 = plt.figure(2)

    if fit_data:
        tau_guess = 200
        fit.fit1d(tau,
                  counts_during_readout,
                  ramsey.fit_ramsey_gaussian_decay,
                  tau_guess,
                  offset_guess,
                  (mod_freq_guess, mod_amp_guess, mod_phase_guess),
                  do_plot=True,
                  do_print=True,
                  newfig=False)
    print SSRO_readout
    plt.plot(tau, SSRO_readout, 'sk')
    plt.xlabel('\Delta t$ (ns)')
    plt.ylabel('Integrated counts')
    plt.title('Ramsey, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm,\n Detuning = '+\
            num2str(detuning/1E6,0)+' MHz, $\pi/2$ length = '+\
            num2str(pi_2_duration,0)+' ns')
    plt.text(0.1 * (tau_max + tau_min), max(counts_during_readout), datapath)
    if save:
        figure2.savefig(datapath + '\\histogram_integrated.png')

    x = 6.0
    y = 8.0

    figure3 = plt.figure(figsize=(x, y))
    plt.pcolor(raw_counts, cmap='hot', antialiased=False)
    plt.xlabel('Readout time (us)')
    plt.ylabel('MW repetition number')
    plt.title('Total histogram, integrated over repetitions')
    plt.colorbar()
    if save:
        figure3.savefig(datapath + '\\histogram_counts_2d.png')

    f.close()

    ###########################################
    ######## SPIN PUMPING #####################
    ###########################################
    v = np.load(datapath + '\\' + sp_file)
    sp_counts = v['counts']
    sp_time = v['time']

    offset_guess = sp_counts[len(sp_counts) - 1]
    init_amp_guess = sp_counts[2]
    decay_guess = 10

    figure4 = plt.figure(4)
    fit.fit1d(sp_time / 1E3,
              sp_counts,
              common.fit_exp_decay_with_offset,
              offset_guess,
              init_amp_guess,
              decay_guess,
              do_plot=True,
              do_print=True,
              newfig=False,
              plot_fitparams_xy=(0.5, 0.5))

    plt.plot(sp_time / 1E3, sp_counts, 'sg')
    plt.xlabel('Time ($\mu$s)')
    plt.ylabel('Integrated counts')
    plt.title('Spin pumping')
    v.close()
    if save:
        figure4.savefig(datapath + '\\spin_pumping.png')

        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#' + time.ctime() + '\n'
        col_names = '#Col0: Interpulse delay (ns)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in arange(noof_datapoints):
            col_vals += num2str(tau[k], 2) + '\t' + num2str(
                counts_during_readout[k], 0) + '\n'
        fo = open(datapath + '\\integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    return True
def plot_dark_esr(datapath, fit_data=True, save=True, f_dip=2.878E9):
    plt.close('all')

    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)

    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath + '\\' + stats_params_file)
    f_center = e['mw_center_freq']
    mwpower = e['mw_power']
    mw_min_freq = e['min_mw_freq']
    mw_max_freq = e['max_mw_freq']
    noof_datapoints = e['noof_datapoints']
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################

    f = np.load(datapath + '\\' + spin_ro_file)
    raw_counts = f['counts']
    repetitions = f['sweep_axis']
    t = f['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size / float(noof_datapoints)

    idx = 0
    counts_during_readout = zeros(noof_datapoints)
    mw_freq = linspace(mw_min_freq, mw_max_freq, noof_datapoints)
    counts_during_readout = sum(raw_counts, axis=1)

    #########################################
    ############ FITTING ####################
    #########################################

    offset_guess = counts_during_readout.max()
    dip_depth_guess = offset_guess - counts_during_readout.min()

    print offset_guess
    print dip_depth_guess

    width_guess = 1E6
    f_dip_guess = f_dip
    noof_dips = 3
    dip_separation = 2E6

    figure2 = plt.figure(2)
    plt.plot(mw_freq / 1E9, counts_during_readout, '-ok')

    if fit_data:
        fit_result, p = fit.fit1d(mw_freq / 1E9,
                                  counts_during_readout,
                                  esr.fit_ESR_gauss,
                                  offset_guess,
                                  dip_depth_guess,
                                  width_guess / 1E9,
                                  f_dip_guess / 1E9,
                                  (noof_dips, dip_separation / 1E9),
                                  do_plot=True,
                                  do_print=True,
                                  newfig=False,
                                  ret=True,
                                  plot_fitonly=True)

        center_peak = fit_result['params_dict']['x0']
        splitting = fit_result['params_dict']['s0']

        print '-1: f = ', (center_peak - splitting), ' GHz'
        print '0: f = ', center_peak, ' GHz'
        print '1: f = ', (center_peak + splitting), ' GHz'

    plt.xlabel('MW frequency (GHz)')
    plt.ylabel('Integrated counts')
    plt.title('MW frequency sweep, MW parking spot $f$ ='+num2str(f_center/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm')

    if save:
        figure2.savefig(datapath + '\\histogram_integrated.png')

    x = 6.0
    y = 8.0

    figure3 = plt.figure(figsize=(x, y))
    plt.pcolor(raw_counts, cmap='hot', antialiased=False)
    plt.xlabel('Readout time (us)')
    plt.ylabel('MW repetition number')
    plt.title('Total histogram, integrated over repetitions')
    plt.colorbar()
    if save:
        figure3.savefig(datapath + '\\histogram_counts_2d.png')

    f.close()

    ###########################################
    ######## SPIN PUMPING #####################
    ###########################################

    v = np.load(datapath + '\\' + sp_file)
    sp_counts = v['counts']
    sp_time = v['time']

    offset_guess = sp_counts[len(sp_counts) - 1]
    init_amp_guess = sp_counts[2]
    decay_guess = 10

    figure4 = plt.figure(4)
    fit.fit1d(sp_time / 1E3,
              sp_counts,
              common.fit_exp_decay_with_offset,
              offset_guess,
              init_amp_guess,
              decay_guess,
              do_plot=True,
              do_print=True,
              newfig=False,
              plot_fitparams_xy=(0.5, 0.5))

    plt.plot(sp_time / 1E3, sp_counts, 'sg')
    plt.xlabel('Time ($\mu$s)')
    plt.ylabel('Integrated counts')
    plt.title('Spin pumping')
    v.close()
    if save:
        figure4.savefig(datapath + '\\spin_pumping.png')

        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#' + time.ctime() + '\n'
        col_names = '#Col0: MW freq (GHz)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in arange(noof_datapoints):
            col_vals += num2str(mw_freq[k] / 1E9, 10) + '\t' + num2str(
                counts_during_readout[k], 0) + '\n'
        fo = open(datapath + '\\integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    return True
Пример #18
0
def pi_over_two_calibration(datapath, norm,guess,fit_data = True, save = True,close_fig=True,new_fig=True):
    """ 
    Datapath should be a folder that contains the actual measurement results,
    so for example: datapath = 'D:\data\yyyymmdd\hhmmss_spin_control_suffix'
    Flag fit_data if data should be fit.
    Flag save if data should be saved (in the data directory)
    guess =  [a,b] for fit of line a+b*x
    nrom = [ms0,ms1]
    """

    print 'Analyzing spin control data...'

    # Create directories for saving figures and saving processed data:
    if not os.path.exists(os.path.join(datapath,'figures')):
        os.makedirs(os.path.join(datapath,'figures'))
    if not os.path.exists(os.path.join(datapath,'processed_data')): 
        os.makedirs(os.path.join(datapath,'processed_data'))

    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)
    
    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath+'\\'+stats_params_file)
    f_drive = e['mw_drive_freq']
    mwpower = e['mw_power']
    mw_min_len = e['min_sweep_par']
    mw_max_len = e['max_sweep_par']
    name=e['sweep_par_name']
    noof_datapoints = e['noof_datapoints']
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################
    
    g = np.load(datapath+'\\'+spin_ro_file)
    raw_counts = g['counts']
    SSRO_raw = g['SSRO_counts']
    repetitions = g['sweep_axis']
    t = g['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size/float(noof_datapoints)

    idx = 0
    counts_during_readout = np.zeros(noof_datapoints)
    mw_len = np.linspace(mw_min_len,mw_max_len,noof_datapoints)
    counts_during_readout = np.sum(raw_counts, axis = 1)

    SSRO_unnorm = np.zeros(noof_datapoints)
    SSRO_unnorm = np.sum(SSRO_raw, axis = 1)


    ## Renormalize

    SSRO = (SSRO_unnorm-norm[1])/(norm[0]-norm[1])
    #########################################
    ############ FITTING ####################
    #########################################
    
    if fit_data:

        a_guess=guess[0]
        b_guess=guess[1]

        #print 'frequency guess = ',freq_guess


        fit_result = fit.fit1d(mw_len, SSRO, common.fit_line, 
                a_guess, b_guess,
                do_plot = False, ret = True)

        offset = fit_result['params_dict']['a']
        slope = fit_result['params_dict']['b']
        x = np.linspace(mw_min_len, mw_max_len, 501)
        fit_curve = offset + slope*x

        pi_2_pulse_len = (0.5-offset)/slope

    name= spin_ro_file[:len(spin_ro_file)-16]
    if new_fig:
        plot2 = qt.Plot2D(mw_len, SSRO, 'sk',
                title=name, name='Pi_over_2 Cal',clear=True)
        plot2.add(x,fit_curve, '-r',title='fit '+name)
    else:
        plot2 = qt.plots['Cal']
        plot2.add(mw_len, SSRO, 'xk',title=name)
        plot2.add(x,fit_curve, '-r',title='fit '+name)
    plot2.set_xlabel(name)
    plot2.set_ylabel('Integrated counts')
    plot2.set_plottitle(str(name) + ' , driving f ='+num2str(f_drive/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm')
    
    #plt.text(0.1*(mw_max_len+mw_min_len),max(SSRO),datapath)
    if save:
        plot2.save_png(os.path.join(datapath,'figures', 'histogram_integrated'))
    g.close()
    if close_fig:
        plot2.quit()
    print SSRO
    if save:
        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: MW length (ns)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in np.arange(noof_datapoints):
            col_vals += num2str(mw_len[k],2)+'\t'+num2str(counts_during_readout[k],0)+'\n'
        fo = open(os.path.join(datapath, 'processed_data', 'mw_pi_calibration_integrated_histogram.dat'), "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    if save:
        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: MW length (ns)\tCol1: SSRO\n'
        col_vals = str()
        for k in np.arange(noof_datapoints):
            col_vals += num2str(mw_len[k],2)+'\t'+str(SSRO_unnorm[k])+'\n'
        fo = open(os.path.join(datapath, 'processed_data', 'mw_pi_calibration_SSRO_unnorm.dat'), "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()    
    if save:
        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: MW length (ns)\tCol1: SSRO\n'
        col_vals = str()
        for k in np.arange(noof_datapoints):
            col_vals += num2str(mw_len[k],2)+'\t'+str(SSRO[k])+'\n'
        fo = open(os.path.join(datapath, 'processed_data', 'mw_pi_calibration_SSRO_norm.dat'), "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()   

    pi_over_two_dict={"pi_over_two":pi_2_pulse_len,"slope":slope,"offset":offset}
    return pi_over_two_dict
def autoanalyze_single_ssro(rodata, spdata, crdata, save_basepath, 
        binsize=0.131072, reps=1e4, ms=0, closefigs=True, stop=0, firstbin=0):
    """
    Analyzes a single SSRO measurement (can do both ms=0/+-1).
    creates an overview plot over the measurement results, and a plot
    of the measurement fidelity vs the measurement time.
    saves the fidelities and errors vs ro time.

    """

    if stop == 0:
        stop = rodata['time'][-1]/1e3
        sp_stop = spdata['time'][-1]/1e3
    #print rodata['time'][-1]/1e3
    print 'stop = ',stop
    lastbin = int(stop/binsize)
    print 'lastbin = ',lastbin
    print 'binsize = ',binsize
    t0 = time.time()
    ts = timestamp()

    rocounts = rodata['counts']  #.transpose()
    spcounts = spdata['counts']
    info = '' # will be populated with information that is written to a file
    info = """Analyze SSRO measurement:

Measurement settings:
=====================

repetitions: %d
binsize [us]: %f
stop analysis [us]: %f
    -> last bin: %d

Measurement results:
====================

""" % (reps, binsize, stop, lastbin)

    annotation = 'repetitions: %d' % reps

    cpsh_vs_ROtime = """# columns:
# - time
# - counts per shot
"""

    cnts_vs_SPtime = """# columns:
# - time
# - counts
"""

    fig1 = plt.figure(figsize=(16,12))

    ### histogram for photon counts per shot (cpsh)
    cpsh = sum(rocounts[:,firstbin:lastbin], axis=1) # sum over all columns

    ax = plt.subplot(221)
    plt.hist(cpsh, max(cpsh)+1, align='mid', label='counts')
    plt.xlabel('counts/shot')
    plt.ylabel('occurrences')
    plt.title('counts per shot, m_s = %d' % ms)

    mean_cpsh = sum(cpsh)/float(reps)
    annotation += "\nmean c.p.sh. = %.2f" % (mean_cpsh)
    info += "\nmean c.p.sh. = %.2f" % (mean_cpsh)

    pzero = len(where(cpsh==0)[0])/float(reps)
    annotation += "\np(0 counts) = %.2f" % (pzero)
    info += "\np(0 counts) = %.2f" % (pzero)

    plt.figtext(0.45, 0.85, annotation, horizontalalignment='right',
            verticalalignment='top')
    
    ### spin relaxation during readout
    ro_time = rodata['time'][:lastbin] # create time axis [us]
    ro_countrate = sum(rocounts[:,:lastbin], axis=0) / (binsize*1e-6*reps) # [Hz]
    sp_time = spdata['time']
    sp_countrate = spcounts / (binsize*1e-6*reps) # [Hz] 

    savetxt(save_basepath + '_ro_countrate.dat',
         array([ro_time, ro_countrate]).transpose())
    savetxt(save_basepath + '_sp_countrate.dat',
         array([sp_time,sp_countrate]).transpose())
            #array([sp_time, sp_countrate]).transpose())

    ax = plt.subplot(222)
    # ax.set_yscale('log') 
    plt.plot(ro_time, ro_countrate, 'o')
    plt.xlabel('RO time [ns]')
    plt.ylabel('counts [Hz]')
    plt.title('spin relaxation during readout')

    ### spin pumping data

    # convert counts to Hz
    sp = array([j/(binsize*1e-6*reps) for j in spdata['counts']]) 
    ax = plt.subplot(223)
    if False and len(spdata['counts'])>2:
        offset_guess = spdata['counts'][len(spdata['counts'])-1]
        init_amp_guess = spdata['counts'][2]
        decay_guess = 10
        

        fit_result=fit.fit1d(spdata['time'][2:len(spdata['counts'])-1]/1E3, spdata['counts'][2:len(spdata['counts'])-1], 
                common.fit_exp_decay_with_offset, 
                offset_guess, init_amp_guess, decay_guess,
                do_plot = True, do_print = True, newfig = False, ret=True,
                plot_fitparams_xy = (0.5,0.5))

    # ax.set_yscale('log')
    # NOTE: spin pumping starts at 1 us, that is the first datapoint
    # that is retrieved from the adwin. Fit might not be displayed properly
    # anymore now...
    plt.plot(spdata['time']+1E3, sp, 'o')
    plt.xlabel('spin pumping time [ns]')
    plt.ylabel('counts [Hz]')
    plt.title('spin relaxation during pumping')

    ### charge readout
    ax = plt.subplot(224)
    cr = crdata['counts']
    plt.hist(cr, abs(max(cr)-min(cr)+1), label='cr')
    #### plt.hist(cr[:,2], abs(max(cr[:,2])-min(cr[:,2]))+1, label='cr2')
    plt.xlabel('counts')
    plt.ylabel('occurences')
    plt.title('charge readout statistics')
    # plt.legend()

    ### fidelity analysis
    fid_dat = zeros((0,3))

    for i in range(1,lastbin):
        t = i*binsize
        
        # d: hist of counts, c: counts per shot
        d = sum(rocounts[:,:i], axis=1)
        c = sum(d)/float(reps)

        cpsh_vs_ROtime += '%f\t%f\n' % (t, c)
        
        # we get the fidelity from the probability to get zero counts in a
        # shot 
        pzero = len(where(d==0)[0])/float(reps)
        pzero_err = sqrt(pzero*(1-pzero)/reps)
        fid = 1-pzero if ms == 0 else pzero # fidelity calc. depends on ms
        fid_dat = vstack((fid_dat, array([[t, fid, pzero_err]])))

    fig2 = plt.figure()
    plt.errorbar(fid_dat[:,0], fid_dat[:,1], fmt='o', yerr=fid_dat[:,2])
    plt.xlabel('RO time [us]')
    plt.ylabel('ms = %d RO fidelity' % ms)
    plt.title('SSRO fidelity')

    ### saving
    infofile = open(save_basepath+'_autoanalysis.txt', 'w')
    infofile.write(info)
    infofile.close()

    # fidelities
    savez(os.path.join(save_basepath+'_fid_vs_ROtime'), time=fid_dat[:,0],
            fid=fid_dat[:,1], fid_error=fid_dat[:,2])
    savetxt(os.path.join(save_basepath+'_fid_vs_ROtime.dat'), fid_dat)

    # counts per shot
    f = open(save_basepath+'_cpsh_vs_ROtime.dat', 'w')
    f.write(cpsh_vs_ROtime)
    f.close()

    fig1.savefig(save_basepath+'_autoanalysis.pdf', format='pdf')
    fig2.savefig(save_basepath+'_fid_vs_ROtime.pdf', format='pdf')

    totaltime = time.time() - t0
    print 'autoanalysis took %.2f seconds' % totaltime

    if closefigs:
        fig1.clf(); fig2.clf()
        plt.close('all')
def analyze_SP_RO(sp_file,
                  params,
                  folder='',
                  plot=True,
                  save=True,
                  do_print=False,
                  ret=False,
                  name='spin_pumping.png'):
    '''
    Function to plot and fit a single SP or RO curve. 
    

    sp_file     string      (part of) the filename that contains data of interest
    folder      string      folder that contains the data
    '''

    if folder == '':
        folder = os.getcwd()

    v = load(folder + '\\' + sp_file)
    Ex_RO_power = params['Ex_RO_amplitude']
    A_RO_power = params['Ex_RO_amplitude']
    Ex_SP_power = params['Ex_SP_amplitude']
    A_SP_power = params['A_SP_amplitude']

    if 'Spin_RO' in sp_file:
        sp_counts = sum(v['counts'], axis=0)
        title = 'RO Powers: Ex = ' + str(Ex_RO_power * 1E9) + 'nW, A = ' + str(
            A_RO_power * 1E9) + 'nW'
    else:
        sp_counts = v['counts']
        title = 'SP Powers: Ex = ' + str(Ex_SP_power * 1E9) + 'nW, A = ' + str(
            A_SP_power * 1E9) + 'nW'

    sp_time = v['time']
    v.close()

    offset_guess = sp_counts[len(sp_counts) - 1]
    init_amp_guess = max(sp_counts)
    firstpoint = int(find_nearest(sp_counts, init_amp_guess))

    decay_guess = 10

    if plot:
        figure4 = plt.figure(4)
        plt.clf()

    fit_result = fit.fit1d(sp_time[firstpoint:len(sp_counts) - 1] / 1E3,
                           sp_counts[firstpoint:len(sp_counts) - 1],
                           common.fit_exp_decay_with_offset,
                           offset_guess,
                           init_amp_guess,
                           decay_guess,
                           do_plot=plot,
                           do_print=do_print,
                           newfig=False,
                           ret=True,
                           plot_fitparams_xy=(0.5, 0.5))

    if plot:

        plt.plot(sp_time / 1E3, sp_counts, 'sg')
        plt.xlabel('Time ($\mu$s)')
        plt.ylabel('Integrated counts')
        plt.title(title)
        plt.ylim(ymax=max(sp_counts) * 1.2)
        plt.text(0.01 * (max(sp_time / 1E3) + min(sp_time / 1E3)),
                 1.15 * max(sp_counts),
                 folder + sp_file,
                 fontsize='x-small')

        if save:
            figure4.savefig(folder + '\\' + name + '.png')

    if ret:
        return fit_result
Пример #21
0
def rabi_calibration(datapath, ssro_dict={},fit_data = True, save = True,close_fig=False,new_fig=True):
    """ 
    Fits results from a spin_control data using a FFT. 
    Datapath should be a folder that contains the actual measurement results,
    so for example: datapath = 'D:\data\yyyymmdd\hhmmss_spin_control_suffix'
    Flag fit_data if data should be fit.
    Flag save if data should be saved (in the data directory)
    """

    print 'Analyzing spin control data...'

    # Create directories for saving figures and saving processed data:
    if not os.path.exists(os.path.join(datapath,'figures')):
        os.makedirs(os.path.join(datapath,'figures'))
    if not os.path.exists(os.path.join(datapath,'processed_data')): 
        os.makedirs(os.path.join(datapath,'processed_data'))

    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)
    
    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath+'\\'+stats_params_file)
    f_drive = e['mw_drive_freq']
    mwpower = e['mw_power']
    mw_min_len = e['min_mw_length']
    mw_max_len = e['max_mw_length']
    name=['sweep_par_name']
    noof_datapoints = e['noof_datapoints']
    noof_reps = e['completed_repetitions']
    #ro_duration=e['RO_duration']
    ro_duration=26.
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################
    
    g = np.load(datapath+'\\'+spin_ro_file)
    raw_counts = g['counts']
    SSRO_counts = g['SSRO_counts']
    repetitions = g['sweep_axis']
    t = g['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size/float(noof_datapoints)

    idx = 0
    counts_during_readout = np.zeros(noof_datapoints)
    mw_len = np.linspace(mw_min_len,mw_max_len,noof_datapoints)
    counts_during_readout = np.sum(raw_counts, axis = 1)
    SSRO_readout = sum(SSRO_counts, axis = 1)/float(noof_reps)


    # Spin RO corrected for SSRO error
    #
    if ssro_dict:
        f=ssro_dict
        idx = find_nearest(f["times"],ro_duration)
        F0 = f["fid0"][idx]
        F1 = f["fid1"][idx]
        F0err = f["fid0_err"][idx]
        F1err = f["fid1_err"][idx]
        SSRO_readout_corr = zeros(len(SSRO_readout))
        readout_error = zeros(len(SSRO_readout))
        for i in arange(len(SSRO_readout)):
            
            ms0_events = SSRO_readout[i]*noof_reps
            ms1_events = noof_reps*(1-SSRO_readout[i])
            corr = spin_control.SSRO_correct(array([ms1_events,ms0_events]),
                   F0=F0,F1=F1,F0err=F0err,F1err=F1err)
            SSRO_readout_corr[i]=corr[0][0]
            readout_error[i] = corr[1][0] 
            counts_during_readout=SSRO_readout_corr
            ylabel = 'P(ms=0)'
    else:
        readout_error=zeros(len(counts_during_readout))
        ylabel = 'Integrated Counts'
    #########################################
    ############ FITTING ####################
    #########################################
    
    if fit_data:
        FFT = np.fft.fft(counts_during_readout)
        N = int(noof_datapoints)
        timestep = (mw_max_len-mw_min_len)/float(noof_datapoints-1)
        freq = np.fft.fftfreq(N,d = timestep)

        #Remove offset:
        FFT[freq == 0] = 0
        
        plot1 = plot.Plot2D(freq*1E3, abs(FFT), 'sb')
        plot1.set_xlabel('Frequency (MHz)')
        plot1.set_ylabel('Amplitude')
        plot1.set_plottitle('FFT (offset removed)')
        plot1.set_title('FFT')

        if save:
            plot1.save_png(os.path.join(datapath, 'figures', 'fft_signal_rabi.png'))

        freq_guess = freq[find_nearest(abs(FFT),abs(FFT).max())]
        amp_guess = (counts_during_readout.max()+counts_during_readout.min())/2.0
        offset_guess = counts_during_readout.min()+(counts_during_readout.max()+\
                counts_during_readout.min())/2.0
        phase_guess = 0

        #print 'frequency guess = ',freq_guess


        fit_result = fit.fit1d(mw_len, counts_during_readout, rabi.fit_rabi_simple, 
                freq_guess, amp_guess, offset_guess, phase_guess,
                do_plot = False, ret = True)

        f = fit_result['params_dict']['f']
        a = fit_result['params_dict']['a']
        A = fit_result['params_dict']['A']
        phi = fit_result['params_dict']['phi']
        x = np.linspace(mw_min_len, mw_max_len, 501)
        fit_curve = a + A*np.cos(2*np.pi*(f*x + phi/360))

        pi_pulse_len = 0.5*1/f
        pi_2_pulse_len = 0.5*pi_pulse_len
    print f
    name= spin_ro_file[:len(spin_ro_file)-16]
    if new_fig:
        plot2 = qt.plots['Cal']
        plot2.clear()
       
        plot2 = plot.plot(mw_len, counts_during_readout, 'k',yerr=readout_error,
                title=name,name='Cal')
        plot2.add(x,fit_curve, '-r',title='fit '+name)
    else:
        plot2 = qt.plots['Cal']
        plot2.add(mw_len, counts_during_readout, 'xk',yerr=readout_error,
                title=name)
        plot2.add(x,fit_curve, '-r',title='fit '+name)
    plot2.set_xlabel(name)
    plot2.set_ylabel(ylabel)
    plot2.set_plottitle(str(name) + ' , frabi ='+num2str(f*1E3,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm')
    
    #plt.text(0.1*(mw_max_len+mw_min_len),max(counts_during_readout),datapath)
    if save:
        plot2.save_png(os.path.join(datapath,'figures', 'histogram_integrated'))
    g.close()
    plot1.quit()
    if close_fig:
        plot2.quit()

    if save:
        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: MW length (ns)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in np.arange(noof_datapoints):
            col_vals += num2str(mw_len[k],2)+'\t'+num2str(counts_during_readout[k],0)+'\n'
        fo = open(os.path.join(datapath, 'processed_data', 'mw_pi_calibration_integrated_histogram.dat'), "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()
    
    if 'len' in name:
        minimum = pi_pulse_len
        
    else:
        minimum=x[find_nearest(fit_curve,fit_curve.min())]

    return minimum
Пример #22
0
    def calibrate(self, steps):  # calibration values in uW
        x = arange(0, steps)
        y = zeros(steps, dtype=float)

        self.apply_voltage(0)
        ins_pm.set_wavelength(self._wavelength * 1e9)
        time.sleep(2)
        bg = ins_pm.get_power()

        print 'background power: %.4f uW' % (bg * 1e6)

        time.sleep(2)

        V_max = self.get_V_max()

        for a in x:
            self.apply_voltage(a * V_max / (steps - 1))
            time.sleep(1)
            y[a] = ins_pm.get_power() - bg

            print 'measured power at %.2f V: %.4f uW' % \
                    (a/float(steps-1)*V_max, y[a]*1e6)

        x = x / float(steps - 1) * V_max
        a, xc, k = max(y), .5, 5.
        fitres = fit.fit1d(x,
                           y,
                           common.fit_AOM_powerdependence,
                           a,
                           xc,
                           k,
                           do_print=True,
                           do_plot=False,
                           ret=True)

        fd = zeros(len(x))
        if type(fitres) != type(False):
            p1 = fitres['params_dict']
            self.set_cal_a(p1['a'])
            self.set_cal_xc(p1['xc'])
            self.set_cal_k(p1['k'])
            fd = fitres['fitdata']
        else:
            print 'could not fit calibration curve!'


        dat = qt.Data(name='aom_calibration_'+self._name+'_'+\
                self._cur_controller)
        dat.add_coordinate('Voltage [V]')
        dat.add_value('Power [W]')
        dat.add_value('fit')
        dat.create_file()
        plt = qt.Plot2D(dat,
                        'rO',
                        name='aom calibration',
                        coorddim=0,
                        valdim=1,
                        clear=True)
        plt.add_data(dat, coorddim=0, valdim=2)
        dat.add_data_point(x, y, fd)
        dat.close_file()

        self.save_cfg()
        print(self._name + ' calibration finished')
Пример #23
0
from analysis import common, fit, rabi


data = load("Rabi-0_SpinReadout.npz")

j = 0
time = []
counts = []

for i in data["MW burst time"]:
    time.append(i)
    print j
    counts.append(sum(data["counts"][j]))
    j = j + 1


amp = (max(counts) - min(counts)) / 2.0
offset = (max(counts) + min(counts)) / 2.0
freq = 0.001
decay = 500.0

plt.plot(time, counts, "o")
fit_result = fit.fit1d(
    np.array(time), np.array(counts), rabi.fit_rabi_damped_exp, freq, amp, offset, decay, do_plot=True, ret=True
)
plt.show()
plt.savefig("rabi_fitted.png")
    def num2str(num, precision):
        return "%0.*f" % (precision, num)

    A = fit.Parameter(max(measured_power - BG) / 2)
    B = fit.Parameter(max(measured_power - BG) / 2)
    f = fit.Parameter(1 / 2.5)
    phi = fit.Parameter(0)

    def fit_cos(x):
        return A() + B() * cos(2 * pi * f() * x + phi())

    ret = fit.fit1d(
        V_EOM.reshape(-1),
        measured_power.reshape(-1) - BG,
        None,
        fitfunc=fit_cos,
        p0=[A, B, f, phi],
        do_plot=True,
        do_print=True,
        ret=True,
    )
    p = qt.plots["EOM Calibration curve"]
    V = linspace(EOM_min_voltage, EOM_max_voltage, V_step_size / 10)
    qt.plot(V, fit_cos(V), "r-", name="EOM Calibration curve")

plt.save_png(file_directory[0:65] + "calibration_EOM_curve.png")

print "Extinction = max/min = " + num2str(max(measured_power - BG) / min(measured_power - BG), 0)

print "Done"
def plot_dark_esr(datapath, fit_data = True, save = True, f_dip = 2.878E9):
    plt.close('all')

    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)
    
    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath+'\\'+stats_params_file)
    f_center = e['mw_center_freq']
    mwpower = e['mw_power']
    mw_min_freq = e['min_mw_freq']
    mw_max_freq = e['max_mw_freq']
    noof_datapoints = e['noof_datapoints']
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################
    
    f = np.load(datapath+'\\'+spin_ro_file)
    raw_counts = f['counts']
    repetitions = f['sweep_axis']
    t = f['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size/float(noof_datapoints)

    idx = 0
    counts_during_readout = zeros(noof_datapoints)
    mw_freq = linspace(mw_min_freq,mw_max_freq,noof_datapoints)
    counts_during_readout = sum(raw_counts, axis = 1)

    #########################################
    ############ FITTING ####################
    #########################################

    offset_guess = counts_during_readout.max()
    dip_depth_guess = offset_guess - counts_during_readout.min()

    print offset_guess
    print dip_depth_guess

    width_guess = 1E6
    f_dip_guess = f_dip
    noof_dips = 3
    dip_separation = 2E6

    figure2 = plt.figure(2)
    plt.plot(mw_freq/1E9,counts_during_readout, '-ok')

    if fit_data:
        fit_result, p = fit.fit1d(mw_freq/1E9, counts_during_readout, 
                esr.fit_ESR_gauss, offset_guess, dip_depth_guess, width_guess/1E9,
                f_dip_guess/1E9, (noof_dips, dip_separation/1E9),
                do_plot = True, do_print = True, newfig = False, ret = True, 
                plot_fitonly = True)


        center_peak = fit_result['params_dict']['x0']
        splitting = fit_result['params_dict']['s0']

        print '-1: f = ', (center_peak - splitting), ' GHz'
        print '0: f = ', center_peak, ' GHz'
        print '1: f = ', (center_peak + splitting), ' GHz'

    plt.xlabel('MW frequency (GHz)')
    plt.ylabel('Integrated counts')
    plt.title('MW frequency sweep, MW parking spot $f$ ='+num2str(f_center/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm')
   
    if save:
        figure2.savefig(datapath+'\\histogram_integrated.png')

    x = 6.0
    y = 8.0

    figure3 = plt.figure(figsize=(x,y))
    plt.pcolor(raw_counts, cmap = 'hot', antialiased=False)
    plt.xlabel('Readout time (us)')
    plt.ylabel('MW repetition number')
    plt.title('Total histogram, integrated over repetitions')
    plt.colorbar()
    if save:
        figure3.savefig(datapath+'\\histogram_counts_2d.png')

    f.close()

    ###########################################
    ######## SPIN PUMPING #####################
    ###########################################

    v = np.load(datapath+'\\'+sp_file)
    sp_counts = v['counts']
    sp_time = v['time']

    offset_guess = sp_counts[len(sp_counts)-1]
    init_amp_guess = sp_counts[2]
    decay_guess = 10

    figure4 = plt.figure(4)
    fit.fit1d(sp_time/1E3, sp_counts, common.fit_exp_decay_with_offset, 
            offset_guess, init_amp_guess, decay_guess,
            do_plot = True, do_print = True, newfig = False,
            plot_fitparams_xy = (0.5,0.5))
    
    plt.plot(sp_time/1E3,sp_counts,'sg')
    plt.xlabel('Time ($\mu$s)')
    plt.ylabel('Integrated counts')
    plt.title('Spin pumping')
    v.close()
    if save:
        figure4.savefig(datapath+'\\spin_pumping.png')

        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: MW freq (GHz)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in arange(noof_datapoints):
            col_vals += num2str(mw_freq[k]/1E9,10)+'\t'+num2str(counts_during_readout[k],0)+'\n'
        fo = open(datapath+'\\integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    return True
    time.sleep(1)
    y_BG[a] = adwin.get_countrates()[counter-1]
    print 'step %s, counts %s'%(a,y_BG[a])
        
if mw:
    SMB100.set_status('off')

#path = 'D:\\measuring\\data'  + '\\'+time.strftime('%Y%m%d') + '\\' + time.strftime('%H%M%S', time.localtime()) + '_saturation_'+name+'\\'
#if not os.path.isdir(path):
#    os.makedirs(path)
    
x_axis = x/float(steps-1)*max_power*1e6
#p_init = [400000, 80]
#p_fit = fit.fit_SaturationFunction(x_axis,y_NV-y_BG,p_init)
A, sat = max(y_NV-y_BG), .5*max_power*1e6
fitres = fit.fit1d(x_axis,y_NV-y_BG, common.fit_saturation, 
A, sat, do_print=True, do_plot=False, ret=True)

dat = qt.Data(name='Saturation_curve_'+name)
dat.create_file()
dat.add_coordinate('Power [uW]')
dat.add_value('Counts [Hz]')
plt = qt.Plot2D(dat, 'rO', name='Saturation curve', coorddim=0, valdim=1, clear=True)
fd = zeros(len(x_axis))        
if type(fitres) != type(False):
    p1 = fitres['params_dict']
    fit_A = p1['A']
    fit_sat = p1['xsat']
    fd = fitres['fitdata']
    
    print ('maximum count rate: %.1f cps, saturation power: %.1f microwatt'%(fit_A,fit_sat))
   
def plot_rabi(datapath, fit_data = True, with_detuning = False, save = True):

    plt.close('all')
    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)
    
    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath+'\\'+stats_params_file)
    f_drive = e['mw_drive_freq']
    mwpower = e['mw_power']
    mw_min_len = e['min_mw_length']
    mw_max_len = e['max_mw_length']
    noof_datapoints = e['noof_datapoints']
    noof_reps = e['completed_repetitions']
    e.close()

    
    ###########################################
    ######## SPIN RO  #########################
    ###########################################
    
    f = np.load(datapath+'\\'+spin_ro_file)
    raw_counts = f['counts']
    SSRO_counts = f['SSRO_counts']
    repetitions = f['sweep_axis']
    t = f['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size/float(noof_datapoints)

    idx = 0
    counts_during_readout = zeros(noof_datapoints)
    mw_len = linspace(mw_min_len,mw_max_len,noof_datapoints)
    counts_during_readout = sum(raw_counts, axis = 1)
    SSRO_readout = sum(SSRO_counts, axis = 1)/float(noof_reps)
    

    #########################################
    ############ FITTING ####################
    #########################################
    
    if fit_data:
        FFT = fft.fft(SSRO_readout)
        N = int(noof_datapoints)
        timestep = (mw_max_len-mw_min_len)/float(noof_datapoints-1)
        freq = fft.fftfreq(N,d = timestep)

        #Remove offset:
        FFT[freq == 0] = 0

        figure1 = plt.figure(1)
        plt.bar(freq*1E3,abs(FFT), width = 0.4*1E3*(freq[1]-freq[0]), align = 'center')
        plt.xlabel('Frequency (MHz)')
        plt.ylabel('Amplitude')
        plt.title('FFT (offset removed)')
        
        if save:
            figure1.savefig(datapath+'\\fft_signal_rabi.png')

        freq_guess = freq[find_nearest(abs(FFT),abs(FFT).max())]
        amp_guess = (counts_during_readout.max()+counts_during_readout.min())/2.0
        offset_guess = counts_during_readout.min()+(counts_during_readout.max()+\
                counts_during_readout.min())/2.0
        phase_guess = 0

    figure3 = plt.figure(3)
    plt.clf()
    ax1 = figure3.add_subplot(111)
   
    if fit_data and with_detuning:
        tau_guess = 200
        fit.fit1d(mw_len, counts_during_readout, 
                rabi.fit_rabi_multiple_detunings, 
                amp_guess, offset_guess, freq_guess, tau_guess,
                (0,0),(2.2E-3,0),(2*2.2E-3,0),
                do_plot = True, do_print = True, newfig = False)
    elif fit_data:
        [fit_result, p] = fit.fit1d(mw_len, counts_during_readout, rabi.fit_rabi_simple, 
                freq_guess, amp_guess, offset_guess, phase_guess,
                do_plot = True, do_print = True, newfig = False, ret = True)

        #pi_pulse_len = 0.5*1/fit_result['params_dict']['f']
        #pi_2_pulse_len = 0.5*pi_pulse_len

        #print 'pi pulse length = ', pi_pulse_len
        #print 'pi/2 pulse length = ',pi_2_pulse_len
    

    #ax2 = figure2.add_subplot(111, sharex=ax1, frameon=False)
    #ax2.plot(mw_len,counts_during_readout, 'sk')

    plt.xlabel('MW length (ns)')
    plt.ylabel('Integrated counts')
    plt.title('MW length sweep, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm')
    plt.text(0.1*(mw_max_len+mw_min_len),max(counts_during_readout),datapath)
    if save:
        figure3.savefig(datapath+'\\histogram_integrated.png')


    figure2 = plt.figure(2)
    plt.clf()
    ax1 = figure2.add_subplot(111)
    #plt.plot(mw_len,SSRO_readout, 'sk')

    if fit_data and with_detuning:
        tau_guess = 200
        fit.fit1d(mw_len, SSRO_readout, 
                rabi.fit_rabi_multiple_detunings, 
                amp_guess, offset_guess, freq_guess, tau_guess,
                (0,0),(2.2E-3,0),(2*2.2E-3,0),
                do_plot = True, do_print = True, newfig = False)
    elif fit_data:
        [fit_result, p] = fit.fit1d(mw_len, SSRO_readout, rabi.fit_rabi_simple, 
                freq_guess, amp_guess, offset_guess, phase_guess,
                do_plot = True, do_print = True, newfig = False, ret = True)

        pi_pulse_len = 0.5*1/fit_result['params_dict']['f']
        pi_2_pulse_len = 0.5*pi_pulse_len

        print 'pi pulse length = ', pi_pulse_len
        print 'pi/2 pulse length = ',pi_2_pulse_len
    

    #ax2 = figure2.add_subplot(111, sharex=ax1, frameon=False)
    #ax2.plot(mw_len,counts_during_readout, 'sk')
    plt.ylim([0,1])
    plt.xlabel('MW length (ns)')
    plt.ylabel('P($m_s=0$)')
    plt.title('MW length sweep, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm')
    plt.text(0.1*(mw_max_len+mw_min_len),max(counts_during_readout),datapath)
    if save:
        figure2.savefig(datapath+'\\histogram_integrated_SSRO.png')

    x = 6.0
    y = 8.0

    figure4 = plt.figure(figsize=(x,y))
    plt.pcolor(raw_counts, cmap = 'hot', antialiased=False)
    plt.xlabel('Readout time (us)')
    plt.ylabel('MW repetition number')
    plt.title('Total histogram, integrated over repetitions')
    plt.colorbar()
    if save:
        figure4.savefig(datapath+'\\histogram_counts_2d.png')

    f.close()
    

    ###########################################
    ######## SPIN PUMPING #####################
    ###########################################
    v = np.load(datapath+'\\'+sp_file)
    sp_counts = v['counts']
    sp_time = v['time']

    offset_guess = sp_counts[len(sp_counts)-1]
    init_amp_guess = sp_counts[2]
    decay_guess = 10

    figure5 = plt.figure()
    fit.fit1d(sp_time/1E3, sp_counts, common.fit_exp_decay_with_offset, 
            offset_guess, init_amp_guess, decay_guess,
            do_plot = True, do_print = True, newfig = False,
            plot_fitparams_xy = (0.5,0.5))
    
    plt.plot(sp_time/1E3,sp_counts,'sg')
    plt.xlabel('Time ($\mu$s)')
    plt.ylabel('Integrated counts')
    plt.title('Spin pumping')
    v.close()
    if save:
        figure5.savefig(datapath+'\\spin_pumping.png')

        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: MW length (ns)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in arange(noof_datapoints):
            col_vals += num2str(mw_len[k],2)+'\t'+num2str(counts_during_readout[k],0)+'\n'
        fo = open(datapath+'\\integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    return True
Пример #28
0
def dark_esr_calibration(datapath, fit_data = True, save = True, f_dip = 2.858E9):


    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)
    
    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k

    e = np.load(datapath+'\\'+stats_params_file)
    f_center = e['mw_center_freq']
    mwpower = e['mw_power']
    mw_min_freq = e['min_mw_freq']
    mw_max_freq = e['max_mw_freq']
    noof_datapoints = e['noof_datapoints']
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################
    
    g = np.load(datapath+'\\'+spin_ro_file)
    raw_counts = g['counts']
    repetitions = g['sweep_axis']
    t = g['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size/float(noof_datapoints)

    idx = 0
    counts_during_readout = np.zeros(noof_datapoints)
    mw_freq = np.linspace(mw_min_freq,mw_max_freq,noof_datapoints)
    counts_during_readout = np.sum(raw_counts, axis = 1)

    #########################################
    ############ FITTING ####################
    #########################################

    offset_guess = counts_during_readout.max()
    dip_depth_guess = offset_guess - counts_during_readout.min()

    print 'offset guess = ',offset_guess
    print 'dip depth guess = ',dip_depth_guess

    width_guess = 1E6
    f_dip_guess = f_dip
    noof_dips = 3
    dip_separation = 2E6

    if fit_data:
        fit_result = fit.fit1d(mw_freq, counts_during_readout, esr.fit_ESR_gauss, 
            offset_guess, dip_depth_guess, width_guess,
            f_dip_guess, (noof_dips, dip_separation),
            do_plot = False, do_print = False, 
            newfig = False, ret = True)

        x0 = fit_result['params_dict']['x0']
        a = fit_result['params_dict']['a']
        A = fit_result['params_dict']['A']
        sigma = fit_result['params_dict']['sigma']
        s0 = fit_result['params_dict']['s0']

        x = np.linspace(mw_min_freq, mw_max_freq, 501)
        fit_curve = np.zeros(len(x))

        x0 = [x0-s0, x0, x0+s0]
        for k in range(noof_dips):
            fit_curve += np.exp(-((x-x0[k])/sigma)**2)
        fit_curve = a*np.ones(len(x)) - A*fit_curve


    plot1 = qt.Plot2D(mw_freq/1E9, counts_during_readout, '-ok', x/1E9, fit_curve, '-r',name='desr',clear=True)  
    plot1.set_xlabel('MW frequency (GHz)')
    plot1.set_ylabel('Integrated counts')
    plot1.set_plottitle('MW frequency sweep, laser parking spot f ='+num2str(f_center/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm')
    if save:
        plot1.save_png(datapath+'\\histogram_integrated.png')

    g.close()
    #plot1.quit()

    if save:
        #Save a dat file for use in e.g. Origin with the dark esr data.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: MW freq (GHz)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in range(noof_datapoints):
            col_vals += num2str(mw_freq[k]/1E9,10)+'\t'+num2str(counts_during_readout[k],0)+'\n'
        fo = open(datapath+'\\mw_f_calibration_integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    return x0
def plot_esmw(datapath, fit_data = True, save = True):
    plt.close('all')

    suffix = 'esmw'

    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)
    
    e = np.load(datapath+'\\'+suffix+'-1_statics_and_parameters.npz')
    f_drive = e['mw_drive_freq']
    mwpower = e['mw_power']
    mw_min_freq = e['min_esmw_freq']
    mw_max_freq = e['max_esmw_freq']
    noof_datapoints = e['noof_datapoints']
    e.close()
    
    spin_ro_file = list()
    sp_file = list()
    
    for idx in arange(noof_datapoints):
        for k in files:
            if k == suffix+'-'+num2str(idx,0)+'_Spin_RO.npz':
                spin_ro_file.append(k)
            if k == suffix+'-'+num2str(idx,0)+'_SP_histogram.npz':
                sp_file.append(k)



    ###########################################
    ######## SPIN RO  #########################
    ###########################################
    
    mw_freq = linspace(mw_min_freq,mw_max_freq,noof_datapoints)
    fit_par=[]
    for idx in arange(noof_datapoints):
        f = np.load(datapath+'\\'+spin_ro_file[idx])
        raw_counts = f['counts']
        repetitions = f['sweep_axis']
        t = f['time']

        tot_size = len(repetitions)
        reps_per_point = tot_size/float(noof_datapoints)

        counts_during_readout = sum(raw_counts, axis = 0)
        ro_time = arange(0,shape(raw_counts)[1])
        figure1 = plt.figure(1)
        
        offset_guess = counts_during_readout.min()
        init_amp_guess = counts_during_readout.max()
        decay_guess = 10

        if fit_data:
            fit_result,p=fit.fit1d(ro_time[arange(4,len(ro_time)-1)], 
                    counts_during_readout[arange(4,len(ro_time)-1)], 
                    common.fit_exp_decay_with_offset, 
                    offset_guess, init_amp_guess, decay_guess,
                    do_plot = True, do_print = True, newfig = False,
                    plot_fitparams_xy = (0.5,0.5),
                    ret=True)
            if fit_result != False:
                fit_par.append(fit_result['params'][2])
            else:
                fit_par.append(0)
        plt.plot(ro_time, counts_during_readout, 'or')
        plt.xlabel('Read-out duration ($\mu$s)')
        plt.ylabel('Integrated counts')
        plt.title('Read-out with MW, driving $f$ ='+num2str(f_drive/1E6,1)+\
                ' MHz, power = '+num2str(mwpower,0)+' dBm')
        if save:
            figure1.savefig(datapath+'\\histogram_integrated'+num2str(idx,0)+'.png')
        plt.clf()

        x = 6.0
        y = 8.0

        figure2 = plt.figure(figsize=(x,y))
        plt.pcolor(raw_counts, cmap = 'hot', antialiased=False)
        plt.xlabel('Readout time (us)')
        plt.ylabel('MW repetition number')
        plt.title('Total histogram, integrated over repetitions')
        plt.colorbar()
        if save:
            figure2.savefig(datapath+'\\histogram_counts_2d'+num2str(idx,0)+'.png')
        plt.clf()

        f.close()
        
        ###########################################
        ######## SPIN PUMPING #####################
        ###########################################
        v = np.load(datapath+'\\'+sp_file[idx])
        sp_counts = v['counts']
        sp_time = v['time']

        offset_guess = sp_counts[len(sp_counts)-1]
        init_amp_guess = sp_counts[2]
        decay_guess = 10

        figure3 = plt.figure(3)
        if fit_data:
            fit.fit1d(sp_time/1E3, sp_counts, common.fit_exp_decay_with_offset, 
                    offset_guess, init_amp_guess, decay_guess,
                    do_plot = True, do_print = True, newfig = False,
                    plot_fitparams_xy = (0.5,0.5))
        
        plt.plot(sp_time/1E3,sp_counts,'sg')
        plt.xlabel('Time ($\mu$s)')
        plt.ylabel('Integrated counts')
        plt.title('Spin pumping')
        v.close()
        if save:
            figure3.savefig(datapath+'\\spin_pumping'+num2str(idx,0)+'.png')
        plt.clf()
    
    if save:
        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: MW Freq (ns)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in arange(len(mw_freq)):
            col_vals += num2str(mw_freq[k],4)+'\t'+num2str(counts_during_readout[k],0)+'\n'
        fo = open(datapath+'\\integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()
    
    if fit_data:
        plt.close('all')
        print len(mw_freq)
        print len(fit_par)
        figure4 = plt.figure(4)
        plt.plot(mw_freq/1E6,fit_par, '-r')
        plt.xlabel('MW frequency (MHz)')
        plt.ylabel('Decay constant')
        
        if save:
            figure4.savefig(datapath+'\\decay_constant_vs_mw_freq.png')
        plt.clf()



    return fit_par
Пример #30
0
def esr_calibration(datapath, fit_data = True, save = True, f_dip = 2.828E9):

    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)
    
    for k in files:
        if '.npz' in k:
            data_file = k
    data = np.load(datapath+'\\'+data_file)
    
    mw_freq = data['freq']
    counts = data['counts']
    data.close()

    f_dip_guess=f_dip
    offset_guess = counts.max()
    dip_depth_guess = offset_guess - counts.min()
    width_guess = 5e-3

    #########################################
    ############ FITTING ####################
    #########################################


    if fit_data:
        
        fit_result=fit.fit1d(mw_freq/1E9, counts, common.fit_gauss, 
            offset_guess, dip_depth_guess, f_dip_guess/1E9,width_guess,
            do_plot = False, do_print = False, newfig = False,ret=True)
        
        x0 = fit_result['params_dict']['x0']
        a = fit_result['params_dict']['a']
        A = fit_result['params_dict']['A']
        sigma = fit_result['params_dict']['sigma']
        #s0 = fit_result[0]['params_dict']['s0']

        x = np.linspace(mw_freq.min(), mw_freq.max(), 501)
        fit_curve = np.zeros(len(x))

        
        fit_curve = np.exp(-(((x/1E9)-x0)/sigma)**2)
        fit_curve = a*np.ones(len(x)) + A*fit_curve

    plot1 = qt.Plot2D(mw_freq/1E9, counts, '-ok', x/1E9, fit_curve, '-r',name='ESR',clear=True) 
    plot1.set_xlabel('MW frequency (GHz)')
    plot1.set_ylabel('Integrated counts')
    plot1.set_plottitle('MW frequency sweep')
    if save:
        plot1.save_png(datapath+'\\histogram_integrated.png')

    data.close()
    plot1.clear()
    plot1.quit()

    if save:
        #Save a dat file for use in e.g. Origin with the dark esr data.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: MW freq (GHz)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in range(len(counts)):
            col_vals += num2str(mw_freq[k]/1E9,10)+'\t'+num2str(counts[k],0)+'\n'
        fo = open(datapath+'\\mw_f_calibration_integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    return x0*1E9
def plot_Pulse_cal(datapath, fit_data = True, save = True):

    plt.close('all')
    ###########################################
    ######## MEASUREMENT SPECS ################
    ###########################################
    files = os.listdir(datapath)
    
    for k in files:
        if 'statics_and_parameters.npz' in k:
            stats_params_file = k
        if 'Spin_RO.npz' in k:
            spin_ro_file = k
        if 'SP_histogram.npz' in k:
            sp_file = k


    e = np.load(datapath+'\\'+stats_params_file)

    f_drive = e['mw_drive_freq']
    mwpower = e['mw_power']
    min_pulse_nr = e['min_pulse_nr']
    max_pulse_nr = e['max_pulse_nr']
    noof_datapoints = e['noof_datapoints']
    noof_reps = e['completed_repetitions']
    e.close()

    ###########################################
    ######## SPIN RO  #########################
    ###########################################
    

    f = np.load(datapath+'\\'+spin_ro_file)
    raw_counts = f['counts']
    repetitions = f['sweep_axis']
    SSRO_counts = f['SSRO_counts']
    t = f['time']

    tot_size = len(repetitions)
    reps_per_point = tot_size/float(noof_datapoints)

    idx = 0
    counts_during_readout = zeros(noof_datapoints)
    pulse_nr = linspace(min_pulse_nr,max_pulse_nr,noof_datapoints)
    counts_during_readout = sum(raw_counts, axis = 1)
    SSRO_readout = sum(SSRO_counts, axis = 1)/float(noof_reps)
    

    #########################################
    ############ FITTING ####################
    #########################################
    
    #FIXME to be implemented
    figure2=plt.figure(2)
    figure2.clf()
    plt.plot(pulse_nr,SSRO_readout, 'sk')
    plt.xlabel('Pulse nr')
    plt.ylabel('P ms=0')
    plt.title('MW length sweep, driving $f$ ='+num2str(f_drive/1E6,1)+\
            ' MHz, power = '+num2str(mwpower,0)+' dBm')
    #plt.text(0.1*(mw_max_len+mw_min_len),max(counts_during_readout),datapath)
    if save:
        figure2.savefig(datapath+'\\histogram_integrated.png')

    x = 6.0
    y = 8.0

    figure3 = plt.figure(figsize=(x,y))
    plt.pcolor(raw_counts, cmap = 'hot', antialiased=False)
    plt.xlabel('Readout time (us)')
    plt.ylabel('MW repetition number')
    plt.title('Total histogram, integrated over repetitions')
    plt.colorbar()
    if save:
        figure3.savefig(datapath+'\\histogram_counts_2d.png')

    f.close()
    

    ###########################################
    ######## SPIN PUMPING #####################
    ###########################################

    v = np.load(datapath+'\\'+sp_file)
    sp_counts = v['counts']
    sp_time = v['time']

    offset_guess = sp_counts[len(sp_counts)-1]
    init_amp_guess = sp_counts[2]
    decay_guess = 10

    figure4 = plt.figure(4)
    fit.fit1d(sp_time/1E3, sp_counts, common.fit_exp_decay_with_offset, 
            offset_guess, init_amp_guess, decay_guess,
            do_plot = True, do_print = True, newfig = False,
            plot_fitparams_xy = (0.5,0.5))
    
    plt.plot(sp_time/1E3,sp_counts,'sg')
    plt.xlabel('Time ($\mu$s)')
    plt.ylabel('Integrated counts')
    plt.title('Spin pumping')
    v.close()
    if save:
        figure4.savefig(datapath+'\\spin_pumping.png')

        #Save a dat file for use in e.g. Origin with the rabi oscillation.
        curr_date = '#'+time.ctime()+'\n'
        col_names = '#Col0: MW length (ns)\tCol1: Integrated counts\n'
        col_vals = str()
        for k in arange(noof_datapoints):
            col_vals += num2str(pulse_nr[k],2)+'\t'+num2str(counts_during_readout[k],0)+'\n'
        fo = open(datapath+'\\integrated_histogram.dat', "w")
        for item in [curr_date, col_names, col_vals]:
            fo.writelines(item)
        fo.close()

    return True
Пример #32
0
    def num2str(num, precision):
        return "%0.*f" % (precision, num)

    A = fit.Parameter(max(measured_power - BG) / 2)
    B = fit.Parameter(max(measured_power - BG) / 2)
    f = fit.Parameter(1 / 2.5)
    phi = fit.Parameter(0)

    def fit_cos(x):
        return A() + B() * cos(2 * pi * f() * x + phi())

    ret = fit.fit1d(V_EOM.reshape(-1),
                    measured_power.reshape(-1) - BG,
                    None,
                    fitfunc=fit_cos,
                    p0=[A, B, f, phi],
                    do_plot=True,
                    do_print=True,
                    ret=True)
    p = qt.plots['EOM Calibration curve']
    V = linspace(EOM_min_voltage, EOM_max_voltage, V_step_size / 10)
    qt.plot(V, fit_cos(V), 'r-', name='EOM Calibration curve')

plt.save_png(file_directory[0:65] + 'calibration_EOM_curve.png')

print 'Extinction = max/min = ' + num2str(
    max(measured_power - BG) / min(measured_power - BG), 0)

print 'Done'