由于MIP问题需要很长的计算时间,如果计算时间超过一小时,如何指示cplex返回当前最佳解决方案,例如相对间隙为5%?
我个人认为我可以同时使用这两个功能:model.parameters.timelimit.set()
和model.parameters.mip.tolerances.mipgap.set()
,但我如何将它们结合起来呢?
答案 0 :(得分:2)
您必须使用回调来强制执行这两个条件。 CPLEX附带的mipex4.py
示例显示了如何执行此操作。
以下是示例中的回调:
class TimeLimitCallback(MIPInfoCallback):
def __call__(self):
if not self.aborted and self.has_incumbent():
gap = 100.0 * self.get_MIP_relative_gap()
timeused = self.get_time() - self.starttime
if timeused > self.timelimit and gap < self.acceptablegap:
print("Good enough solution at", timeused, "sec., gap =",
gap, "%, quitting.")
self.aborted = True
self.abort()
其余的相关部分:
c = cplex.Cplex(filename)
timelim_cb = c.register_callback(TimeLimitCallback)
timelim_cb.starttime = c.get_time()
timelim_cb.timelimit = 1
timelim_cb.acceptablegap = 10
timelim_cb.aborted = False
c.solve()
sol = c.solution
print()
# solution.get_status() returns an integer code
print("Solution status = ", sol.get_status(), ":", end=' ')
# the following line prints the corresponding string
print(sol.status[sol.get_status()])
if sol.is_primal_feasible():
print("Solution value = ", sol.get_objective_value())
else:
print("No solution available.")