def fit_mn_hght_bg(xvals,zorig,invorig,sigj,mn_new,spread,powj=2): """ Fits mean, height, and background for a gaussian of known sigma. Height and background are fit linearly. Mean is fit through a grid search algorithm (may be better to change to a nonlinear fitter?) """ # ts = time.time() mn_old = -100 lp_ct = 0 while abs(mn_new-mn_old)>0.001: mn_old = np.copy(mn_new) # t1 = time.time() hght, bg = sf.best_linear_gauss(xvals,sigj,mn_old,zorig,invorig,power=powj) # t2 = time.time() mn_new, mn_new_std = sf.best_mean(xvals,sigj,mn_old,hght,bg,zorig,invorig,spread,power=powj) # t3 = time.time() # print("Linear time = {}s".format(t2-t1)) # print("Nonlinear time = {}s".format(t3-t2)) # time.sleep(5) lp_ct+=1 if lp_ct>1e3: break # print "Loop count is ", lp_ct # print("Len xvals = {}".format(len(xvals))) # te = time.time() # print("Total fit time is {}s".format(te-ts)) # time.sleep(5) return mn_new, hght,bg
def linear_mn_hght_bg(xvals,yvals,invals,sigma,mn_est,power=2): """ Find mean of gaussian with linearized procedure. Use eqn dx = dh/h * sigma/2 * exp(1/2) where dh = max - min residual Once mean is found, determines best fit hght and bg """ gauss_model = sf.gaussian(xvals,sigma,center=mn_est,height=np.max(yvals),power=power) mn_est_err = 100 mn_est_err_old = 0 loop_ct = 0 while abs(mn_est_err-mn_est_err_old)>0.01 and loop_ct < 1: mn_est_err_old = np.copy(mn_est_err) mn_est_old = np.copy(mn_est) residuals = yvals-gauss_model dh = (np.max(residuals)-np.min(residuals))/np.max(yvals) sign = 1 if np.argmax(residuals) < np.argmin(residuals): sign = -1 dx = sign*sigma*dh*np.exp(1/2)/2 mn_est += dx hght, bg = sf.best_linear_gauss(xvals,sigma,mn_est,yvals,invals,power=power) gauss_model = sf.gaussian(xvals,sigma,center=mn_est,height=hght,bg_mean=bg,power=power) mn_est_err = abs(mn_est_old - mn_est) loop_ct += 1 # hght, bg = sf.best_linear_gauss(xvals,sigma,mn_est,yvals,invals,power=power) return mn_est, hght, bg