def fit(self): self.logger.info('Method %s' % self.config['method']) self.logger.info('Parameter names %s' % self.config['params']) gmod = Model(self.callable, independent_vars=self.config['independent'].keys(), param_names=self.config['params'], method=self.config['method']) self._set_params(self.config['params'], self.config['initial_values'], self.config['limits'], gmod) self.config['independent']['x'] = self.param_dict['wave_range'] helper_param = {key:val for key, val in self.config['independent'].items() if key != 'x'} self.logger.debug("Setting %s parameters fix" % helper_param) self.result = gmod.fit(self.param_dict['spectra_range'], weights=self.param_dict['weights'], **self.config['independent']) self.param_dict['variables'] = dict() for key in self.result.params.keys(): self.param_dict['variables'][key] = dict() self.param_dict['variables'][key]['stderr'] = self.result.params[key].stderr self.param_dict['variables'][key]['value'] = self.result.params[key].value return self.result, self.param_dict
def lmDDOPhaseFit(xdata, ydata, params, f0_range = 1.2, Q_range = 3): f0= params[0] Q=1/(2*params[2]) x = xdata y = ydata #Define a linear model and a Damped Oscillator Model # ddophase_mod = ExpressionModel('off + m*x- arctan(1/Q * 1/(f0/x - x/f0))-') ddophase_mod = Model(phase) #Initial Pars for Linear Model pars = ddophase_mod.make_params(off=0, m=0, f0=f0, Q=Q) #Add fit parameters, Center, Amplitude, and Sigma pars['f0'].set(min=f0/f0_range, max=f0*f0_range) pars['Q'].set(min=Q/Q_range, max=Q*Q_range) #Create full model. Add linear model and all peaks #Initialize fit init = ddophase_mod.eval(pars, x=x) #Do the fit. The weight exponential can weight the points porportional to the #amplitude of y point. In this way, points on peak can be given more weight. out=ddophase_mod.fit(y, pars,x=x) #Get the fit parameters fittedf0= out.params['f0'].value fittedQ = out.params['Q'].value #Returns the output fit as well as an array of the fit parameters """Returns output fit as will as list of important fitting parameters""" return out, [fittedf0, np.nan, np.nan, fittedQ]
def rescale_reframe(scisub, refsub, verbose=False): """Example function with types documented in the docstring. `PEP 484`_ type annotations are supported. If attribute, parameter, and return types are annotated according to `PEP 484`_, they do not need to be included in the docstring: Args: param1 (int): The first parameter. param2 (str): The second parameter. Returns: bool: The return value. True for success, False otherwise. .. _PEP 484: https://www.python.org/dev/peps/pep-0484/ """ params = Parameters() params.add('sigma', 1.0, True, 0.0, inf) image_sub = Model(res_sigma_image_flat, independent_vars=['scisub', 'refsub']) image_sub_results = image_sub.fit(data=scisub.ravel(), params=params, scisub=scisub, refsub=refsub) if verbose: print('Sigma of Rescale: {}'.format(image_sub_results.params['sigma'].value)) return partial_res_sigma_image(image_sub_results.params['sigma'].value)
def make_models(model,peaks): """ Make composite models for multiple peaks Arguments: -- models -- peaks: dict of {prefix:"peak_name_", model_params:()} """ if len(peaks)<2: mod = Model(model,prefix=peaks[0][0]) p_guess = mod.make_params() values = peaks[0][1:] update_params(p_guess,values) elif len(peaks)>1: mod = Model(model,prefix=peaks[0][0]) values = peaks[0][1:] print(values) for i in peaks[1:]: mod += Model(model,prefix=i[0]) values.extend(i[1:]) p_guess = mod.make_params() update_params(p_guess,values) return mod, p_guess
def gauss_step_const(signal, guess): """ Fits high contrast data very well """ if guess == False: return [0, 0] else: amp, centre, stdev, offset = guess data = np.array([range(len(signal)), signal]).T X = data[:,0] Y = data[:,1] # gauss_mod = Model(gaussian) gauss_mod = Model(gaussian) const_mod = ConstantModel() step_mod = StepModel(prefix='step') pars = gauss_mod.make_params(height=amp, center=centre, width=stdev / 3., offset=offset) # pars = gauss_mod.make_params(amplitude=amp, center=centre, sigma=stdev / 3.) gauss_mod.set_param_hint('sigma', value = stdev / 3., min=stdev / 2., max=stdev) pars += step_mod.guess(Y, x=X, center=centre) pars += const_mod.guess(Y, x=X) mod = const_mod + gauss_mod + step_mod result = mod.fit(Y, pars, x=X) # write error report #print result.fit_report() print "contrast fit", result.redchi return X, result.best_fit, result.redchi
def get_resvar(x, y, mod='linear', zero_intercept=False): """ If `mod == 'linear'` then uses linear regression; otherwise `mod == 'sigmoid'` and uses sigmoid regression. """ assert len(x) == len(y) if len(x) < 3 or mod == 'linear': model = Model(linear) params = model.make_params() params['a'].value = (y.max() - y.min()) / (x.max() - x.min()) params['b'].value = y.min() if zero_intercept: params['b'].value = 0 params['b'].vary = False modfit = model.fit(y, x=x, params=params) else: model = Model(sigmoid) modfit = model.fit(y, x=x, a=y.max(), b=1 / (x.max() - x.min()), c=x.max()) finex = np.linspace(x.min(), x.max(), 50) result = { 'mod': mod, 'params': modfit.best_values, 'resvar': modfit.residual.var(), 'y': modfit.best_fit, 'finex': finex, 'finey': modfit.eval(x=finex), 'r2': 1 - modfit.residual.var() / np.var(y), 'modfit': modfit} return result
def fit_data_bg(x, y, peak_pos, peak_type='LO', width=None, bg_ord=0): """ Builds a lmfit model of peaks in listed by index in `peak_pos` Parameters ---------- peak_type : string (default='lorentizian') Peaks can be of the following types: - 'LO' : symmetric lorentzian - 'GA' : symmetric gaussain - 'VO' : symmetric pseudo voigt max_width : int (default = total points/10) max width (in data points) that peak fitted can be bg_ord: int order of the background polynomial 0: constant, 1: linear, ... Returns ------- out: fitted model """ # need to define peak width finding if width is None: width = guess_peak_width(x, y) # start with polynomial background model = PolynomialModel(bg_ord, prefix='bg_') pars = model.make_params() if peak_type == 'LO': peak_function = lorentzian elif peak_type == 'GA': peak_function = gaussian elif peak_type == 'VO': peak_function = voigt # add peak type for all peaks for i, peak in enumerate(peak_pos): temp_model = Model(peak_function, prefix='p%s_' % i) pars.update(temp_model.make_params()) model += temp_model # set initial background as flat line at zeros for i in range(bg_ord + 1): pars['bg_c%i' % i].set(0) # give values for other peaks, keeping width and height positive for i, peak in enumerate(peak_pos): pars['p%s_x0' % i].set(x[peak]) pars['p%s_fwhm' % i].set(width, min=0) pars['p%s_amp' % i].set(y[peak], min=0) out = model.fit(y, pars, x=x) return out
def multi_disk_fit(arcmin_sma, intens, intens_err, bounds, psf): h_mat_0 = numpy.ones(len(bounds - 1)) mod = Model(multi_disk_func) pars = mod.make_params(I0 = 1.0, h_mat = h_mat_0, bounds = bounds, PSF = PSF) pars['bounds'].vary = False pars['PSF'].vary = False results = mod.fit(intens, params = pars, x = arcmin_sma, weights = 1.0/intens_err) pdb.set_trace()
def fit_D_phi_powerlaw(phi_, D): """fit stuff""" Dmod = Model(Dhop_powerlaw) params = Dmod.make_params() params['p'].set(0.3) result = Dmod.fit(D, params, phi=phi_) print result.fit_report(min_correl=0.5) p = result.params['p'].value return p
def fit(self): self.logger.info('Method %s' % self.config['method']) gmod = Model(self.callable, independent_vars=['x'], param_names=self.config['params'], method=self.config['method']) self._set_params(self.config['params'], self.config['initial_values'], self.config['limits'], gmod) self.result = gmod.fit(self.param_dict['spectra_range'], x=self.param_dict['wave_range']) for key in self.result.params.keys(): self.param_dict[key] = dict() self.param_dict[key]['stderr'] = self.result.params[key].stderr self.param_dict[key]['value'] = self.result.params[key].value return self.result, self.param_dict
def lmfit(mjd,flux,fluxerr): t0_guess = mjd[np.argmax(flux)] tau_fall_guess = 40. tau_rise_guess = -5. A = 150. B = 20. # nflux = np.zeros(2+len(np.array(flux))) # nfluxerr = np.ones(2+len(np.array(flux)))/10. # nmjd = np.zeros(2+len(np.array(flux))) # # nflux[1:-1] = flux # nfluxerr[1:-1] = fluxerr # nmjd[1:-1] = mjd # nmjd[1] = mjd[0]-100. # nmjd[-1] = mjd[-1]+150 # # flux = nflux # fluxerr = nfluxerr # mjd = nmjd bmod = Model(bazinfunc) bmod.set_param_hint('t0', value=t0_guess, min=t0_guess-20, max=t0_guess+20) bmod.set_param_hint('tau_fall', value=tau_fall_guess) bmod.set_param_hint('tau_rise', value=tau_rise_guess) bmod.set_param_hint('A',value=A) bmod.set_param_hint('B',value=B) pars = bmod.make_params() #print(bmod.param_names) #print(bmod.independent_vars) # print(np.array(flux)) # print(np.array(1./np.array(fluxerr))) # print(np.array(mjd)) result = bmod.fit(np.array(flux),method='leastsq',weights=1./np.array(fluxerr), t=np.array(mjd)) #print(result.fit_report()) # plt.clf() # plt.errorbar(np.array(mjd), np.array(flux), yerr=fluxerr,fmt='o') # plt.plot(np.array(mjd), result.init_fit, 'k--') # plt.plot(np.array(mjd), result.best_fit, 'r-') # #plt.xlim(mjd[1],mjd[-2]) # plt.savefig('bazinfit.png') chisq = result.redchi ps = result.best_values popt = [ps['t0'],ps['tau_fall'],ps['tau_rise'],ps['A'],ps['B']] #print('popt',popt) #sys.exit() # if chisq < 2.: # input('good chisq!') # popt, pcov, infodict, errmsg, ier = curve_fit(bazinfunc, mjd, flux, # sigma=fluxerr, p0=p0, maxfev=2000000, full_output=True) # # chisq = (infodict['fvec'] ** 2).sum() / (len(infodict['fvec']) - len(popt)) return chisq,popt
def Gaussian_Fit(xData,yData, cen, ifPlot=False): gmod = Model(gaussian) result = gmod.fit(yData, x=xData, amp=5, cen=cen, wid=1) if ifPlot == True : plt.plot(xData, yData, 'bo') plt.plot(xData, result.best_fit, 'r-') plt.ylim(min(min(result.best_fit),min(xData)),max(max(result.best_fit),max(yData))) plt.show() return result.best_values, result.best_fit
def test_extra_param_issues_warning(self): # The function accepts extra params, Model will warn but not raise. def flexible_func(x, amplitude, center, sigma, **kwargs): return gaussian(x, amplitude, center, sigma) flexible_model = Model(flexible_func) pars = flexible_model.make_params(**self.guess()) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") flexible_model.fit(self.data, pars, x=self.x, extra=5) self.assertTrue(len(w) == 1) self.assertTrue(issubclass(w[-1].category, UserWarning))
def linefit(fitam, fitcps, fitweights): try: model = Model(linefunc) params = Parameters() params.add('linem', value=5) params.add('linek', value=0.25, min=0, max=1) fit = model.fit(asarray(fitcps), params, fitweights, linex=asarray(fitam)) fitvalues = fit.best_values fiterr = fit.covar except RuntimeError: return float('nan'), float('nan') return [[fitvalues['linem'], fitvalues['linek']], fiterr]
def fit_D_phi(phi_, D, c1, c2): """fit stuff""" Dmod = Model(Dhop) params = Dmod.make_params() params['c1'].set(c1, vary=False) params['c2'].set(c2, vary=False) params['c3'].set(1, vary=False) params['beta'].set(0.70, min=0) result = Dmod.fit(D, params, phi=phi_) print result.fit_report(min_correl=0.5) beta = result.params['beta'].value c3 = result.params['c3'].value return c3, beta
def fit_D_phi_alt(phi_, D, c1, c2, c1o, c2o): """fit stuff""" Dmod = Model(Dhopalt) params = Dmod.make_params() params['c1'].set(c1, vary=False) params['c2'].set(c2, vary=False) params['c1o'].set(c1o, vary=False) params['c2o'].set(c2o, vary=False) params['c3'].set(0.25) result = Dmod.fit(D, params, phi=phi_) print result.fit_report(min_correl=0.5) c3 = result.params['c3'].value return c3
def fit_Dinf_model(Input, diffusion, startindex, endindex): time_ = diffusion[startindex:endindex,0] D = diffusion[startindex:endindex,1] Dmod = Model(Dinf_model) params = Dmod.make_params() params['var1'].set(0.1) params['Dinf'].set(0.0001)#, min = 0, max=0.1) result = Dmod.fit(D, params, time=time_) print result.fit_report(min_correl=0.5) var1 = result.params['var1'].value Dinf = result.params['Dinf'].value Dinfstderr = result.params['Dinf'].stderr return var1, Dinf, Dinfstderr
def fit_data(x, y, peak_pos, peak_type='LO', width=None): """ Builds a lmfit model of peaks in listed by index in `peak_pos` with lineshape given by `peak_type`. Parameters ---------- x : array y : array peak_pos : array of peak postion indices peak_type : string Peaks can be of the following types: - 'LO' : symmetric lorentzian (default) - 'GA' : symmetric gaussain - 'VO' : symmetric pseudo voigt width : float amp : float Returns ------- out : Fitted lmfit model """ # get appropriate line shape function if peak_type == 'LO': peak_function = lorentzian elif peak_type == 'GA': peak_function = gaussian elif peak_type == 'VO': peak_function = voigt # build model model = Model(peak_function, prefix='p0_') for i, p in enumerate(peak_pos[1:]): model += Model(peak_function, prefix='p%s_' % str(i+1)) pars = model.make_params() # initialize params for i, p in enumerate(peak_pos): pars['p%s_x0' % i].set(x[p]) pars['p%s_fwhm' % i].set(width, min=0) pars['p%s_amp' % i].set(y[p], min=0) out = model.fit(y, pars, x=x) return out
def test_extra_param_issues_warning(self): # The function accepts extra params, Model will warn but not raise. guess = self.guess() guess['extra'] = 5 def flexible_func(x, height, center, sigma, **kwargs): return gaussian(x, height, center, sigma) flexible_model = Model(flexible_func, ['x']) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") flexible_model.fit(self.data, x=self.x, **guess) self.assertTrue(len(w) == 1) self.assertTrue(issubclass(w[-1].category, UserWarning))
def FitBiExpo_ResTime(xdata,ydata,pixdim,lambda_p,isplot=False): # flatten the input xx = xdata.flatten() yy = ydata.flatten() # normalize the input ymax = np.amax(yy) nydata = yy/ymax fmod = Model(Func_BiExpo) initialp = {'a0':[0.0,1.0,0.0],'b0':[0.0,0.0,0.0],'a1':[1.0,-5.0,-10.],'b1':[1.0,1.0,0.0]} chisqrThresh = 0.15 for ii in range(len(initialp['a0'])): result = fmod.fit(np.squeeze(nydata),x=np.squeeze(xdata),a0=initialp['a0'][ii],b0=initialp['b0'][ii],a1=initialp['a1'][ii],b1=initialp['b1'][ii]) param = result.params.valuesdict() auc = param['a0']/(param['b0'] + lambda_p) + param['a1']/(param['b1'] + lambda_p) if result.chisqr > chisqrThresh or auc < 0.0: print 'fit with tnc: chisqr = {}, auc = {}'.format(result.chisqr,auc) else: print 'leastsq: good fit!' break if result.chisqr > chisqrThresh or auc < 0.0: for ii in range(len(initialp['a0'])): result = fmod.fit(np.squeeze(nydata),x=np.squeeze(xdata),a0=initialp['a0'][ii],b0=initialp['b0'][ii],a1=initialp['a1'][ii],b1=initialp['b1'][ii],method='tnc') if result.chisqr > chisqrThresh or auc < 0.0: print 'fit with tnc: chisqr = {}, auc = {}'.format(result.chisqr,auc) else: print 'tnc: good fit!' break # set up best-fit result param = result.params.valuesdict() p1 = [param['a0'],param['b0'],param['a1'],param['b1']] fitydata = ymax*result.eval(x=xdata) # regularize the fitted result r2 = GetR2(ydata,fitydata) xfit = np.linspace(np.amin(xx),np.amax(xx),500)[:,np.newaxis] yfit = ymax*result.eval(x=xfit) if isplot: fig = plt.figure() ax = fig.add_subplot(111) ax.plot(xx,yy,'ro',label='Original data') ax.plot(xfit,yfit,label='Fitted data') plt.show() return p1,r2,ymax,xfit,yfit
def test_constraints_function_call(): """Test a constraint with simple function call in Model class.""" x = [1723, 1773, 1823, 1523, 1773, 1033.03078, 1042.98077, 1047.90937, 1053.95899, 1057.94906, 1063.13788, 1075.74218, 1086.03102] y = [0.79934, -0.31876, -0.46852, 0.05, -0.21, 11.1708, 10.31844, 9.73069, 9.21319, 9.12457, 9.05243, 8.66407, 8.29664] def VFT(T, ninf=-3, A=5e3, T0=800): return ninf + A/(T-T0) vftModel = Model(VFT) vftModel.set_param_hint('D', vary=False, expr=r'A*log(10)/T0') result = vftModel.fit(y, T=x) assert 2600.0 < result.params['A'].value < 2650.0 assert 7.0 < result.params['D'].value < 7.5
def _iterate(simulation, expected, guess, bounds, variables, independent, callable_, global_, local_): biased_parameters = np.zeros((len(local_['input']), len(expected))) success_ar = np.zeros(len(local_['input'])) expected_dict = {key: value for key, value in zip(variables, expected)} gmod = Model(callable_, independent_vars=independent.keys(), param_names=variables, method='lbfgsb') for param, ini, limits in zip(variables, guess, bounds): gmod.set_param_hint(param, value=ini, min=limits[0], max=limits[1]) independent[global_['param']] = global_['input'] for i, input_ in enumerate(local_['input']): independent[local_['param']] = input_ result = gmod.fit(simulation, verbose=False, **independent) print(result.fit_report()) success_ar[i] = result.success biased_parameters[i] = np.array([result.params[key].value - expected_dict[key] for key in variables]) return biased_parameters, success_ar
def prueba(): y2 = [49.0, 49.0, 101.0, 67.0, 65.0, 52.0, 49.0, 49.0, 54.0, 49.0, 48.0, 49.0] y = [i-50 for i in y2] x = linspace(0.0, 11.0, num=12) #variable ind para evento x2 = linspace(0.0, 11.0, num=400) #variable ind para fit gmod = Model(gaussian) #Generar un Modelo Gaussiano peak = max(y) result = gmod.fit(y, x=x, amp=peak, cen=5, wid=1) final = gmod.eval(x=x2, amp=result.best_values['amp'], cen=result.best_values['cen'], wid=result.best_values['wid']) plt.plot(x, y, 'bo') plt.plot(x, result.init_fit, 'k--') #plt.plot(x, result.best_fit, 'r-') plt.plot(x2, final, 'r-') plt.show()
def fitGauss(self, xdata=None, ydata=None, withBG=False, inits=None): ''' Usage: fitGauss(xdata,ydata,withBG=False,inits=None) xdata and ydata must have the same length, and a well defined peak withBG: fit gaussian with linear background inits: withBG == False -> [A,mu,sigma] withBG == True -> [A,mu,sigma,m,b] ''' def gauss(x, A, mu, sigma): return A*np.exp(-(x-mu)**2/(2.*sigma**2)) def gaussBG(x, A, mu, sigma, m, b): return b+m*x+A*np.exp(-(x-mu)**2/(2.*sigma**2)) if withBG: gBGmod = Model(gaussBG) else: gmod = Model(gauss) if inits is None: mu_i = xdata[np.argmax(ydata)] A_i = np.max(ydata) sigma_i = 0.5 if withBG: m_i = -0.1 b_i = ydata[np.argmax(ydata)-50] else: A_i = inits[0] mu_i = inits[1] sigma_i = inits[2] if withBG: m_i = inits[3] b_i = inits[4] if withBG: results = gBGmod.fit(ydata,x=xdata,A=A_i,mu=mu_i,sigma=sigma_i,b=b_i,m=m_i) else: results = gmod.fit(ydata,x=xdata,A=A_i,mu=mu_i,sigma=sigma_i) return results
def test_params_usersyms(self): # test passing usersymes to Parameters() def myfun(x): return x**3 params = Parameters(usersyms={"myfun": myfun}) params.add("a", value=2.3) params.add("b", expr="myfun(a)") xx = np.linspace(0, 1, 10) yy = 3 * xx + np.random.normal(scale=0.002, size=len(xx)) model = Model(lambda x, a: a * x) result = model.fit(yy, params=params, x=xx) assert_(np.isclose(result.params['a'].value, 3.0, rtol=0.025)) assert_(result.nfev > 3) assert_(result.nfev < 300)
def setUp(self): self.x = np.linspace(-10, 10, num=1000) np.random.seed(1) self.noise = 0.01*np.random.randn(*self.x.shape) self.true_values = lambda: dict(amplitude=7.1, center=1.1, sigma=2.40) self.guess = lambda: dict(amplitude=5, center=2, sigma=4) # return a fresh copy self.model = Model(gaussian, ['x']) self.data = gaussian(x=self.x, **self.true_values()) + self.noise
def gaussfit2d(box, boxsize): a = amax(box) bx, by = unravel_index(box.argmax(), box.shape) c = 2 d = amin(box) stdout.write('Box size: ' + str(box.shape) + ' boxsize: ' + str(boxsize) + '\n') stdout.write('Input [bx,by]: [{:6.1f}'.format(bx) + ', {:6.1f}'.format(by) + ']' + ' Width {:6.1f}'.format(c) + ' Amp {:6.1f}'.format(a) + ' Bkgnd {:6.1f}'.format(d) + '\n') gaussxn = [] gaussyn = [] for l in range(boxsize): for m in range(boxsize): gaussxn.append(l) gaussyn.append(m) gausspopped = 0 box = box.flatten() stdout.write('size of [gaussXn, gaussYn, box]: [{:6.1f}'.format(len(gaussxn)) + ', {:6.1f}'.format(len(gaussyn)) + ', {:6.1f}'.format(box.size) + ']\n') for l in range(len(box)): if box[l - gausspopped] > ccdNonLinear: box = delete(box, l - gausspopped) gaussxn.pop(l - gausspopped) gaussyn.pop(l - gausspopped) gausspopped += 1 gaussxn = asarray(gaussxn) gaussyn = asarray(gaussyn) try: model = Model(func=gaussfunc2d, independent_vars=["gaussx", "gaussy"], param_names=["a", "bx", "by", "c", "d"]) params = Parameters() params.add('a', value=a, min=0) params.add('bx', value=bx, min=0, max=49) params.add('by', value=by, min=0, max=49) params.add('c', value=c, min=0, max=50) params.add('d', value=d, min=d - 50, max=d + 50) fit = model.fit(box, gaussx=gaussxn, gaussy=gaussyn, params=params) fitvalues = fit.best_values except RuntimeError: fitreturn = float('nan') else: stdout.write('[x,y]: [{:6.1f}'.format(fitvalues['bx']) + ', {:6.1f}'.format(fitvalues['by']) + ']' + ' Width {:6.1f}'.format(fitvalues['c']) + ' Amp {:6.1f}'.format(fitvalues['a']) + ' Bkgnd {:6.1f}'.format(fitvalues['d']) + '\n') fitreturn = (fitvalues['bx'], fitvalues['by'], fitvalues['c'], fitvalues['a'], fitvalues['d']) return fitreturn
def test_wrapped_model_func(self): x = np.linspace(-1, 1, 51) y = 2.0 * x + 3 + 0.0003 * x * x y += np.random.normal(size=len(x), scale=0.025) mod = Model(linear_func) pars = mod.make_params(a=1.5, b=2.5) tmp = mod.eval(pars, x=x) self.assertTrue(tmp.max() > 3) self.assertTrue(tmp.min() > -20) result = mod.fit(y, pars, x=x) self.assertTrue(result.chisqr < 0.05) self.assertTrue(result.aic < -350) self.assertTrue(result.errorbars) self.assertTrue(abs(result.params['a'].value - 2.0) < 0.05) self.assertTrue(abs(result.params['b'].value - 3.0) < 0.41)
def test_Model_set_state(gmodel): """Test for Model class function _set_state. This function is just calling `_buildmodel`, which will be tested below together with the use of `funcdefs`. """ out = gmodel._get_state() new_model = Model(lmfit.lineshapes.lorentzian) new_model = new_model._set_state(out) assert new_model.prefix == gmodel.prefix assert new_model._param_root_names == gmodel._param_root_names assert new_model.param_names == gmodel.param_names assert new_model.independent_vars == gmodel.independent_vars assert new_model.nan_policy == gmodel.nan_policy assert new_model.name == gmodel.name assert new_model.opts == gmodel.opts
def one_var_fit(x, y): pmodel = Model(fit_form_1var_4order) index_emin = y.index(min(y)) emin = y[index_emin] amin = x[index_emin] yfit = [a - amin for a in y] Pa_i = polyfit(x, yfit, 4) result = pmodel.fit(y, x=x, k=emin, a0=amin, m1=Pa_i[2], gam1=Pa_i[3], del1=Pa_i[4]) return result
def test_constraints3(): """test a constraint with simple function call""" x = [1723, 1773, 1823, 1523, 1773, 1033.03078, 1042.98077, 1047.90937, 1053.95899, 1057.94906, 1063.13788, 1075.74218, 1086.03102] y = [0.79934, -0.31876, -0.46852, 0.05, -0.21, 11.1708, 10.31844, 9.73069, 9.21319, 9.12457, 9.05243, 8.66407, 8.29664] def VFT(T, ninf=-3, A=5e3, T0=800): return ninf + A/(T-T0) vftModel = Model(VFT) vftModel.set_param_hint('D', vary=False, expr=r'A*log(10)/T0') result = vftModel.fit(y, T=x) assert(result.params['A'].value > 2600.0) assert(result.params['A'].value < 2650.0) assert(result.params['D'].value > 7.0) assert(result.params['D'].value < 7.5)
def create_model(self): params = Parameters() params.add('ocv', value=self.voltage[-1], min=0, max=10) taus = [math.pow(10, i) for i in range(self.circuits)] weights = np.zeros(self.circuits) params.add('t0', value=taus[0], min=0.01) params.add('w0', value=weights[0]) for i in range(1, self.circuits): params.add('delta' + str(i), value=taus[i] - taus[i - 1], min=0.0) params.add('t' + str(i), expr='delta' + str(i) + '+t' + str(i - 1)) params.add('w' + str(i), value=weights[i]) for i in range(self.circuits, 5): params.add('t' + str(i), value=1, vary=False) params.add('w' + str(i), value=0, vary=False) self.params = params self.model = Model(self._model)
def test_weird_param_hints(self): # tests Github Issue 312, a very weird way to access param_hints def func(x, amp): return amp*x m = Model(func) models = {} for i in range(2): m.set_param_hint('amp', value=1) m.set_param_hint('amp', value=25) models[i] = Model(func, prefix='mod%i_' % i) models[i].param_hints['amp'] = m.param_hints['amp'] self.assertEqual(models[0].param_hints['amp'], models[1].param_hints['amp'])
def test_sum_of_two_gaussians(self): # two user-defined gaussians model1 = self.model f2 = lambda x, amp, cen, sig: gaussian(x, amplitude=amp, center=cen, sigma=sig) model2 = Model(f2) values1 = self.true_values() values2 = {'cen': 2.45, 'sig': 0.8, 'amp': 3.15} data = (gaussian(x=self.x, **values1) + f2(x=self.x, **values2) + self.noise/3.0) model = self.model + model2 pars = model.make_params() pars['sigma'].set(value=2, min=0) pars['center'].set(value=1, min=0.2, max=1.8) pars['amplitude'].set(value=3, min=0) pars['sig'].set(value=1, min=0) pars['cen'].set(value=2.4, min=2, max=3.5) pars['amp'].set(value=1, min=0) true_values = dict(list(values1.items()) + list(values2.items())) result = model.fit(data, pars, x=self.x) assert_results_close(result.values, true_values, rtol=0.01, atol=0.01) # user-defined models with common parameter names # cannot be added, and should raise f = lambda: model1 + model1 self.assertRaises(NameError, f) # two predefined_gaussians, using suffix to differentiate model1 = models.GaussianModel(prefix='g1_') model2 = models.GaussianModel(prefix='g2_') model = model1 + model2 true_values = {'g1_center': values1['center'], 'g1_amplitude': values1['amplitude'], 'g1_sigma': values1['sigma'], 'g2_center': values2['cen'], 'g2_amplitude': values2['amp'], 'g2_sigma': values2['sig']} pars = model.make_params() pars['g1_sigma'].set(2) pars['g1_center'].set(1) pars['g1_amplitude'].set(3) pars['g2_sigma'].set(1) pars['g2_center'].set(2.4) pars['g2_amplitude'].set(1) result = model.fit(data, pars, x=self.x) assert_results_close(result.values, true_values, rtol=0.01, atol=0.01) # without suffix, the names collide and Model should raise model1 = models.GaussianModel() model2 = models.GaussianModel() f = lambda: model1 + model2 self.assertRaises(NameError, f)
def fitsqsphere(q, sqdata, Ncutoff=None): ''' This will fit to a sphere structure factor. The weights are weighted towards high q (q^4) output: dictionary : parameters : the parameters sqx : the q values sqy : the data sqfit : the fit to the data ''' from ScatterSim.NanoObjects import SphereNanoObject, PolydisperseNanoObject from lmfit import Model, Parameters if Ncutoff is None: Ncutoff = 0 # the function def calc_sphereff(q, radius, sigma_R, A, B): pargs = {'radius': radius, 'sigma_R': sigma_R} sphere = PolydisperseNanoObject(SphereNanoObject, pargs=pargs, argname='radius', argstdname='sigma_R') sqmodel = sphere.form_factor_squared_isotropic(q) return A * sqmodel + B # using lmfit # radius = 4.41;sigma_R = radius*.08 params = Parameters() params.add('radius', value=4.41) params.add('sigma_R', value=0.08) params.add('A', value=1e-4, min=0) params.add('B', value=1, min=0) model = Model(calc_sphereff) res = model.fit(sqdata, q=q, params=params, weights=q**4) best_fit = res.best_fit return Arguments(parameters=res.best_values, sqx=q, sqy=sqdata, sqfit=best_fit)
def fit_Ecal_onedip(xdata, ydata, c1, guessed_sigma=.01): ''' This just fits one dip, a PseudoVoigt with inverse amplitude. Useful for getting peak COM. ''' # just fit the first # theta-tth factor factor = 1 # TODO : a1, a2 the number of peaks (this makes 2*2 = 4) # TODO : Make a Model #def dips(x, c0, wavelength, a1, a2, sigma): def dips(x, c1, a1, sigma): sign = -1 result = voigt(x=x, amplitude=sign * a1, center=c1, sigma=sigma) return result model = Model(dips) + LinearModel() guessed_average = np.mean(ydata) guessed_amplitude = np.abs(np.min(ydata) - guessed_average) # Fill out initial guess. init_guess = { 'c1': Parameter('intercept', value=c1), 'sigma': Parameter('sigma', value=guessed_sigma), 'a1': Parameter('a1', guessed_amplitude, min=0), 'intercept': Parameter("intercept", 0), 'slope': Parameter("slope", guessed_average), } params = Parameters(init_guess) # fit_kwargs = dict(ftol=1) fit_kwargs = dict() result = model.fit(ydata, x=xdata, params=params, fit_kwargs=fit_kwargs) print("Found center to be at theta : {}".format(result.best_values['c1'])) plt.figure(2) plt.clf() plt.plot(xdata, ydata, linewidth=0, marker='o', color='b', label="data") plt.plot(xdata, result.best_fit, color='r', label="best fit") plt.legend() return result
def gaussianPeakFit(data, peak): # fits Gaussian to peak in histogram data # select regions around peak lower = peak - 10 upper = peak + 10 if lower < 0: lower = 0 if upper > len(data): upper = len(data) # get corresponding data x, y = zip(*data[lower:upper]) # get x and y co-ordinate of peak px, py = data[peak] # fit Gaussian to peak region gmodel = Model(gaussian) gfit = gmodel.fit(y, x=x, A=py, mu=px, sig=1 / np.sqrt(py)) return (gfit)
def fit_plot(array, datacol='.b', fitcol='k', data_kws=None, do_title=True, seq_nbr=None): x = np.linspace(0, len(array), len(array)) y = array N = len(array) mod = Model(tuning_function) pars = Parameters() y = y - np.min(y) pars.add_many(('j', y.argmax(), True, 0.0, N), ('B', 15., True, 0.1, 360), ('fmax', y.max(), True, 0.0, 100.)) out = mod.fit(y, pars, x=x, nan_policy='omit') return out.best_values, (1 - out.residual.var() / np.var(y))
def gaussian_1(x, y, x0, sigma): def gaus(x, a, x0, sigma): # this gauss is pre-defeined return a / (np.sqrt(6.28) * sigma) * exp(-(x - x0)**2 / (2 * sigma**2)) #model = GaussianModel(prefix = 'peak_') + ConstantModel() gmodel = Model(gaus) #params = model.make_params(a=1.0, x0=mean, # sigma=sigma, delta = 5) #result = gmodel.fit(y, x=x, a =max(y), x0 = mean, sigma = sigma, delta = 10) result = gmodel.fit(y, x=x, a=max(y), x0=1550, sigma=sigma) with open('fit_result_1gaussian.txt', 'wb') as txt_file: txt_file.write(format(result.fit_report())) print(result.fit_report()) print('the error is %10.5f' % error(y, result.best_fit)) plt.plot(x, y) plt.plot(x, result.best_fit) plt.savefig('1gaussian.png') plt.show() return
def _make_lines(self): self._lines_pref = self._lines_func.__name__ + '_' + str( self._id) + '_' line = LMModel(self._lines_func, prefix=self._lines_pref, series=self._series) d = self._defs self._pars = line.make_params() self._pars.add_many( #(self._lines_pref+'z', d['z'], d['z_vary'], d['z_min'], d['z_max'], # d['z_expr']), (self._lines_pref + 'z', d['z'], d['z_vary'], d['z'] - 1e-4, d['z'] + 1e-4, d['z_expr']), (self._lines_pref + 'logN', d['logN'], d['logN_vary'], d['logN_min'], d['logN_max'], d['logN_expr']), (self._lines_pref + 'b', d['b'], d['b_vary'], d['b_min'], d['b_max'], d['b_expr']), (self._lines_pref + 'btur', d['btur'], d['btur_vary'], d['btur_min'], d['btur_max'], d['btur_expr'])) self._lines = line
def test_initialize_Model_kws(): """Test for Model class initialized with **kws.""" kws = {'amplitude': 10.0} model = Model(lmfit.lineshapes.gaussian, independent_vars=['x', 'amplitude'], **kws) assert model._param_root_names == ['center', 'sigma'] assert model.param_names == ['center', 'sigma'] assert model.independent_vars == ['x', 'amplitude'] assert model.opts == kws
def fit_rabi(x, y): """ Args: x (numpy.ndarray): A one-dimensional real-valued numpy array, the independent variable y (numpy.ndarray): A one-dimensional real-valued numpy array, the dependent variable. Returns: type: lmfit.model.ModelResult """ c_guess = guess_c(x, y) amp_guess = guess_amp(x, y) freq_guess = guess_freq(x, y) phase_guess = guess_phase(x, y) decay_guess = guess_decay(x, y) model = Model(decaying_sinusoid) rabi_fit_result = model.fit(y, x=x, c=c_guess, amp=amp_guess, freq=freq_guess, phase=phase_guess, decay=decay_guess) return rabi_fit_result
def fit_planck(self): T_wien, em_wien = fit_wien(self.lamda, self.I2) bmmodel = Model(planck, independent_vars=['lamda']) params = Parameters() params.add('T', value=T_wien) params.add('em', value=em_wien) self.result = bmmodel.fit(self.I2, params, lamda=self.lamda) # write error report report_fit(self.result) self.result.params.pretty_print() Ifit = bmmodel.eval(self.result.params, lamda=self.lamda) plt.figure() plt.plot(self.lamda * 1e9, self.I2, label='T gradient + absorption') plt.plot(self.lamda * 1e9, Ifit, label='Fitted ' + str(self.result.params.valuesdict()['T']) + ' K') plt.xlabel("wavelegnth (nm)") plt.ylabel("radiance (W/m^3)") plt.legend()
def evaluate_angles(filepath, num_angles_in, angular_resolution_in, timepoint): # read data, evaluate and fit to model, generate distribution map global angular_resolution global num_angles global distribution global coverage global a global c global k num_angles = num_angles_in angular_resolution = angular_resolution_in num_angles_evaluated = 360 // angular_resolution countdata = np.zeros((num_angles, num_angles_evaluated)) for i in range(0, num_angles): countname = filepath + "angularcount" + str(timepoint).zfill( 4) + "_" + str(i).zfill(4) + ".txt" with open(countname, "r") as countstream: for line in countstream: currentline = line.split(",") for j in range(0, len(currentline)): countdata[i, j] = currentline[j] a.resize(num_angles_evaluated, 1) c.resize(num_angles_evaluated, 1) k.resize(num_angles_evaluated, 1) distribution.resize(num_angles_evaluated, num_angles) coverage.resize(num_angles_evaluated) for i in range(0, num_angles_evaluated): r = countdata[:, i] gmodel = Model(vonmises) x = np.array(range(0, 360, 360 // num_angles)) result = gmodel.fit(r, x=x, amp=r.max(0), cen=i * angular_resolution, kappa=np.pi / 4.0) a[i] = result.params['amp'].value c[i] = result.params['cen'].value k[i] = result.params['kappa'].value distribution[i] = vonmises(np.arange(0, 360, 360 // num_angles), a[i], c[i], k[i]) return
def generate_prediction(self, model): model.inject_square_current(self.params['injected_square_current']) aps = self.get_APs(model) ap_times = np.array([ap.get_beginning()[1] for ap in aps]) if len(aps) >= 4: isis = get_diff(ap_times) isi_delays = ap_times[1:] - self.params['injected_square_current'][ 'delay'].rescale('ms').magnitude isi_delays = isi_delays - isi_delays[0] def isi_func(t, A, B, tau): return A + B * np.exp(-t / (1.0 * tau)) from lmfit import Model model = Model(isi_func) params = model.make_params(A=isis[-1], B=-1.0, tau=10.0) params['A'].min = 0 params['B'].max = 0 params['tau'].min = 0 result = model.fit(isis, t=isi_delays, params=params) A = result.best_values["A"] B = result.best_values["B"] tau = result.best_values["tau"] if debug: from matplotlib import pyplot as plt print(result.fit_report()) plt.plot(isi_delays, isis, 'bo') plt.plot(isi_delays, result.best_fit, 'r-') plt.show() return {'mean': self.get_final_result(A, B, tau), 'std': 0, 'n': 1} return none_score
def curve_fitting_reference(df_ref, arg_fit): # store as dictionary or dataframe # noise + Sensor + reference modelRef = Model(_1Voigt_v2) widG = (arg_fit['fit range ref'][1] - arg_fit['fit range ref'][0]) / 2 ampL = df_ref.loc[arg_fit['fit range ref'][0] + widG:arg_fit['fit range ref'][1]].max() cenL = df_ref.loc[arg_fit['fit range ref'][0] + widG:arg_fit['fit range ref'][1]].idxmax() widL = (arg_fit['fit range ref'][1] - arg_fit['fit range ref'][0]) / 2 paramsRef = modelRef.make_params(weight=0.5, ampG=df_ref.max(), cenG=df_ref.idxmax(), widG=widG, ampL=ampL, cenL=cenL, widL=widL) paramsRef['ampG'].min = 0 paramsRef['ampG'].max = 10 paramsRef['ampL'].min = 0 paramsRef['ampL'].max = 10 paramsRef['cenG'].min = 0 paramsRef['cenL'].min = 0 paramsRef['widG'].min = 0 paramsRef['widL'].min = 0 paramsRef['widG'].max = 100 paramsRef['widL'].max = 100 # ========================================== # lmfit - fitting df_tofit = pd.DataFrame(df_ref) df_tofit = df_tofit.sort_index() result_ = modelRef.fit(df_tofit[df_tofit.columns[0]].values.tolist(), paramsRef, x=np.array(df_tofit.index), nan_policy='omit') df_result = pd.DataFrame(result_.best_fit, index=df_tofit.index) return df_result, result_
def test__parse_params_inspect_signature(): """Test for _parse_params function using inspect.signature.""" # 1. function with a positional argument def func_var_positional(a, *b): pass with pytest.raises(ValueError, match=r"varargs '\*b' is not supported"): Model(func_var_positional) # 2. function with a keyword argument def func_keyword(a, b, **c): pass mod = Model(func_keyword) assert mod._func_allargs == ['a', 'b'] assert mod._func_haskeywords is True assert mod.independent_vars == ['a'] assert mod.def_vals == {} # 3. function with keyword argument only def func_keyword_only(**b): pass mod = Model(func_keyword_only) assert mod._func_allargs == [] assert mod._func_haskeywords is True assert mod.independent_vars == [] assert mod._param_root_names is None # 4. function with default value def func_default_value(a, b, c=10): pass mod = Model(func_default_value) assert mod._func_allargs == ['a', 'b', 'c'] assert mod._func_haskeywords is False assert mod.independent_vars == ['a'] assert isinstance(mod.def_vals, dict) assert_allclose(mod.def_vals['c'], 10)
class T2RamseyModel(Model): __doc__ = """Class for T2 Ramsey model""" def __init__(self, *args, **kwargs): super(T2RamseyModel, self).__init__(fn_T2_Ramsey, *args, **kwargs) __model__ = Model(fn_T2_Ramsey) def guess(self, x, y, **kwargs): """Takes x and y data and generates initial guesses for fit parameters. """ ym = y.min() yM = y.max() a_guess = 0.5 * (yM - ym) * 1.2 b_guess = 0.5 * (yM + ym) t_guess = 0.25 * x[-1] d_guess = get_freq_from_fft(x, y, b_guess) x_guess = 0.0 pars = self.make_params(baseline=b_guess, amplitude=a_guess, T2=t_guess, detuning=d_guess, x0=x_guess) pars['amplitude'].value = kwargs.pop('amplitude_guess', a_guess) pars['baseline'].value = kwargs.pop('baseline_guess', b_guess) pars['T2'].value = kwargs.pop('T2_guess', t_guess) pars['detuning'].value = kwargs.pop('detuning_guess', d_guess) pars['x0'].value = kwargs.pop('x0_guess', x_guess) return update_param_vals(pars, self.prefix, **kwargs) def do_fit(self, x, y, errs=None, **kwargs): """Performs a fit. """ par = self.guess(x, y, **kwargs) if errs is not None: fit = self.fit(y, x=x, weights=1.0 / errs, params=par, fit_kws={"nan_policy": "omit"}) else: fit = self.fit(y, x=x, params=par, fit_kws={"nan_policy": "omit"}) return fit def report_fit(self, x, y, **kwargs): """Reports the results of a fit. May change depending on what we want this to return. """ if not len(x) == len(y): raise ValueError("Lengths of x and y arrays must be equal.") if not len(x) > MIN_DATA_POINTS: raise ValueError("You must provide more than {} data points.".format(MIN_DATA_POINTS)) fit = self.do_fit(x, y, **kwargs) t_fit = fit.params['T2'] d_fit = fit.params['detuning'] return fit, (t_fit.value, t_fit.stderr), (d_fit.value, d_fit.stderr)
def gaussFitData(x: list, y: list) -> (float, float): """ Since it's a gaussian fit for both rows and columns, two seperate 1D gaussian is fitted. Reference: https://lmfit.github.io/lmfit-py/model.html """ def gaussian(x, amp, cen, wid, offset): """1-d gaussian: gaussian(x, amp, cen, wid)""" return (amp / (sqrt(2 * pi) * wid)) * exp(-(x - cen)**2 / (2 * wid**2)) + offset gmodel = Model(gaussian) result = gmodel.fit(y, x=x, amp=5, cen=5, wid=1, offset=0) #print(result.fit_report()) # Read the center and width of atom cloud from a json string center = result.params["cen"].value width = result.params["wid"].value amp = result.params["amp"].value offset = result.params["offset"].value return center, width, amp
def fit_vonMises(self, spikes, verbose=False): theta = self.sim_params['angle_input']*np.pi/180 fr = np.zeros(len(spikes.spiketrains)) for i, st in enumerate(spikes.spiketrains): fr[i] = np.float(len (st)) def mises(x, sigma, amp, m=np.pi/2): kappa = 1. / sigma**2 exp_c = np.exp(np.cos(2*(x-m))*kappa) return amp * exp_c #/(2*np.pi*iv(0, kappa)) from lmfit import Model vonM_mod = Model(mises) #vonM_mod.param_names #vonM_mod.independent_vars y = np.array(fr) x = np.linspace(0, np.pi, len(spikes.spiketrains)) result = vonM_mod.fit(y, x = x, sigma=np.pi/2, amp=y.mean(), m=np.pi/2) if verbose: print(result.fit_report()) return x, y, result
def fitdata2(self, signalwindow): timeofsunmax = self.simtofmax / 100 + 3 [max, minmax, maxmax] = utils.suntemptoadc(np.array([50, 30, 120]), self.simmax) [fithourarray, fitradio] = self.getdataforfit(signalwindow) #return max*np.exp(-((x - mu)/sigma)**2) + b*x**2 + c*x + d gmodel = Model(utils.expofunc2) # gmodel = Model(utils.expofunc0) params = Parameters() baseline = np.mean(fitradio[10]) params.add('a', value=max, min=minmax, max=maxmax) params.add('mu', value=timeofsunmax) params.add('sigma', value=1, min=0.5, max=2) params.add('b', value=0) params.add('c', value=0) params.add('d', value=0) result = gmodel.fit(fitradio, x=fithourarray, params=params) # result.eval_uncertainty() # print(result.fit_report()) return result
def fit_decay_time_param_decay( x: np.ndarray, y: np.ndarray, weights: np.ndarray = None, param_guesses: tuple = (1., 10, 0)) -> ModelResult: """ Fit experimental data x, y to an exponential decay parameterized by a decay time, or inverse decay rate. :param x: The independent variable, e.g. depth or time :param y: The dependent variable, e.g. survival probability :param weights: Optional weightings of each point to use when fitting. :param param_guesses: initial guesses for the parameters :return: a lmfit Model """ _check_data(x, y, weights) decay_model = Model(decay_time_param_decay) params = decay_model.make_params(amplitude=param_guesses[0], decay_time=param_guesses[1], offset=param_guesses[2]) return decay_model.fit(y, x=x, params=params, weights=weights)
def fitPhaseFromAmp(theta,f, w0,Q): phase=theta phase = fixPhase(phase) FWHM=w0/Q w0idx, w0=find_nearestx(f, w0) maxval,wmax=find_nearestx(f, w0+3*FWHM) minval,wmin=find_nearestx(f, w0-3*FWHM) fixedphase=(phase-phase[w0idx])*180/np.pi gmod = Model(DDOphase) result = gmod.fit(fixedphase[minval:maxval], x=f[minval:maxval], w0=w0, \ Q=Q, m =0, b=0) # plt.plot(data.f[minval:maxval], result.init_fit, 'r-') # plt.plot(data.f[minval:maxval], result.best_fit, 'b-') # plt.plot(data.f[minval:maxval], fixedphase[minval:maxval], 'g') Q = result.params['Q'].value w0 = result.params['w0'].value m = result.params['m'].value b = result.params['b'].value fout = f[minval:maxval] pout = fixedphase[minval:maxval] return result, [w0, Q, m,b], [fout, pout]
def update_fits(attr, old, new): if 0 in fit_select.active: bDf = pd.DataFrame(data={'x': df.Day, 'y': df.Projection}) b_source.data = b_source.from_df(bDf) proj_resid = np.sum((df.Projection - df.Measurement)**2) source_residual_table.data['Projection Residual'] = [proj_resid] if 1 in fit_select.active: model = Model(default_model) result = model.fit(df.Measurement, x=df.Day, a=1, b=1) fit = result.best_fit cDf = pd.DataFrame(data={'x': df.Day, 'y': fit}) c_source.data = c_source.from_df(cDf) dDf = pd.DataFrame(data={ 'a': result.best_values['a'], 'b': result.best_values['b'] }, index=[0]) source_data_table.data = source_data_table.from_df(dDf) fit_resid = np.sum((df.Projection - fit)**2) source_residual_table.data['Fit Residual'] = [fit_resid] update()
def fitz_qso(spec, zguess, fluxpoly=True): flux_median = np.median(spec['flux']) parameters = Parameters() # (Name, Value, Vary, Min, Max, Expr) parameters.add_many(('z', zguess, True, None, None, None), ('eigen1', flux_median * 0.4, True, None, None, None), ('eigen2', flux_median * 0.4, True, None, None, None), ('eigen3', flux_median * 0.1, True, None, None, None), ('eigen4', flux_median * 0.1, True, None, None, None), ('fluxcal0', 0.0, fluxpoly, None, None, None), ('fluxcal1', 0.0, fluxpoly, None, None, None), ('fluxcal2', 0.0, fluxpoly, None, None, None)) galaxy_model = Model(eigensum_qso, missing='drop') result = galaxy_model.fit(spec['flux'], wave=spec['wave'], weights=1 / spec['error']**2, params=parameters, missing='drop') return result
def fitPhaseFromAmp(theta, f, w0, Q): phase = theta phase = fixPhase(phase) FWHM = w0 / Q w0idx, w0 = find_nearestx(f, w0) maxval, wmax = find_nearestx(f, w0 + 3 * FWHM) minval, wmin = find_nearestx(f, w0 - 3 * FWHM) fixedphase = (phase - phase[w0idx]) * 180 / np.pi gmod = Model(DDOphase) result = gmod.fit(fixedphase[minval:maxval], x=f[minval:maxval], w0=w0, \ Q=Q, m =0, b=0) # plt.plot(data.f[minval:maxval], result.init_fit, 'r-') # plt.plot(data.f[minval:maxval], result.best_fit, 'b-') # plt.plot(data.f[minval:maxval], fixedphase[minval:maxval], 'g') Q = result.params['Q'].value w0 = result.params['w0'].value m = result.params['m'].value b = result.params['b'].value fout = f[minval:maxval] pout = fixedphase[minval:maxval] return result, [w0, Q, m, b], [fout, pout]
def example(): # possible values from get_ssa import get_ssa from Model import IrradianceModel zenith = 53.1836240528 AMass = 1.66450160404 rel_h = 0.665 pressure = 950 AM = 5 ssa = get_ssa(rel_h, AM) iteration = 20 alphas = np.zeros(len(range(1, iteration)) + 1) x = np.linspace(200, 800, 100) irr = IrradianceModel_python(AMass, rel_h, ssa, zenith, pressure) irr_symbol = IrradianceModel(x, zenith, AMass, pressure, ssa) func = irr_symbol._irradiance_ratio() y = irr.irradiance_ratio(x, 2.5, 0.06, 0.0, 1.0, 1.0) for i in range(0, iteration): ssa = get_ssa(rel_h, AM) print(ssa) irr = IrradianceModel_python(AMass, rel_h, ssa, zenith, pressure) yerror = np.random.normal(0, 0.009, len(x)) y = irr.irradiance_ratio(x, 1.5, 0.06, 0.0, 0.6, 0.9) + yerror weights = 1 / yerror gmod = Model(irr.irradiance_ratio, independent_vars=["x"], param_names=["alpha", "beta", "g_dsa", "g_dsr"]) gmod.set_param_hint("alpha", value=1.0, min=-0.2, max=2.5) gmod.set_param_hint("beta", value=0.01, min=0.0, max=2.0) gmod.set_param_hint("g_dsa", value=0.6, min=0.0, max=1.0) gmod.set_param_hint("g_dsr", value=0.9, min=0.0, max=1.0) print(gmod.param_hints) print(gmod.param_names) print(gmod.independent_vars) result = gmod.fit(y, x=x) print(result.fit_report()) alphas[i] = result.params["alpha"].value # plt.plot(x, y, label='%s' % AM) # plt.plot(x, result.best_fit, 'r-', label='fit') y = irr.irradiance_ratio(x, 1.5, 0.06, 0.0, 0.6, 0.9) y2 = irr.irradiance_ratio(x, 1.5, 0.08, 0.0, 0.6, 0.9) plt.legend() plt.show()
def getCentroVentana(venX, venY, matriz): #Obtenemos la submatriz subM = matriz[venX:venX + TAM_VENTANA * 2, venY:venY + TAM_VENTANA * 2] #Obtenemos el centro del spot contenido en la ventana en la dirección X x = np.arange(TAM_VENTANA * 2) y = np.sum(subM, axis=1) gmod = Model(gaussian) resultX = gmod.fit(y, x=x, amp=np.max(y) - np.median(y), cen=TAM_VENTANA, wid=2, level=np.median(y)) #Obtenemos el centro del spot contenido en la ventana en la dirección Y x2 = np.arange(TAM_VENTANA * 2) y2 = np.sum(subM, axis=0) gmod2 = Model(gaussian) resultY = gmod2.fit(y2, x=x2, amp=np.max(y2) - np.median(y2), cen=TAM_VENTANA, wid=2, level=np.median(y2)) #Centro del spot {X,Y} centroSub = np.array( [resultX.best_values["cen"], resultY.best_values["cen"]]) #Realizamos un cambio de coordenadas para obtener el centro en la matriz de datos desvX = centroSub[0] - TAM_VENTANA centroX = venX + TAM_VENTANA + desvX desvY = centroSub[1] - TAM_VENTANA centroY = venY + TAM_VENTANA + desvY centro = [centroX, centroY] return centro
def evaluate_angles(self, filepath, timepoint="0", usetimepoint=True): # read data, evaluate and fit to model, generate distribution map for i in range(0, self.num_angles): if usetimepoint: countname = filepath + "angularcount" + str(timepoint).zfill( 4) + "_" + str(i).zfill(4) + ".txt" else: countname = filepath + "angularcount" + str(i).zfill( 4) + ".txt" #if file doesn't exist, use previous timepoints try: with open(countname, "r") as countstream: for line in countstream: currentline = line.split(",") for j in range(0, len(currentline)): self.countdata[i, j] = currentline[j] except: countname = filepath + "angularcount" + str( timepoint - 1).zfill(4) + "_" + str(i).zfill(4) + ".txt" with open(countname, "r") as countstream: for line in countstream: currentline = line.split(",") for j in range(0, len(currentline)): self.countdata[i, j] = currentline[j] for i in range(0, self.num_angles_evaluated): r = self.countdata[:, i] gmodel = Model(ut.vonmises) x = np.array(range(0, 360, 360 // self.num_angles)) result = gmodel.fit(r, x=x, amp=r.max(0), cen=i * self.angular_resolution, kappa=np.pi / 4.0) self.a[i] = result.params['amp'].value self.c[i] = result.params['cen'].value self.k[i] = result.params['kappa'].value self.distribution[i] = ut.vonmises( np.arange(0, 360, 360 // self.num_angles_evaluated), self.a[i], self.c[i], self.k[i]) return
def fit_arc_equation(points): if len(points) < 2: return None _points = np.array(points).transpose() _x = _points[0, 1:] - _points[0, 0] _y = _points[1, 1:] - _points[1, 0] _r = np.sqrt(_x ** 2 + _y ** 2) _r = _r / _r[0] * 5 _theta = np.arctan2(_y, _x) _theta = _theta - _theta[0] # def _arc_equation(r, k1, k2): # r0 = 5 # return k2 * (r - r0)**2 + k1 * (r - r0) def _arc_equation(x, k1, k2): r0 = 5 return k2 * (x - r0) ** 2 + k1 * (x - r0) model = Model(_arc_equation) params = model.make_params(k1=1, k2=1) params['k1'].value = 0 params['k1'].vary = False result = model.fit(_theta, params, x=_r) # popt, pcov = curve_fit(_arc_equation, _r, _theta) # perr = np.sqrt(np.diag(pcov)) print(_r) print(_theta) # print(_r, _theta) # print(f"k1: {popt[0]:.1e} +/- {perr[0]:.1e}") # print(f"k2: {popt[1]:.1e} +/- {perr[0]:.1e}") SSres = ((result.best_fit - _theta) ** 2).sum() SStot = ((_theta - _theta.mean()) ** 2).sum() r_squared = 1 - SSres / SStot print(r_squared) plt.plot(_r, _theta) # plt.plot(_r, _arc_equation(_r, popt[0], popt[1])) return _r, result