Solve Gurobi model repeatedly in Python

强颜欢笑 提交于 2019-12-11 13:26:36

问题


I need to solve a gurobi model repeatedly (with different variable values each iteration). Rather than rebuild the model each iteration, I have tried setting up the model, then looping through repeated optimizations, but the variable values do not update. Here is a simple example.

n = Model("Test")
a = n.addVar(lb=0,name = "a")
b = n.addVar(lb=0,name = "b")
a=1
b=1
x = n.addVar(lb=0,name = "x")
y = n.addVar(lb=0,name = "y")
n.update()
n.setObjective(a*x + b*y,GRB.MAXIMIZE)
n.addConstr(x + y <= 10)
n.addConstr(2*x + 3*y <= 20)
n.addConstr(y<=5)
n.update
n.optimize()
for v in n.getVars():
    print('%s %g' % (v.varName, v.x))

print('Obj: %g' % n.objVal)

for i in (1,10):
    n.update()
    a=i*2
    b=100/i
    n.optimize()
    for v in n.getVars():
        print('%s %g' % (v.varName, v.x))

How do I use the existing model over and over again?


回答1:


Presumably you're missing a call to n.setObjective() in the loop. You're just updating local variables without actually touching the model at all.




回答2:


Are a and b constants only? Then, you only need to add the lines

x.obj = i*2
y.obj = 100/i

in the loop and you can remove a and b completly.

Full example, corrected some minor issues and put the a=b=1 in the loop for the i=0-iteration:

from gurobipy import Model, GRB

n = Model('Test')
x = n.addVar(lb=0, name='x')
y = n.addVar(lb=0, name='y')
n.update()
n.ModelSense = GRB.MAXIMIZE
n.addConstr(x + y <= 10)
n.addConstr(2 * x + 3 * y <= 20)
n.addConstr(y <= 5)
n.update()

for i in range(10):
    x.Obj = i*2 if i else 1
    y.Obj = 100/i if i else 1
    n.optimize()
    for v in n.getVars():
        print('%s %g' % (v.varName, v.x))
    print('Obj: %g' % n.objVal)


来源:https://stackoverflow.com/questions/30060500/solve-gurobi-model-repeatedly-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!