I am using an user-defined model function to fit a dataset with lmfit. However it seems I am not capable of fixing some of the parameters of the function, so they won't be changed during the fitting algo. I already used comments from other threads, as well as the doc and can't see the problem:
import numpy as np
from lmfit import Model
data = np.loadtxt('impedance.txt')
w = data[:, 0]
y1 = data[:, 1]
y2 = data[:, 2]
z = y1/y2
f = w/(2.*np.pi)
#model function to be fitted on
def Ztot(f, RP=1E4, RS=10, C=1E-9, L=10E-3):
return np.abs((1/((1/RP + 1/(complex(0, 1)*2*np.pi*f*L))**(-1) + RS) + complex(0, 1)*2*np.pi*f*C)**(-1))
gmodel = Model(Ztot)
params = gmodel.make_params()
params['RS'].max = 100
params['RS'].min = 0
params['C'].vary = False
print(params)
result = gmodel.fit(z, f=f)
print(result.fit_report())
However when I check the fitting report, the parameters were varied:
[[Variables]]
RP: 75381.4485 (init = 10000)
RS: -2280.34148 (init = 10)
C: 3.6066e-10 (init = 1e-09)
L: 0.06200475 (init = 0.01)
That's of course not what I want. What am I missing?!
Too long for a comment: it is always important to include actual code that you actually ran and really include the full and complete set of results and error messages that you got. The code you posted simply cannot have produced that result.
First, doing params = gmodel.make_params()
will produce parameters without specifying their initial values. As a result, the initial values will be -Inf
, which will almost certainly cause every model evaluation to fail immediately -- you will get an exception, not a workable result. You must always set initial values for all parameters. There are no exceptions.
But that is all sort of beside the point, and your bounds and fixing of your C
parameter is all useless because you do not include params
in your call to gmodel.fit()
.