Let's say that we have a curve that have an n-number of curves that are contributing to its shape. In my basic example, working with NMR peaks, I have 3 peaks defined:
Here, I have used the following method for fitting these three peaks at once:
def lor_3(x, R1, F1, R2, F2, R3, F3):
return (R1) / (R1**2 + 4 * np.pi**2 * (x-F1)**2) +\
(R2) / (R2**2 + 4 * np.pi**2 * (x-F2)**2) +\
(R3) / (R3**2 + 4 * np.pi**2 * (x-F3)**2)
popt, pcov = optimize.curve_fit(lor_3, X, y, p0=[11, 750, 5.5, 800, 11, 850])
Code which works nicely to fit these kind of peaks. However, if I have a more complex case:
Then the situations is not that easy. I would have to define a lot of functions with 1, 2, 3, 6 or whatever peaks contributing to the total curve depending on the case.
Is there any optimal way to perform fit of N - curves with scipy.optimize.curve_fit or with other Python tool?
Thanks!
You can use
lmfit
(see https://lmfit.github.io/lmfit-py/examples/example_expression_model.html).First, let's define a
lor
function (based on yours)and some sample data
Now let's sum up all
lor
curvesLet's suppose this is the curve you actually want to fit.
To fit this curve, we can first find the peaks
and you see that are the
F
s of our distinctlor
functionsFinally, we import
ExpressionModel
fromlmfit
and define a model string based onlor
function and found peakswe can now initialize the model and parameters, that will be only
R
s (because we already haveF
s, the peaks)and fit the curve (where
y
is the curve you want to fit, i.e. the curve you got)Inspect results report
and check the plot