通过 python 求解线性规划

Solving linear programming by python

我想用 Python 求解线性规划。型号是:

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

所以我尝试了这个:

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

但是我得到了:

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

正如我在评论部分提到的,只需将 sum(x1 , x2) 更改为 x1 + x2 即可解决问题。另外,您应该尝试用 model.solve() 解决 model!所以:

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

如果你想知道最优解,避免Gekko的完整报告,你可以设置model.solve(disp=False)然后试试:

x1[0] , x2[0]

这给了我:

(1.0, 1.0)

然后你的objective函数是x1 + x2,你可以得到objective函数的最优值:

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