#!/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.importsysimportmathimportgurobipyasgpfromgurobipyimportGRB# Define callback functiondefmycallback(model,where):ifwhere==GRB.Callback.MIPNODE:ifmodel.cbGet(GRB.Callback.MIPNODE_STATUS)==GRB.OPTIMAL:integers=[]fixval=[]forvinmodel.getVars():ifv.vtype!=GRB.CONTINUOUS:x=model.cbGetNodeRel(v)integers+=[v]fixval+=[math.ceil(x-1e-5)]# Round all int vars upmodel.cbSetSolution(integers,fixval)iflen(sys.argv)<2:print("Usage: heurcb.py filename")sys.exit(0)# Read and solve modelmodel=gp.read(sys.argv[1])# Turn off Gurobi heuristicsmodel.setParam("Heuristics",0)# Solve modelmodel.optimize(mycallback)
Help and Feedback