Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
pfit = Parameters()
pfit.add(name='amp_g', value=10)
pfit.add(name='cen_g', value=9)
pfit.add(name='wid_g', value=1)
pfit.add(name='amp_tot', value=20)
pfit.add(name='amp_l', expr='amp_tot - amp_g')
pfit.add(name='cen_l', expr='1.5+cen_g')
pfit.add(name='wid_l', expr='2*wid_g')
pfit.add(name='line_slope', value=0.0)
pfit.add(name='line_off', value=0.0)
sigma = 0.021 # estimate of data error (for all data points)
myfit = Minimizer(residual, pfit,
fcn_args=(x,), fcn_kws={'sigma':sigma, 'data':data},
scale_covar=True)
myfit.prepare_fit()
init = residual(myfit.params, x)
result = myfit.leastsq()
print(' Nfev = ', result.nfev)
print( result.chisqr, result.redchi, result.nfree)
report_fit(result.params, min_correl=0.3)
fit = residual(result.params, x)
assert(result.params['cen_l'].value == 1.5 + result.params['cen_g'].value)
assert(result.params['amp_l'].value == result.params['amp_tot'].value - result.params['amp_g'].value)
'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 output_values(param1, iteration, residual):
report_fit(param1)
def test_numdifftools_with_bounds(fit_method):
pytest.importorskip("numdifftools")
if fit_method in ['shgo', 'dual_annealing']:
pytest.importorskip("scipy", minversion="1.2")
# load data to be fitted
data = np.loadtxt(os.path.join(os.path.dirname(__file__), '..', 'examples',
'test_peak.dat'))
x = data[:, 0]
y = data[:, 1]
# define the model and initialize parameters
mod = VoigtModel()
params = mod.guess(y, x=x)
params['amplitude'].set(min=25, max=70)
params['sigma'].set(max=1)
params['center'].set(min=5, max=15)
# do fit, here with leastsq model
result = mod.fit(y, params, x=x, method='leastsq')
result_ndt = mod.fit(y, params, x=x, method=fit_method)
# assert that fit converged to the same result
vals = [result.params[p].value for p in result.params.valuesdict()]
vals_ndt = [result_ndt.params[p].value for p in result_ndt.params.valuesdict()]
assert_allclose(vals_ndt, vals, rtol=0.1)
assert_allclose(result_ndt.chisqr, result.chisqr, rtol=1e-5)
def test_saveload_usersyms():
"""Test save/load of modelresult with non-trivial user symbols,
this example uses a VoigtModel, wheree `wofz()` is used in a
constraint expression"""
x = np.linspace(0, 20, 501)
y = gaussian(x, 1.1, 8.5, 2) + lorentzian(x, 1.7, 8.5, 1.5)
np.random.seed(20)
y = y + np.random.normal(size=len(x), scale=0.025)
model = VoigtModel()
pars = model.guess(y, x=x)
result = model.fit(y, pars, x=x)
savefile = 'tmpvoigt_modelresult.sav'
save_modelresult(result, savefile)
assert_param_between(result.params['sigma'], 0.7, 2.1)
assert_param_between(result.params['center'], 8.4, 8.6)
assert_param_between(result.params['height'], 0.2, 1.0)
time.sleep(0.25)
result2 = load_modelresult(savefile)
assert_param_between(result2.params['sigma'], 0.7, 2.1)
assert_param_between(result2.params['center'], 8.4, 8.6)
assert_param_between(result2.params['height'], 0.2, 1.0)
def test_least_squares_cov_x(peakdata, bounds):
"""Test calculation of cov. matrix from Jacobian, with/without bounds."""
x = peakdata[0]
y = peakdata[1]
# define the model and initialize parameters
mod = VoigtModel()
params = mod.guess(y, x=x)
if bounds:
params['amplitude'].set(min=25, max=70)
params['sigma'].set(min=0, max=1)
params['center'].set(min=5, max=15)
else:
params['sigma'].set(min=-np.inf)
# do fit with least_squares and leastsq algorithm
result = mod.fit(y, params, x=x, method='least_squares')
result_lsq = mod.fit(y, params, x=x, method='leastsq')
# assert that fit converged to the same result
vals = [result.params[p].value for p in result.params.valuesdict()]
vals_lsq = [result_lsq.params[p].value for p in
def test_bounds_expression():
# load data to be fitted
data = np.loadtxt(os.path.join(os.path.dirname(__file__), '..', 'examples',
'test_peak.dat'))
x = data[:, 0]
y = data[:, 1]
# define the model and initialize parameters
mod = VoigtModel()
params = mod.guess(y, x=x)
params['amplitude'].set(min=0, max=100)
params['center'].set(min=5, max=10)
# do fit, here with leastsq model
result = mod.fit(y, params, x=x)
# assert that stderr and correlations are correct [cf. lmfit v0.9.10]
assert_almost_equal(result.params['sigma'].stderr, 0.00368468, decimal=6)
assert_almost_equal(result.params['center'].stderr, 0.00505496, decimal=6)
assert_almost_equal(result.params['amplitude'].stderr, 0.13861506,
decimal=6)
assert_almost_equal(result.params['gamma'].stderr, 0.00368468, decimal=6)
assert_almost_equal(result.params['fwhm'].stderr, 0.00806917, decimal=6)
assert_almost_equal(result.params['height'].stderr, 0.03009459, decimal=6)
def test_save_load_modelresult(dill):
"""Save/load ModelResult with/without dill."""
if dill:
pytest.importorskip("dill")
else:
lmfit.jsonutils.HAS_DILL = False
# create model, perform fit, save ModelResult and perform some tests
model, params = create_model_params(x, y)
result = model.fit(y, params, x=x)
save_modelresult(result, SAVE_MODELRESULT)
file_exists = wait_for_file(SAVE_MODELRESULT, timeout=10)
assert file_exists
text = ''
with open(SAVE_MODELRESULT, 'r') as fh:
text = fh.read()
assert_between(len(text), 8000, 25000)
# load the saved ModelResult from file and compare results
result_saved = load_modelresult(SAVE_MODELRESULT)
check_fit_results(result_saved)
clear_savefile(SAVE_MODEL)
def test_composite_with_expression(self):
expression_model = models.ExpressionModel("exp(-x/x0)", name='exp')
amp_model = models.ConstantModel(prefix='amp_')
off_model = models.ConstantModel(prefix='off_', name="off")
comp_model = off_model + amp_model * expression_model
x = self.x
true_values = self.true_values()
data = comp_model.eval(x=x, **true_values) + self.noise
# data = 0.25 + 1 * np.exp(-x / 2.)
params = comp_model.make_params(**self.guess())
result = comp_model.fit(data, x=x, params=params)
assert_results_close(result.values, true_values, rtol=0.01, atol=0.01)
data_components = comp_model.eval_components(x=x)
self.assertIn('exp', data_components)
def test_user_defined_gaussian_plus_constant(self):
data = self.data + 5.0
model = self.model + models.ConstantModel()
guess = self.guess()
pars = model.make_params(c=10.1, **guess)
true_values = self.true_values()
true_values['c'] = 5.0
result = model.fit(data, pars, x=self.x)
assert_results_close(result.values, true_values, rtol=0.01, atol=0.01)