Reputation: 43
I tried to use GEKKO variables in self-defined function in python. 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
Upvotes: 3
Views: 707
Reputation: 163
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. To make an array of Gekko variables, you need to either use Gekko arrays, or nested lists. 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)
Upvotes: 2