在python lmfit中设置包含自变量的参数表达式 [英] Set parameter expression that contains the independent variable in python lmfit
问题描述
我有参数未知的参数字典(来自其他函数),我遍历该字典将其组件添加到lmfit模型中,如下所示:
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')
其中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.
推荐答案
首先,dict
是内置函数,将其用作变量名可能会造成破坏.
First, dict
is a builtin and using it for a variable name can cause havoc.
要在表达式中使用x
,必须像在
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
但是:您应该小心使用ndarrays.它可以工作,但是lmfit中的参数通常是浮点数.
But: You should be careful doing this with ndarrays. It can work, but Parameters in lmfit are generally meant to be floats.
这篇关于在python lmfit中设置包含自变量的参数表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!