简体   繁体   English

在python中使用自定义函数中的GEKKO变量的问题

[英]Problem of using GEKKO variables in self-defined function in python

I tried to use GEKKO variables in self-defined function in python. 我试图在python中使用自定义函数中的GEKKO变量。 But there are always annoying errors which I cannot find reason for. 但总有令人烦恼的错误,我找不到理由。 Could you please give me a favour? 你能帮个忙吗?

The whole code is too long. 整个代码太长了。 So I only picked the important lines here to show the problem. 所以我只选择了这里的重要线来表明问题。

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()

The errors are as following: 错误如下:

#### for intera[index]:
ValueError: setting an array element with a sequence.
#### for inter[i][j]:
TypeError: a float is required

Unfortunately Gekko doesn't have full support for numpy arrays right now, and the error comes from trying to insert a Gekko variable into a numpy array. 不幸的是,Gekko目前还没有完全支持numpy数组,而错误来自于尝试将Gekko变量插入到numpy数组中。 To make an array of Gekko variables, you need to either use Gekko arrays, or nested lists. 要创建一个Gekko变量数组,您需要使用Gekko数组或嵌套列表。 Here's an example of both approaches: 以下是两种方法的示例:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM