简体   繁体   中英

Solve Gurobi model repeatedly in Python

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?

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM