def fit_laserscan(x, y, do_print=True): p0, fitfunc, fitfunc_str = common.fit_lorentz(0, np.max(y), np.sum(x * y) / np.sum(y), 0.2) return fit.fit1d(x, y, None, p0=p0, fitfunc=fitfunc, fitfunc_str=fitfunc_str, do_print=do_print, ret=True)
def fit_lorentzian(self, **kw): y = kw.pop('y', self.y_data) x = kw.pop('x', self.frq_data) g_gamma = kw.pop('g_gamma', 15) plot_title = kw.pop('plot_title', '') plot_fit = kw.pop('plot_fit', False) fixed = kw.pop('fixed', []) g_a = np.average(y) g_A = max(y) - g_a g_x0 = self.frq_data[np.argmax(y)] p0, fitfunc, fitfunc_str = common.fit_lorentz(g_a, g_A, g_x0, g_gamma) fit_result = fit.fit1d(x, y, None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True, fixed=fixed) if 'gamma' not in fit_result['params_dict']: fig, ax = plt.subplots(figsize=(10, 4)) ax.plot(x, y) print 'WARNING: COULD NOT FIT gamma' return 0, 10 gamma = np.abs(fit_result['params_dict']['gamma']) u_gamma = np.abs(fit_result['error_dict']['gamma']) x0 = fit_result['params_dict']['x0'] FWHM = gamma u_FWHM = u_gamma if plot_fit: fig, ax = plt.subplots(figsize=(10, 4)) plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], len(x) * 10), ax=ax, label='Fit', show_guess=True, plot_data=True) ax.set_title('FWHM = %.1f +- %.1f GHz %s' % (FWHM, u_FWHM, plot_title)) fig.savefig(self.folder + '/lorentzian_fit_%s.png' % (plot_title)) plt.show(fig) plt.close(fig) return FWHM, u_FWHM
def plot_and_fit_single_peak(self, g_a1, g_A1, g_x01, g_gamma1, fixed=[], **kw): p0, fitfunc, fitfunc_str = common.fit_lorentz(g_a1, g_A1, g_x01, g_gamma1) fit_result = fit.fit1d(self.x, self.y, None, p0=p0, fitfunc=fitfunc, do_print=True, ret=True, fixed=fixed) fig, ax = plt.subplots(figsize=(8, 4)) plot.plot_fit1d(fit_result, np.linspace(self.x[0], self.x[-1], 10 * len(self.x)), ax=ax, label='Fit', show_guess=True, plot_data=True, color='red', data_linestyle='-', print_info=False) ax.set_xlim(self.x[0], self.x[-1]) if self.use_timetrace: ax.set_xlabel("Time (ms)", fontsize=14) else: ax.set_xlabel("datapoints", fontsize=14) ax.set_ylabel("Intensity (a.u.)", fontsize=14) linewidth = fit_result['params_dict']['gamma1'] u_linewidth = fit_result['error_dict']['gamma1'] plt.savefig(os.path.join(self.indir, self.filename + '_fit.png')) plt.show() return linewidth, u_linewidth
def fit_peak(self, intensity, indices, peak_frequencies, peak_intensity, plot_fit=False, **kw): """ This function fits every presumed peak location with a lorentzian. If the fit fails it rejects it as a peak. Input parameters: intensity - 1 d array of intensity data indices - indices of the peaks peak_frequencies - frequencies of the peaks peak_intensity - intensity of the peaks g_gamma - the guess parameter of Lorentzians FWHM. Default: 0.2 g_offset - the guess parameter of the offset of the Lorentzian. Default:0 plot_fit - whether to plot each fit. default = False Output parameters: x0s - 1d array of the fitted peak locations u_x0s - 1d array of the uncertainty in the fitted peak locations """ report_fails = kw.pop('report_fails', False) x0s = np.array([]) u_x0s = np.array([]) g_gamma = kw.pop('g_gamma', self.ana_pars['g_gamma']) max_gamma = kw.pop('max_gamma', self.ana_pars['max_gamma']) min_gamma = kw.pop('min_gamma', self.ana_pars['min_gamma']) fit_peak_window = kw.pop( 'fit_peak_window', self.ana_pars['fit_peak_window']) # in multiples of gamma frequency_range = np.abs(self.frequencies[-1] - self.frequencies[0]) indices_around_peak = int((len(self.frequencies) / frequency_range) * g_gamma * fit_peak_window) success = np.zeros(len(indices)) nr_fails = 0 for i, ii, g_x0, g_A in zip(np.arange(len(indices)), indices, peak_frequencies, peak_intensity * g_gamma): if ii - indices_around_peak < 0: i_min = 0 else: i_min = ii - indices_around_peak if ii + indices_around_peak > len(self.frequencies) - 1: i_max = -1 else: i_max = ii + indices_around_peak intensity_around_peak = intensity[i_min:i_max] frequencies_around_peak = self.frequencies[i_min:i_max] g_offset = np.average(intensity_around_peak) fixed = [] p0, fitfunc, fitfunc_str = common.fit_lorentz( g_offset, g_A, g_x0, g_gamma) fit_result = fit.fit1d(frequencies_around_peak, intensity_around_peak, None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True, fixed=fixed) #if the fit failed, it outputs the variable 'success', that is an integer flag. #If it is 1,2,3,4 the fit succeeded, otherwise it failed. #Break the loop if the fit failed if fit_result['success'] == False: nr_fails += 1 continue if fit_result == 5: #print 'fit failed' nr_fails += 1 continue res_rms = fit_result['residuals_rms'] / np.average( frequencies_around_peak) gamma = fit_result['params_dict']['gamma'] u_gamma = fit_result['error_dict']['gamma'] x0 = fit_result['params_dict']['x0'] u_x0 = fit_result['error_dict']['x0'] A = fit_result['params_dict']['A'] # print x0,A,gamma if plot_fit: # print indices_around_peak # print wavelengths_around_peak print 'plot fit' fig, ax = plt.subplots() # ax.plot(wavelengths,intensity) plot.plot_fit1d(fit_result, np.linspace(frequencies_around_peak[0], frequencies_around_peak[-1], len(frequencies_around_peak)), ax=ax, label='Fit', show_guess=True, plot_data=True) plt.show() # if A < 20: # print 'peak intensity is too low; disregarding' # continue if u_x0 > np.abs(frequencies_around_peak[-1] - frequencies_around_peak[0]): if plot_fit: print 'uncertainty in peak position too large; disregarding: ', 'x0', x0, '+-', u_x0 nr_fails += 1 continue if u_gamma > np.abs(gamma): if plot_fit: print 'uncertainty in gamma too large; disregarding: ', 'gamma', gamma, '+-', u_gamma nr_fails += 1 continue if ((np.abs(gamma) > max_gamma) or (np.abs(gamma) < min_gamma)): if plot_fit: print 'ignoring this peak, since gamma is not within specs:', min_gamma, '<', gamma, '>', max_gamma nr_fails += 1 continue if A * gamma < 0: if report_fails or plot_fit: print 'ignoring since negative ' nr_fails += 1 continue success[i] = 1 #mark this peak as succesfully fitted x0s = np.append(x0s, x0) u_x0s = np.append(u_x0s, u_x0) if report_fails: print 'number of failed fits:', nr_fails return x0s, u_x0s, success # import os # import sys # import numpy as np # sys.path.append("H:\My Documents\measuring/") # %matplotlib inline # import analysis.scripts.cavity.oscilloscope_analysis as oa # import analysis.scripts.cavity.fit_oscilloscope_data as od # data_dir = "K:/ns\qt\Diamond\Projects\Cavities\data/20160426/EOM_lw_LT/" # file_name = "NNNNNNNLOWT007.csv" # filename = os.path.join(data_dir,file_name) # EOM_freq = 6 # reload(oa) # reload(od) # data = oa.load_data(filename) # od.get_linewidth(data,EOM_freq)
def fit_piezo_plots(data_folder, x_datas, y_datas, nr_repetitions=1, tag='', V_min=0, V_max=1, set_range_V=False, save_data=True, threshold=0.1, show_plots=True, show_avg_plots=False, averaging=True, **kw): 'This function plots all length scans within the given timestamp range' print '### YOU\'RE ANALYSING PIEZO SCANS ### \n' do_determine_drift = kw.pop('do_determine_drift', False) timestamps = kw.pop('timestamps', None) if do_determine_drift and timestamps == None: print 'Drift cannot be determined since no timestamps are provided. Provide timestamps.' do_determine_drift = False N_points = 100 #the number of points around the resonant centre cavity length that are averaged for all scans conversion_factor = 111 #nm / V . This is the calculated conversion factor from piezo voltage to distance moved LW = [] t = [] peak_positions = [] times = [] frequency = [] standard_dev = [] T = np.array([]) Ts = np.zeros(2 * N_points) for i in np.arange(nr_repetitions): if do_determine_drift: time = timestamps[i] if nr_repetitions > 1: V, y = x_datas[i], y_datas[i] else: V, y = x_datas, y_datas if len(V) == 0: continue T = np.append(T, 1) ''' If a certain range for V is selected, delete all the datapoints outside this range ''' if set_range_V == True: ind_min = np.where(V < V_min) ind_max = np.where(V > V_max) # print len(V) V = np.delete(V, ind_max[0]) V = np.delete(V, ind_min) y = np.delete(y, ind_max[0]) y = np.delete(y, ind_min) else: V_max = max(V) V_min = min(V) max_index, max_value = max(enumerate(y), key=operator.itemgetter(1)) if max_value < threshold: print "removing plot, max value < threshold" continue offset = 0.01 amplitude = 2 * max_value x0 = V[max_index] gamma = 0.002 """ Fit a Lorentzian """ fixed = [] p0, fitfunc, fitfunc_str = common.fit_lorentz(offset, amplitude, x0, gamma) fit_result = fit.fit1d(V, y, None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True, fixed=fixed) A = fit_result['params_dict']['A'] a = offset x0 = fit_result['params_dict']['x0'] gamma = fit_result['params_dict']['gamma'] u_gamma = fit_result['error_dict']['gamma'] # f2 = np.linspace(min(f),max(f),1001) function = a + 2 * A / np.pi * gamma / (4 * (V - x0)**2 + gamma**2) if A > 5 * max_value: continue Linewidth = gamma # u_Linewidth = u_gamma LW.append(Linewidth) peak_positions = np.append(peak_positions, x0) if do_determine_drift: times = np.append(times, time) dLs, V_zoom, y_zoom, zoom_success = zoom_around_peak( V, y, x0, N_points, conversion_factor=conversion_factor) if zoom_success: #if the ranging was not succesful, y_plot does not have the right dimension to fit on Ts, and should not be taken into account final_dLs = dLs Ts = Ts + y_zoom if (show_avg_plots and zoom_success): plot_current_and_average_transmission(dLs, Ts, T, y_zoom) if show_plots: ''' Plot figure ''' fig, ax = plt.subplots(figsize=(6, 4)) plot.plot_fit1d(fit_result, np.linspace(V_zoom[0], V_zoom[-1], len(V_zoom) * 10), data_linestyle='-', data_color='navy', data_lw=2, ax=ax, color='r', show_guess=True, plot_data=True, label='fit', add_txt=False) ax.legend() ax.set_xlabel('Voltage [V]', fontsize=14) ax.set_ylabel('Transmission (arb. units)', fontsize=14) ax.tick_params(axis='both', which='major', labelsize=14) ax.set_xlim(V_zoom[0], V_zoom[-1]) ax.set_title(data_folder + ' \n Cavity linewidth in length is %s $\pm$ %s nm' % (round(Linewidth * conversion_factor, 2), round(u_Linewidth * conversion_factor, 3))) if save_data == True: fig.savefig(data_folder + '/' + "piezofit_" + tag + "_" + str(i) + ".png") plt.show() plt.close() if len(T) == 0: print "No piezo data with these timestamps" average_LW = sum(LW) / len(LW) variance_LW = sum([(x - average_LW)**2 for x in LW]) / len(LW) st_dev_LW = np.sqrt(variance_LW) print 10 * '*' + 'Average linewidth is ', round( average_LW * conversion_factor, 3), '+-', round(st_dev_LW * conversion_factor, 4), ' nm ' + 10 * '*' #fit the averaged data -> if the linewidth is worse, the averaging is not done well. if averaging: offset = 0.05 amplitude = 2 * max_value x0 = 0 gamma = 0.3 fixed = [] p0, fitfunc, fitfunc_str = common.fit_lorentz(offset, amplitude, x0, gamma) fit_result = fit.fit1d(final_dLs, Ts / len(T), None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True, fixed=fixed) A = fit_result['params_dict']['A'] a = offset x0 = fit_result['params_dict']['x0'] gamma = fit_result['params_dict']['gamma'] u_gamma = fit_result['error_dict']['gamma'] fig, ax = plt.subplots(figsize=(6, 4)) plot.plot_fit1d(fit_result, np.linspace(final_dLs[0], final_dLs[-1], 10 * len(final_dLs)), ax=ax, color='navy', show_guess=True, plot_data=True, data_color='darkorange', data_linestyle='-', data_lw=3, lw=1.5, label='fit', add_txt=False) ax.legend() ax.set_xlabel('detuning in length (nm)', fontsize=14) ax.set_ylabel('Transmission (a.u.)', fontsize=14) ax.tick_params(axis='both', which='major', labelsize=14) ax.set_xlim(final_dLs[0], final_dLs[-1]) ax.set_title(data_folder + ' \n Cavity linewidth in length is %s $\pm$ %s nm' % (round(gamma, 3), round(u_gamma, 3))) fig.savefig(data_folder + '/' + tag + "average_transmission " + ".png") plt.tight_layout() plt.show() plt.close() if do_determine_drift: determine_drift(times, peak_positions, data_folder) return average_LW * conversion_factor, st_dev_LW * conversion_factor
def fit_fine_laser_plots(date, timestamp, folder, f_min, f_max, set_range_f=False, save_data=False, threshold=0.1): 'This function plots all fine laser scans within the given timestamp range' T = [] LW = [] for i in range(len(timestamp)): time = timestamp[i] data_folder, f, y, name = load_fine_lr_scan(folder=folder, timestamp=time, return_folder=True) if len(f) == 0: continue T.append(1) f = f * 30. / 3. ''' Assigns f_min and f_max ''' if set_range_f == True: ind_min = np.where(f < f_min) ind_max = np.where(f > f_max) f = np.delete(f, ind_max[0]) f = np.delete(f, ind_min[0]) y = np.delete(y, ind_max[0]) y = np.delete(y, ind_min[0]) else: f_max = max(f) f_min = min(f) max_index, max_value = max(enumerate(y), key=operator.itemgetter(1)) if max_value < threshold: continue offset = 0.01 amplitude = max_value x0 = f[max_index] sigma = 5 gamma = 5 fixed = [] p0, fitfunc, fitfunc_str = common.fit_lorentz(offset, amplitude, x0, gamma) fit_result = fit.fit1d(f, y, None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True, fixed=fixed) #print fit_result['params_dict'] A = fit_result['params_dict']['A'] a = fit_result['params_dict']['a'] x0 = fit_result['params_dict']['x0'] #sigma = fit_result['params_dict']['sigma'] gamma = fit_result['params_dict']['gamma'] u_gamma = fit_result['error_dict']['gamma'] # f2 = np.linspace(min(f),max(f),1001) function = a + 2 * A / np.pi * gamma / (4 * (f - x0)**2 + gamma**2) if A > 5 * max_value: print 'fit failed' continue Linewidth = np.abs(gamma) u_Linewidth = u_gamma LW.append(Linewidth) ''' Plot figure ''' fig, ax = plt.subplots(figsize=(6, 4.7)) ax.plot(f, y, 'bo', label='data') plot.plot_fit1d(fit_result, np.linspace(f[0], f[-1], len(f)), ax=ax, color='r', show_guess=True, plot_data=False, label='fit', add_txt=False) #ax.plot(f,function, 'g', label='testplot') ax.legend() ax.set_xlabel('Frequency [GHz]', fontsize=14) ax.set_ylabel('Transmission (arb. units)', fontsize=14) ax.tick_params(axis='both', which='major', labelsize=14) ax.set_xlim(f_min, f_max) ax.set_title(data_folder + '\n Linewidth in frequency is %s $\pm$ %s GHz' % (round(Linewidth, 2), round(u_Linewidth, 2))) if save_data == True: try: fig.savefig(data_folder + '/fit.png') fig.savefig(data_folder + '/fit.pdf') except: print('figure not saved') plt.show() plt.close() if len(T) == 0: print "No fine laser data with these timestamps" average_LW = sum(LW) / len(LW) variance_LW = sum([(x - average_LW)**2 for x in LW]) / len(LW) st_dev_LW = np.sqrt(variance_LW) print 'Average LW_piezo is ', round( average_LW, 1), ' GHz with a standard deviation of ', round(st_dev_LW, 1), ' GHz'
def fit_piezo_plots(data_folder,x_datas,y_datas,nr_repetitions=1,tag='',V_min=0, V_max=1, set_range_V = False, save_data = True, threshold = 0.1,show_plots=True, show_avg_plots=False ,averaging = True,**kw): 'This function plots all length scans within the given timestamp range' print '### YOU\'RE ANALYSING PIEZO SCANS ### \n' do_determine_drift = kw.pop('do_determine_drift',False) timestamps = kw.pop('timestamps', None) if do_determine_drift and timestamps == None: print 'Drift cannot be determined since no timestamps are provided. Provide timestamps.' do_determine_drift = False N_points = 100 #the number of points around the resonant centre cavity length that are averaged for all scans conversion_factor = 111 #nm / V . This is the calculated conversion factor from piezo voltage to distance moved LW = [] t = [] peak_positions = [] times = [] frequency = [] standard_dev = [] T = np.array([]) Ts = np.zeros(2*N_points) for i in np.arange(nr_repetitions): if do_determine_drift: time = timestamps[i] if nr_repetitions > 1: V,y = x_datas[i],y_datas[i] else: V,y = x_datas,y_datas if len(V) == 0: continue T = np.append(T,1) ''' If a certain range for V is selected, delete all the datapoints outside this range ''' if set_range_V == True: ind_min = np.where(V < V_min) ind_max = np.where(V > V_max) # print len(V) V = np.delete(V, ind_max[0]) V = np.delete(V, ind_min) y = np.delete(y, ind_max[0]) y = np.delete(y, ind_min) else: V_max = max(V) V_min = min(V) max_index, max_value = max(enumerate(y), key = operator.itemgetter(1)) if max_value < threshold: print "removing plot, max value < threshold" continue offset = 0.01 amplitude = 2*max_value x0 = V[max_index] gamma = 0.002 """ Fit a Lorentzian """ fixed = [] p0, fitfunc, fitfunc_str = common.fit_lorentz(offset, amplitude, x0, gamma) fit_result = fit.fit1d(V,y, None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True,fixed=fixed) A = fit_result['params_dict']['A'] a = offset x0 = fit_result['params_dict']['x0'] gamma = fit_result['params_dict']['gamma'] u_gamma = fit_result['error_dict']['gamma'] # f2 = np.linspace(min(f),max(f),1001) function = a + 2*A/np.pi*gamma/(4*(V-x0)**2+gamma**2) if A > 5 *max_value: continue Linewidth = gamma# u_Linewidth = u_gamma LW.append(Linewidth) peak_positions = np.append(peak_positions, x0) if do_determine_drift: times = np.append(times,time) dLs, V_zoom, y_zoom, zoom_success = zoom_around_peak(V, y, x0, N_points, conversion_factor = conversion_factor) if zoom_success: #if the ranging was not succesful, y_plot does not have the right dimension to fit on Ts, and should not be taken into account final_dLs = dLs Ts = Ts + y_zoom if (show_avg_plots and zoom_success): plot_current_and_average_transmission(dLs,Ts,T,y_zoom) if show_plots: ''' Plot figure ''' fig,ax = plt.subplots(figsize=(6,4)) plot.plot_fit1d(fit_result, np.linspace(V_zoom[0],V_zoom[-1],len(V_zoom)*10 ), data_linestyle = '-',data_color = 'navy', data_lw = 2,ax=ax,color='r',show_guess=True, plot_data=True, label = 'fit', add_txt=False) ax.legend() ax.set_xlabel('Voltage [V]',fontsize=14) ax.set_ylabel('Transmission (arb. units)',fontsize=14) ax.tick_params(axis = 'both', which = 'major',labelsize = 14) ax.set_xlim(V_zoom[0],V_zoom[-1]) ax.set_title(data_folder + ' \n Cavity linewidth in length is %s $\pm$ %s nm' %(round(Linewidth*conversion_factor,2), round(u_Linewidth*conversion_factor,3))) if save_data == True: fig.savefig(data_folder +'/'+ "piezofit_"+tag+"_"+str(i)+".png") plt.show() plt.close() if len(T) ==0: print "No piezo data with these timestamps" average_LW = sum(LW)/len(LW) variance_LW = sum([(x-average_LW)**2 for x in LW])/len(LW) st_dev_LW = np.sqrt(variance_LW) print 10*'*' + 'Average linewidth is ', round(average_LW*conversion_factor,3), '+-', round(st_dev_LW*conversion_factor,4), ' nm '+ 10*'*' #fit the averaged data -> if the linewidth is worse, the averaging is not done well. if averaging: offset = 0.05 amplitude = 2*max_value x0 = 0 gamma = 0.3 fixed = [] p0, fitfunc, fitfunc_str = common.fit_lorentz(offset, amplitude, x0, gamma) fit_result = fit.fit1d(final_dLs,Ts/len(T), None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True,fixed=fixed) A = fit_result['params_dict']['A'] a = offset x0 = fit_result['params_dict']['x0'] gamma = fit_result['params_dict']['gamma'] u_gamma = fit_result['error_dict']['gamma'] fig,ax = plt.subplots(figsize=(6,4)) plot.plot_fit1d(fit_result, np.linspace(final_dLs[0],final_dLs[-1],10*len(final_dLs)), ax=ax,color='navy',show_guess=True, plot_data=True, data_color = 'darkorange',data_linestyle ='-',data_lw =3,lw = 1.5,label = 'fit', add_txt=False) ax.legend() ax.set_xlabel('detuning in length (nm)',fontsize=14) ax.set_ylabel('Transmission (a.u.)',fontsize=14) ax.tick_params(axis = 'both', which = 'major',labelsize = 14) ax.set_xlim(final_dLs[0],final_dLs[-1]) ax.set_title(data_folder + ' \n Cavity linewidth in length is %s $\pm$ %s nm' %(round(gamma,3), round(u_gamma,3))) fig.savefig(data_folder +'/'+ tag+"average_transmission " + ".png") plt.tight_layout() plt.show() plt.close() if do_determine_drift: determine_drift(times,peak_positions, data_folder) return average_LW*conversion_factor, st_dev_LW*conversion_factor
def fit_fine_laser_plots(date, timestamp, folder, f_min, f_max, set_range_f = False, save_data = False, threshold=0.1): 'This function plots all fine laser scans within the given timestamp range' T = [] LW = [] for i in range(len(timestamp)): time = timestamp[i] data_folder, f,y, name = load_fine_lr_scan(folder = folder, timestamp = time, return_folder = True) if len(f) == 0: continue T.append(1) f = f*30./3. ''' Assigns f_min and f_max ''' if set_range_f == True: ind_min = np.where(f < f_min) ind_max = np.where(f > f_max) f = np.delete(f, ind_max[0]) f = np.delete(f, ind_min[0]) y = np.delete(y, ind_max[0]) y = np.delete(y, ind_min[0]) else: f_max = max(f) f_min = min(f) max_index, max_value = max(enumerate(y), key = operator.itemgetter(1)) if max_value < threshold: continue offset = 0.01 amplitude = max_value x0 = f[max_index] sigma = 5 gamma = 5 fixed = [] p0, fitfunc, fitfunc_str = common.fit_lorentz(offset, amplitude, x0, gamma) fit_result = fit.fit1d(f,y, None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True,fixed=fixed) #print fit_result['params_dict'] A = fit_result['params_dict']['A'] a = fit_result['params_dict']['a'] x0 = fit_result['params_dict']['x0'] #sigma = fit_result['params_dict']['sigma'] gamma = fit_result['params_dict']['gamma'] u_gamma = fit_result['error_dict']['gamma'] # f2 = np.linspace(min(f),max(f),1001) function = a + 2*A/np.pi*gamma/(4*(f-x0)**2+gamma**2) if A > 5 *max_value: print 'fit failed' continue Linewidth = np.abs(gamma) u_Linewidth = u_gamma LW.append(Linewidth) ''' Plot figure ''' fig,ax = plt.subplots(figsize=(6,4.7)) ax.plot(f,y, 'bo', label = 'data') plot.plot_fit1d(fit_result, np.linspace(f[0],f[-1],len(f)), ax=ax,color='r',show_guess=True, plot_data=False, label = 'fit', add_txt=False) #ax.plot(f,function, 'g', label='testplot') ax.legend() ax.set_xlabel('Frequency [GHz]',fontsize=14) ax.set_ylabel('Transmission (arb. units)',fontsize=14) ax.tick_params(axis = 'both', which = 'major',labelsize = 14) ax.set_xlim(f_min,f_max) ax.set_title(data_folder+'\n Linewidth in frequency is %s $\pm$ %s GHz' %(round(Linewidth,2), round(u_Linewidth,2))) if save_data == True: try: fig.savefig(data_folder+'/fit.png') fig.savefig(data_folder+'/fit.pdf') except: print('figure not saved') plt.show() plt.close() if len(T) ==0: print "No fine laser data with these timestamps" average_LW = sum(LW)/len(LW) variance_LW = sum([(x-average_LW)**2 for x in LW])/len(LW) st_dev_LW = np.sqrt(variance_LW) print 'Average LW_piezo is ', round(average_LW,1), ' GHz with a standard deviation of ', round(st_dev_LW,1), ' GHz'
offset = 0.00 amplitude = max_value x0 = V[max_index] exponent = 1 decay_constant = 3 sigma = 0.0004 gamma = 0.5 if fitting_method == 'gauss': p0, fitfunc, fitfunc_str = common.fit_gauss( offset, amplitude, x0, sigma) elif fitting_method == 'exp': p0, fitfunc, fitfunc_str = common.fit_general_exponential( offset, amplitude, x0, decay_constant, exponent) elif fitting_method == 'lorentz': p0, fitfunc, fitfunc_str = common.fit_lorentz( offset, amplitude, x0, gamma) fit_result = fit.fit1d(V, y, None, p0=p0, fitfunc=fitfunc, do_print=True, ret=True, fixed=fixed) # # # chi2 = fit_result['chisq'] # # # print "chi squared is %s" %chi2 ''' In order to calculate the linewidth a help-function is created which resembles the fitting function (by means of the fitting parameters). Of this function all indices where the function exceeds the half maximum are stored in