pleas let me know how to put GEKKO Parameter in Variable

Viewed 305

I want to put GEKKO Parameter 'N' in Varibale 'Y', but i got an error like below one. I mean that the Parameter 'N' should be changed continuously when the optimization is going on. Is there any other way that could make a changing N?

from gekko import GEKKO
m = GEKKO()
k = 10
N = m.Param(value=[i+1 for i in range(6)])

Y = m.Array(m.Var, (N, k))
for i in range(N):
    for j in range(k):
        Y[i, j].value = 0
        Y[i, j].lower = 0
        Y[i, j].upper = 1
Traceback (most recent call last):
  File "C:\Users\johnh\Desktop\test.py", line 6, in <module>
    Y = m.Array(m.Var, (N, k))
  File "C:\Python37\lib\site-packages\gekko\gekko.py", line 1916, 
  in Array x = np.ndarray(dim,dtype=object)
TypeError: 'GKParameter' object cannot be interpreted
  as an integer
1 Answers

Gekko requires that the problem structure (equations) remain constant but variable values and bounds can change. If you don't want the last rows of variables then you can set up a static matrix and then turn on or off each row with lower=upper=0. When the lower and upper bounds are equal, the variable is fixed at that value and not used by the optimizer.

from gekko import GEKKO
m = GEKKO()
k = 3
N = 6
Y = m.Array(m.Var, (N, k))

for i in range(N):
    for j in range(k):
        Y[i, j].value = 0
        Y[i, j].lower = 0
        if i<N:
            Y[i, j].upper = 1
        else:
            Y[i, j].upper = 0
        m.Maximize(Y[i,j])
    m.solve(disp=False)
    print('Problem: ' + str(i))
    print(Y)

This produces 6 solutions where the value of Y is maximized.

Problem: 0
[[[1.0] [1.0] [1.0]]
 [[0.0] [0.0] [0.0]]
 [[0.0] [0.0] [0.0]]
 [[0.0] [0.0] [0.0]]
 [[0.0] [0.0] [0.0]]
 [[0.0] [0.0] [0.0]]]
Problem: 1
[[[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[0.0] [0.0] [0.0]]
 [[0.0] [0.0] [0.0]]
 [[0.0] [0.0] [0.0]]
 [[0.0] [0.0] [0.0]]]
Problem: 2
[[[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[0.0] [0.0] [0.0]]
 [[0.0] [0.0] [0.0]]
 [[0.0] [0.0] [0.0]]]

Each time through the loop, it is solving with one more row of variables.

Problem: 3
[[[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[0.0] [0.0] [0.0]]
 [[0.0] [0.0] [0.0]]]
Problem: 4
[[[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[0.0] [0.0] [0.0]]]
Problem: 5
[[[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]
 [[1.0] [1.0] [1.0]]]
Related