我已经阅读了文档并试图理解如何使用scipy.optimize.minimize(),但我的代码就是不工作,它一直显示“ValueError:用户提供的目标函数必须返回标量值。”
下面是我的代码:
PH = np.linspace(0, 14, 71)
ni_total = 0.1
citrate_total = 0.9
ammonia_total = 0.3
def concs(citrate_total,ni_total, ammonia_total, PH):
h = 10**(-PH)
def equations(p):
cit3, nio2, nh4 = p
Hcit = h*cit3*k4
H2cit = h*Hcit*k3
H3cit = h*H2cit*k2
ni2pfree = (nio2*k1*(h**2))/(1+((nio2*k1*(h**2))/ni_total))
NiH2cit = k7*ni2pfree*H2cit
NiHcit = k6*ni2pfree*Hcit
Nicit = k5*ni2pfree*cit3
nh3 = k8*nh4/h
nin4p2 = k9*(nh4**4)/(h**2)
nin6p2 = k10*(nh4**6) /(h**4)
return (citrate_total - Hcit - H2cit - H3cit - Nicit - NiHcit - NiH2cit - cit3,
ni_total - Nicit - NiHcit - NiH2cit - ni2pfree - nin4p2- nin6p2- nio2,
ammonia_total-nh3-4*nin4p2-6*nin6p2-nh4)
initial_guess=[0.1,0.1,0.1]
res = minimize(equations,initial_guess)
cit3 = res.x[0]
nio2 = res.x[1]
nh4 = res.x[2]
ni2pfree = (nio2 * k1 * (h**2)) / (1 + ((nio2 * k1 * (h**2)) / ni_total))
Hcit = h * cit3 *k4
H2cit = h * Hcit * k3
H3cit = h * H2cit * k2
NiH2cit = k7 * ni2pfree * H2cit
NiHcit = k6 * ni2pfree * Hcit
Nicit = k5 * ni2pfree * cit3
nh3 = k8 * nh4 / h
nin4p2 = k9 * (nh4**4) / (h**2)
nin6p2 = k10 * (nh4**6) / (h**4)
return [cit3, nio2, nh4, ni2pfree, Hcit, H2cit, H3cit, NiH2cit, NiHcit, Nicit,nh3,nin4p2,nin6p2]
1条答案
按热度按时间q43xntqr1#
函数scipy.optimize.minimize()(其中)将目标
fun
和初始值x0
作为自变量。fun
必须返回单个真实的(也称为标量);而不是列表或元组。相反,您的函数返回
更改为
与
equations()
的函数值x
进行比较,您实际上想要最小化equations()
。