Try our new documentation site (beta).
Callbacks
Example: callback
The final example we consider is callback
, which demonstrates
the use of Gurobi callbacks. Callbacks are used to report on the
progress of the optimization or to modify the behavior of the Gurobi
solver. To use a callback, the user writes a routine that implements
the desired behavior. The routine is passed to the Gurobi optimizer
when optimization begins, and the routine is called regularly during
the optimization process. One argument of the user routine is a
where
value, which indicates from where in the optimization
process the callback is invoked. The user callback routine can call
the optimization library to query certain values. We refer the reader
to the callback section of the Gurobi Reference
Manual
for more precise details.
Our callback example implements a simple termination scheme: the user passes a node count into the callback, and the callback asks the optimizer to terminate when that node count is reached. This is implemented in C as follows:
GRBcbget(cbdata, where, GRB_CB_MIP_NODCNT, &nodecnt); if (nodecnt > limit) GRBterminate(model);In Python, this is implemented as:
nodecnt = model.cbGet(GRB.Callback.MIP_NODCNT) if nodecnt > model._mynodelimit: model.terminate()To obtain the current node count, the user routine calls the
cbget
routine (the GRBcbget
function in C, or the
cbGet
method on the model object in C++, C#, Java, and Python).
Our callback example also prints progress information. In C:
GRBcbget(cbdata, where, GRB_CB_MIP_NODCNT, &nodecnt); if (nodecnt - mydata->lastmsg >= 100) { ... printf("%7.0f ...", nodecnt, ...); }In Python:
nodecnt = model.cbGet(GRB.Callback.MIP_NODCNT) if nodecnt % 100 == 0: print(int(nodecnt), "...")Again, the user callback calls the
cbGet
routine to query the
state of the optimization.