def test_model_nan_policy(self): x = np.linspace(0, 10, 201) np.random.seed(0) y = gaussian(x, 10.0, 6.15, 0.8) y += gaussian(x, 8.0, 6.35, 1.1) y += gaussian(x, 0.25, 6.00, 7.5) y += np.random.normal(size=len(x), scale=0.5) y[55] = y[91] = np.nan mod = PseudoVoigtModel() params = mod.make_params(amplitude=20, center=5.5, sigma=1, fraction=0.25) params['fraction'].vary = False # with raise, should get a ValueError result = lambda: mod.fit(y, params, x=x, nan_policy='raise') self.assertRaises(ValueError, result) # with propagate, should get no error, but bad results result = mod.fit(y, params, x=x, nan_policy='propagate') self.assertTrue(result.success) self.assertTrue(np.isnan(result.chisqr)) self.assertTrue(np.isnan(result.aic)) self.assertFalse(result.errorbars) self.assertTrue(result.params['amplitude'].stderr is None) self.assertTrue(abs(result.params['amplitude'].value - 20.0) < 0.001) # with omit, should get good results result = mod.fit(y, params, x=x, nan_policy='omit') self.assertTrue(result.success) self.assertTrue(result.chisqr > 2.0) self.assertTrue(result.aic < -100) self.assertTrue(result.errorbars) self.assertTrue(result.params['amplitude'].stderr > 0.1) self.assertTrue(abs(result.params['amplitude'].value - 20.0) < 5.0) self.assertTrue(abs(result.params['center'].value - 6.0) < 0.5)
def test_model_nan_policy(self): """Tests for nan_policy with NaN values in the input data.""" x = np.linspace(0, 10, 201) np.random.seed(0) y = gaussian(x, 10.0, 6.15, 0.8) y += gaussian(x, 8.0, 6.35, 1.1) y += gaussian(x, 0.25, 6.00, 7.5) y += np.random.normal(size=len(x), scale=0.5) # with NaN values in the input data y[55] = y[91] = np.nan mod = PseudoVoigtModel() params = mod.make_params(amplitude=20, center=5.5, sigma=1, fraction=0.25) params['fraction'].vary = False # with raise, should get a ValueError result = lambda: mod.fit(y, params, x=x, nan_policy='raise') msg = ( 'NaN values detected in your input data or the output of your ' 'objective/model function - fitting algorithms cannot handle this!' ) self.assertRaisesRegex(ValueError, msg, result) # with propagate, should get no error, but bad results result = mod.fit(y, params, x=x, nan_policy='propagate') self.assertTrue(result.success) self.assertTrue(np.isnan(result.chisqr)) self.assertTrue(np.isnan(result.aic)) self.assertFalse(result.errorbars) self.assertTrue(result.params['amplitude'].stderr is None) self.assertTrue(abs(result.params['amplitude'].value - 20.0) < 0.001) # with omit, should get good results result = mod.fit(y, params, x=x, nan_policy='omit') self.assertTrue(result.success) self.assertTrue(result.chisqr > 2.0) self.assertTrue(result.aic < -100) self.assertTrue(result.errorbars) self.assertTrue(result.params['amplitude'].stderr > 0.1) self.assertTrue(abs(result.params['amplitude'].value - 20.0) < 5.0) self.assertTrue(abs(result.params['center'].value - 6.0) < 0.5) # with 'wrong_argument', should get a ValueError err_msg = r"nan_policy must be 'propagate', 'omit', or 'raise'." with pytest.raises(ValueError, match=err_msg): mod.fit(y, params, x=x, nan_policy='wrong_argument')
def calc_center_pseudoVoigt(vx,vy): mod = PseudoVoigtModel() y = vy pars = mod.guess(y, x=vx) out = mod.fit(y, pars, x=vx) center = out.best_values['center'] return center
def voigt(x, y): # Voigt fit to a curve x_shifted = x - x.min() # Shifting to 0 y_shifted = y - y.min() # Shifting to 0 mod = PseudoVoigtModel() # Setting model type pars = mod.guess(y_shifted, x=x_shifted) # Estimating fit out = mod.fit(y_shifted, pars, x=x_shifted) # Fitting fit # print(out.fit_report(min_correl=0.25)) # Outputting best fit results print("Voigt FWHM = ", out.params['fwhm'].value) # Outputting only FWHM out.plot() # Plotting fit
def fit_one_Psudo_Voigt(x_lst,y_lst): ''' Fits one Pseudo Voigt returns the results object ''' mod = PseudoVoigtModel(independent_vars=['x'],nan_policy='raise') x_lst = np.asarray(x_lst) y_lst = np.asarray(y_lst) # Guess good values computer mod.guess(y_lst,x = x_lst) result = mod.fit(y_lst, x = x_lst) return result
def center_psi(file_name): #print(file_name) psi, vx, vy = read_file(file_name) vy = processing_of_data(psi,vx,vy) legenda = file_name.split('/')[-1] #plt.grid() #plt.legend(loc=0) #import pdb; pdb.set_trace() plt.plot(vx,vy,label=legenda) mod = PseudoVoigtModel() y=vy pars = mod.guess(y, x=vx) out = mod.fit(y, pars, x=vx) center =out.best_values['center'] print('center: {} <--> psi: {}'.format(center,psi)) return psi, center
def test_figure_title_using_title_keyword_argument(peakdata): """Test setting figure title using title keyword argument.""" x, y = peakdata pvmodel = PseudoVoigtModel() params = pvmodel.guess(y, x=x) result = pvmodel.fit(y, params, x=x) ax = result.plot_fit(title='test') assert ax.axes.get_title() == 'test' ax = result.plot_residuals(title='test') assert ax.axes.get_title() == 'test' fig, _ = result.plot(title='test') assert fig.axes[0].get_title() == 'test' assert fig.axes[1].get_title() == '' # no title for fit subplot
def test_figure_default_title(peakdata): """Test default figure title.""" x, y = peakdata pvmodel = PseudoVoigtModel() params = pvmodel.guess(y, x=x) result = pvmodel.fit(y, params, x=x) ax = result.plot_fit() assert ax.axes.get_title() == 'Model(pvoigt)' ax = result.plot_residuals() assert ax.axes.get_title() == 'Model(pvoigt)' fig, _ = result.plot() assert fig.axes[0].get_title() == 'Model(pvoigt)' # default model.name assert fig.axes[1].get_title() == '' # no title for fit subplot
def test_priority_setting_figure_title(peakdata): """Test for setting figure title: title keyword argument has priority.""" x, y = peakdata pvmodel = PseudoVoigtModel() params = pvmodel.guess(y, x=x) result = pvmodel.fit(y, params, x=x) ax = result.plot_fit(ax_kws={'title': 'ax_kws'}, title='test') assert ax.axes.get_title() == 'test' ax = result.plot_residuals(ax_kws={'title': 'ax_kws'}, title='test') assert ax.axes.get_title() == 'test' fig, _ = result.plot(ax_res_kws={'title': 'ax_res_kws'}, title='test') assert fig.axes[0].get_title() == 'test' assert fig.axes[1].get_title() == '' fig, _ = result.plot(ax_fit_kws={'title': 'ax_fit_kws'}, title='test') assert fig.axes[0].get_title() == 'test' assert fig.axes[1].get_title() == ''
def test_figure_title_using_title_to_ax_kws(peakdata): """Test setting figure title by supplying ax_{fit,res}_kws.""" x, y = peakdata pvmodel = PseudoVoigtModel() params = pvmodel.guess(y, x=x) result = pvmodel.fit(y, params, x=x) ax = result.plot_fit(ax_kws={'title': 'ax_kws'}) assert ax.axes.get_title() == 'ax_kws' ax = result.plot_residuals(ax_kws={'title': 'ax_kws'}) assert ax.axes.get_title() == 'ax_kws' fig, _ = result.plot(ax_res_kws={'title': 'ax_res_kws'}) assert fig.axes[0].get_title() == 'ax_res_kws' assert fig.axes[1].get_title() == '' fig, _ = result.plot(ax_fit_kws={'title': 'ax_fit_kws'}) assert fig.axes[0].get_title() == 'Model(pvoigt)' # default model.name assert fig.axes[1].get_title() == '' # no title for fit subplot
def fit_voigt(xp: XPS_experiment, region: str, prefix: str = 'v_', pars: list = None, bounds: list = None, ax=None, flag_plot: bool = True): """General method for fitting voigt model Input ---------- xp : class XPS_experiment XPS data region : str core level name pars, bounds : list initial guess of the fit parameters and bounds. If unspecified, guessed automatically Returns ----------- fitv : lmfit.model fit result to Voigt model """ from lmfit.models import PseudoVoigtModel, GaussianModel x = xp.dfx[region].dropna().energy y = xp.dfx[region].dropna().counts mod = PseudoVoigtModel(prefix=prefix) if pars == None: pars = mod.guess(y, x=x) pars[prefix + 'sigma'].set(value=1) # Usually guessed wrong anyway pars[prefix + 'fraction'].set(value=0.2, min=0.15, max=0.20) fitv = mod.fit(y, pars, x=x) xp.fit.update({region: fitv}) if flag_plot: hatchplot_fit(xp, region, fitv, ax=ax, plot_comps=True) return fitv
def fittingPseudoVoigt(x, y): #fits a pseudovoigt curve mod = PseudoVoigtModel() pars = mod.guess(y, x=x) out = mod.fit(y, pars, x=x) print(out.fit_report(min_correl=0.25)) return out.best_fit
# get point-spread function data psf = pu.load_muv_point_spread_function() # set model x and y variables detector_pixels = np.arange(len(psf)) detector_pixel_edges = np.linspace(0, len(psf) - 1, len(psf) + 1) # initialize model model = PseudoVoigtModel() # use model's built-in initial parameters guessing option initial_parameters = model.guess(psf, x=detector_pixels) # fit the model to the point-spread function data result = model.fit(psf, initial_parameters, x=detector_pixels) params = result.params parnames = sorted(params) # make a figure and axes fig, axes = plt.subplots(2, 1, figsize=(5, 4), sharex=True, gridspec_kw={'height_ratios': [4, 1]}, constrained_layout=True) # plot the IUVS data axes[0].step(detector_pixel_edges, np.concatenate((psf, [psf[-1]])), where='post',
def fit_double_voigt(xp: XPS_experiment, region: str, pars: list = None, bounds: list = None, sepPt: float = None, frac: float = None, lb: str = None, ax=None, flag_plot: bool = True, plot_comps: bool = False, DEBUG: bool = False): """Fitting double voigt model Input ---------- xp : class XPS_experiment XPS data region : str core level name pars, bounds : list initial guess of the fit parameters and bounds. If unspecified, guessed automatically sepPt : float separation point in energy between the two peaks. If unspecified guessed automatically flag_plot, DEBUG : bool flags to plot intermediate and final fit results Returns ----------- fitv : lmfit.model fit result to Voigt model """ from lmfit.models import PseudoVoigtModel x = xp.dfx[region].dropna().energy y = xp.dfx[region].dropna().counts if sepPt == None: sepPt = find_separation_point(x, y) x1 = x[x < sepPt].values x2 = x[x > sepPt].values y1 = y[x < sepPt].values y2 = y[x > sepPt].values mod1 = PseudoVoigtModel(prefix='v1_') mod2 = PseudoVoigtModel(prefix='v2_') if pars == None: pars1 = mod1.guess(y1, x=x1) pars1['v1_sigma'].set(value=1) # Usually guessed wrong anyway pars2 = mod2.guess(y2, x=x2) pars2['v2_sigma'].set(value=1) # Usually guessed wrong anyway if frac != None: pars1['v1_fraction'].set(value=frac, vary=False) pars2['v2_fraction'].set(value=frac, vary=False) mod = mod1 + mod2 pars = mod.make_params() pars.update(pars1) pars.update(pars2) if DEBUG: # Fit & plot individual components separately fit1 = mod1.fit(y1, x=x1, params=pars1) fit2 = mod2.fit(y2, x=x2, params=pars2) plot_fit_result(xp, region, fit1) plot_fit_result(xp, region, fit2) fitv = mod.fit(y, pars, x=x) xp.fit.update({region: fitv}) if flag_plot: hatchplot_fit(xp, region, fitv, ax=ax, plot_comps=True) return fitv