Concepts
Features
Reference
A callback is a user function that is called periodically by the GurobiOptimizer in order to allow the user to query or modify the state of theoptimization. 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 theoptimization. Your callback function can then callModel.cbGet toquery the optimizer for details on the state of the optimization.
Gurobi callbacks can be used both to monitor the progress of the optimizationand to modify the behavior of the Gurobi Optimizer. A simple user callbackfunction might callModel.cbGet to produce a custom display, orperhaps to terminate optimization early (usingModel.terminate) or toproceed 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 thecurrent node, and then useModel.cbCut orModel.cbLazy toadd a constraint to cut off that solution, orModel.cbSetSolution toimport a heuristic solution built from that solution. For multi-objectiveproblems, you might useModel.cbStopOneMultiObj to interruptthe optimization process of one of theoptimization steps in a multi-objective MIP problem without stopping thehierarchical optimization process.
GRB.Callback provides a set of constants that are used within theuser callback function. The first set of constants provide the options for thewhere argument to the user callback function. Thewhere argumentindicates from where in the optimization process the user callback is beingcalled. Options are listed in theCallback Codessection of this document.
The other set of constants provide the options for thewhat argument toModel.cbGet. Thewhat argument is used by the user callback toindicate what piece of status information it would like to retrieve. The fulllist of options can be found in theCallback Codessection. As with thewhere argument, you refer to awhat constantthroughGRB.Callback. For example, the simplex objective value wouldbe requested usingGRB.Callback.SPX_OBJVAL.
When solving a model using multiple threads, the user callback is only evercalled from a single thread, so you don’t need to worry about the thread-safetyof your callback. However, if the solve was started asynchronously usingModel.optimizeAsync then the callback is called from the backgroundthread running the optimization. You must make sure that your callback code andforeground code do not interact in a thread-unsafe manner.
A few parameters arecallback settable.These parameters can be modified from within a callback invocation by using theModel.cbSetParam method.
The following sections provide brief examples of usage of Python functions andclass instances as callbacks. You can also look atcallback.py andtsp.py for details of how to use Gurobi callbacks fromPython.
The simplest form of a callback is a Python function that takes themodelandwhere arguments. This allows you to access the callback functionsmentioned in the previous section via themodel argument:
defcallback(model,where):ifwhere==GRB.Callback.MIP:best_objective=model.cbGet(GRB.Callback.MIP_OBJBST)...model.optimize(callback)
Python functions capture variable names from their enclosing scope. This meansthat if you define your callback function in a scope with access to your modelvariables, you can use them within your callback:
model=gp.Model(env=env)x=model.addVars(5)...defcallback(model,where):ifwhere==GRB.Callback.MIPSOL:solution_values=model.cbGetSolution(x)...model.optimize(callback)
This approach fails if you reassign variables from the enclosing scope orotherwise attempt to use them to store data between callback invocations. SeeWhy am I getting an UnboundLocalError when the variable has a value? in the Python documentation fordetails. If you need to maintain state between callback calls, you should passan instance of a callable class toModel.optimize as described inthe next section.
If your program needs to maintain state data between callback calls, you can usean instance of a callable class to store this state. A class is made callable byimplementing a__call__ method. The__call__method must take themodel andwhere arguments.
For example, the following class would track improvements in the objective witheach new solution found during a MIP solve:
classSolutionCallback:def__init__(self):self.previous_best_objective=Nonedef__call__(self,model,where):ifwhere==GRB.Callback.MIPSOL:# Query the objective value of the new solutionbest_objective=model.cbGet(GRB.Callback.MIPSOL_OBJ)# Check against stored state and report improvement in the# (minimization) objectiveifself.previous_best_objectiveisNone:print(f"First solution found with objective:{best_objective}")else:improvement=self.previous_best_objective-best_objectiveprint(f"New solution found; improved by{improvement}")# Store the current objective for the next callself.previous_best_objective=best_objective# Use a new instance of SolutionCallback as the callbackcallback=SolutionCallback()model.optimize(callback)
Callbacks can also be used with the tuner. The callback function passed toModel.tune must take two positional arguments:tunercb andwhere. In contrast to callbacks used for theModel.optimizemethod, the first argument passed to the callback function is aTunerCb object, not theModel object that startedthe tuner.
The only functionality available in the tuner callback is to terminate thetuner by calling theterminate method of theTunerCb object. For example, the following code would stop atuning run ifshould_stop_tuner() returnsTrue:
defcallback(tunercb,where):ifshould_stop_tuner():tunercb.terminate()model.tune(callback)
Warning
You must not call theterminate method of theModel object while the tuner is running. This will not stop thetuner and may have unintended effects.
Object type passed to the tuner callback. It provides a handle to callbackcontrol methods available while the tuning tool is running.
Generate a request to terminate the current tuning run. This method mayonly be called from a tuning callback. Note that, in general, the requestwon’t be acted upon immediately.
Help and Feedback