Example: complex termination criteria in a callback

Illustrates how to use a callback to set complex criteria for termination in the Python API.

This example uses the class of informational MIP callbacks, MIPInfoCallback, to set multiple criteria for termination of a Python application.

Tip

For simple, straight forward termination of CPLEX (for example, to intercept a user action, such as clicking a button on a GUI), a callback is not necessary. Instead, use the method use_aborter of the Cplex object.

The class MIPInfoCallback can also query the incumbent solution vector, slacks on linear constraints, slacks on quadratic constraints, and other measures of progress.

>>> class StopCriterion(cplex.callbacks.MIPInfoCallback):
...   def __call__(self):
...     if self.get_num_nodes() > 1000:
...       if self.get_MIP_relative_gap() < 0.1:
...         self.abort()
...         return
...     else: # we’ve processed fewer than 1000 nodes
...       if self.get_MIP_relative_gap() < 0.001:
...         self.abort()
...         return
>>> c = cplex.Cplex("myprob.mps")
>>> c.register_callback(StopCriterion)
>>> c.solve()
[. . . CPLEX log . . .]
>>> c.solution.MIP.get_mip_relative_gap()
0.093
>>> c.solution.progress.get_num_nodes_processed()
223