Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading