lmfit / lmfit-py

Non-Linear Least Squares Minimization, with flexible Parameter settings, based on scipy.optimize, and with many additional classes and methods for curve fitting.
https://lmfit.github.io/lmfit-py/
Other
1.05k stars 272 forks source link

ModelResult.fit() does not use provided params #960

Closed Trayder closed 1 month ago

Trayder commented 1 month ago

First Time Issue Code

Yes, I read the instructions and I am sure this is a GitHub Issue.

Description

When using ModelResult.fit() the provided params are not being used as the initial values. In the below example, result_leastsq.params shows that result_brute.params was used as the initial values rather than the params provided. result_leastsq.init_params does report the correct values.

A Minimal, Complete, and Verifiable example
import numpy as np
import lmfit
import copy

x = np.linspace(-10, 10, 100)
y = 3 * x**2 - 2 * x + 1 + np.random.normal(scale=10, size=x.size)

def quadratic(x, a, b, c):
    return a * x**2 + b * x + c

model = lmfit.Model(quadratic)
params = model.make_params(a=dict(value=1, min=-10, max=10),
                           b=dict(value=0, min=-10, max=10),
                           c=dict(value=0, min=-10, max=10),)
result_brute = model.fit(y, params, x=x, method='brute')
result_leastsq = copy.deepcopy(result_brute)
result_leastsq.fit(method='leastsq',params=result_brute.candidates[49].params)
Version information

Python: 3.11.9 (main, Apr 19 2024, 16:48:06) [GCC 11.2.0]

lmfit: 1.3.1, scipy: 1.14.0, numpy: 2.0.0,asteval: 1.0.0, uncertainties: 3.2.1

newville commented 1 month ago

@Trayder I think I see the problem here... or at least "a problem". ModelResult.fit() to re-fit is not using the passed in parameters uniformly as initial values. I think that is probably what you are reporting, and will try to push a fix to that soon.

To be clear, I think that is the problem you were reporting, but you were not specific. In the future and for any such reports, explicitly state what you expected to get and what you actually got. For lmfit, including a fit report is highly recommended.