Python API - Callbacks#
- class Callbacks#
Gurobi callback class. A callback is a user function that is called periodically by the Gurobi Optimizer in order to allow the user to query or modify the state of the optimization. More precisely, if you pass a function that takes two arguments (
model
andwhere
) as the argument toModel.optimize
orModel.computeIIS
, your function will be called during the optimization. Your callback function can then callModel.cbGet
to query the optimizer for details on the state of the optimization.Gurobi callbacks can be used both to monitor the progress of the optimization and to modify the behavior of the Gurobi Optimizer. A simple user callback function might call
Model.cbGet
to produce a custom display, or perhaps to terminate optimization early (usingModel.terminate
) or to proceed to the next phase of the computation (usingModel.cbProceed
). More sophisticated MIP callbacks might useModel.cbGetNodeRel
orModel.cbGetSolution
to retrieve values from the solution to the current node, and then useModel.cbCut
orModel.cbLazy
to add a constraint to cut off that solution, orModel.cbSetSolution
to import a heuristic solution built from that solution. For multi-objective problems, you might useModel.cbStopOneMultiObj
to interrupt the optimization process of one of the optimization steps in a multi-objective MIP problem without stopping the hierarchical optimization process.The Gurobi callback class provides a set of constants that are used within the user callback function. The first set of constants in this class list the options for the
where
argument to the user callback function. Thewhere
argument indicates from where in the optimization process the user callback is being called. Options are listed in the Callback Codes section of this document.The other set of constants in this class list the options for the
what
argument toModel.cbGet
. Thewhat
argument is used by the user callback to indicate what piece of status information it would like to retrieve. The full list of options can be found in the Callback Codes section. As with thewhere
argument, you refer to awhat
constant throughGRB.Callback
. For example, the simplex objective value would be requested usingGRB.Callback.SPX_OBJVAL
.If you would like to pass data to your callback function, you can do so through the
Model
object. For example, if your program includes the statementmodel._value = 1
before the optimization begins, then your callback function can query the value ofmodel._value
. Note that the name of the user data field must begin with an underscore.When solving a model using multiple threads, the user callback is only ever called from a single thread, so you don’t need to worry about the thread-safety of your callback.
Note that changing parameters from within a callback is not supported, doing so may lead to undefined behavior.
You can look at callback.py for details of how to use Gurobi callbacks.