Note
Click here to download the full example code
Using an ExpressionModelΒΆ
ExpressionModels allow a model to be built from a user-supplied expression. See: https://lmfit.github.io/lmfit-py/builtin_models.html#user-defined-models
import matplotlib.pyplot as plt
import numpy as np
from lmfit.models import ExpressionModel
Generate synthetic data for the user-supplied model:
Define the ExpressionModel and perform the fit:
this results in the following output:
print(result.fit_report())
plt.plot(x, y, 'bo')
plt.plot(x, result.init_fit, 'k--', label='initial fit')
plt.plot(x, result.best_fit, 'r-', label='best fit')
plt.legend(loc='best')
plt.show()

Out:
[[Model]]
Model(_eval)
[[Fit Statistics]]
# fitting method = leastsq
# function evals = 52
# data points = 201
# variables = 3
chi-square = 0.02388884
reduced chi-square = 1.2065e-04
Akaike info crit = -1810.56740
Bayesian info crit = -1800.65749
[[Variables]]
amp: 3.40319891 +/- 0.00566306 (0.17%) (init = 5)
cen: 1.79855794 +/- 9.6053e-04 (0.05%) (init = 5)
wid: 0.49989437 +/- 9.6053e-04 (0.19%) (init = 1)
[[Correlations]] (unreported correlations are < 0.100)
C(amp, wid) = 0.577
Total running time of the script: ( 0 minutes 0.166 seconds)