Set parameter expression containing independent variable in python lmfit

I have a parameter dictionary with an unknown number of these parameters (comes from another function), I looped the dictionary to add its components to the lmfit model like this:

from lmfit import Parameters
fit_params = Parameters()
for params_name in dict.keys():
    current_param = dict[param_name]
    fit_params.add(param_name)

      

I wanted to add an expression to each parameter with

fit_params[param_name].set(expr = 'some_expression_in_function_of_x')

      

where x is my independent variable, when running the program, I have this error:

NameError
Traceback (most recent call last):
File "D:\Python\ThinPhy_File_By_File\test_code.py", line 52, in <module>
<_ast.Module object at 0x00000145F661C4E0>
              ^^^
name 'x' is not defined
File "C:\Python36\lib\site-packages\lmfit\parameter.py", line 548, in __repr__
sval = repr(self._getval())
File "C:\Python36\lib\site-packages\lmfit\parameter.py", line 639, in _getval
check_ast_errors(self._expr_eval)
File "C:\Python36\lib\site-packages\lmfit\parameter.py", line 21, in check_ast_errors
expr_eval.raise_exception(None)
File "C:\Python36\lib\site-packages\lmfit\asteval.py", line 167, in raise_exception
raise exc(self.error_msg)
NameError: name 'x' is not defined in expr='<_ast.Module object at 0x00000145F661C4E0>'

      

Is there a way to define an expression that contains a model independent variable? or how to define it.

0


source to share


1 answer


First, it dict

is built-in and using it for a variable name can lead to chaos.

To use yours x

in an expression, you need to add yours x

to the symbol table used to evaluate the expression, for example with



fit_params = Parameters()
fit_params._asteval.symtable['x'] = x

      

But: You have to be careful when doing this with ndarrays. It might work, but the options in lmfit are usually for floats.

+1


source







All Articles