问题
I have dictionary of parameters with unknown number of those parameters (comes from other function), I looped through the dictionary to add its components to an lmfit models as follows:
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 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 any way to define an expression that contains the model independent variable? or how to define it.
回答1:
First, dict
is a builtin and using it for a variable name can cause havoc.
To use your x
in an expression, you would have to add your x
to the symbol table used to evaluate the expression, as with
fit_params = Parameters()
fit_params._asteval.symtable['x'] = x
But: You should be careful doing this with ndarrays. It can work, but Parameters in lmfit are generally meant to be floats.
来源:https://stackoverflow.com/questions/41729783/set-parameter-expression-that-contains-the-independent-variable-in-python-lmfit