Callbacks#
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
and where
) as the argument to Model.optimize
or
Model.computeIIS
, your function will be called during the
optimization. Your callback function can then call Model.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 (using Model.terminate
) or to
proceed to the next phase of the computation (using Model.cbProceed
).
More sophisticated MIP callbacks might use Model.cbGetNodeRel
or
Model.cbGetSolution
to retrieve values from the solution to the
current node, and then use Model.cbCut
or Model.cbLazy
to
add a constraint to cut off that solution, or Model.cbSetSolution
to
import a heuristic solution built from that solution. For multi-objective
problems, you might use Model.cbStopOneMultiObj
to interrupt
the optimization process of one of the
optimization steps in a multi-objective MIP problem without stopping the
hierarchical optimization process.
GRB.Callback
provides a set of constants that are used within the
user callback function. The first set of constants provide the options for the
where
argument to the user callback function. The where
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 provide the options for the what
argument to
Model.cbGet
. The what
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 the where
argument, you refer to a what
constant
through GRB.Callback
. For example, the simplex objective value would
be requested using GRB.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
statement model._value = 1
before the optimization begins, then your
callback function can query the value of model._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.