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