Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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_height_fwhm_calculation(peakdata):
"""Test for correctness of height and FWHM calculation."""
# mu = 0
# variance = 1.0
# sigma = np.sqrt(variance)
# x = np.linspace(mu - 20*sigma, mu + 20*sigma, 100.0)
# y = norm.pdf(x, mu, 1)
x = peakdata[0]
y = peakdata[1]
check_height_fwhm(x, y, lineshapes.voigt, models.VoigtModel())
check_height_fwhm(x, y, lineshapes.pvoigt, models.PseudoVoigtModel())
check_height_fwhm(x, y, lineshapes.pearson7, models.Pearson7Model())
check_height_fwhm(x, y, lineshapes.moffat, models.MoffatModel())
check_height_fwhm(x, y, lineshapes.students_t, models.StudentsTModel())
check_height_fwhm(x, y, lineshapes.breit_wigner, models.BreitWignerModel())
check_height_fwhm(x, y, lineshapes.damped_oscillator,
models.DampedOscillatorModel())
check_height_fwhm(x, y, lineshapes.dho,
models.DampedHarmonicOscillatorModel())
check_height_fwhm(x, y, lineshapes.expgaussian,
models.ExponentialGaussianModel())
check_height_fwhm(x, y, lineshapes.skewed_gaussian,
models.SkewedGaussianModel())
check_height_fwhm(x, y, lineshapes.donaich, models.DonaichModel())
x = x-9 # Lognormal will only fit peaks with centers < 1
check_height_fwhm(x, y, lineshapes.lognormal, models.LognormalModel())
def test_param_set():
np.random.seed(2015)
x = np.arange(0, 20, 0.05)
y = gaussian(x, amplitude=15.43, center=4.5, sigma=2.13)
y = y + 0.05 - 0.01*x + np.random.normal(scale=0.03, size=len(x))
model = VoigtModel()
params = model.guess(y, x=x)
# test #1: gamma is constrained to equal sigma
assert(params['gamma'].expr == 'sigma')
params.update_constraints()
sigval = params['sigma'].value
assert_allclose(params['gamma'].value, sigval, 1e-4, 1e-4, '', True)
# test #2: explicitly setting a param value should work, even when
# it had been an expression. The value will be left as fixed
gamval = 0.87543
params['gamma'].set(value=gamval)
assert(params['gamma'].expr is None)
assert(not params['gamma'].vary)
assert_allclose(params['gamma'].value, gamval, 1e-4, 1e-4, '', True)
def test_height_and_fwhm_expression_evalution_in_builtin_models():
"""Assert models do not throw an ZeroDivisionError."""
mod = models.GaussianModel()
params = mod.make_params(amplitude=1.0, center=0.0, sigma=0.9)
params.update_constraints()
mod = models.LorentzianModel()
params = mod.make_params(amplitude=1.0, center=0.0, sigma=0.9)
params.update_constraints()
mod = models.SplitLorentzianModel()
params = mod.make_params(amplitude=1.0, center=0.0, sigma=0.9, sigma_r=1.0)
params.update_constraints()
mod = models.VoigtModel()
params = mod.make_params(amplitude=1.0, center=0.0, sigma=0.9, gamma=1.0)
params.update_constraints()
mod = models.PseudoVoigtModel()
params = mod.make_params(amplitude=1.0, center=0.0, sigma=0.9, fraction=0.5)
params.update_constraints()
mod = models.MoffatModel()
params = mod.make_params(amplitude=1.0, center=0.0, sigma=0.9, beta=0.0)
params.update_constraints()
mod = models.Pearson7Model()
params = mod.make_params(amplitude=1.0, center=0.0, sigma=0.9, expon=1.0)
params.update_constraints()
mod = models.StudentsTModel()
assert_allclose(pars['g_sigma'].value, 1.3, rtol=1)
mod = models.LorentzianModel(prefix='l_')
pars = mod.guess(y, x=x)
assert_allclose(pars['l_amplitude'].value, 3, rtol=2)
assert_allclose(pars['l_center'].value, 0.25, rtol=1)
assert_allclose(pars['l_sigma'].value, 1.3, rtol=1)
mod = models.SplitLorentzianModel(prefix='s_')
pars = mod.guess(y, x=x)
assert_allclose(pars['s_amplitude'].value, 3, rtol=2)
assert_allclose(pars['s_center'].value, 0.25, rtol=1)
assert_allclose(pars['s_sigma'].value, 1.3, rtol=1)
assert_allclose(pars['s_sigma_r'].value, 1.3, rtol=1)
mod = models.VoigtModel(prefix='l_')
pars = mod.guess(y, x=x)
assert_allclose(pars['l_amplitude'].value, 3, rtol=2)
assert_allclose(pars['l_center'].value, 0.25, rtol=1)
assert_allclose(pars['l_sigma'].value, 1.3, rtol=1)
mod = models.SkewedVoigtModel(prefix='l_')
pars = mod.guess(y, x=x)
assert_allclose(pars['l_amplitude'].value, 3, rtol=2)
assert_allclose(pars['l_center'].value, 0.25, rtol=1)
assert_allclose(pars['l_sigma'].value, 1.3, rtol=1)
# Lorentzian model
mod = LorentzianModel()
pars = mod.guess(y, x=x)
out = mod.fit(y, pars, x=x)
print(out.fit_report(min_correl=0.25))
plt.figure()
plt.plot(x, y, 'b-')
plt.plot(x, out.best_fit, 'r-', label='Lorentzian Model')
plt.legend(loc='best')
plt.show()
# Voigt model
mod = VoigtModel()
pars = mod.guess(y, x=x)
out = mod.fit(y, pars, x=x)
print(out.fit_report(min_correl=0.25))
fig, axes = plt.subplots(1, 2, figsize=(12.8, 4.8))
axes[0].plot(x, y, 'b-')
axes[0].plot(x, out.best_fit, 'r-', label='Voigt Model\ngamma constrained')
axes[0].legend(loc='best')
# free gamma parameter
pars['gamma'].set(value=0.7, vary=True, expr='')
out_gamma = mod.fit(y, pars, x=x)
axes[1].plot(x, y, 'b-')
axes[1].plot(x, out_gamma.best_fit, 'r-', label='Voigt Model\ngamma unconstrained')
mod, params = qudi_fitting.make_lorentzian_model()
p=Parameters()
params.add('amplitude',value=30.)
params.add('center',value=920.)
params.add('sigma',value=10)
params.add('c',value=10.)
data_noisy = (mod.eval(x=x_axis, params=params)
+ 0.2*np.random.normal(size=x_axis.shape))
para=Parameters()
# para.add('sigma',value=p['sigma'].value)
# para.add('amplitude',value=p['amplitude'].value)
voigt_mod = models.VoigtModel()
plt.figure()
plt.plot(x_axis, data_noisy, label='measured data')
plt.xlabel('Time micro-s')
plt.ylabel('signal')
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.show()
error, amplitude, x_zero, sigma, offset = qudi_fitting.estimate_lorentzpeak(x_axis, data_noisy)
# data_noisy = data_noisy - data_noisy.min()
# params = voigt_mod.make_params()
params = mod.make_params()