How do I use callbacks to terminate the solver?
这篇文章可以看作是上一个问题的升级问题:
如果是比较基本的终止条件,使用Gurobi中的基本参数基本就可以实现想要的功能了。但对于更加复杂的条件,可以使用callback()函数来终止运行。
这篇文章同样转自Gurobi-support
原文链接:https://support.gurobi.com/hc/en-us/articles/360047717291
Custom termination criteria can be set within callbacks in order to avoid calling optimize() several times. The following example uses the Python API to implement a “soft” time limit that is only valid under certain conditions, such as a found solution that is “good enough”. The TimeLimit parameter forces the optimization to terminate after 100 seconds. In addition, when the MIP gap is smaller than 50% and at least 5 seconds have passed, the optimization will terminate.
可以在回调中设置自定义终止条件,以避免optimize()多次调用。下面的示例使用 Python API 来实现仅在特定条件下有效的“软”时间约束,例如找到的解决方案“足够好”。TimeLimit参数强制优化在 100 秒后终止。此外,当 MIP 差距小于 50% 且至少经过 5 秒时,优化将终止。具体代码如下。
import gurobipy as gp
from gurobipy import GRB
softlimit = 5
hardlimit = 100
def softtime(model, where):
if where == GRB.Callback.MIP:
runtime = model.cbGet(GRB.Callback.RUNTIME)
objbst = model.cbGet(GRB.Callback.MIP_OBJBST)
objbnd = model.cbGet(GRB.Callback.MIP_OBJBND)
gap = abs((objbst - objbnd) / objbst)
if runtime > softlimit and gap < 0.5:
model.terminate()
model.setParam('TimeLimit', hardlimit)
model.optimize(softtime)
上面这段代码很容易看懂,实现了软时间约束和硬时间约束,并且避免了重复调用model.optimize().
本文还给出了Further information:
How do I change parameters in a callback?
Callback codes
Python callback example(原链接) —— 粘贴文档