def center_on_cos(raw_quadratures, phi0=None, omega=None, snap_omega=False): mean = scipy.average(raw_quadratures, axis=1) no_angles, no_pulses = raw_quadratures.shape model = Model(cos_model) offset, amplitude, phi0, omega = guess_initial_parameters( mean, phi0, omega) model.set_param_hint("offset", value=offset) model.set_param_hint("amplitude", min=0., value=amplitude) model.set_param_hint("phi0", value=phi0) model.set_param_hint("omega", min=0., value=omega) model.make_params(verbose=False) steps = scipy.arange(no_angles) res = model.fit(mean, x=steps, verbose=False) omega_param = res.params["omega"] if snap_omega: appx_omega = float(omega_param) no_pi_intervals = int(round(pi / appx_omega)) omega = pi / no_pi_intervals omega_param.set(omega, vary=False) res.fit(mean, x=steps, verbose=False) d_value, p_value_ks = kstest(res.residual, 'norm') mean_fit = res.eval(x=steps) offset = mean - mean_fit aligned_quadratures = raw_quadratures - offset[:, None] centered_quadratures = aligned_quadratures - float(res.params["offset"]) return (centered_quadratures, float(omega_param), float(res.params["phi0"]), p_value_ks)
def center_on_cos(raw_quadratures, phi0=None, omega=None, snap_omega=False): mean = scipy.average(raw_quadratures, axis=1) no_angles, no_pulses = raw_quadratures.shape model = Model(cos_model) offset, amplitude, phi0, omega = guess_initial_parameters(mean, phi0, omega) model.set_param_hint("offset", value=offset) model.set_param_hint("amplitude", min=0., value=amplitude) model.set_param_hint("phi0", value=phi0) model.set_param_hint("omega", min=0., value=omega) model.make_params(verbose=False) steps = scipy.arange(no_angles) res = model.fit(mean, x=steps, verbose=False) omega_param = res.params["omega"] if snap_omega: appx_omega = float(omega_param) no_pi_intervals = int(round(pi/appx_omega)) omega = pi/no_pi_intervals omega_param.set(omega, vary=False) res.fit(mean, x=steps, verbose=False) d_value, p_value_ks = kstest(res.residual, 'norm') mean_fit = res.eval(x=steps) offset = mean-mean_fit aligned_quadratures = raw_quadratures - offset[:,None] centered_quadratures = aligned_quadratures - float(res.params["offset"]) return (centered_quadratures, float(omega_param), float(res.params["phi0"]), p_value_ks)
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 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 OptimizeDevicParameters2(self): for c in [0, 1, 2]: fmodel = Model(self.DevicCalFunc) # create parameters -- these are named from the function arguments -- # giving initial values params = fmodel.make_params(A=self.DevicParam_A[c], B=self.DevicParam_B[c], n=self.DevicParam_n[c]) # fix n: params['n'].vary = False # limit parameter values params['A'].min = 0 params['A'].max = 100 params['B'].min = 0 params['B'].max = 500 result = fmodel.fit(self.D, params, x=self.ODnet[:, c]) self.DevicParam_A[c] = result.params['A'] self.DevicParam_B[c] = result.params['B'] self.Sigma_A[c] = result.params['A'].stderr self.Sigma_B[c] = result.params['B'].stderr self.Sigma_n[c] = 0.0 print("Fit results for channel {}:".format(c)) # result.plot_fit() print(result.fit_report()) print('') self.show_calibration_plot()
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 create_xrf_line(x, params, linedict, linefunc): funcmodel = Model(linefunc) # start with the function parameters... funcparams = funcmodel.make_params() # # copy the function based parameters from params to funcparams # for key in params: if key in funcparams: funcparams[key].value = params[key].value funcparams[key].min = params[key].min funcparams[key].max = params[key].max funcparams[key].vary = params[key].vary result = np.zeros_like(x) sigma_keys = [s for s in funcparams.keys() if 'sigma' in s] for key, linegroup in linedict.iteritems(): if key in params: for line in linegroup: # update funcparams funcparams["area"].value = params[key].value*\ line.intensity funcparams["center"].value = line.line_energy for ii in sigma_keys: funcparams[ii].value = np.sqrt(params[ii].value**2 + \ (line.line_energy*0.001)) result = result + funcmodel.eval(funcparams, x=x) return result
def create_xrf_lmfit_parameters(exptdesc, linedict, linefunc): funcmodel = Model(linefunc) funcparams = funcmodel.make_params() # remove the area and center parameter funcparams.pop("area", None) funcparams.pop("center", None) # get the function name linename = linefunc.__name__ # For each element in the linedict add a parameter # which will control the area for key in exptdesc["lineshape"]["element"][linename].keys(): if key in funcparams: funcparams[key].value = \ exptdesc["lineshape"]["element"][linename][key]["value"] funcparams[key].min = \ exptdesc["lineshape"]["element"][linename][key]["min"] funcparams[key].max = \ exptdesc["lineshape"]["element"][linename][key]["max"] funcparams[key].vary = \ exptdesc["lineshape"]["element"][linename][key]["vary"] for key in linedict: if not '+' in key: funcparams.add( key, **exptdesc["lineshape"]["element"][linename]["area"]) return funcparams
def decay_fitting(xdata,ydata,ystderr, init, no_trials = 1): # Declare model and initializing data print('Fitting now...') lzmod = Model(exp_decay) print(fitguess) # Set parameter hints lzmod.set_param_hint('amp', value = init[0]) lzmod.set_param_hint('dec', value = init[1] ) lzmod.set_param_hint('yoff', value = init[2]) lzmod.set_param_hint('ps', value = init[3]) pars = lzmod.make_params() fit = lzmod.fit(ydata, pars, x=xdata, weights=1/ystderr, verbose=False) #print fit.fit_report() amp_est = fit.params['amp'].value amp_std = fit.params['amp'].stderr decay_est = fit.params['dec'].value decay_std = fit.params['dec'].stderr yoff_est = fit.params['yoff'].value yoff_std = fit.params['yoff'].stderr redchi = fit.redchi # Return back the result list with the following order: result_list = [amp_est, amp_std, decay_est, decay_std,yoff_est,yoff_std, redchi] return (result_list,fit)
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 on_fit_button_released(self): p0 = dict() truth_list = [] self.fit_function.__defaults__ = () for i in range(len(self.args)): top_widget = self.tw.topLevelItem(i) p0[self.args[i]] = self.tw.itemWidget(top_widget, 2).value() truth_list.append( bool(self.tw.itemWidget(top_widget, 0).checkState())) fitmodel = Model(self.fit_function) params = fitmodel.make_params(**p0) for i, flag in enumerate(truth_list): if not flag: params[self.args[i]].vary = False try: x, y = self.data_item.getData() if np.isnan(y).any(): end = np.isnan(y).argmax() y = y[:end] x = x[:end] result = fitmodel.fit(y, params, x=x) except Exception as e: print(e) self.plot_active = True self.params = [] for i, (_, value) in enumerate(result.params.valuesdict().items()): self.tw.topLevelItem(i).setText(3, str(value)) top_widget = self.tw.topLevelItem(i) self.tw.itemWidget(top_widget, 2).setValue(float(value)) self.fit_function.__defaults__ = self.defaults self.params.append(value) self.fit_curve_drawn = True
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
class DLS: """Load DLS models for fitting autocorrelation functions using the cumulant method A great explanation for this fitting procedure was written by Barbara Frisken 20 August 2001 Vol. 40, No. 24 APPLIED OPTICS Arguments: mu_2 -- Bool fit second cumulant term, mu_2, to estimate polydispersity of sample mu_3 -- Bool fit third cumulant term, mu_3, to estimate skew on polydispersity """ def __init__(self, mu_2=True, mu_3=False, **qkwargs): #self._q = self.q(**qkwargs) # use only simple exp function if not mu_2: self.g = Model(g) # fit mu_2 and mu_3 elif mu_3: self.g = Model(cumulant3) # fit only mu_2 else: self.g = Model(cumulant2) self.pars = self.g.make_params(D=1e-10, B=1.0, beta=0.5, mu_2=1.0e5, mu_3=1.0)
def lmfit_fourier(x, y): x = np.array(x) y = np.array(y) freq = np.fft.fftfreq(len(x), (x[1] - x[0])) # assume uniform spacing Fy = abs(np.fft.fft(y)) guess_freq = abs(freq[ np.argmax(Fy[1:]) + 1]) # excluding the zero frequency "peak", which is related to offset guess_amp = np.std(y) * 2.**0.5 guess_offset = np.mean(y) #guess = np.array([guess_amp, 2.*np.pi*guess_freq, 0., guess_offset]) def sinfunc(x, A, w, p, c): return A * np.sin(w * x + p) + c gmodel = Model(sinfunc) params = gmodel.make_params(A=guess_amp, w=2. * np.pi * guess_freq, p=0., c=guess_offset) sinus_fit = gmodel.fit(y, params, x=x) return sinus_fit.best_fit
def make_lmfit(indep, dep, names, degree=2, mindep=-1.0, maxdep=0.4): med_dep = np.median(dep) numpts = (degree + 1)**len(indep) names_new = [st + '_ind' for st in names] x = np.empty( (0, degree + 1)) # To set up grid on which true dust parameter n will be defined per = np.percentile(indep, [1.0, 99.0], axis=1) for i in range(len(indep)): x = np.append(x, np.linspace(per[0, i], per[1, i], degree + 1)[None, :], axis=0) xx = np.meshgrid(*x) #N-D Grid for polynomial computations pmod = Model(polymod, independent_vars=names_new, param_names=['c' + str(d) for d in range(numpts)]) pars = pmod.make_params() for i in range(numpts): pars.add('c' + str(i), value=med_dep, min=mindep, max=maxdep, vary=True) kwargs = {'xx': xx} for name, ind in zip(names_new, indep): kwargs[name] = ind res = pmod.fit(dep, params=pars, **kwargs) # print(res.fit_report()) return xx, res
def lorentz_fitting(data, init, no_trials=1): # Declare model and initializing data print('Fitting now...') lzmod = Model(lorentzian) xdata = data[:, 0] ydata = data[:, 1] ystderr = data[:, 2] / np.sqrt(no_trials) # Set parameter hints lzmod.set_param_hint('amp', value=init[0], min=0) lzmod.set_param_hint('width', value=init[1], min=0) lzmod.set_param_hint('mean', value=init[2]) pars = lzmod.make_params() fit = lzmod.fit(ydata, pars, x=xdata, weights=1 / ystderr, verbose=False) #print fit.fit_report() amp_est = fit.params['amp'].value amp_std = fit.params['amp'].stderr width_est = fit.params['width'].value width_std = fit.params['width'].stderr mean_est = fit.params['mean'].value mean_std = fit.params['mean'].stderr redchi = fit.redchi # Return back the result list with the following order: result_list = [ amp_est, amp_std, width_est, width_std, mean_est, mean_std, redchi ] return result_list
def approach_fit(y): fmodel = Model(approach) # initial values params = fmodel.make_params(E=0, E0=0, D=1e-6, rtip=25e-7, k0=1, n=1, alpha=0.5, T=293) # fix parameters: params['T'].vary = False params['alpha'].vary = False params['rtip'].vary = False params['E0'].vary = False params['E'].vary = False # fit parameters to data with various *static* values of b: # for b in range(10): # params['T'].value = 293 # params['alpha'].value = 0.5 # params['rtip'].value = 25e-7 # params['E0'].value = 0 # params['E'].value = 0.4 result = fmodel.fit(i, params, x=L)
def GaussManual(signal, guess): """ Fits high contrast data very well """ amp, centre, stdev, offset = guess data = np.array([range(len(signal)), signal]).T X = data[:, 0] Y = data[:, 1] gauss_mod = Model(gaussian) pars = gauss_mod.make_params(center=centre, sigma=stdev, amplitude=amp, offset=offset) pars['center'].vary = False pars['sigma'].min = stdev pars['sigma'].max = stdev + 5. mod = gauss_mod result = mod.fit(Y, pars, x=X) fwhm = result.best_values['sigma'] * 2.3548 return X, result.best_fit, result.best_values['sigma'] * 4
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_lm_sin(xdata, ydata): sinemodel = Model(sine_func) params = sinemodel.make_params(a=1, b=0.1) result = sinemodel.fit(ydata, params, x=xdata) # result = sinemodel.fit(ydata, x=xdata, a=1, b=0.1) #params not required this way return result
def gaussline(data, flareinds, ind, guess_out, plot=True, offset=0, mags=1, exguess=False, more=False): ''' Fits gaussian+line composite model to the 13 flares. Inputs: ------- data: sog4 flareinds: flareinds ind: index of flare in flareinds to fit guess_out: gaussian output to use as a guess for the amp, cen, and wid plot: default True -- plots best fit on flare data offset: vertical offset mags: original or detrended data (defaultt 1 for original data) exguess: default False; make True if guess_out is list of guess parameters rather than gaussian result more: returns result rather than best parameter values if True (default False) Output: ------- if more: returns fit result else: returns best fit cen, amp, and wid ''' x = data['MJD-50000'][flareinds[ind][0]:flareinds[ind][1]] #default mag 1 is original data; 5 is detrended if mags == 1: imag = data['I mag'] else: imag = data['I detrend 2'] y = offset + np.max(imag[flareinds[ind][0]:flareinds[ind][1]] ) - imag[flareinds[ind][0]:flareinds[ind][1]] mod = Model(gaussian) + Model(line) #using guesses from gaussian model if exguess: amp, cen, wid = guess_out[0], guess_out[1], guess_out[2] else: gf = guess_out[ ind].best_values #getting guesses from previous fit (just gaussian) amp, cen, wid = gf['amplitude'], gf['center'], gf['sigma'] pars = mod.make_params(amp=amp, cen=cen, wid=wid, slope=0, intercept=1) pars['amp'].min = 0.0 #center constrained to be within 30 days of .05 offset center pars['cen'].min = cen - 30 pars['cen'].max = cen + 30 #positive width pars['wid'].min = 0.0 result = mod.fit(y, pars, x=x) if plot: plt.plot(x, y, 'bo') #plot best fit model and center plt.plot(x, result.best_fit, 'r-', label='best fit') plt.axvline(result.best_values['cen'], color='black') plt.legend(loc='best') plt.show() if more: return result else: return result.best_values
def test_unprefixed_name_collisions(self): # tests Github Issue 710 np.random.seed(0) x = np.linspace(0, 20, 201) y = 6 + x * 0.55 + gaussian(x, 4.5, 8.5, 2.1) + np.random.normal(size=len(x), scale=0.03) def myline(x, a, b): return a + b * x def mygauss(x, a, b, c): return gaussian(x, a, b, c) mod = Model(myline, prefix='line_') + Model(mygauss, prefix='peak_') pars = mod.make_params(line_a=5, line_b=1, peak_a=10, peak_b=10, peak_c=5) pars.add('a', expr='line_a + peak_a') result = mod.fit(y, pars, x=x) self.assertTrue(result.params['peak_a'].value > 4) self.assertTrue(result.params['peak_a'].value < 5) self.assertTrue(result.params['peak_b'].value > 8) self.assertTrue(result.params['peak_b'].value < 9) self.assertTrue(result.params['peak_c'].value > 1.5) self.assertTrue(result.params['peak_c'].value < 2.5) self.assertTrue(result.params['line_a'].value > 5.5) self.assertTrue(result.params['line_a'].value < 6.5) self.assertTrue(result.params['line_b'].value > 0.25) self.assertTrue(result.params['line_b'].value < 0.75) self.assertTrue(result.params['a'].value > 10) self.assertTrue(result.params['a'].value < 11)
def Rturn_Vmax(r_array, v_array, negative=False): r_array, v_array = abs(r_array), abs(v_array) r_array = np.append(r_array, 0.1) v_array = np.append(v_array, 5) v0 = np.nanmedian(v_array) try: #x0=[250,5,0,1] #vmax ,r_turn,beta,gamma = optimization.curve_fit(vrot, r_array, v_array, p0=x0, bounds = ([0,0,0,0],[500,60,1,50]))[0] mod = Model(vrot) mod.set_param_hint('v_max', value=v0, vmin=0, vmax=360) mod.set_param_hint('beta', value=0, vary=False, min=0, max=1.0) mod.set_param_hint('R_turn', value=5, min=0, max=35) mod.set_param_hint('gamma', value=1, min=-2, max=12) pars = mod.make_params() result = mod.fit(v_array, r_sky=r_array) #, fit_method = "Powell") best = result.best_values vmax, r_turn, gamma, beta = best["v_max"], best["R_turn"], best[ "gamma"], best["beta"] except (RuntimeError, TypeError, ValueError): vmax, r_turn, gamma, beta = 500, 0, 1, 1 return vmax, r_turn, beta, gamma
def phaser(x, y, fc, y0): def phaseFit(x, Qt, fr): return y0 - 180 * np.arctan(2 * Qt * (x - fr) / fr) / np.pi gmodel = Model(phaseFit) gmodel = gmodel + LinearModel() # print(gmodel.param_names) # print(gmodel.independent_vars) df = 0.002 dy = 50 Qt = 30000 dQt = Qt params = gmodel.make_params() params.add('y0', value=y0, min=y0 - dy, max=y0 + dy) params.add('Qt', value=Qt, min=Qt - dQt, max=Qt + dQt) params.add('fr', value=fc, min=fc - df, max=fc + df) params.add('intercept', value=1, vary=True) params.add('slope', value=0, vary=True) result = gmodel.fit(y, params, x=x) return result
def get_fit_result( data, init_params, model_function, ): ''' find best fit parameters. :param data: DataFrame raw data. index values are sampling events. :param init_params: dict :param model_function function to fit data with. :return: result: ModelResult ''' x = data.index.values y = data.values model = Model(model_function) for param, init_value in init_params.items(): model.set_param_hint(param, value=init_value) params = model.make_params() result = model.fit(y, params, t=x) return result
def _fit(self, reference_point, order): """ This is meant to be used privately, when the pprint_disp is handled by another function. The `fit` method is for public use. """ if self.is_coeff or self.is_dispersion_array: warnings.warn("No need to fit another curve.") return else: if self.GD_mode: order -= 1 self.fitorder = order _function = _fit_config[order] x, y = np.copy(self.x), np.copy(self.y) x -= reference_point if _has_lmfit: fitmodel = Model(_function) pars = fitmodel.make_params( **{f"b{i}": 1 for i in range(order + 1)}) result = fitmodel.fit(y, x=x, params=pars) else: popt, pcov = curve_fit(_function, x, y, maxfev=8000) if _has_lmfit: dispersion, dispersion_std = transform_lmfit_params_to_dispersion( *_unpack_lmfit(result.params.items()), drop_first=True, dof=1) fit_report = result.fit_report() self.fitted_curve = result.best_fit else: dispersion, dispersion_std = transform_cf_params_to_dispersion( popt, drop_first=True, dof=1) fit_report = ( "To display detailed results you must have `lmfit` installed." ) self.fitted_curve = _function(x, *popt) if self.GD_mode: _, idx = find_nearest(self.x, reference_point) dispersion = np.insert(dispersion, 0, self.fitted_curve[idx]) dispersion_std = np.insert(dispersion_std, 0, 0) # The below line must have 7 elements, so slice these redundant coeffs.. dispersion, dispersion_std = dispersion[: -1], dispersion_std[: -1] self.coef_array = self.coef_temp(*dispersion) self.coef_std_array = self.coef_std_temp(*dispersion_std) return dispersion, dispersion_std, fit_report
def Fit_Modified_SEIR(CN, missing_days=0, RN=None, fit_method="least_squares", **R_0_kwargs): if RN is not None: y_data = train_data [(train_data ["State"] == CN)].Fatalities.values else: if len(train_data ["State"] == CN) > len(train_data ["State"] == "United States"): y_data = train_data [(train_data ["State"] == CN)].Fatalities.values else: y_data = train_data [train_data ["State"] == CN].Fatalities.values Max_d = len(train_data.groupby("Date").sum().index) + missing_days y_data = np.concatenate((np.zeros(missing_days), y_data)) # State Population N = "please import the state population here" # Infectious period (please read the manuscript for more information) D = 10 x_data = np.linspace(0, Max_d - 1, Max_d, dtype=int) # Solver def Modified_SEIR_deaths(x, N, D, CFR_O, CFR_S, R_0_delta, **R_0_kwargs): t_, S_, E_, I_, R_, X, R_0_, N_, CFR_ = Modified_SEIR(N, D, Max_d, CFR_O, CFR_S, R_0=New_R_0, **R_0_kwargs) return X[x] mod = Model(Modified_SEIR_deaths) # Initial values and bounds mod.set_param_hint('N', value=N, vary=False) mod.set_param_hint('D', value=D, vary=False) mod.set_param_hint('CFR_O', value=0.01, min=0.0001, max=0.1) mod.set_param_hint('CFR_S', value=0.1, min=0.0001, max=1.0) mod.set_param_hint('R_0_start', value=2.5, min=1.0, max=5.0) mod.set_param_hint('R_0_end', value=0.7, min=0.01, max=5.0) mod.set_param_hint('x0', value=30.0, min=0.0, max=float(Max_d)) mod.set_param_hint('k', value=0.1, min=0.01, max=5.0) ''' if R_0_kwargs: for arg in R_0_kwargs: mod.set_param_hint(arg, value=R_0_kwargs[arg]) ''' params = mod.make_params() params.add('R_0_delta', value=1.0, min=0.0, expr="R_0_start - R_0_end") result = mod.fit(y_data, params, method=fit_method, x=x_data) CFR_O = result.params["CFR_O"].value CFR_S = result.params["CFR_S"].value R_0_result_params = {} for val in R_0_kwargs: R_0_result_params[val] = result.params[val].value return result, CN, y_data, N, D, Max_d, CFR_O, CFR_S, R_0_result_params
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 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 fit_model_error(t, y, wt=1): gmodel = Model(correlation) gmodel.set_param_hint('g0', value=0.1) gmodel.set_param_hint('tauD', value=1e-4, min=1e-6, max=100) gmodel.set_param_hint('sp', value=0.01, min=0.001, max=0.1) gmodel.set_param_hint('bl', value=1e-6) pars = gmodel.make_params() return gmodel.fit(y, pars, t=t, weights=wt)
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 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 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_routine_first_order(freq, spec): mymodel = Model(first_order) params = mymodel.make_params(a=-2, m=-1.2e-2) result = mymodel.fit(spec, params, x=freq) chi2 = result.chisqr red_chi2 = result.redchi a = result.best_values['a'] m = result.best_values['m'] return a, m, chi2, red_chi2
def plotfile(): #------------------------------------------------------------------------------------------------------------------ # This function plots magnetization and spin current data #------------------------------------------------------------------------------------------------------------------ #------------------------------------------------------------------------------------------------------------------ # parameters #------------------------------------------------------------------------------------------------------------------ timestep = 100000 # number of steps #------------------------------------------------------------------------------------------------------------------ # reading the input files of the simulation: Spin_STM-File, NN-table, DMI-vector #------------------------------------------------------------------------------------------------------------------ job = "mag.dat" infile = open(job, "r") #------------------------------------------------------------------------------------------------------------------------------ # defining output arrays #-------------------------------------------------------------------------------------------------------------------------- magx_array = [] magy_array = [] magz_array = [] time_array = [] #-------------------------------------------------------------------------------------------------------------------------------- # reading and extracting the input file #----------------------------------------------------------------------------------------------------------------------------------- for index, line in enumerate(infile): current_line = line.split() time_array.append(int(current_line[0])) magx_array.append(float(current_line[1])) magy_array.append(float(current_line[2])) magz_array.append(float(current_line[3])) #-------------------------------------------------------------------------------------------------------------------------------- # fit of the data #----------------------------------------------------------------------------------------------------------------------------------- def mag(x, a): return a + 0 * x gmodel = Model(mag) result = gmodel.fit(magx_array, x=time_array, a=0.5) params = gmodel.make_params() print(result.fit_report()) #--------------------------------------------------------------------------------------------------------------------------- #creating the plots #-------------------------------------------------------------------------------------------------------------------------- pp = PdfPages('mag_0.5.pdf') plt.plot(time_array, magx_array, label='m_x') plt.plot(time_array, result.best_fit, label='Fit') plt.xlabel('time') plt.ylabel('magnetization comp.') plt.savefig(pp, format='pdf') pp.close() plt.legend() plt.show()
def fit_model(t, y, jj, zjj, meanz, stdd): gmodel = Model(gaus1) gmodel.set_param_hint('a', value=zjj, min=0.8*zjj, max=1.2*zjj) gmodel.set_param_hint('b', value=jj, min=jj-2, max=jj+2) gmodel.set_param_hint('w', value=1.2, min=0.1, max=20) gmodel.set_param_hint('y0', value=meanz, min=meanz - stdd/2, max=meanz + stdd/2) pars = gmodel.make_params() return gmodel.fit(y, pars, t=t)
def fit_gaussian_peak(w, f, amp_hint=-0.5, cen_hint=None, wid_hint=0.01, shift_hint=0.8, minmax='min'): """Fit a single Gaussian to a spectrum line. Gaussian G(x)=shift+amp*e^(-(x-cen)^2/(2*wid^2)) Uses lmfit package. Parameters ---------- w, f : 1d arrays Spectrum range where the minimum is located. amp_hint : float Amplitude value to be used as 1st guess when performing the fit. cen_hint : float Wavelength of the minimum location, to be used as 1st guess when fitting. If None, the mean value of `w` is used. wid_hint : float shift_hint : float minmax = str Specifies if the peak to be fitted is a minimum or a maximum, to know if the gaussian amplitude parameter `amp` must be negative or positive, respectively. Default: 'min'. Returns ------- lmfit results object """ def gaussian(x, amp=1, cen=0, wid=1, shift=0): return shift + amp * np.exp(-(x - cen)**2 / (2 * wid**2)) # Fit model and parameters mod = Model(gaussian) # Amplitude `amp` if minmax == 'min': mod.set_param_hint('amp', value=amp_hint, max=0.) elif minmax == 'max': mod.set_param_hint('amp', value=amp_hint, min=0.) # Center `cen` if cen_hint is None: cen_hint = np.mean(w) mod.set_param_hint('cen', value=cen_hint) # Width `wid` mod.set_param_hint('wid', value=wid_hint, min=0.) # Shift in the y-axis `shift` mod.set_param_hint('shift', value=shift_hint) # mod.set_param_hint('fwhm', expr='2.35482004503*wid') # mod.set_param_hint('height', expr='shift+amp') gfitparams = mod.make_params() # Fit lmfitresult = Model(gaussian).fit(f, x=w, params=gfitparams) return lmfitresult
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 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_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_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 tau_fitter(data,nbins, verbose=True): profile_peak = np.max(data) binpeak = np.argmax(data) modelname = GxETrain model = Model(modelname) model.set_param_hint('nbins', value=nbins, vary=False) model.set_param_hint('sigma', value=15, vary=True, min =0, max = nbins) model.set_param_hint('mu', value=binpeak, vary=True, min=0, max = nbins) model.set_param_hint('A',value=profile_peak, vary=True, min=0) model.set_param_hint('tau',value=200, vary=True, min=0) model.set_param_hint('dc',value = 0, vary = True) pars = model.make_params() xax=np.linspace(1,nbins,nbins) #"""Fit data""" result = model.fit(data,pars,x=xax) if verbose == True: print(result.fit_report(show_correl = True)) else: print "To see fit report, use verbose=True" noiselessmodel = result.best_fit besttau = result.best_values['tau'] taustd = result.params['tau'].stderr ##estimated 1 sigma error if taustd == None: taustd = 0 bestsig = result.best_values['sigma'] bestmu = result.best_values['mu'] bestA = result.best_values['A'] bestdc = result.best_values['dc'] bestsig_std = result.params['sigma'].stderr bestmu_std = result.params['mu'].stderr bestA_std = result.params['A'].stderr bestdc_std = result.params['dc'].stderr bestparams = np.array([bestsig,bestmu,bestA,bestdc]) bestparams_std = np.array([bestsig_std,bestmu_std,bestA_std,bestdc_std]) """correlations with sigma""" corsig = result.params['sigma'].correl #corA = result.params['A'].correl #corlist = [corsig,corA] rchi = result.redchi #return best values and std errors on the other parameters as well return result, noiselessmodel, besttau, taustd, bestparams, bestparams_std, rchi, corsig
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 tau_1D_fitter(data,nbins): profile_peak = np.max(data) binpeak = np.argmax(data) modelname = GxETrain1D model = Model(modelname) model.set_param_hint('nbins', value=nbins, vary=False) model.set_param_hint('sigma', value=15, vary=True, min =0, max = nbins) model.set_param_hint('mu', value=binpeak, vary=True, min=0, max = nbins) model.set_param_hint('A',value=profile_peak, vary=True,min=0) model.set_param_hint('tau1',value=200, vary=True, min=0) # model.set_param_hint('tau1',value=166.792877, vary=False) model.set_param_hint('dc',value = 0, vary = True) pars = model.make_params() result = model.fit(data,pars,x=np.linspace(1,nbins,nbins)) # print(result.fit_report(show_correl = False)) noiselessmodel = result.best_fit besttau = result.best_values['tau1'] taustd = result.params['tau1'].stderr ##estimated 1 sigma error if taustd == None: taustd = 0 bestsig = result.best_values['sigma'] bestmu = result.best_values['mu'] bestA = result.best_values['A'] bestdc = result.best_values['dc'] bestsig_std = result.params['sigma'].stderr bestmu_std = result.params['mu'].stderr bestA_std = result.params['A'].stderr bestdc_std = result.params['dc'].stderr bestparams = np.array([bestsig,bestmu,bestA,bestdc]) bestparams_std = np.array([bestsig_std,bestmu_std,bestA_std,bestdc_std]) """correlations with sigma""" corsig = result.params['sigma'].correl #corA = result.params['A'].correl #corlist = [corsig,corA] rchi = result.redchi return result, noiselessmodel, besttau, taustd, bestparams, bestparams_std, rchi, corsig
def GaussManual(signal, guess): """ Fits high contrast data very well """ amp, centre, stdev, offset = guess data = np.array([range(len(signal)), signal]).T X = data[:,0] Y = data[:,1] gauss_mod = Model(gaussian) pars = gauss_mod.make_params(center=centre, sigma=stdev, amplitude=amp, offset=offset) pars['center'].vary = False pars['sigma'].min = stdev pars['sigma'].max = stdev + 5. mod = gauss_mod result = mod.fit(Y, pars, x=X) fwhm = result.best_values['sigma'] * 2.3548 return X, result.best_fit, result.best_values['sigma'] * 4
def fitPeak(im, x0, y0, subSize=10, init_params={'amp': 10, 'x0': 10, 'y0': 10, 'sigma_x': 1.0, 'sigma_y': 1.0}): subImage = im[y0 - subSize:y0 + subSize, x0 - subSize:x0 + subSize] peakModel = Model(gaussian2d, independent_vars=['x', 'y']) x, y = np.meshgrid(range(2 * subSize), range(2 * subSize)) p = peakModel.make_params(amp=init_params['amp'], x0=init_params['x0'], y0=init_params['y0'], sigma_x=init_params['sigma_x'], sigma_y=init_params['sigma_y']) result = peakModel.fit(subImage, x=x, y=y, params=p, method='powell') return (result.values['x0'] + x0 - subSize, result.values['y0'] + y0 - subSize)
def GaussStepConst(signal, guess): """ Fits high contrast data very well """ if guess == False: return [0, 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') gauss_mod.set_param_hint('width', value = stdev / 2., min=stdev / 3., max=stdev) gauss_mod.set_param_hint('fwhm', expr='2.3548*width') pars = gauss_mod.make_params(height=amp, center=centre, width=stdev / 2., offset=offset) pars += step_mod.guess(Y, x=X, center=centre) pars += const_mod.guess(Y, x=X) pars['width'].vary = False mod = const_mod + gauss_mod + step_mod result = mod.fit(Y, pars, x=X) # write error report #print result.fit_report() fwhm = result.best_values['width'] * 2.3548 return X, result.best_fit, result.redchi, fwhm
def tau_fitter(data,nbins): profile_peak = np.max(data) binpeak = np.argmax(data) modelname = GxETrain model = Model(modelname) model.set_param_hint('nbins', value=nbins, vary=False) model.set_param_hint('sigma', value=15, vary=True, min =0, max = nbins) model.set_param_hint('mu', value=binpeak, vary=True, min=0, max = nbins) model.set_param_hint('A',value=profile_peak, vary=True) model.set_param_hint('tau',value=200, vary=True, min=0) model.set_param_hint('dc',value = 0, vary = True) pars = model.make_params() #"""Fit data""" result = model.fit(data,pars,x=np.linspace(1,nbins,nbins)) # print(result.fit_report(show_correl = False)) noiselessmodel = result.best_fit besttau = result.best_values['tau'] taustd = result.params['tau'].stderr ##estimated 1 sigma error return noiselessmodel, besttau, taustd
def main(spec, output, plot): """ """ dD = 3 # 3 km/s Doppler FWHM for the lines data = np.loadtxt(spec) x = data[:,0] y = data[:,1] w = data[:,2] # Catch NaNs and invalid values: mask_x = np.ma.masked_equal(x, -9999).mask mask_y = np.isnan(y) mask = np.array(reduce(np.logical_or, [mask_x, mask_y])) mx = x[~mask] my = y[~mask] mw = w[~mask] # Create the model and set the parameters mod1 = Model(Voigt, prefix='V1_') pars = mod1.make_params() mod2 = Model(Voigt, prefix='V2_') pars += mod2.make_params() mod = mod1 + mod2 # Edit the model parameter starting values, conditions, etc... # Background parameters pars['V1_a'].set(value=0, expr='', vary=False) pars['V1_b'].set(value=0, expr='', vary=False) pars['V2_a'].set(value=0, expr='', vary=False) pars['V2_b'].set(value=0, expr='', vary=False) # Line center pars['V1_nu_0'].set(value=-47., vary=True, min=-50, max=-44) pars['V2_nu_0'].set(value=-38., vary=True, min=-40, max=-36) # Line area pars['V1_A'].set(value=-1e-2, max=-1e-8) pars['V2_A'].set(value=-1e-2, max=-1e-8) # Line width pars['V1_alphaD'].set(value=dD, vary=False) pars['V2_alphaD'].set(value=dD, vary=False) pars['V1_alphaL'].set(value=1, vary=True, min=0) pars['V2_alphaL'].set(value=1, vary=True, min=0) # Fit the model using a weight #print len(my), len(mx) modx = np.array([mx, mx, mx]) try: fit = mod.fit(my, pars, nu=mx, weights=mw) fit1 = Voigt(mx, fit.params['V1_alphaD'].value, fit.params['V1_alphaL'].value, fit.params['V1_nu_0'].value, fit.params['V1_A'].value, fit.params['V1_a'].value, 0) fit2 = Voigt(mx, fit.params['V2_alphaD'].value, fit.params['V2_alphaL'].value, fit.params['V2_nu_0'].value, fit.params['V2_A'].value, 0, 0) fit3 = fit.best_fit mody = np.array([fit1, fit2, fit3]) bfit = fit.best_fit except TypeError: bfit = np.zeros(mx.shape) mody = np.zeros(modx.shape) #fit1 = Voigt(mx, fit.params['V1_alphaD'].value, fit.params['V1_alphaL'].value, #fit.params['V1_nu_0'].value, fit.params['V1_A'].value, fit.params['V1_a'].value, 0) #fit2 = Voigt(mx, fit.params['V2_alphaD'].value, fit.params['V2_alphaL'].value, #fit.params['V2_nu_0'].value, fit.params['V2_A'].value, 0, 0) #fit3 = fit.best_fit #mody = np.array([fit1, fit2, fit3]) #modx = np.array([mx, mx, mx]) if len(mx) == 0: mx = np.zeros(10) my = np.zeros(10) bfit = np.zeros(10) modx = np.array([mx, mx, mx]) mody = np.zeros(modx.shape) crrls.plot_model(mx, my, modx, mody, plot) np.savetxt(output, np.c_[mx, bfit])
def main(spec, output, plot): """ """ dD = 3 # 3 km/s Doppler FWHM for the lines data = np.loadtxt(spec) x = data[:,0] y = data[:,1] w = data[:,2] # Catch NaNs and invalid values: mask_x = np.ma.masked_equal(x, -9999).mask mask_y = np.isnan(y) mask = np.array(reduce(np.logical_or, [mask_x, mask_y])) mx = x[~mask] my = y[~mask] mw = w[~mask] # Create the model and set the parameters mod1 = Model(Voigt, prefix='V1_') pars = mod1.make_params() #mod2 = Model(Voigt, prefix='V2_') #pars += mod2.make_params() mod = mod1 #+ mod2 # Edit the model parameter starting values, conditions, etc... # Background parameters pars['V1_a'].set(value=0, expr='', vary=False) pars['V1_b'].set(value=0, expr='', vary=False) #pars['V2_a'].set(value=0, expr='', vary=False) #pars['V2_b'].set(value=0, expr='', vary=False) # Line center pars['V1_nu_0'].set(value=-47., vary=True, min=-50, max=-45) #pars['V2_nu_0'].set(value=-37.6, expr='V1_nu_0+9.4', vary=False) # Line area pars['V1_A'].set(value=-1e-2, max=-1e-8) #pars['V2_A'].set(value=-1e-2, max=-1e-8) # Line width pars['V1_alphaD'].set(value=dD, vary=True, min=0.) #pars['V2_alphaD'].set(value=dD, vary=True, min=0.) pars['V1_alphaL'].set(value=1, vary=True, min=0, max=250.) #pars['V2_alphaL'].set(value=1, vary=True, min=0, max=250.) # Fit the model using a weight fit = mod.fit(my, pars, nu=mx, weights=mw) fit1 = Voigt(mx, fit.params['V1_alphaD'].value, fit.params['V1_alphaL'].value, fit.params['V1_nu_0'].value, fit.params['V1_A'].value, fit.params['V1_a'].value, 0) #fit2 = Voigt(mx, fit.params['V2_alphaD'].value, fit.params['V2_alphaL'].value, #fit.params['V2_nu_0'].value, fit.params['V2_A'].value, 0, 0) fit3 = fit.best_fit #mody = np.array([fit1, fit2, fit3]) mody = np.array([fit1, fit3]) #modx = np.array([mx, mx, mx]) modx = np.array([mx, mx]) # Disable for now, and check this: http://stackoverflow.com/questions/4931376/generating-matplotlib-graphs-without-a-running-x-server # fir a possible fix. crrls.plot_model(mx, my, modx, mody, plot) np.savetxt(output, np.c_[mx, fit.best_fit])
# k1 = 1.501169e-01 # 待求参数 # k2 = 1.209591e-01 # 待求参数 # k3 = 9.115386e-01 # 待求参数 # k4 = -7.802862e-01 # 待求参数 # k5 = 1.938117e+00 # 待求参数 # k6 = 9.155105e-02 if __name__ == '__main__': x = np.linspace(1, 200, 200) # y = 10*cos(x) + sin(x)+exp(-2)*sin(x) y = - 1/2*sin(x+2)+1 mod = Model(my_sin) + Model(my_damping) pars = mod.make_params(w1=6.3367e-09, k=-6.8788e+05, w2=-0.00114982, a=0.09950371, b=1.00498756, c=2, m=0, n=10) pars['a'].set(min=0.01, max=0.9999) result = mod.fit(y, pars, x=x) print(result.fit_report()) fig = plt.figure(figsize=(20, 10)) initial, = plt.plot(x, y, 'bo-') # plt.plot(x, result.init_fit, 'k--') best_fit, = plt.plot(x, result.best_fit, 'r*-') plt.legend(handles=[initial, best_fit, ], labels=['initial', 'best_fit'], loc='best') plt.show()
from lmfit import Model data = loadtxt('model1d_gauss.dat') x = data[:, 0] y = data[:, 1] + 0.25*x - 1.0 def gaussian(x, amp, cen, wid): """1-d gaussian: gaussian(x, amp, cen, wid)""" return (amp / (sqrt(2*pi) * wid)) * exp(-(x-cen)**2 / (2*wid**2)) def line(x, slope, intercept): """a line""" return slope*x + intercept mod = Model(gaussian) + Model(line) pars = mod.make_params(amp=5, cen=5, wid=1, slope=0, intercept=1) result = mod.fit(y, pars, x=x) print(result.fit_report()) plt.plot(x, y, 'bo') plt.plot(x, result.init_fit, 'k--') plt.plot(x, result.best_fit, 'r-') plt.show() # <end examples/doc_model_two_components.py>
w50min = float((0.3/100)*P) w50max = float((3.0/100)*P) smin = w50min/(2*np.sqrt(2*np.log(2))) smax = w50max/(2*np.sqrt(2*np.log(2))) modelname = GxETrain model = Model(modelname) model.set_param_hint('sigma', value=s, vary=True, min=smin, max=smax) model.set_param_hint('mu', value=m, vary=True) model.set_param_hint('A',value=1.5, vary=True, min=0) model.set_param_hint('tau',value=200, vary=True, min=0) pars = model.make_params() #print model.param_hints #modelname2 = GxESingleFold #model2 = Model(modelname2) # #model2.set_param_hint('sigma', value=s, vary=True, min=smin, max=smax) #model2.set_param_hint('mu', value=m, vary=True) #model2.set_param_hint('A',value=1.5, vary=True, min=0) #model2.set_param_hint('tau',value=200, vary=True, min=0) #pars2 = model2.make_params() ##print model2.param_hints # #modelname3 = GxFE #model3 = Model(modelname3) #
def fit_data(x, y, peak_pos, peak_type='LO', max_width=None, bg_ord=2): """ Builds a lmfit model of peaks in listed by index in `peak_pos` Uses some basic algorithms to determine initial parameters for amplitude and fwhm (limit on fwhm to avoid fitting background as peaks) 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 ------- pars : model parameters model : model object """ # need to define peak width finding pw = guess_peak_width(x, y) peak_guess = x[peak_pos] # 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 lorentizian peak for all peaks for i, peak in enumerate(peak_guess): temp_model = Model(peak_function, prefix='p%s_' % i) pars.update(temp_model.make_params()) model += temp_model # set inital 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 for i, peak in enumerate(peak_pos): # could set bounds #, min=x[peak]-5, max=x[peak]+5) pars['p%s_x0' % i].set(x[peak]) pars['p%s_fwhm' % i].set(pw / 2, min=pw * 0.25, max=pw * 2) # here as well #, min=0, max=2*max(y)) pars['p%s_amp' % i].set(y[peak]) out = model.fit(y, pars, x=x) return out
def fitexps(self, x, y, amp=5): dexpmodel = Model(doubleexp, independent_vars=['x']) params = dexpmodel.make_params(amp=amp, C0=5, C1=1, tau0=5, tau1=0.5) print ('Params: ', [p for p in params.values()]) self.fitresult = dexpmodel.fit(y, params, x=x)
for x in range(len(retractZ)): if (retractZ[x] - x_shift) < 0: originPt = x break # Fit WLC model to rupture separation = (retractZ - (retractD - y_shift) - x_shift) skipPLT5 = True gmod = Model(WLCmodel) gmod.set_param_hint('L_C', value = -60.0) gmod.set_param_hint('L_P', value = -0.38, min=-0.42, max=-0.34) gmod.set_param_hint('a', value = 0.0, min=-10.0, max=10.0) gmod.set_param_hint('b', value = 0.0, min=-10.0, max=10.0) params = gmod.make_params() try: result = gmod.fit(smooth25[originPt:ruptureI], x=separation[originPt:ruptureI]) # method='cobyla' except Exception: skipPLT5 = False sys.exc_clear() if skipPLT5: x_off = result.params['a'].value y_off = result.params['b'].value WLC_P = result.params['L_P'].value WLC_L0 = result.params['L_C'].value else: x_off = 0.0 y_off = 0.0 WLC_P = 0.0 WLC_L0 = 0.0
def build_model(self, peak_type='LO', max_width=None, bg_ord=2): """ Builds a lmfit model of peaks in listed by index in `peak_pos` Uses some basic algorithms to determine initial parameters for amplitude and fwhm (limit on fwhm to avoid fitting background as peaks) Parameters ---------- peak_type : string (default='lorentizian') Peaks can be of the following types: - 'LO' : symmetric lorentzian - 'GA' : symmetric gaussain 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 ------- pars : model parameters model : model object """ x = self.x y = self.y pw = self.test_peak_width peak_guess = self.x[self.peak_pos] print("Building model ... ") # start with polynomial background # second order model = PolynomialModel(bg_ord, prefix='bg_') pars = model.make_params() if peak_type == 'LO': peak_function = lorentzian self.afactor = pi self.wfactor = 2.0 elif peak_type == 'GA': peak_function = gaussian self.afactor = sqrt(2 * pi) self.wfactor = 2.354820 elif peak_type == 'VO': peak_function = voigt self.afactor = sqrt(2 * pi) self.wfactor = 3.60131 # add lorentizian peak for all peaks for i, peak in enumerate(peak_guess): temp_model = Model(peak_function, prefix='p%s_' % i) pars.update(temp_model.make_params()) model += temp_model # set inital 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 for i, peak in enumerate(self.peak_pos): print('Peak %i: pos %s, height %s' % (i, x[peak], y[peak])) # could set bounds #, min=x[peak]-5, max=x[peak]+5) pars['p%s_center' % i].set(x[peak]) pars['p%s_sigma' % i].set(pw / 2, min=pw * 0.25, max=pw * 2) # here as well #, min=0, max=2*max(y)) pars['p%s_amplitude' % i].set(self.amplitude(y[peak], (pw / 2))) self.pars = pars self.model = model return self.pars, self.model
tau.append(data[:,1]) wei.append(data[:,2]) nnow = int(re.findall('\d+', stack)[0]) n.append(nnow) dn = fc.set_dn(trans) specie, trans, nn, freq = fc.make_line_list('CI', 1500, dn) nii = crrls.best_match_indx2(n[i], nn) f0.append(freq[nii]) tmin = min(tau[i]) weight = np.power(wei[i], 2) v1 = Model(crrls.Voigt, prefix='v0_') pars3 = v1.make_params() mod3 = v1 pars3['v0_gamma'].set(value=0.1, vary=True, expr='', min=0.0) pars3['v0_center'].set(value=-47., vary=True, max=-30, min=-49) pars3['v0_amplitude'].set(value=-0.1, vary=True, max=-1e-8) pars3['v0_sigma'].set(value=dD_fix0, vary=False) fit3.append(mod3.fit(tau[i], pars3, x=vel[i], weights=weight)) # Plot things res3.append(tau[i] - fit3[i].best_fit) voigt0 = crrls.Voigt(vel[i], fit3[i].params['v0_sigma'].value, fit3[i].params['v0_gamma'].value,