我尝试在python的自定义函数中使用GEKKO变量。但是总有一些令人讨厌的错误,我找不到原因。你能帮我个忙吗?
整个代码太长。因此,我仅在此处选择重要的行来显示问题。
index = 0
na = 3
inter = np.zeros((na,na))
intera = np.zeros(na*na)
# all the other unmentioned parameters are constant.
def myfunction(x1,x2):
...
gvol_fv = A + B * x1 + C * x1 ** 2
for i in range(na):
for j in range(na):
print(index,aij[index],bij[index],cij[index])
intera[index] = aij[index] + bij[index] * x1 + cij[index] * x1**2
inter[i][j] = math.exp((aij[index] + bij[index] * x1 + cij[index] * x1**2.0 / 1000.0)/x1)
index = index+1
print(index)
...
return [ac1,ac2] # ac1 and ac2 are very complicated variables.
x1 = m.Const(300.0)
x21,x22 = [m.Var(0.01,0.0,1.0) for i in range (2)]
mf_x21_1 = myfunction(x1,x21)[0]
mf_x21_2 = myfunction(x1,x21)[1]
mf_x22_1 = myfunction(x1,x22)[0]
mf_x22_2 = myfunction(x1,x22)[1]
m.Equation(mf_x21_1==mf_x22_1)
m.Equation(mf_x21_2==mf_x22_2)
m.options.IMODE = 1
m.solve()
错误如下:
#### for intera[index]:
ValueError: setting an array element with a sequence.
#### for inter[i][j]:
TypeError: a float is required
答案 0 :(得分:2)
不幸的是,Gekko目前不完全支持numpy数组,并且错误来自尝试将Gekko变量插入numpy数组。要创建Gekko变量数组,您需要使用Gekko数组或嵌套列表。这是这两种方法的示例:
from gekko import GEKKO
m = GEKKO()
ni = 3 # number of rows
nj = 2 # number of columns
# best method: use m.Array function
x = m.Array(m.Var,(ni,nj))
m.Equations([x[i][j]==i*j+1 for i in range(ni) for j in range(nj)])
# another way: list comprehensions
y = [[m.Var() for j in range(nj)] for i in range(ni)]
for i in range(ni):
for j in range(nj):
m.Equation(x[i][j]**2==y[i][j])
# summation
z = m.Var()
m.Equation(z==sum([sum([x[i][j] for i in range(ni)]) for j in range(nj)]))
m.solve()
print('x:')
print(x)
print('y=x**2:')
print(y)
print('z')
print(z.value)