Sumukh08
Sumukh08

Reputation: 23

Solving an Equation in gekko

This is a part of my code:

import gekko as GEKKO
for i in range(0,4,1):
    m = GEKKO()
    x = m.Var()
    e_i1 = R_n[0,0] * A_slice[i,0] + R_n[1, 0] * A_slice[i, 1]
    e_i2 = R_n[0, 1] * A_slice[i, 1] + R_n[1, 1] * A_slice[i, 1]
    r = get_determinante(R_n)
    d = P[0,i]
    m.Equation(e_i1*R_n[0,1]*x + e_i1*R_n[1,1]*A_slice[i,4] - e_i2*R_n[0,0]*x + e_i2*R_n[1,0]*A_slice[i,4] == r * d)
    m.solve()
    print(x)

however it is not printing x.

Any Reasons?

Upvotes: 2

Views: 446

Answers (1)

John Hedengren
John Hedengren

Reputation: 14386

Try printing the value of x as:

print(x.value)

The variable x is a Gekko variable type and the results are loaded into x.value as a numpy array. To access the value, you can print x.value or x.value[0] to get just the first element of the array.

You are creating a new Gekko model, variables, and equations on each loop. You can also declare an x array of values with x=m.Array(m.Var,4) and solve all of the equations and variables simultaneously without a loop. This may help speed up your code. If you do this then you'll need to print each value of x as:

print([x[i].value[0] for i in range(4)])

Here is a self-contained example with array functions:

from gekko import GEKKO
m = GEKKO()
# variable array dimension
n = 3 # rows
p = 2 # columns
# create array
x = m.Array(m.Var,(n,p))
for i in range(n):
   for j in range(p):
      x[i,j].value = 2.0
      x[i,j].lower = -10.0
      x[i,j].upper = 10.0
# create parameter
y = m.Param(value = 1.0)
# sum columns
z = [None]*p
for j in range(p):
   z[j] = m.Intermediate(sum([x[i,j] for i in range(n)]))
# objective
m.Obj(sum([z[j]**2 + y for j in range(p)]))
# minimize objective
m.solve()
print(x)

Upvotes: 1

Related Questions