我已经编写了以下函数来计算反应系统中单个反应激发的概率,并将函数的输出存储为数组,即系统中每个反应激发的概率:
def propensity_calc(LHS, popul_num, stoch_rate):
propensity = np.zeros(len(LHS))
for row in range(len(LHS)):
a = stoch_rate[row]
for i in range(len(popul_num)):
if (popul_num[i] >= LHS[row, i]):
binom_rxn = binom(popul_num[i], LHS[row, i])
a = a*binom_rxn
else:
a = 0
break
propensity[row] = a
return propensity该函数的输入是3个阵列,popul_num具有每个反应物的离散分子数,LHS是一个2D阵列,其中包含系统中每个反应的每个分子物种之间的比率,stoch_rate是每个反应的速率。
现在,我想在另一个函数中使用scipy.misc.derivative方法调用propensity_calc函数来计算偏导数: bji(x) = daj(x)/xi,其中aj(x)是上述propensity_calc函数的结果,xi是popul_num数组的相应元素。
这是我到目前为止所写的:
from scipy.misc import derivative
from scipy import optimize
def time_step_calc(popul_num, state_change_array, a0):
# equation 22:
expctd_net_change = a0*state_change_array
print("expected net change:\n", expctd_net_change)
# equation 24 partial differentiation:
for x in range(len(popul_num)):
part_propensity_diff = derivative(lambda LHS, popul_num, stoch_rate: propensity_calc, popul_num[x]) <-- Error here with the number of arguments passed to lambda
# equation 26:
t_step = epsi*a0 / sum(expctd_net_change*part_propensity_diff)
delta_t = optimize.fmin(t_step, 0.00012)
print("calculated delta_t:\n", delta_t)
return delta_t为了将propensity_calc函数传递给scipy.derviative,我尝试使用一个lambda函数,但得到了以下错误:
File "C:\Users\Mike\AppData\Local\Programs\Python\Python38-32\lib\site-packages\scipy\misc\common.py", line 119, in derivative
val += weights[k]*func(x0+(k-ho)*dx,*args)
TypeError: <lambda>() missing 2 required positional arguments: 'popul_num' and 'stoch_rate'我已经阅读了lambda文档,但我仍然不明白我错在哪里,关于如何修复这个错误并进行偏导数有什么建议吗?
干杯
发布于 2020-06-02 16:30:06
您定义的lambda是一个包含三个参数的常量函数,这三个参数始终返回一个函数。既然你想要一个一维函数(据我所知),你的意思可能是:
lambda popul_num: propensity_calc(LHS, popul_num, stoch_rate)这可以理解为“接受一个名为popul_num的参数并返回propensity_calc(LHS, popul_num, stoch_rate)的函数”。
通过在点popul_num[x]处使用上述lambda调用scipy.misc.derivative,您将获得点(LHS, popul_num, stoch_rate)处propensity_calc相对于popul_num的偏导数的值。这意味着在这种情况下,您必须定义LHS和stoch_rate。实际上,不要忘记偏导数仍然是三个参数的函数。
发布于 2020-06-02 16:40:03
通常,Scipy只会向lambda函数传递一个参数,因此它只传递LHS的值。请看scipy documentation中的示例
from scipy.misc import derivative
def f(x):
return x**3 + x**2
derivative(func=f, x0=1.0, dx=1e-6)
4.9999999999217337这里,4.99是f在x=1上的导数,当x移动1e-6时。假设f有两个变量:
def f(x, y):
return x**3 + y**2如果您想要关于y的偏导数,那么您需要一个包装函数来让scipy了解要更改的变量。这看起来像这样:
def wrapper(y):
return f(x, y)当然,现在需要一个x的值。
x = 1
derivative(wrapper, 2)
4.0https://stackoverflow.com/questions/62147654
复制相似问题