def do_plot_sp(tlength,binlength,clr,t0,y_raw,ax,inset=False): x_raw=np.arange(len(y_raw))/1000. #us x=x_raw[0:tlength] y=y_raw[0:tlength] x_rb=rb.average(x,order=binlength) y_rb=rb.average(y,order=binlength) fit_d_exp_tail = fit.fit1d(x_raw,y_raw, common.fit_double_exp_decay_with_offset, 0, 1, 1, 1, 0.1, do_plot = False, ret = True) ydfit=fit_d_exp_tail['fitdata'] if not inset: fit_exp_tail = fit.fit1d(x_raw,y_raw, common.fit_exp_decay_with_offset, 0, 1, 1, do_plot = False, ret = True) yfit=fit_exp_tail['fitdata'] ax.plot(x_rb,y_rb,'o',mec =clr['bright'], color="none") if not inset: ax.plot(x_raw,yfit,color =clr['medium']) ax.plot(x_raw,ydfit,color =clr['dark']) plt.xlabel('time ($\mathrm{\mu}$s)') if not inset: plt.xlim(-0.2,tlength/1000.) plt.ylabel('clicks (kHz)') else: plt.xlim(-0.9,tlength/1000.) plt.ylabel('clicks (MHz)') return fit_d_exp_tail
def g2_hist(self, range=(-520,520), bins=2*52): # NOTE bins should be an even number! self.peaks = {} self.amplitudes = [] self.normpeaks = {} for i,d in enumerate(self.deltas): hy,hx = np.histogram(self.coincidences[i]+self.offset, bins=bins, range=range) self.peaks[d] = (hy,hx) self.fitdt = hx[1]-hx[0] if d != 0: A = fit.Parameter(max(hy)) def fitfunc(x): return A()*np.exp(-abs(x)/self.tau) fit.fit1d(hx[:-1]+(hx[1]-hx[0])/2., hy, None, fitfunc=fitfunc, p0=[A], do_print=True, fixed=[]) self.amplitudes.append(A()) # normalize peaks self.meanamp = np.mean(self.amplitudes) for d in self.peaks: self.normpeaks[d] = (self.peaks[d][0]/self.meanamp, self.peaks[d][1]) return True
def g2_hist(self, range=(-520, 520), bins=2 * 52): # NOTE bins should be an even number! self.peaks = {} self.amplitudes = [] self.normpeaks = {} for i, d in enumerate(self.deltas): hy, hx = np.histogram(self.coincidences[i] + self.offset, bins=bins, range=range) self.peaks[d] = (hy, hx) self.fitdt = hx[1] - hx[0] if d != 0: A = fit.Parameter(max(hy)) def fitfunc(x): return A() * np.exp(-abs(x) / self.tau) fit.fit1d(hx[:-1] + (hx[1] - hx[0]) / 2.0, hy, None, fitfunc=fitfunc, p0=[A], do_print=True, fixed=[]) self.amplitudes.append(A()) # normalize peaks self.meanamp = np.mean(self.amplitudes) for d in self.peaks: self.normpeaks[d] = (self.peaks[d][0] / self.meanamp, self.peaks[d][1]) return True
def plot_relaxation_vs_sweep(self, ms, st, save=True, **kw): ret = kw.get('ret', None) ax = kw.get('ax', None) ax2 = kw.get('ax2', None) if ax == None: fig = self.default_fig(figsize=(6,4)) ax = self.default_ax(fig) fig2 = self.default_fig(figsize=(10,6)) #fig2.title('Relaxation fit vs' + self.sweep_name) else: save = False name= '_ms'+ str(ms) + '_' + str(st) sweep=self.sweep_pts[::2] taus=np.zeros(len(sweep)) for i,sw in enumerate(sweep): #print i start,length=getattr(self,'_get_'+st+'_window')(ms,i) y,x=self._get_relaxation(ms, i, start, length) x=x[:-1] res = fit.fit1d(x,y, common.fit_exp_decay_shifted_with_offset, 0, y[0], 1000, x[0], ret=True, do_print=False, fixed=[3]) if res != False: ax2=plt.subplot(3,np.ceil(float(len(sweep)+1)/3),i+1) plot.plot_fit1d(res, x, ax=ax2, plot_data=True, print_info=False) ax2.text(ax2.get_xlim()[-1]*0.8,ax2.get_ylim()[-1]*0.8, '{:.2f}'.format(sw),horizontalalignment='right') if (res['params_dict']['A'] > 10*res['params_dict']['a']): taus[i]=res['params_dict']['tau']/1e3 else: print 'Sweep point {} ignored'.format(i) else: print 'Could not fit sweep point {}'.format(i) skip_points = kw.get('skip_points', 0) xx=sweep[taus>1.][skip_points:] yy=taus[taus>1.][skip_points:] #y(x) = A * exp(-(x-x0)/tau) + a #g_a : offset #g_A : initial Amplitude #g_tau : decay constant #g_x0 : x offset res2 = fit.fit1d(xx,yy, common.fit_exp_decay_with_offset, 10, yy[0], xx[len(xx)/2]/2., ret=True, do_print=True, fixed=[]) ax.plot(xx,yy, 'o') #ax.plot(sweep,10+yy[0]*np.exp(-(sweep- xx[0])/(xx[len(xx)/2]/2.))) if res2 != False: plot.plot_fit1d(res2, xx, ax=ax, plot_data=False, print_info=True) #ax.colorbar() ax.set_xlabel(self.sweep_name) ax.set_ylabel('ms={} {}-relaxation time [us]'.format(ms,st)) return res if save: self.save_fig_incremental_filename(fig,name+'_relaxation_vs_sweep') if ret == 'ax': return ax if ret == 'fig': return fig
def fitNflips (N, cM, fixAmpl = False, fixOff=False, show_plots = True): cM_m1 = squeeze(asarray(cM[0, :])) cM_0 = squeeze(asarray(cM[1, :])) cM_p1 = squeeze(asarray(cM[2, :])) A_guess = 1. off_guess= 0. p_guess=0.05 fixP = [] if fixAmpl == True: fixP.append(0) if fixOff == True: fixP.append(1) fit_m1 = fit.fit1d (asarray(N), cM_m1, common.fit_nuclearSpinFlips_1, A_guess, off_guess, p_guess, fixed = fixP, do_plot = show_plots, ret = True) fit_0 = fit.fit1d (asarray(N), cM_0, common.fit_nuclearSpinFlips_2, A_guess, off_guess, p_guess, fixed = fixP, do_plot = show_plots, ret=True) fit_p1 = fit.fit1d (asarray(N), cM_p1, common.fit_nuclearSpinFlips_3, A_guess, off_guess, p_guess, fixed = fixP, do_plot = show_plots, ret=True) results = [fit_m1, fit_0, fit_p1] print fit_m1[0]['fitdata'] plt.figure() plt.plot (N, fit_m1[0]['fitdata'], 'b', label = 'mI=-1') plt.plot (N, fit_0[0]['fitdata'], 'r', label = 'mI=0') plt.plot (N, fit_p1[0]['fitdata'], 'k', label = 'mI=+1') plt.plot (N, cM_m1, '>b') plt.plot (N, cM_0, 'ro') plt.plot (N, cM_p1, 'kD') plt.rcParams.update({'font.size': 18}) plt.xlabel ('number of read-out steps', fontsize = 16) plt.ylabel ('readout corrected nuclear spin fidelity', fontsize = 16) plt.legend (loc =1, prop={'size':12}) plt.show() return results
def fitNflips(N, cM, fixAmpl=False, fixOff=False, show_plots=True): cM_m1 = squeeze(asarray(cM[0, :])) cM_0 = squeeze(asarray(cM[1, :])) cM_p1 = squeeze(asarray(cM[2, :])) A_guess = 1. off_guess = 0. p_guess = 0.05 fixP = [] if fixAmpl == True: fixP.append(0) if fixOff == True: fixP.append(1) fit_m1 = fit.fit1d(asarray(N), cM_m1, common.fit_nuclearSpinFlips_1, A_guess, off_guess, p_guess, fixed=fixP, do_plot=show_plots, ret=True) fit_0 = fit.fit1d(asarray(N), cM_0, common.fit_nuclearSpinFlips_2, A_guess, off_guess, p_guess, fixed=fixP, do_plot=show_plots, ret=True) fit_p1 = fit.fit1d(asarray(N), cM_p1, common.fit_nuclearSpinFlips_3, A_guess, off_guess, p_guess, fixed=fixP, do_plot=show_plots, ret=True) results = [fit_m1, fit_0, fit_p1] print fit_m1[0]['fitdata'] plt.figure() plt.plot(N, fit_m1[0]['fitdata'], 'b', label='mI=-1') plt.plot(N, fit_0[0]['fitdata'], 'r', label='mI=0') plt.plot(N, fit_p1[0]['fitdata'], 'k', label='mI=+1') plt.plot(N, cM_m1, '>b') plt.plot(N, cM_0, 'ro') plt.plot(N, cM_p1, 'kD') plt.rcParams.update({'font.size': 18}) plt.xlabel('number of read-out steps', fontsize=16) plt.ylabel('readout corrected nuclear spin fidelity', fontsize=16) plt.legend(loc=1, prop={'size': 12}) plt.show() return results
def fit_two_lorentzian_peaks(V,y,offset,amplitude,x0,gamma,amplitude2,gamma2,splitting,fixed): """ Function that fits two lorentzian peaks to noisy data. Input: V - the x array of data y - the y array of data offset - guess for the fit offset amplitude - guess for the amplitude of the highest peak x0 - guess for the location of the highest peak gamma - guess for the FWHM of the highest peak amplitude2 - guess for the amplitude of the lowest peak gamma2 - guess for the FWHM of the lowest peak splitting - guess for the splitting between the two peaks fixed - array of the parameters to be fixed in fit function. (keep order; e.g.to fix spliting: fixed = [5]) """ #First try fitting with the left peak the largest dx2_1 = splitting p0_1, fitfunc_1, fitfunc_str_1 = common.fit_2lorentz_splitting(offset, amplitude, x0, gamma, amplitude2, dx2_1, gamma2) fit_result_1 = fit.fit1d(V,y, None, p0=p0_1, fitfunc=fitfunc_1, do_print=False, ret=True,fixed=fixed) #Then try fitting with the right peak the largest dx2_2 = - splitting p0_2, fitfunc_2, fitfunc_str_2 = common.fit_2lorentz_splitting(offset, amplitude, x0, gamma, amplitude2, dx2_2, gamma2) fit_result_2 = fit.fit1d(V,y, None, p0=p0_2, fitfunc=fitfunc_2, do_print=False, ret=True,fixed=fixed) discard_1 = False discard_2 = False if fit_result_1['params_dict']['A2']*fit_result_1['params_dict']['gamma2'] < 0: # print 'discard first fit' discard_1 = True if fit_result_2['params_dict']['A2']*fit_result_2['params_dict']['gamma2'] < 0: # print 'discard second fit' discard_2 = True if discard_1 and discard_2: print 'discarding both Lorentzian fits since they do not give a positive transmission' fit_failed = True else: fit_failed = False if (fit_result_1['chisq'] < fit_result_2['chisq']) or discard_2: fit_result = fit_result_1 left_peak_high = True else: fit_result = fit_result_2 left_peak_high = False return fit_result, left_peak_high, fit_failed
def epulse_fidelity(folder, ax, *args): a = sequence.SequenceAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='ssro') a.get_electron_ROC() a.plot_result_vs_sweepparam(ax=ax, name='ssro') x = a.sweep_pts.reshape(-1)[:] y = a.p0.reshape(-1)[:] of = fit.Parameter(args[0], 'of') of2 = fit.Parameter(0, 'of2') of3 = fit.Parameter(0, 'of3') fitfunc_str = '(1-of)' def fitfunc_fid(x): return (1. - of()) fit_result = fit.fit1d(x, y, None, p0=[of], fixed=[], fitfunc=fitfunc_fid, fitfunc_str=fitfunc_str, do_print=True, ret=True) #plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax, # plot_data=False, print_info=False) return fit_result
def fit_linear(folder, ax, value, *args): a = sequence.SequenceAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='ssro') a.get_electron_ROC() a.plot_result_vs_sweepparam(ax=ax, name='ssro') x = a.sweep_pts.reshape(-1)[:] y = a.p0.reshape(-1)[:] ax.set_title(a.timestamp) a = fit.Parameter(args[0], 'a') b = fit.Parameter(args[0], 'b') fitfunc_str = 'a x + b' def fitfunc(x): return a() * x + b() fit_result = fit.fit1d(x, y, None, p0=[a, b], fitfunc=fitfunc, fitfunc_str=fitfunc_str, do_print=True, ret=True) plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False) return fit_result
def calibrate_epulse_amplitude(folder, ax, *args): a = sequence.SequenceAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='ssro') a.get_electron_ROC() a.plot_result_vs_sweepparam(ax=ax, name='ssro') x = a.sweep_pts.reshape(-1)[:] y = a.p0.reshape(-1)[:] ax.set_title(a.timestamp) x0 = fit.Parameter(args[0], 'x0') of = fit.Parameter(args[1], 'of') a = fit.Parameter(args[2], 'a') fitfunc_str = '(1-of) + a (x-x0)**2' def fitfunc_parabolic(x): return (1. - of()) + a() * (x - x0())**2 fit_result = fit.fit1d(x, y, None, p0=[of, a, x0], fitfunc=fitfunc_parabolic, fitfunc_str=fitfunc_str, do_print=True, ret=True) plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=True) return fit_result
def fit_population_vs_detuning(folder, ax, *args): a = mbi.MBIAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='adwindata') a.get_electron_ROC( ) # a.get_N_ROC(0.97,0.03,0.96,0.01,0.93,0.01)#(0.99, 0.02, 0.94, 0.005) ax = a.plot_results_vs_sweepparam(ret='ax', name='adwindata') x = a.sweep_pts.reshape(-1)[:] y = a.p0.reshape(-1)[:] guess_a = 1 guess_A = -0.8 guess_F = 0.005 guess_x0 = args[0] fit_result = fit.fit1d(x, y, rabi.fit_population_vs_detuning, guess_a, guess_A, guess_F, guess_x0, fixed=[], do_print=True, ret=True) plot.plot_fit1d(fit_result, np.linspace(a.sweep_pts[0], a.sweep_pts[-1], 201), ax=ax, plot_data=False) return fit_result
def fit_correlation_parabolic(folder, ax, *args, **kw): which_correlation = kw.pop('which_correlation', 2) a = mbi.MBIAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='adwindata') a.get_correlations(name='adwindata') a.plot_results_vs_sweepparam(ax=ax, mode='correlations') x = a.sweep_pts.reshape(-1)[:] y = a.normalized_correlations[:, which_correlation] x0 = fit.Parameter(args[0], 'x0') of = fit.Parameter(args[1], 'of') a = fit.Parameter(args[2], 'a') fitfunc_str = '(1-of) + a (x-x0)**2' def fitfunc_parabolic(x): return (1. - of()) + a() * (x - x0())**2 fit_result = fit.fit1d(x, y, None, p0=[of, a, x0], fitfunc=fitfunc_parabolic, fitfunc_str=fitfunc_str, do_print=True, ret=True) plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False) return fit_result
def _fit(self, X, Y): #Fit parabole: o + A * (x-c)**2 ['g_o', 'g_A', 'g_c'] guess_o = np.min(Y) guess_A = ((np.max(Y) - np.min(Y)) / (X[np.argmax(Y)] - X[np.argmin(Y)])**2) guess_c = X[np.argmin(Y)] print 'fit guess ', guess_A, guess_c, guess_o fitres = fit.fit1d(X, Y, common.fit_parabole, guess_o, guess_A, guess_c, len(X), do_print=False, ret=True) if fitres['success'] != False: p1 = fitres['params_dict'] print p1 fd = fitres['fitfunc'](X) p = plt.plot(name=self._plot_name) p.add(X, fd, '-b') else: print '\tCould not fit curve!' return None, None return p1['A'], p1['c']
def fit_exp(x=[], y=[], plot_fits=False): guess_b = 10. guess_c = 0. b = fit.Parameter(guess_b, 'b') def fitfunc(x): return np.exp(-np.abs((x) / b())) xx = np.linspace(0, x[-1], 1000) fit_result = fit.fit1d(x, y, None, p0=[b], fitfunc=fitfunc, do_print=False, ret=True) b_fit = fit_result['params_dict']['b'] err_b = fit_result['error_dict']['b'] if plot_fits: plt.figure() plt.plot(x * 1000, y, '.b') plt.plot(xx * 1000, np.exp(-np.abs((xx) / b_fit)), 'r') plt.xlabel('time [msec]') plt.show() return b_fit, err_b
def fit_linear(folder=None, ax=None, a_guess=1., b_guess=0.): """ fit a x + b from Sequence in folder """ a, ax, x, y = plot_result(folder, ax) a = fit.Parameter(a_guess, 'a') b = fit.Parameter(b_guess, 'b') fitfunc_str = 'a x + b' def fitfunc(x): return a() * x + b() fit_result = fit.fit1d(x, y, None, p0=[a, b], fitfunc=fitfunc, fitfunc_str=fitfunc_str, do_print=True, ret=True) plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False) return fit_result
def fit_calibration(self, V, freq, fixed): guess_b = -21.3 guess_c = -0.13 guess_d = 0.48 guess_a = freq[0] +3*guess_b-9*guess_c+27*guess_d a = fit.Parameter(guess_a, 'a') b = fit.Parameter(guess_b, 'b') c = fit.Parameter(guess_c, 'c') d = fit.Parameter(guess_d, 'd') p0 = [a, b, c, d] fitfunc_str = '' def fitfunc(x): return a()+b()*x+c()*x**2+d()*x**3 fit_result = fit.fit1d(V,freq, None, p0=p0, fitfunc=fitfunc, fixed=fixed, do_print=False, ret=True) if (len(fixed)==2): a_fit = fit_result['params_dict']['a'] c_fit = fit_result['params_dict']['c'] return a_fit, c_fit else: a_fit = fit_result['params_dict']['a'] b_fit = fit_result['params_dict']['b'] c_fit = fit_result['params_dict']['c'] d_fit = fit_result['params_dict']['d'] return a_fit, b_fit, c_fit, d_fit
def fit_parabola(x, y, guess_x0, guess_amp, guess_of, fixed, show_fit = True, save = True): x0 = fit.Parameter(guess_x0, 'x0') A = fit.Parameter(guess_amp, 'A') o = fit.Parameter(guess_of, 'o') p0 = [x0, A, o] fitfunc_str = '' fitfunc_str = 'o + A*(x - x0)^2' def fitfunc(x): return o() + A() * (x - x0) ** 2. fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc, fixed=fixed, do_print=True, ret=True) if show_fit: plot.plot_fit1d(fit_result, np.linspace(0,x[-1],201), plot_data=True) # print "pi pulse = {:.5f} ".format(1/f()/2.) + a.sweep_name # ax.set_title(a.timestamp+'\n'+a.measurementstring) if save: plt.savefig(os.path.join(folder, 'Calibrate_Pi_analysis_parabolafit.png'))
def fit_gauss(x, y, **kw): a = kw.pop('a', 0.1) A = kw.pop('A', 0.7) x0 = kw.pop('x0', 0) T = kw.pop('T', 1000) n = kw.pop('n', 2) fixed = kw.pop('fixed', [0, 2, 4]) show_guess = kw.pop('show_guess', False) do_print = kw.pop('do_print', False) p0, fitfunc, fitfunc_str = common.fit_general_exponential(a, A, x0, T, n) if show_guess: ax.plot(np.linspace(0, x[-1], 201), fitfunc(np.linspace(0, x[-1], 201)), ':', lw=2) fit_result = fit.fit1d(x, y, None, p0=p0, fitfunc=fitfunc, do_print=do_print, ret=True, fixed=fixed) return fit_result
def plot_last_histogram(self): y, x = self._hist, self._hist_bins[ 1:] * self._hist_binsize_ns #np.histogram(self._dts_ns, bins = np.linspace(self.get_roi_min(), self.get_roi_max(),pts))#np.min(dts[dts>0]),np.max(dts),pts)) plotname = self.get_name() + '_histogram' qt.plot(x, y, name=plotname, clear=True) f = common.fit_exp_decay_shifted_with_offset #A * exp(-(x-x0)/tau) + a #['g_a', 'g_A', 'g_tau', 'g_x0'] args = [1, np.max(y) * 0.1, 12, x[np.argmax(y) + 2.]] first_fit_bin = int( np.round(self._plot_extra_range / self._hist_binsize_ns)) xf, yf = x[first_fit_bin:], y[first_fit_bin:] fitres = fit.fit1d(xf, yf, f, *args, fixed=[0], do_print=False, ret=True, maxfev=100) plot_pts = 200 x_p = np.linspace(min(xf), max(xf), plot_pts) if fitres['success']: y_p = fitres['fitfunc'](x_p) print 'fit success' else: y_p = f(*args)[1](x_p) print 'fit failed' print fitres['params_dict'] qt.plot(x_p, y_p, 'b', name=plotname, clear=False) self.y = y self.x = x
def analysis(): dp=os.path.join(meas_folder, date) amp=[] phase=[] j=0 color=['Crimson','RoyalBlue'] ramsey_data={} for i in datafolders: tau_guess = 3000 offset_guess=0.5 freq=1e-3 amp=0.5 result=sc.analyse_plot_results_vs_sweepparam(i,yname='P(mI=0)',Nuclcor=False,dataname='Spin_RO',d=date) resultcor=sc.analyse_plot_results_vs_sweepparam(i,yname='P(mI=0)',Nuclcor=True,dataname='Spin_RO',d=date) fit_result = fit.fit1d(result['x'], result['y'], ramsey.fit_ramsey_gaussian_decay, tau_guess, offset_guess, (freq,amp,90), do_print = True , ret = True) fit_x=np.linspace(result['x'].min(),result['x'].max(),201) ramsey_data['fit_x']=fit_x if label[j]=='mI=-1': ramsey_data['datamin1']=result['y'] ramsey_data['xmin1']=result['x'] ramsey_data['udatamin1']=result['uy'] ramsey_data['fitmin1']=fit_result['fitfunc'](fit_x) ramsey_data['datamin1_cor']=resultcor['y'] else: ramsey_data['datazero']=result['y'] ramsey_data['xzero']=result['x'] ramsey_data['udatazero']=result['uy'] ramsey_data['fitzero']=fit_result['fitfunc'](fit_x) ramsey_data['datazero1_cor']=resultcor['y'] np.savez(os.path.join(basepath,name),**ramsey_data) j+=1
def fit_correlation_oscillation(folder, ax, *args, **kw): which_correlation = kw.pop("which_correlation", 2) a = mbi.MBIAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name="adwindata") a.get_correlations(name="adwindata") a.plot_results_vs_sweepparam(ax=ax, mode="correlations") x = a.sweep_pts.reshape(-1)[:] y = a.normalized_correlations[:, which_correlation] x0 = fit.Parameter(args[0], "x0") f = fit.Parameter(args[1], "f") A = fit.Parameter(args[2], "A") o = fit.Parameter(0.25, "o") fitfunc_str = "(1 - A) + A * cos(2pi f (x - x0))" def fitfunc(x): return o() + A() * np.cos(2 * np.pi * f() * (x - x0())) fit_result = fit.fit1d( x, y, None, p0=[f, A, x0, o], fitfunc=fitfunc, fitfunc_str=fitfunc_str, do_print=True, ret=True ) plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False) return fit_result
def fit_calibration(V, freq): guess_b = (freq[-1] - freq[0]) / (V[-1] - V[0]) guess_a = freq[0] print 'Initial guess: ', guess_a, guess_b a = fit.Parameter(guess_a, 'a') b = fit.Parameter(guess_b, 'b') p0 = [a, b] fitfunc_str = '' def fitfunc(x): return a() + b() * x fit_result = fit.fit1d(V, freq, None, p0=p0, fitfunc=fitfunc, fixed=[], do_print=False, ret=True) a_fit = fit_result['params_dict']['a'] b_fit = fit_result['params_dict']['b'] print 'a= ', a_fit print 'b=', b_fit return a_fit, b_fit
def plot_desr(do_save=False): folder=r'M:\tnw\ns\qt\Diamond\Projects\Magnetometry with adaptive measurements\Data\raw_data\20141014\130500_PulsarDarkESR_FM_Gretel_sil10' ssro_calib_folder = toolbox.latest_data(contains='AdwinSSRO_SSROCalibration') print ssro_calib_folder a = sequence.SequenceAnalysis(folder) a.get_sweep_pts() a.get_readout_results('ssro') a.get_electron_ROC(ssro_calib_folder=ssro_calib_folder) x = a.sweep_pts # convert to MHz y = a.p0.reshape(-1)[:] # ax.plot(x,y) fig2 = plt.figure(figsize=(2,1.25)) fig2.clf() ax2 = fig2.add_subplot(111) #a.plot_result_vs_sweepparam(ret=True, name='ssro',ax=ax2) ax2.set_xlim([-3,3]) ax2.set_ylim(0.5,1) ax2.yaxis.set_ticks([0.5,0.75,1]) #ax2.xaxis.set_ticks([0.5,0.75,1]) guess_x0= 2.845334 guess_offset = 1 guess_Nsplit = 2.18e-3 guess_sigma = 0.0001 guess_A_min1 = 0.4 guess_A_plus1 = 0.25 guess_A_0 = 0.3 A_min1 = fit.Parameter(guess_A_min1, 'A_min1') A_plus1 = fit.Parameter(guess_A_plus1, 'A_plus1') A_0 = fit.Parameter(guess_A_0, 'A_0') o = fit.Parameter(guess_offset, 'o') x0 = fit.Parameter(guess_x0, 'x0') sigma = fit.Parameter(guess_sigma, 'sigma') Nsplit = fit.Parameter(guess_Nsplit, 'Nsplit') def fitfunc(x): return o() - np.abs(A_min1())*np.exp(-((x-(x0()-Nsplit()))/sigma())**2) \ - np.abs(A_plus1())*np.exp(-((x-(x0()+Nsplit()))/sigma())**2) \ - np.abs(A_0())*np.exp(-((x-x0())/sigma())**2) \ print x fit_result = fit.fit1d(x, y, None, p0 = [A_min1, A_plus1, A_0, sigma, o, x0, Nsplit], fitfunc = fitfunc, do_print=True, ret=True, fixed=[]) print fitfunc(x) x_fit=np.linspace(a.sweep_pts[0],a.sweep_pts[-1],2001) y_fit=fit_result['fitfunc'](x_fit) ax2.plot(1e3*(x_fit-2.845334),y_fit,color='Grey',linewidth=2) ax2.errorbar(1e3*(a.sweep_pts-2.845334),a.p0,yerr=a.u_p0,color=colors[3],fmt='o') ax2.set_ylabel('P($m_s =0$)') ax2.set_xlabel('Pulse detuning (MHz)') if do_save: fig2.savefig(r'M:\tnw\ns\qt\Diamond\Projects\Magnetometry with adaptive measurements\Data\analyzed data\desr.pdf', bbox_inches='tight')
def poly_fit_frq(self, **kw): plot_fit = kw.pop('plot_fit', True) g_x0 = self.x_data[0] g_a0 = self.frq_data[0] g_a1 = (self.frq_data[-1] - self.frq_data[0]) / (self.x_data[-1] - self.x_data[0]) g_a2 = -0.2 g_a3 = 2 fixed = [] p0, fitfunc, fitfunc_str = common.fit_poly_shifted( g_x0, g_a0, g_a1, g_a2, g_a3) fit_result = fit.fit1d(self.x_data, self.frq_data, None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True, fixed=fixed) if plot_fit: plot.plot_fit1d(fit_result, np.linspace(self.x_data[-1], self.x_data[0], 10 * len(self.x_data)), label='Fit', show_guess=False, plot_data=True, color='red', data_linestyle='-', print_info=True) self.frq_data = fit_result['fitfunc'](self.x_data) return self.frq_data
def fit_correlation_parabolic(folder, ax, *args, **kw): which_correlation = kw.pop("which_correlation", 2) a = mbi.MBIAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name="adwindata") a.get_correlations(name="adwindata") a.plot_results_vs_sweepparam(ax=ax, mode="correlations") x = a.sweep_pts.reshape(-1)[:] y = a.normalized_correlations[:, which_correlation] x0 = fit.Parameter(args[0], "x0") of = fit.Parameter(args[1], "of") a = fit.Parameter(args[2], "a") fitfunc_str = "(1-of) + a (x-x0)**2" def fitfunc_parabolic(x): return (1.0 - of()) + a() * (x - x0()) ** 2 fit_result = fit.fit1d( x, y, None, p0=[of, a, x0], fitfunc=fitfunc_parabolic, fitfunc_str=fitfunc_str, do_print=True, ret=True ) plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False) return fit_result
def analyze_dark_esr(folder, ax=None, **kw): if ax == None: fig, ax = plt.subplots(1,1) ssro_calib_folder = toolbox.latest_data(contains='AdwinSSRO_SSROCalibration') a = sequence.SequenceAnalysis(folder) a.get_sweep_pts() a.get_readout_results('ssro') a.get_electron_ROC(ssro_calib_folder=ssro_calib_folder) x = a.sweep_pts # convert to MHz y = a.p0.reshape(-1)[:] a.plot_result_vs_sweepparam(ret=None, name='ssro', ax=ax) guess_ctr = x[np.floor(len(x)/2.)] fit_result = fit.fit1d(x, y, esr.fit_ESR_gauss, guess_offset, guess_amplitude, guess_width, guess_ctr, # (2, guess_splitN), #(2, guess_splitC), # (2, guess_splitB), #(3, guess_splitN), do_print=True, ret=True, fixed=[]) plot.plot_fit1d(fit_result, np.linspace(min(x), max(x), 1000), ax=ax, plot_data=False, **kw) ax.set_xlabel('MW frq (GHz)') ax.set_ylabel(r'fidelity wrt. $|0\rangle$') ax.set_title(a.timestamp+'\n'+a.measurementstring) plt.savefig(os.path.join(folder, 'darkesr_analysis.png'), format='png') return fit_result
def optimize_z(z_range=0.4, nr_pts=5, green_power=100e-6): z_current = mos.get_z() zs = np.linspace(z_current - z_range / 2., z_current + z_range / 2., nr_pts) SN = np.zeros(nr_pts) green_aom.set_power(green_power) for i, z in enumerate(zs): print i, z mos.set_z(z) SN[i] = get_signal_to_noise() if (msvcrt.kbhit() and msvcrt.getch() == 'q'): break d = qt.Data(name='z_optimization_sn') d.add_coordinate('z (um)') d.add_value('SN') d.create_file() filename = d.get_filepath()[:-4] d.add_data_point(zs, SN) d.close_file() print filename fitargs = (np.min(SN), np.max(SN), zs[np.argmax(SN)], 0.1) gaussian_fit_SN = fit.fit1d(zs, SN, common.fit_gauss_pos, *fitargs, do_print=False, ret=True) p0 = gaussian_fit_SN['params_dict'] #qt.plot(zs,SN,name='sn_measurement_z',clear=True) zp = np.linspace(min(zs), max(zs), 100) # p_c = qt.plot(zp,gaussian_fit_SN['fitfunc'](zp), name='SN_vs_z') # p_c.save_png(filename+'.png') # p_c = qt.Plot2D(d, 'bO-', coorddim=0, name='z_optimization_sn', valdim=1, clear=True) # p_c.save_png(filename+'.png') print p0 if gaussian_fit_SN['success']: print 'z0', p0['x0'] if (p0['x0'] < min(zs)) or (p0['x0'] > max(zs)): 'optimum out of scan range. setting to max point: ', zs[np.argmax( SN)] mos.set_z(zs[np.argmax(SN)]) else: 'optimize succeeded. new z:', p0['x0'] mos.set_z(p0['x0']) #return gaussian_fit_SN else: 'fit failed, setting back to intial positon', z_current mos.set_z(z_current)
def analyze_dark_esr_single(x, y, guess_ctr, guess_offset=1, guess_width=0.2e-3, guess_amplitude=0.3, ret='f0', **kw): guess_ctr = x[y.argmin()] print 'guess_ctr = ' + str(guess_ctr) ## I added this to be more robust for SSRO calibration.Please monitor if this is better - Machiel may-2014 guess_offset = np.average(y) dip_threshold = guess_offset - 1.5 * np.std(y) print guess_offset print dip_threshold print min(y) if min(y) > dip_threshold: print 'Could not find dip' return fit_result = fit.fit1d(x, y, esr.fit_ESR_gauss, guess_offset, guess_amplitude, guess_width, guess_ctr, do_print=True, ret=True, fixed=[]) f0 = fit_result['params_dict']['x0'] u_f0 = fit_result['error_dict']['x0'] return f0, u_f0
def get_signal_to_noise(): opt_ins = qt.instruments['opt1d_counts'] x, y = opt_ins.run(dimension='x', scan_length=1.2, nr_of_points=51, pixel_time=100, return_data=True, gaussian_fit=True) fitargs = (np.min(y), np.max(y), x[np.argmax(y)], 0.1) #print fitargs, len(p) gaussian_fit = fit.fit1d(x, y, common.fit_gauss_pos, *fitargs, do_print=False, ret=True) print gaussian_fit['success'] p0 = gaussian_fit['params_dict'] plot(x, y, name='sn_measurement', clear=True) xp = linspace(min(x), max(x), 100) plot(xp, gaussian_fit['fitfunc'](xp), name='sn_measurement') print 'signal/noise : {:.0f}/{:.0f} = {:.2f}'.format( p0['A'], p0['a'], p0['A'] / p0['a']) return gaussian_fit
def analyze_dark_esr_single(x,y,guess_ctr, guess_offset = 1, guess_width = 0.2e-3, guess_amplitude = 0.3, ret='f0', **kw): guess_ctr = x[y.argmin()] print 'guess_ctr = '+str(guess_ctr) ## I added this to be more robust for SSRO calibration.Please monitor if this is better - Machiel may-2014 guess_offset=np.average(y) dip_threshold=guess_offset-1.5*np.std(y) print guess_offset print dip_threshold print min(y) if min(y) > dip_threshold: print 'Could not find dip' return fit_result = fit.fit1d(x, y, esr.fit_ESR_gauss, guess_offset, guess_amplitude, guess_width, guess_ctr, do_print=True, ret=True, fixed=[]) f0 = fit_result['params_dict']['x0'] u_f0 = fit_result['error_dict']['x0'] return f0, u_f0
def calibrate_epulse_rabi(folder, ax, *args, **kws): fit_phi = kws.pop('fit_phi', True) fit_k = kws.pop('fit_k', True) a = sequence.SequenceAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='ssro') a.get_electron_ROC() a.plot_result_vs_sweepparam(ax=ax, name='ssro') x = a.sweep_pts.reshape(-1)[:] y = a.p0.reshape(-1)[:] ax.set_title(a.timestamp) f = fit.Parameter(args[0], 'f') A = fit.Parameter(args[1], 'A') x0 = fit.Parameter(0, 'x0') k = fit.Parameter(0, 'k') p0 = [f, A] if fit_phi: p0.append(x0) if fit_k: p0.append(k) fitfunc_str = '(1 - A) + A * exp(-kx) * cos(2pi f (x - x0))' def fitfunc(x) : return (1.-A()) + A() * np.exp(-k()*x) * \ np.cos(2*np.pi*(f()*(x - x0()))) fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc, fitfunc_str=fitfunc_str, do_print=True, ret=True) plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax, plot_data=False, print_info=False) return fit_result
def epulse_fidelity(folder, ax, *args): a = sequence.SequenceAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='ssro') a.get_electron_ROC() a.plot_result_vs_sweepparam(ax=ax, name='ssro') x = a.sweep_pts.reshape(-1)[:] y = a.p0.reshape(-1)[:] of = fit.Parameter(args[0], 'of') of2 = fit.Parameter(0, 'of2') of3 = fit.Parameter(0, 'of3') fitfunc_str = '(1-of)' def fitfunc_fid(x) : return (1.-of()) fit_result = fit.fit1d(x,y, None, p0=[of], fixed = [], fitfunc=fitfunc_fid, fitfunc_str=fitfunc_str, do_print=True, ret=True) #plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax, # plot_data=False, print_info=False) return fit_result
def fit_gaussian(folder, ax, *args): a = sequence.SequenceAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='ssro') a.get_electron_ROC() a.plot_result_vs_sweepparam(ax=ax, name='ssro') x = a.sweep_pts.reshape(-1)[:] y = a.p0.reshape(-1)[:] ax.set_title(a.timestamp) x0 = fit.Parameter(args[0], 'x0') a = fit.Parameter(0.5, 'a') o = fit.Parameter(0.5, 'o') c = fit.Parameter(15, 'c') f = fit.Parameter(1./500, 'f') fitfunc_str = 'o + a * exp( - ( (x-x0)/c )^2) ' def fitfunc(x): return o() + a() * np.exp( -((x-x0())/ c())**2) fit_result = fit.fit1d(x,y, None, p0=[o,x0,a,c], fixed = [], fitfunc=fitfunc, fitfunc_str=fitfunc_str, do_print=True, ret=True) plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax, plot_data=False) return fit_result
def calibrate_epulse_amplitude(folder, ax, *args): a = sequence.SequenceAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='ssro') a.get_electron_ROC() a.plot_result_vs_sweepparam(ax=ax, name='ssro') x = a.sweep_pts.reshape(-1)[:] y = a.p0.reshape(-1)[:] ax.set_title(a.timestamp) x0 = fit.Parameter(args[0], 'x0') of = fit.Parameter(args[1], 'of') a = fit.Parameter(args[2], 'a') fitfunc_str = '(1-of) + a (x-x0)**2' def fitfunc_parabolic(x): return (1.-of()) + a() * (x-x0())**2 fit_result = fit.fit1d(x,y, None, p0=[of, a, x0], fitfunc=fitfunc_parabolic, fitfunc_str=fitfunc_str, do_print=True, ret=True) plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax, plot_data=False, print_info=True) return fit_result
def fit_sweep_pump_power(x, y, L=0.042): guess_b = 1 guess_a = max(y) a = fit.Parameter(guess_a, 'a') b = fit.Parameter(guess_b, 'b') p0 = [a, b] fitfunc_str = '' def fitfunc(x): return a() * np.sin(L * (b() * x)**0.5)**2 fit_result = fit.fit1d(x, y, None, p0=p0, fitfunc=fitfunc, fixed=[], do_print=True, ret=True) a_fit = fit_result['params_dict']['a'] b_fit = fit_result['params_dict']['b'] print 'a= ', a_fit print 'b=', b_fit return a_fit, b_fit
def fit_rabi(folder=None, ax = None, f_guess=0.9, A_guess=1,fit_phi = False,fit_k = False): """ fit (1 - A) + A * exp(-kx) * cos(2pi f (x - x0)) from Sequence in folder """ a, ax, x, y = plot_result(folder,ax) f = fit.Parameter(f_guess, 'f') A = fit.Parameter(A_guess, 'A') x0 = fit.Parameter(0, 'x0') k = fit.Parameter(0, 'k') p0 = [f, A] if fit_phi: p0.append(x0) if fit_k: p0.append(k) fitfunc_str = '(1 - A) + A * exp(-kx) * cos(2pi f (x - x0))' def fitfunc(x) : return (1.-A()) + A() * np.exp(-k()*x) * \ np.cos(2*np.pi*(f()*(x - x0()))) fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc, fitfunc_str=fitfunc_str, do_print=True, ret=True) plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax, plot_data=False, print_info=False) return fit_result
def analyze_dark_esr(x,y,guess_ctr, guess_splitN, guess_offset = 1, guess_width = 0.2e-3, guess_amplitude = 0.3, ret='f0', **kw): j=0 min_dip_depth = 0.9 print 'j = '+str(j) print y[21] k = len(y) while y[j]>min_dip_depth and j < len(y)-2: #y[j]>0.93*y[j+1]: # such that we account for noise k = j j += 1 #j = len(y)-2 if k > len(y)-3: print 'Could not find dip' return else: guess_ctr = x[k]+ guess_splitN #convert to GHz and go to middle dip print 'guess_ctr= '+str(guess_ctr) print 'k'+str(k) ## I added this to be more robust for SSRO calibration.Please monitor if this is better - Machiel may-2014 fit_result = fit.fit1d(x, y, esr.fit_ESR_gauss, guess_offset, guess_amplitude, guess_width, guess_ctr, (3, guess_splitN), do_print=True, ret=True, fixed=[4]) if ret == 'f0': f0 = fit_result['params_dict']['x0'] u_f0 = fit_result['error_dict']['x0'] return f0, u_f0
def fit_sin_and_calc_phi(x,y,ax = False): g_a = 0.0 g_A = np.amax(y) g_phi = x[np.argmax(y)] ### frequency guess is hardcoded as this is mainly intended for specific entangling oscillations. g_f = 1/360. p0s, fitfunc,fitfunc_str = common.fit_cos(g_f,g_a,g_A,g_phi) fit_result = fit.fit1d(x,y, None, p0=p0s, fitfunc=fitfunc, ret=True,fixed=[0,1]) if ax: plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax, plot_data=False,print_info = False) A = fit_result['params_dict']['A'] phi = fit_result['params_dict']['phi'] if A < 0: phi = phi + 180 A = -A phi = np.mod(-phi,360) phi_u = fit_result['error_dict']['phi'] print 'A,phi,phi_u ', A, phi, phi_u return phi, phi_u # Phi and Phi_u
def calibrate_Npulse_rabi(folder, ax, *args): a = mbi.MBIAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name="adwindata") a.get_electron_ROC() a.plot_results_vs_sweepparam(ax=ax, name="adwindata") x = a.sweep_pts.reshape(-1)[:] y = a.p0[:, 0] f = fit.Parameter(args[0], "f") A = fit.Parameter(args[1], "A") o = fit.Parameter(0.5, "o") x0 = fit.Parameter(0, "x0") p0 = [f, A, x0, o] fitfunc_str = "o + A * cos(2pi f x - 2pi phi)" def fitfunc(x): return o() + A() * np.cos(2 * np.pi * (f() * (x - x0()))) fit_result = fit.fit1d(x, y, None, p0=p0, fitfunc=fitfunc, fitfunc_str=fitfunc_str, do_print=True, ret=True) plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False) return fit_result
def determine_drift(times, peak_positions, data_folder): times_dec = [] ftr = [3600,60,1] for time in times: time_dec = sum([a*b for a,b in zip(ftr, [ int(time[0:2]),int(time[2:4]),int(time[4:6]) ]) ]) times_dec = np.append(times_dec, time_dec) times_dec = times_dec - times_dec[0] g_a = 2.13 g_b = 0.0007 fixed=[] p0, fitfunc, fitfunc_str = common.fit_line(g_a, g_b) fit_result = fit.fit1d(times_dec,peak_positions, None, p0=p0, fitfunc=fitfunc, do_print=False, ret=True,fixed=fixed) b = fit_result['params_dict']['b'] u_b = fit_result['error_dict']['b'] fig,ax = plt.subplots(figsize=(6,4.7)) ax = plot.plot_fit1d(fit_result, np.linspace(times_dec[0],times_dec[-1],10*len(times_dec)), ax=ax,color='r',show_guess=True, plot_data=True, label = 'fit', add_txt=False, ret='ax') ax.set_xlabel('time (s)') ax.set_ylabel('peak position (V)') ax.set_title(data_folder + ' \n Drift is {} $\pm$ {} mV/s '.format(round(b*1.e3,3), round(u_b*1.e3,3))) fig.savefig(data_folder +'/'+ "drift " + ".png") plt.show() plt.close()
def analyse_data(self, filename): data = np.loadtxt(filename) counts = data[:, 1] freq = data[:, 0] * 1e-9 guess_offset = counts[0] guess_amplitude = np.max(counts) - np.min(counts) guess_width = 0.005 guess_ctr = 2.88 success = False fit_result = fit.fit1d(freq, counts, esr.fit_ESR_gauss, guess_offset, guess_amplitude, guess_width, guess_ctr, do_print=False, ret=True) if fit_result['success'] == 1 and abs(fit_result['params_dict']['x0'] - guess_ctr) < 0.1: success = True plot.plot_fit1d(fit_result, np.linspace(np.min(freq), np.max(freq), 1000), plot_data=True, add_txt=True, plot_title=None) plt.savefig(filename + '_fit' + '.png') plt.close() return success
def calibrate_epulse_amplitude(folder, ax, *args, **kw): double_ro = kw.pop("double_ro", "False") a = mbi.MBIAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name="adwindata") a.get_electron_ROC() a.plot_results_vs_sweepparam(ax=ax, name="adwindata") x = a.sweep_pts.reshape(-1)[:] if double_ro == "electron": y = a.p0[:, 0] elif double_ro == "nitrogen": y = a.p0[:, 1] else: y = a.p0.reshape(-1)[:] x0 = fit.Parameter(args[0], "x0") of = fit.Parameter(args[1], "of") a = fit.Parameter(args[2], "a") fitfunc_str = "(1-of) + a (x-x0)**2" def fitfunc_parabolic(x): return (1.0 - of()) + a() * (x - x0()) ** 2 fit_result = fit.fit1d( x, y, None, p0=[of, a, x0], fitfunc=fitfunc_parabolic, fitfunc_str=fitfunc_str, do_print=True, ret=True ) plot.plot_fit1d(fit_result, np.linspace(x[0], x[-1], 201), ax=ax, plot_data=False, print_info=False) return fit_result
def fit_exp(x, y, guess_a, guess_A, guess_tau, fixed=[], show_fit=True, save=True, timestamp='', **kw): ''' Fit single exponential to T1 data ''' p0, fitfunc, fitfunc_str = common.fit_exp_decay_with_offset( guess_a, guess_A, guess_tau) fit_result = fit.fit1d(x, y, None, p0=p0, fitfunc=fitfunc, fixed=fixed, do_print=True, ret=True) # Plot fit and format if requested keys = sorted(kw.keys()) if show_fit: if len(keys) == 0: plot.plot_fit1d(fit_result, np.linspace(0, x[-1], 201), plot_data=True) elif len(keys) != 0 and 'ax' in keys: ax = kw['ax'] plot.plot_fit1d(fit_result, np.linspace(0, x[-1], 201), plot_data=False, ax=ax) elif len(keys) != 0 and 'ax' not in keys: print 'length of keyword arguments =', len(keys) raise Exception( "Your keywords for plot formatting didn't contain a pyplot axis with keyword 'ax'. Please provide it." ) if 'xlabel' in keys: ax.set_xlabel(kw['xlabel']) if 'ylabel' in keys: ax.set_ylabel(kw['ylabel']) if timestamp != '': if timestamp == None: folder = toolbox.latest_data('ElectronT1') else: folder = toolbox.data_from_time(timestamp) if save: plt.savefig(os.path.join(folder, 'Calibrate_Pi_analysis_fit.png')) return fit_result
def fast_pi2(): folder = toolbox.latest_data('cal_fast_pi_over_2') a = mbi.MBIAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='adwindata') a.get_electron_ROC() #a.plot_results_vs_sweepparam(ax=ax, name='adwindata') x = a.sweep_pts y = a.p0.reshape(-1) u_y = a.u_p0.reshape(-1) n = a.sweep_name x2 = x[::2] y2 = y[1::2] - y[::2] u_y2 = np.sqrt(u_y[1::2]**2 + u_y[::2]**2) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), sharex=True) ax1.errorbar(x2, y2, yerr=u_y2, fmt='o') ax1.set_xlabel(n) ax1.set_title('Difference btw. Pi/2-Pi and Pi/2' + '\n' + a.timestamp) ax1.set_ylabel('Difference') m = fit.Parameter((y[-1] - y[0]) / (x[-1] - x[0]), 'm') x0 = fit.Parameter(x2.mean(), 'x0') p0 = [m, x0] def ff(x): return m() * (x - x0()) fitfunc_str = 'm * (x - x0)' fit_result = fit.fit1d(x2, y2, None, p0=p0, fitfunc=ff, fitfunc_str=fitfunc_str, do_print=True, ret=True) ax2.errorbar(x2, y[0::2], yerr=u_y[0::2], fmt='o', label='Pi/2') ax2.errorbar(x2, y[1::2], yerr=u_y[1::2], fmt='o', label='Pi/2 - Pi') ax2.legend(frameon=True, framealpha=0.5) ax2.set_ylabel('P(0)') ax2.set_xlabel(n) if fit_result != False: ax2.axvline(x0(), c='k', lw=2) ax2.axhline(0.5, c='k', lw=2) ax2.set_title('X marks the spot') plot.plot_fit1d(fit_result, np.linspace(x2[0], x2[-1], 201), ax=ax1, plot_data=False, print_info=True) return x0(), 0
def calibrate(self, steps): # calibration values in uW rng = np.arange(0,steps) x = np.zeros(steps,dtype = float) y = np.zeros(steps,dtype = float) self.set_power(0) self._ins_pm.set_wavelength(self._wavelength) 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=np.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(0.5) y[a] = self._ins_pm.get_power() - bg print 'measured power at %.2f V: %.4f uW' % \ (x[a], y[a]*1e6) #x= x*(V_max-V_min)/float(steps-1)+V_min a, xc, k = np.copysign(np.max(y), V_max + V_min), np.copysign(.1, V_max + V_min), np.copysign(5., V_max + V_min) fitres = fit.fit1d(x,y, common.fit_AOM_powerdependence, a, xc, k, do_print=True, ret=True) fd = np.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['fitfunc'](x) 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 analyze_nmr_single(timestamp = None,center_guess = False, ax=None, ret=None,min_dip_depth = 0.85 , **kw): if ax == None: fig, ax = plt.subplots(1,1) x = np.zeros((0)) y = np.zeros((0)) ysig = np.zeros((0)) # rdts = np.zeros((0)) for i in range(20): timestamp, folder = toolbox.latest_data(contains = 'NuclearRFRabi_111_1_sil18Rabi_C5_el1_positive_'+str(i)+'run',return_timestamp = True) a = mbi.MBIAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='adwindata') a.get_electron_ROC() x = np.append(x,a.sweep_pts[:]) y = np.append(y,a.p0[:]) ysig = np.append(ysig,a.u_p0[:]) print dir(a) for i in range(len(x)-1): print x[i], x[i+1]-x[i] if center_guess == True: guess_ctr = float(raw_input('Center guess?')) else: guess_ctr = x[y.argmin()] print 'guess_ctr = '+str(guess_ctr) # # try fitting fit_result = fit.fit1d(x, y, esr.fit_ESR_gauss, guess_offset, guess_amplitude, guess_width, guess_ctr, do_print=False, ret=True, fixed=[]) # fit_result = fit.fit1d(x, y, common.fit_2gauss, guess_offset, # guess_amplitude, guess_ctr-30e-3,guess_width, guess_amplitude, guess_ctr+30e-3,guess_width, # do_print=False, ret=True, fixed=[]) fit_result['yerr'] = ysig plot.plot_fit1d(fit_result, np.linspace(min(x), max(x), 1000), ax=ax, plot_data=True, **kw) ax.set_xlabel('RF frq (kHz)') ax.set_ylabel(r'fidelity wrt. $|0\rangle$') ax.set_title(a.timestamp+'\n'+a.measurementstring) plt.savefig(os.path.join(folder, 'nmr_analysis.png'), format='png') if ret == 'f0': f0 = fit_result['params_dict']['x0'] u_f0 = fit_result['error_dict']['x0'] ax.text(f0, 0.8, '$f_0$ = ({:.3f} +/- {:.3f})'.format( (f0-2.8)*1e3, u_f0*1e3), ha='center') return (f0-2.8)*1e3, u_f0*1e3
def Carbon_control_sweep_N_zoom(timestamp=None, measurement_name = ['adwindata'], A = [0.5, 0.5], fitfunc_type = 'single', plot_fit = False, do_print = False, show_guess = True, yaxis = [-0.05,1.05]): ''' Function to analyze data for optimization of the number of pulses for a controlled C13 gate. ''' if timestamp != None: folder = toolbox.data_from_time(timestamp) else: folder = toolbox.latest_data('Decoupling') fit_results = [] for k in range(0,len(measurement_name)): a = mbi.MBIAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='adwindata') a.get_electron_ROC() ax = a.plot_results_vs_sweepparam(ret='ax') ax.set_ylim(yaxis) ax.axhspan(0,0.5,fill=False,ls='dotted') x = a.sweep_pts.reshape(-1)[:] y = a.p0.reshape(-1)[:] y_u = a.u_p0.reshape(-1)[:] ax.set_xlim(x[0]-1,x[-1]+1) p0, fitfunc, fitfunc_str = common.fit_poly(A) if show_guess: ax.plot(np.linspace(x[0],x[-1],201), fitfunc(np.linspace(x[0],x[-1],201)), ':', lw=2) fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc, do_print=True, ret=True,fixed=[3]) if plot_fit == True: plot.plot_fit1d(fit_result, np.linspace(x[0],x[-1],201), ax=ax, plot_data=False,print_info = True) fit_results.append(fit_result) print folder plt.savefig(os.path.join(folder, 'analyzed_result.pdf'), format='pdf') plt.savefig(os.path.join(folder, 'analyzed_result.png'), format='png') diff = np.abs(y - 0.5) print diff print 'Optimum number of pulses N = ' + str(x[np.argmin(diff)]) print 'with y-0.5 = ' + str(y[np.argmin(diff)]-0.5) + ' +/- ' + str(y_u[np.argmin(diff)]) # freq = fit_results[0]['params_dict']['f1'] # period = 1/freq # print 'Period is %s pulses ' %(period) # # N_pi = round(period*.5/2)*2.0 # N_pi2 = round(period/2*.25)*2.0 # # print 'Pi pulse: %s pulses' %N_pi # print 'Pi2 pulse: %s pulses' %N_pi2 return fit_results
def analyse_Ramsey(folder='', T2=3e3, Ampl=-1. / 3, detuning=3e-3, hf_N=2.17e-3, *arg): timestamp = kw.pop(timestamp, None) guess_tau = T2 guess_a = 0.5 guess_A = Ampl guess_hf_N = hf_N guess_det = detuning guess_hf_C = hf_C if timestamp != None: folder = toolbox.data_from_time(timestamp) elif folder != '': folder = toolbox.latest_data('Ramsey') a = sequence.SequenceAnalysis(folder) a.get_sweep_pts() a.get_readout_results(name='ssro') a.get_electron_ROC() x = a.sweep_pts y = a.p0 ax = a.plot_result_vs_sweepparam(ret='ax', name='ssro') params_0, fitfunc_0, fitfunc_str_0 = ramsey.fit_ramsey_14N_fixed_13C_opt( guess_tau, guess_A, guess_a, guess_det, guess_hf_N) x_0 = np.linspace(0, a.sweep_pts[-1], 1000) ax.plot(x_0, fitfunc_0(x_0), 'r--', lw=1) #fit_xvals=np.linspace(res['x'][0],res['x'][-1],fit_num_points) fit_result = fit.fit1d(x, y, ramsey.fit_ramsey_14N_fixed_13C_opt, guess_tau, guess_A, guess_a, guess_det, guess_hf_N, fixed=[], do_print=True, ret=True) #fit_result = False if fit_result != False: plot.plot_fit1d(fit_result, np.linspace(0, a.sweep_pts[-1], 201), ax=ax, plot_data=False) plt.savefig(os.path.join(folder, 'electronramsey_analysis.pdf'), format='pdf')
def plot_single_rabi_curve(folder, ax, color, label, tot, utot, tot_mean): a = sequence.MagnetometrySequenceAnalysis(folder) RO, uRO = a.get_magnetometry_phase_calibration( name='adwindata', ssro_calib_folder= r'M:\tnw\ns\qt\Diamond\Projects\Magnetometry with adaptive measurements\Data\raw_data\20141127\162130_AdwinSSRO_SSROCalibration_Gretel_sil10' ) guess_f1 = 20e-3 #in GHz guess_A1 = 0.5 guess_phi1 = np.pi guess_tau = 96 guess_a = 0.5 a.sweep_pts = a.sweep_pts print a.sweep_pts #ax.set_ylim([0.0,1.05]) amp = (max(a.p0) - min(a.p0)) / 2. offset = (max(a.p0) + min(a.p0)) / 2. freq = 1 / 8000. decay = 10000. fit_result = fit.fit1d(a.sweep_pts, a.p0, rabi.fit_rabi_damped_exp, freq, amp, offset, decay, fixed=[], do_print=False, ret=True) A = fit_result['params_dict']['A'] * 2 F = fit_result['params_dict']['f'] eF = fit_result['error_dict']['f'] #print fit_result print min(a.p0), A print 'frq', F * 1e6, '+-', eF, 'kHz' x_fit = np.linspace(a.sweep_pts[0], a.sweep_pts[-1], 501) y_fit = fit_result['fitfunc'](x_fit) ax.plot(x_fit * 1e-3, y_fit, '-', color='Grey', linewidth=2) ax.errorbar(a.sweep_pts * 1e-3, a.p0, yerr=a.u_p0, color=color, fmt='o', label=label) if len(tot) == 0: tot = (a.p0 - mean(a.p0)) utot = a.u_p0 tot_mean = mean(a.p0) else: tot = tot + (a.p0 - mean(a.p0)) utot = utot + a.u_p0 tot_mean = tot_mean + mean(a.p0) print max(a.u_p0) return tot, a.sweep_pts, utot, tot_mean, A
def plot_single_ramsey_curve(folder,ax,color,label,fit_carbon): a=np.loadtxt(folder) guess_A = 0.5 guess_phi1 = 0*np.pi/2. guess_phi2 = 0*np.pi/2. guess_phi3 = 0*np.pi/2. guess_hf=2.18 guess_tau = 3 guess_a = 0.5 guess_det = 5 guess_C1 = .2 sweep_pts=a[:,0]*1e-3 p0=a[:,2] u_p0=a[:,3] #ax.set_ylim([0.0,1.05]) if fit_carbon ==False: fit_result = fit.fit1d(sweep_pts, p0, ramsey.fit_ramsey_hyperfinelines_fixed, guess_tau, guess_A,guess_a, guess_det,guess_hf,guess_phi1,guess_phi2,guess_phi3, #(guess_f3, guess_A3, guess_phi3), fixed=[], do_print=True, ret=True) else: guess_A=0.5/6. p=np.pi guess_phi3=p guess_phi2=p guess_phi1=p fit_result = fit.fit1d(sweep_pts, p0, ramsey.fit_ramsey_14N_fixed_13C_opt, guess_tau, guess_A,guess_a, guess_det,guess_hf,guess_phi1,guess_phi2,guess_phi3,guess_C1, #(guess_f3, guess_A3, guess_phi3), fixed=[], do_print=True, ret=True) #ax.errorbar(sweep_pts,p0,yerr=u_p0,mec=color,fmt='o',label=label,markeredgewidth=1,mfc='None') ax.plot(sweep_pts,p0,'.',mec=color,label=label,markeredgewidth=1,mfc='None') x_fit=np.linspace(sweep_pts[0],sweep_pts[-1],501) y_fit=fit_result['fitfunc'](x_fit) ax.plot(x_fit,y_fit,'-',color='Grey',linewidth=0.75) ax.set_xlim([0,4]) ax.set_ylim([0,1]) ax.set_yticks([0,0.5,1]) ax.legend()
def fit_double_exponential(self, name='', save=True, log_plot=True, offset=0, **kw): ret = kw.get('ret', None) ax = kw.get('ax', None) indices = kw.pop('indices',range(self.sweep_length)) if ax == None: fig = self.default_fig(figsize=(6,4)) ax = self.default_ax(fig) else: save = False xx=self.tail_hist_b[:-1] for i in indices: yy=self.tail_hist_h[i]+offset*i if log_plot: ax.semilogy(xx,yy,'-') else: ax.plot(xx,yy) guess_xo = 50. guess_tau = 50. guess_tau2 = 300. guess_o = 50. guess_A = 500. guess_AA = 500. AA=fit.Parameter(guess_A, 'A') A=fit.Parameter(guess_AA, 'AA') o=fit.Parameter(guess_o, 'o') xo = fit.Parameter(guess_xo, 'xo') tau = fit.Parameter(guess_tau, 'tau') tau2 = fit.Parameter(guess_tau2, 'tau2') p0 = [A, AA, o, xo, tau, tau2] #print p0 def fitfunc(x): #return o() + A() *np.exp(-(x-xo())/tau()) return o() + A() * np.exp(-((x-xo())/tau())) + AA()*np.exp(-((x-xo())/tau2())) fit_result = fit.fit1d(xx, yy, None, p0=p0, fitfunc=fitfunc, fixed=[], do_print=True, ret=True) x_fit=np.linspace(xx[0],xx[-1],500) y_fit=fit_result['fitfunc'](x_fit) ax.plot(x_fit,y_fit,color='k') ax.set_xlabel('Time after sync [ns]') ax.set_ylabel('Counts') if save: self.save_fig_incremental_filename(fig,'plot_tail_hist_all') if ret == 'ax': return ax if ret == 'fig': return fig
def calibrate_pi2_noMBI(folder): a = sequence.SequenceAnalysis(folder) a.get_sweep_pts() a.get_readout_results('ssro') a.get_electron_ROC() x = a.sweep_pts y = a.p0 u_y = a.u_p0 n = a.sweep_name a.finish() x2 = x[::2] print x2 y2 = y[1::2] - y[::2] u_y2 = np.sqrt(u_y[1::2]**2 + u_y[::2]**2) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), sharex=True) ax1.errorbar(x2, y2, yerr=u_y2, fmt='o') ax1.set_xlabel(n) ax1.set_title('Difference btw. Pi/2-Pi and Pi/2') ax1.set_ylabel('Difference') m = fit.Parameter((y[-1] - y[0]) / (x[-1] - x[0]), 'm') x0 = fit.Parameter(y2.mean(), 'x0') p0 = [m, x0] def ff(x): return m() * (x - x0()) fitfunc_str = 'm * (x - x0)' fit_result = fit.fit1d(x2, y2, None, p0=p0, fitfunc=ff, fitfunc_str=fitfunc_str, do_print=True, ret=True) ax2.errorbar(x2, y[0::2], yerr=u_y[0::2], fmt='o', label='Pi/2') ax2.errorbar(x2, y[1::2], yerr=u_y[1::2], fmt='o', label='Pi/2 - Pi') ax2.legend(frameon=True, framealpha=0.5) ax2.set_ylabel('P(0)') ax2.set_xlabel(n) ax2.axvline(x0(), c='k', lw=2) ax2.axhline(0.5, c='k', lw=2) ax2.set_title('X marks the spot') plot.plot_fit1d(fit_result, np.linspace(x2[0], x2[-1], 201), ax=ax1, plot_data=False, print_info=True) fig.savefig(os.path.join(folder, 'pi2_calibration.png'))
def fit_exp(d,yname,xname='RO_times'): offset_guess=d[yname].max() amp_guess=offset_guess decay_guess=10 feedback_fit_result = fit.fit1d(d[xname], d[yname], common.fit_exp_decay_with_offset, offset_guess, amp_guess,decay_guess, do_print = False , ret = True) x=np.linspace(d[xname].min(),d[xname].max(),501) y=feedback_fit_result['fitfunc'](x) return x,y
def meas_BW(min_pos, max_pos, steps, name = 'beamwaist'): #generate list of steps x_list = numpy.linspace(min_pos, max_pos, steps) ins_xps = qt.instruments['xps'] ins_fm = qt.instruments['fm'] # create data object qt.mstart() qt.msleep(0.2) d = qt.Data(name='BeamWaist') d.add_coordinate('displacement (mm)') d.add_value('power') d.create_file() filename=d.get_filepath()[:-4] plot2d = qt.Plot2D(d, name=name) stop_scan = False result = numpy.zeros(steps) for i,cur_x in enumerate(x_list): if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): stop_scan=True ins_xps.set_abs_positionZ(float(-1*cur_x)) qt.msleep(0.05) result[i] = ins_fm.get_power() d.add_data_point(cur_x, result[i]) if stop_scan: break ins_xps.set_abs_positionZ(-1*min_pos) i_max = result.tolist().index(max(result)) i_min = result.tolist().index(min(result)) print 'result imax is: %s' % result[i_max] knife_fit = fit.fit1d(x_list, result,fit_knife_simple, result[i_max], 0, 2, result[i_min], do_print=False,ret=True) if type(knife_fit) != dict: print 'fit failed!' else: print 'best fit params are: A: %.03f x0: %.03f w: %.03f b: %.03f' % ( knife_fit['params'][0], knife_fit['params'][1], knife_fit['params'][2], knife_fit['params'][3]) plot2d.set_plottitle('Beam Waist: %.03f +- %.03f' % (knife_fit['params'][2], knife_fit['error'][2])) d.close_file() plot2d.save_png(filename+'.png') qt.mend()
def analyse_Rabi(guess_frq = 2., guess_amp = 0.2, guess_of = 0.1, **kw) : timestamp = kw.pop('timestamp', None) guess_phi = kw.pop('guess_phi', 0.) guess_k = kw.pop('guess_k', 0.) mbi_analysis = kw.pop('mbi_analysis', False) do_print = kw.pop('do_print', False) o = fit.Parameter(guess_of, 'o') f = fit.Parameter(guess_frq, 'f') A = fit.Parameter(guess_amp, 'A') phi = fit.Parameter(guess_phi, 'phi') k = fit.Parameter(guess_k, 'k') p0 = [f, A, phi, o, k] fitfunc_str = '' if timestamp != None: folder = toolbox.data_from_time(timestamp) else : folder = toolbox.latest_data('ElectronRabi') if mbi_analysis: a = mbi.MBIAnalysis(folder) a.get_sweep_pts() a.get_readout_results('adwindata') a.get_electron_ROC() ax = a.plot_results_vs_sweepparam(ret='ax', name = 'adwindata') else: a = sequence.SequenceAnalysis(folder) a.get_sweep_pts() a.get_readout_results('ssro') a.get_electron_ROC() ax = a.plot_result_vs_sweepparam(ret='ax') x = a.sweep_pts y = a.p0 fitfunc_str = 'o - A + A*e^(-kx)*cos(2pi (fx-phi))' def fitfunc(x): return (o()-A()) + A() * np.exp(-k()*x) * np.cos(2*np.pi*(f()*x - phi())) fit_result = fit.fit1d(x,y, None, p0=p0, fitfunc=fitfunc, fixed=[2], do_print=do_print, ret=True) plot.plot_fit1d(fit_result, np.linspace(0,x[-1],201), ax=ax, plot_data=False) print "\npi pulse at {:.3f} for .\n".format(1/f()/2.) + a.sweep_name # ax.set_title(a.timestamp+'\n'+a.measurementstring) plt.savefig(os.path.join(folder, 'electronrabi_analysis_fit.png')) return fit_result
def electron_T1_analysis(older_than='20161110_180000', newer_than='20161110_141200', mode='init0', Amplitude=2, offset=1, T1=1e9, do_print=True): Folder_list = toolbox.latest_data( contains='ElectronT1_111_1_sil18m0to0switch_on', older_than=older_than, newer_than=newer_than, return_all=True) x_tot = [] y_tot = [] y_var_tot = [] for i in range(len(Folder_list)): print Folder_list[len(Folder_list) - i - 1] Folder = Folder_list[len(Folder_list) - i - 1] x, y, y_var = get_T1_data(Folder) #print y x_tot.extend(list(x)) y_tot.extend(list(y)) y_var_tot.extend(list(y_var)) print x_tot print y_tot print y_var_tot p0, fitfunc, fitfunc_str = common.fit_exp_decay_with_offset( offset, Amplitude, T1) # fit_result = fit.fit1d(x_tot,y_tot, None, p0=p0, fitfunc=fitfunc, do_print=do_print, ret=True) # #plt.plot(x_tot,y_tot) # plot.plot_fit1d(fit_result, np.linspace(0,x_tot[-1],201), ax= None, plot_data=False) fig = plt.figure() ax = fig.add_subplot(111) ax.errorbar(x_tot, y_tot, fmt='o', yerr=y_var_tot) ax.set_ylim([0.0, 1.1]) fit_result = fit.fit1d(x_tot, y_tot, None, p0=p0, fitfunc=fitfunc, do_print=do_print, ret=True) plot.plot_fit1d(fit_result, np.linspace(0, x[-1], 201), ax=ax, plot_data=False) plt.savefig(os.path.join(Folder, 'analyzed_result.pdf'), format='pdf') plt.savefig(os.path.join(Folder, 'analyzed_result.png'), format='png')
def fitDiodeData(x,y): o = fit.Parameter(0,'offset') a = fit.Parameter(-0.2, 'amplitude') tau = fit.Parameter(7, 'tau') fitfunc_str = 'y(x) = o + a*exp(x/tau)' def fitfunc(x): return o() + a() * numpy.exp((x) / (tau())) fit_result = fit.fit1d(x,y, None, p0=[o,tau,a], fixed=[], fitfunc=fitfunc, fitfunc_str=fitfunc_str, do_print=True, ret=True) return fit_result
def optimize_matrix_amplitude(name, Z_matrix, do_fit=True): amplitude = 2.0 #V steps = 21 #XXXXXXXXXXXX 13 amps = np.linspace(-amplitude, amplitude, steps) Z_voltages = dm.voltages_from_matrix(Z_matrix) cur_voltages = dm.get_cur_voltages() logging.debug('DM: Starting optimisation scan') y_NV = np.zeros(steps) for i, amp in enumerate(amps): new_voltages = cur_voltages + amp * Z_voltages dm.set_cur_voltages(new_voltages) if i == 0: time.sleep(2. * int_time / 1000.) y_NV[i] = measure_counts() #qt.msleep(0.2) logging.debug('DM: Starting fit') opt_amp = None if do_fit: f = common.fit_gauss #a + A * exp(-(x-x0)**2/(2*sigma**2)) #['g_a', 'g_A', 'g_x0', 'g_sigma'] args = [100, max(y_NV), 0, 1] fitres = fit.fit1d(amps, y_NV, f, *args, fixed=[], do_print=False, ret=True) if fitres['success']: if fitres['params_dict']['A'] > 0.: opt_amp = fitres['params_dict']['x0'] max_cnts = fitres['params_dict']['A'] + fitres['params_dict'][ 'a'] fp = plot_scan(name, amps, y_NV, fitres['fitfunc']) if opt_amp == None: print 'fit failed, going to max point' opt_amp = amps[np.argmax(y_NV)] max_cnts = np.max(y_NV) fp = plot_scan(name, amps, y_NV) logging.debug('DM: Fitting scan finished') new_voltages = cur_voltages + opt_amp * Z_voltages dm.set_cur_voltages(new_voltages) dm.plot_mirror_surf(True, fp[:-3]) dm.save_mirror_surf(fp[:-4] + '_msurf') counters.set_is_running(True) return max_cnts, opt_amp
def fit_parabolic(folder=None, ax=None, x0_guess=0., of_guess=0.5, a_guess=1., **kw): """ fit (1-of) + a (x-x0)**2 from Sequence in folder """ do_print = kw.pop('do_print', False) fixed = kw.pop('fixed', []) a0, ax, x, y = plot_result(folder, ax, **kw) x0 = fit.Parameter(x0_guess, 'x0') of = fit.Parameter(of_guess, 'of') a = fit.Parameter(a_guess, 'a') x_min = kw.pop("x_min", None) x_max = kw.pop("x_max", None) fit_x = x fit_y = y if x_min is not None: mask = fit_x > x_min fit_x = fit_x[mask] fit_y = fit_y[mask] if x_max is not None: mask = fit_x < x_max fit_x = fit_x[mask] fit_y = fit_y[mask] fitfunc_str = '(1-of) + a (x-x0)**2' def fitfunc_parabolic(x): return (1. - of()) + a() * (x - x0())**2 fit_result = fit.fit1d(fit_x, fit_y, None, p0=[of, a, x0], fitfunc=fitfunc_parabolic, fitfunc_str=fitfunc_str, do_print=do_print, ret=True) fit_result['u_y'] = a0.u_p0 plot.plot_fit1d(fit_result, np.linspace(np.min(fit_x), np.max(fit_x), 201), ax=ax, plot_data=False, **kw) return fit_result