user15189599
user15189599

Reputation:

Solving linear programming by python

I want to solve linear programming with Python. The model is:

Maximizing x1 + x2  
S.t:  
    x1 + x2 <=1  
    0<= x1 , x2 <=1

So I tried this:

from gekko import GEKKO

model = GEKKO(remote=False)
x1 = model.Var(0.2 , lb=0 , ub=1)
x2 = model.Var(0.2 , lb=0 , ub=1)

model.Equation = (sum(x1 , x2) <=1)

model.Maximize(sum(x1 , x2))

But I got:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8024/1372822120.py in <module>
      6 x2 = model.Var(0.2 , lb=0 , ub=1)
      7 
----> 8 model.Equation = (sum(x1 , x2) <=1)
      9 
     10 model.Maximize(sum(x1 , x2))

~\Anaconda3\envs\Python3.10\lib\site-packages\gekko\gk_variable.py in __getitem__(self, key)
     78         return len(self.value)
     79     def __getitem__(self,key):
---> 80         return self.value[key]
     81     def __setitem__(self,key,value):
     82         self.value[key] = value

~\Anaconda3\envs\Python3.10\lib\site-packages\gekko\gk_operators.py in __getitem__(self, key)
    145 
    146     def __getitem__(self,key):
--> 147         return self.value[key]
    148 
    149     def __setattr__(self, name, value):

TypeError: 'float' object is not subscriptable

Upvotes: 3

Views: 140

Answers (1)

Shayan
Shayan

Reputation: 6285

As I mentioned in the comment section, simply changing sum(x1 , x2) to x1 + x2 should solve the issue. Also, you should try Solving the model with model.solve()! so:

from gekko import GEKKO

model = GEKKO(remote=False)
x1 = model.Var(0.2 , lb=0 , ub=1)
x2 = model.Var(0.2 , lb=0 , ub=1)

model.Equation = (x1 + x2 <=1)

model.Maximize(x1 + x2)
model.solve()

If you want to know about the optimal solution and avoid the complete report of Gekko, you can set model.solve(disp=False) and then try:

x1[0] , x2[0]

this gives me:

(1.0, 1.0)

Then whereas your objective function is x1 + x2, You can get the optimal value of the objective function by:

x1[0] + x2[0]
>>> 2.0

Upvotes: 3

Related Questions