Hi, I need to pass a function (here is fun) to lmfit to do fitting as below:
import lmfit, Model
model = Model(fun, independent_vars=ind)
But function have to be this way because lmfit only works this way:
def fun(explicit names for all the parameters):
return string expression of stdout
My issue is that
the function parameters and the returned expression by fun must be changed dynamically in each iteration so I should be able to write a function that its parameters and returns is changing dynamically.
Even any suggestion on how to write a function from two strings (as parameter and return) would be welcomed.
I need the following function been created:
def fit_function(expr, list_var, list_para, dict_data(key_var,list_data) ) ->list_para:
What I have tried:
In fact based on a list of a string (as function parameter) and the stdout print (as return in fun), I should write the fun for each iteration. The following code shows how running lnfca() which is a sympy, symbolic string needs to be passed in fun for every iteration.
def fun_print(ff):
return print(NumPyPrinter().doprint(ff))
fun_print(lnfca())
import contextlib
import io
captured_output = io.StringIO()
with contextlib.redirect_stdout(captured_output):
fun_print(lnfca())
This way stdout print can be captured, but I have no idea how one can write a function this way(changing parameters and return is really crucial here) Is there any way to do it??
in summer to fit a model using lmfit it should be passed to Model as follows:
def f(x, gamma, alpha, beta, eta):
L = x[0]
K = x[1]
return gamma - (1/eta)*np.log(alpha*L**-eta + beta*K**-eta)
fmodel = Model(f)
params = Parameters()
params.add('gamma', value = 1, vary=True, min = 1)
params.add('alpha', value = 0.01, vary=True, max = 1, min = 0)
params.add('beta', value = 0.98, vary=True, max = 1, min = 0)
params.add('eta', value = 1, vary=True, min = -1)
result = fmodel.fit(np.log(VA), params, x=(L,K))
print(result.fit_report())
Please take a look here:
https://stackoverflow.com/questions/69046347/scipy-minimize-scipy-curve-fit-lmfit
But in my case I should make the f function in a dynamic way for each iteration that includes different variables and expression to create the following:
def fit_function(expr, list_var, list_para, dict_data(key_var,list_data) ) :
return expr