如何获取提供的 MIP 启动的 objective 值?
How to get the objective value of provided MIP start?
可以很容易的提供一个MIP启动方案,例如
from gurobipy import Model
mdl = Model()
x = mdl.addVar(vtype="I")
y = mdl.addVar(ub = 5, vtype="I")
x.start = 2.0
y.start = 1.0
mdl.setObjective(x*x-y*y)
mdl.addConstr(x <= 2.0*y)
mdl.optimize()
在这个例子中很容易看出MIP start的值是objective 3.如何通过Gurobi获取MIP start的objective值而不自己计算呢? mdl.objVal
属性仅在调用 mdl.optimize()
方法后可用,然后 returns 最佳 objective 值。
假设您无论如何都想求解模型,您可以使用这样的回调:
from gurobipy import Model, GRB
# ... your model
# The callback saves the objective value of the first found incumbent,
# i.e. the mip start in your case
def callback(model, where):
if where == GRB.Callback.MIPSOL:
if model.cbGet(GRB.Callback.MIPSOL_SOLCNT) == 0:
# creates new model attribute '_startobjval'
model._startobjval = model.cbGet(GRB.Callback.MIPSOL_OBJ)
mdl.optimize(callback)
print(f"MIP Start objVal: {mdl._startobjval}, optimal objVal: {mdl.objVal}")
可以很容易的提供一个MIP启动方案,例如
from gurobipy import Model
mdl = Model()
x = mdl.addVar(vtype="I")
y = mdl.addVar(ub = 5, vtype="I")
x.start = 2.0
y.start = 1.0
mdl.setObjective(x*x-y*y)
mdl.addConstr(x <= 2.0*y)
mdl.optimize()
在这个例子中很容易看出MIP start的值是objective 3.如何通过Gurobi获取MIP start的objective值而不自己计算呢? mdl.objVal
属性仅在调用 mdl.optimize()
方法后可用,然后 returns 最佳 objective 值。
假设您无论如何都想求解模型,您可以使用这样的回调:
from gurobipy import Model, GRB
# ... your model
# The callback saves the objective value of the first found incumbent,
# i.e. the mip start in your case
def callback(model, where):
if where == GRB.Callback.MIPSOL:
if model.cbGet(GRB.Callback.MIPSOL_SOLCNT) == 0:
# creates new model attribute '_startobjval'
model._startobjval = model.cbGet(GRB.Callback.MIPSOL_OBJ)
mdl.optimize(callback)
print(f"MIP Start objVal: {mdl._startobjval}, optimal objVal: {mdl.objVal}")