heurcb.py#
#!/usr/bin/env python3.11
# Copyright 2025, Gurobi Optimization, LLC
# This example uses a callback to implement a simple rounding heuristic.
# It reads a MIP model from a file, sets up the callback, turns off
# the standard heuristics, and then applies the callback heuristic
# at every opportunity.
import sys
import math
import gurobipy as gp
from gurobipy import GRB
# Define callback function
def mycallback(model, where):
if where == GRB.Callback.MIPNODE:
if model.cbGet(GRB.Callback.MIPNODE_STATUS) == GRB.OPTIMAL:
integers = []
fixval = []
for v in model.getVars():
if v.vtype != GRB.CONTINUOUS:
x = model.cbGetNodeRel(v)
integers += [v]
fixval += [math.ceil(x - 1e-5)] # Round all int vars up
model.cbSetSolution(integers, fixval)
if len(sys.argv) < 2:
print("Usage: heurcb.py filename")
sys.exit(0)
# Read and solve model
model = gp.read(sys.argv[1])
# Turn off Gurobi heuristics
model.setParam("Heuristics", 0)
# Solve model
model.optimize(mycallback)