有时候在求解过程中需要获取一些信息、终止优化、添加约束条件(割平面)、嵌入自己的算法等,这些功能需要通过Callback实现,其为用户在求解模型时提供了高级控制功能。
一、定义、调用及参数
定义CallBack函数: def 函数名(model, where): ……
调用CallBack函数: m.optimize(callback函数名)
CallBack函数使用时需要注意两个重要的参数:
where: 回调函数触发点
what: 获取何种信息,what能够获取什么取决于where
where 参数取值:
![17e4544953a28155e76d9a7c516e32a0.png](https://img-blog.csdnimg.cn/img_convert/17e4544953a28155e76d9a7c516e32a0.png)
what参数取值:
what 值取决于 where 的取值,例如 where = MIP 时,what 取值可以是:
![72bde23c5758e4c6b2ef73de63a0e860.png](https://img-blog.csdnimg.cn/img_convert/72bde23c5758e4c6b2ef73de63a0e860.png)
当 where = MIPSOL 时,what的取值可以是:
![f80bc431778b4c51e1133888d4aa2fa3.png](https://img-blog.csdnimg.cn/img_convert/f80bc431778b4c51e1133888d4aa2fa3.png)
如果Where = MIPSOL,what 取 MIP_OBJBST 就会报错。
二、Callback函数的功能
1. 查询信息,例如目标值、节点数等
cbGet(what)
what 能获取何种信息取决于where
例如,查询当前单纯形的目标函数值:
def mycallback(model, where):
if where == GRB.Callback.SIMPLEX:
print(model.cbGet(GRB.Callback.SPX_OBJVAL))
model.optimize(mycallback)
2. 查询变量在当前节点的松弛解
注意 where == GRB.Callback.MIPNODE 且 GRB.Callback.MIPNODE_STATUS == GRB.OPTIMAL 才起作用。
cbGetNodeRel (vars ) (vars 需要查询的变量)
def mycallback(model, where):
if where == GRB.Callback.MIPNODE and model.cbGet(GRB.Callback.MIPNODE_STATUS)== GRB.OPTIMAL :
print model.cbGetNodeRel(