Mip2 Examples#
This section includes source code for all of the Gurobi mip2 examples.
The same source code can be found in the examples
directory of the
Gurobi distribution.
/* Copyright 2025, Gurobi Optimization, LLC */
/* This example reads a MIP model from a file, solves it and
prints the objective values from all feasible solutions
generated while solving the MIP. Then it creates the fixed
model and solves that model. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
GRBmodel *fixed = NULL;
int error = 0;
int ismip;
int j, k, solcount, numvars;
double objn;
int optimstatus, foptimstatus;
double objval, fobjval;
char *varname;
double x;
/* To change settings for a loaded model, we need to get
the model environment, which will be freed when the model
is freed. */
GRBenv *menv, *fenv;
if (argc < 2) {
fprintf(stderr, "Usage: mip2_c filename\n");
exit(1);
}
/* Create environment */
error = GRBloadenv(&env, "mip2.log");
if (error) goto QUIT;
/* Read model from file */
error = GRBreadmodel(env, argv[1], &model);
if (error) goto QUIT;
error = GRBgetintattr(model, "IsMIP", &ismip);
if (error) goto QUIT;
if (ismip == 0) {
printf("Model is not a MIP\n");
goto QUIT;
}
/* Get model environment */
menv = GRBgetenv(model);
if (!menv) {
fprintf(stderr, "Error: could not get model environment\n");
goto QUIT;
}
/* Solve model */
error = GRBoptimize(model);
if (error) goto QUIT;
/* Capture solution information */
error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
if (error) goto QUIT;
printf("\nOptimization complete\n");
if (optimstatus == GRB_OPTIMAL) {
error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
if (error) goto QUIT;
printf("Optimal objective: %.4e\n\n", objval);
} else if (optimstatus == GRB_INF_OR_UNBD) {
printf("Model is infeasible or unbounded\n\n");
goto QUIT;
} else if (optimstatus == GRB_INFEASIBLE) {
printf("Model is infeasible\n\n");
goto QUIT;
} else if (optimstatus == GRB_UNBOUNDED) {
printf("Model is unbounded\n\n");
goto QUIT;
} else {
printf("Optimization was stopped with status = %d\n\n", optimstatus);
goto QUIT;
}
/* Iterate over the solutions and compute the objectives */
error = GRBgetintattr(model, "SolCount", &solcount);
if (error) goto QUIT;
printf("\n");
for ( k = 0; k < solcount; ++k ) {
error = GRBsetintparam(menv, "SolutionNumber", k);
if (error) goto QUIT;
error = GRBgetdblattr(model, GRB_DBL_ATTR_POOLOBJVAL, &objn);
if (error) goto QUIT;
printf("Solution %i has objective: %f\n", k, objn);
}
printf("\n");
/* Create a fixed model, turn off presolve and solve */
error = GRBfixmodel(model, &fixed);
if (error || !fixed) {
fprintf(stderr, "Error: could not create fixed model\n");
goto QUIT;
}
fenv = GRBgetenv(fixed);
if (!fenv) {
fprintf(stderr, "Error: could not get fixed model environment\n");
goto QUIT;
}
error = GRBsetintparam(fenv, "PRESOLVE", 0);
if (error) goto QUIT;
error = GRBoptimize(fixed);
if (error) goto QUIT;
error = GRBgetintattr(fixed, GRB_INT_ATTR_STATUS, &foptimstatus);
if (error) goto QUIT;
if (foptimstatus != GRB_OPTIMAL) {
fprintf(stderr, "Error: fixed model isn't optimal\n");
goto QUIT;
}
error = GRBgetdblattr(fixed, GRB_DBL_ATTR_OBJVAL, &fobjval);
if (error) goto QUIT;
if (fabs(fobjval - objval) > 1.0e-6 * (1.0 + fabs(objval))) {
fprintf(stderr, "Error: objective values are different\n");
}
error = GRBgetintattr(model, "NumVars", &numvars);
if (error) goto QUIT;
/* Print values of nonzero variables */
for ( j = 0; j < numvars; ++j ) {
error = GRBgetstrattrelement(fixed, "VarName", j, &varname);
if (error) goto QUIT;
error = GRBgetdblattrelement(fixed, "X", j, &x);
if (error) goto QUIT;
if (x != 0.0) {
printf("%s %f\n", varname, x);
}
}
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free models */
GRBfreemodel(model);
GRBfreemodel(fixed);
/* Free environment */
GRBfreeenv(env);
return 0;
}
/* Copyright 2025, Gurobi Optimization, LLC */
/* This example reads a MIP model from a file, solves it and
prints the objective values from all feasible solutions
generated while solving the MIP. Then it creates the fixed
model and solves that model. */
#include "gurobi_c++.h"
#include <cmath>
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2) {
cout << "Usage: mip2_c++ filename" << endl;
return 1;
}
GRBEnv *env = 0;
GRBVar *fvars = 0;
try {
env = new GRBEnv();
GRBModel model = GRBModel(*env, argv[1]);
if (model.get(GRB_IntAttr_IsMIP) == 0) {
throw GRBException("Model is not a MIP");
}
model.optimize();
int optimstatus = model.get(GRB_IntAttr_Status);
cout << "Optimization complete" << endl;
double objval = 0;
if (optimstatus == GRB_OPTIMAL) {
objval = model.get(GRB_DoubleAttr_ObjVal);
cout << "Optimal objective: " << objval << endl;
} else if (optimstatus == GRB_INF_OR_UNBD) {
cout << "Model is infeasible or unbounded" << endl;
return 0;
} else if (optimstatus == GRB_INFEASIBLE) {
cout << "Model is infeasible" << endl;
return 0;
} else if (optimstatus == GRB_UNBOUNDED) {
cout << "Model is unbounded" << endl;
return 0;
} else {
cout << "Optimization was stopped with status = "
<< optimstatus << endl;
return 0;
}
/* Iterate over the solutions and compute the objectives */
cout << endl;
for ( int k = 0; k < model.get(GRB_IntAttr_SolCount); ++k ) {
model.set(GRB_IntParam_SolutionNumber, k);
double objn = model.get(GRB_DoubleAttr_PoolObjVal);
cout << "Solution " << k << " has objective: " << objn << endl;
}
cout << endl;
/* Create a fixed model, turn off presolve and solve */
GRBModel fixed = model.fixedModel();
fixed.set(GRB_IntParam_Presolve, 0);
fixed.optimize();
int foptimstatus = fixed.get(GRB_IntAttr_Status);
if (foptimstatus != GRB_OPTIMAL) {
cerr << "Error: fixed model isn't optimal" << endl;
return 0;
}
double fobjval = fixed.get(GRB_DoubleAttr_ObjVal);
if (fabs(fobjval - objval) > 1.0e-6 * (1.0 + fabs(objval))) {
cerr << "Error: objective values are different" << endl;
return 0;
}
int numvars = model.get(GRB_IntAttr_NumVars);
/* Print values of nonzero variables */
fvars = fixed.getVars();
for (int j = 0; j < numvars; j++) {
GRBVar v = fvars[j];
if (v.get(GRB_DoubleAttr_X) != 0.0) {
cout << v.get(GRB_StringAttr_VarName) << " "
<< v.get(GRB_DoubleAttr_X) << endl;
}
}
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch (...) {
cout << "Error during optimization" << endl;
}
delete[] fvars;
delete env;
return 0;
}
/* Copyright 2025, Gurobi Optimization, LLC */
/* This example reads a MIP model from a file, solves it and
prints the objective values from all feasible solutions
generated while solving the MIP. Then it creates the fixed
model and solves that model. */
using System;
using Gurobi;
class mip2_cs
{
static void Main(string[] args)
{
if (args.Length < 1) {
Console.Out.WriteLine("Usage: mip2_cs filename");
return;
}
try {
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
if (model.IsMIP == 0) {
Console.WriteLine("Model is not a MIP");
return;
}
model.Optimize();
int optimstatus = model.Status;
double objval = 0;
if (optimstatus == GRB.Status.OPTIMAL) {
objval = model.ObjVal;
Console.WriteLine("Optimal objective: " + objval);
} else if (optimstatus == GRB.Status.INF_OR_UNBD) {
Console.WriteLine("Model is infeasible or unbounded");
return;
} else if (optimstatus == GRB.Status.INFEASIBLE) {
Console.WriteLine("Model is infeasible");
return;
} else if (optimstatus == GRB.Status.UNBOUNDED) {
Console.WriteLine("Model is unbounded");
return;
} else {
Console.WriteLine("Optimization was stopped with status = "
+ optimstatus);
return;
}
/* Iterate over the solutions and compute the objectives */
Console.WriteLine();
for (int k = 0; k < model.SolCount; ++k) {
model.Parameters.SolutionNumber = k;
double objn = model.PoolObjVal;
Console.WriteLine("Solution " + k + " has objective: " + objn);
}
Console.WriteLine();
/* Create a fixed model, turn off presolve and solve */
GRBModel fixedmodel = model.FixedModel();
fixedmodel.Parameters.Presolve = 0;
fixedmodel.Optimize();
int foptimstatus = fixedmodel.Status;
if (foptimstatus != GRB.Status.OPTIMAL) {
Console.WriteLine("Error: fixed model isn't optimal");
return;
}
double fobjval = fixedmodel.ObjVal;
if (Math.Abs(fobjval - objval) > 1.0e-6 * (1.0 + Math.Abs(objval))) {
Console.WriteLine("Error: objective values are different");
return;
}
GRBVar[] fvars = fixedmodel.GetVars();
double[] x = fixedmodel.Get(GRB.DoubleAttr.X, fvars);
string[] vnames = fixedmodel.Get(GRB.StringAttr.VarName, fvars);
for (int j = 0; j < fvars.Length; j++) {
if (x[j] != 0.0) Console.WriteLine(vnames[j] + " " + x[j]);
}
// Dispose of models and env
fixedmodel.Dispose();
model.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
/* Copyright 2025, Gurobi Optimization, LLC */
/* This example reads a MIP model from a file, solves it and
prints the objective values from all feasible solutions
generated while solving the MIP. Then it creates the fixed
model and solves that model. */
import com.gurobi.gurobi.*;
public class Mip2 {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java Mip2 filename");
System.exit(1);
}
try {
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
if (model.get(GRB.IntAttr.IsMIP) == 0) {
System.out.println("Model is not a MIP");
System.exit(1);
}
model.optimize();
int optimstatus = model.get(GRB.IntAttr.Status);
double objval = 0;
if (optimstatus == GRB.Status.OPTIMAL) {
objval = model.get(GRB.DoubleAttr.ObjVal);
System.out.println("Optimal objective: " + objval);
} else if (optimstatus == GRB.Status.INF_OR_UNBD) {
System.out.println("Model is infeasible or unbounded");
return;
} else if (optimstatus == GRB.Status.INFEASIBLE) {
System.out.println("Model is infeasible");
return;
} else if (optimstatus == GRB.Status.UNBOUNDED) {
System.out.println("Model is unbounded");
return;
} else {
System.out.println("Optimization was stopped with status = "
+ optimstatus);
return;
}
/* Iterate over the solutions and compute the objectives */
System.out.println();
for (int k = 0; k < model.get(GRB.IntAttr.SolCount); ++k) {
model.set(GRB.IntParam.SolutionNumber, k);
double objn = model.get(GRB.DoubleAttr.PoolObjVal);
System.out.println("Solution " + k + " has objective: " + objn);
}
System.out.println();
/* Create a fixed model, turn off presolve and solve */
GRBModel fixed = model.fixedModel();
fixed.set(GRB.IntParam.Presolve, 0);
fixed.optimize();
int foptimstatus = fixed.get(GRB.IntAttr.Status);
if (foptimstatus != GRB.Status.OPTIMAL) {
System.err.println("Error: fixed model isn't optimal");
return;
}
double fobjval = fixed.get(GRB.DoubleAttr.ObjVal);
if (Math.abs(fobjval - objval) > 1.0e-6 * (1.0 + Math.abs(objval))) {
System.err.println("Error: objective values are different");
return;
}
GRBVar[] fvars = fixed.getVars();
double[] x = fixed.get(GRB.DoubleAttr.X, fvars);
String[] vnames = fixed.get(GRB.StringAttr.VarName, fvars);
for (int j = 0; j < fvars.length; j++) {
if (x[j] != 0.0) {
System.out.println(vnames[j] + " " + x[j]);
}
}
// Dispose of models and environment
fixed.dispose();
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". "
+ e.getMessage());
}
}
}
function mip2(filename)
% Copyright 2025, Gurobi Optimization, LLC
%
% This example reads a MIP model from a file, solves it and prints
% the objective values from all feasible solutions generated while
% solving the MIP. Then it creates the associated fixed model and
% solves that model.
% Read model
fprintf('Reading model %s\n', filename);
model = gurobi_read(filename);
cols = size(model.A, 2);
ivars = find(model.vtype ~= 'C');
ints = length(ivars);
if ints <= 0
fprintf('All variables of the model are continuous, nothing to do\n');
return;
end
% Optimize
params.poolsolutions = 20;
result = gurobi(model, params);
% Capture solution information
if ~strcmp(result.status, 'OPTIMAL')
fprintf('This model cannot be solved because its optimization status is %s\n', ...
result.status);
return;
end
% Iterate over the solutions
if isfield(result, 'pool') && ~isempty(result.pool)
solcount = length(result.pool);
for k = 1:solcount
fprintf('Solution %d has objective %g\n', k, result.pool(k).objval);
end
else
fprintf('Solution 1 has objective %g\n', result.objval);
end
% Convert to fixed model
for j = 1:cols
if model.vtype(j) ~= 'C'
t = floor(result.x(j) + 0.5);
model.lb(j) = t;
model.ub(j) = t;
end
end
% Solve the fixed model
result2 = gurobi(model, params);
if ~strcmp(result.status, 'OPTIMAL')
fprintf('Error: fixed model is not optimal\n');
return;
end
if abs(result.objval - result2.objval) > 1e-6 * (1 + abs(result.objval))
fprintf('Error: Objective values differ\n');
end
% Print values of non-zero variables
for j = 1:cols
if abs(result2.x(j)) > 1e-6
fprintf('%s %g\n', model.varnames{j}, result2.x(j));
end
end
#!/usr/bin/env python3.11
# Copyright 2025, Gurobi Optimization, LLC
# This example reads a MIP model from a file, solves it and prints
# the objective values from all feasible solutions generated while
# solving the MIP. Then it creates the associated fixed model and
# solves that model.
import sys
import gurobipy as gp
from gurobipy import GRB
if len(sys.argv) < 2:
print("Usage: mip2.py filename")
sys.exit(0)
# Read and solve model
model = gp.read(sys.argv[1])
if model.IsMIP == 0:
print("Model is not a MIP")
sys.exit(0)
model.optimize()
if model.Status == GRB.OPTIMAL:
print(f"Optimal objective: {model.ObjVal:g}")
elif model.Status == GRB.INF_OR_UNBD:
print("Model is infeasible or unbounded")
sys.exit(0)
elif model.Status == GRB.INFEASIBLE:
print("Model is infeasible")
sys.exit(0)
elif model.Status == GRB.UNBOUNDED:
print("Model is unbounded")
sys.exit(0)
else:
print(f"Optimization ended with status {model.Status}")
sys.exit(0)
# Iterate over the solutions and compute the objectives
model.Params.OutputFlag = 0
print("")
for k in range(model.SolCount):
model.Params.SolutionNumber = k
print(f"Solution {k} has objective {model.PoolObjVal:g}")
print("")
model.Params.OutputFlag = 1
fixed = model.fixed()
fixed.Params.Presolve = 0
fixed.optimize()
if fixed.Status != GRB.OPTIMAL:
print("Error: fixed model isn't optimal")
sys.exit(1)
diff = model.ObjVal - fixed.ObjVal
if abs(diff) > 1e-6 * (1.0 + abs(model.ObjVal)):
print("Error: objective values are different")
sys.exit(1)
# Print values of nonzero variables
for v in fixed.getVars():
if v.X != 0:
print(f"{v.VarName} {v.X:g}")
# Copyright 2025, Gurobi Optimization, LLC
#
# This example reads a MIP model from a file, solves it and
# prints the objective values from all feasible solutions
# generated while solving the MIP. Then it creates the fixed
# model and solves that model.
library(Matrix)
library(gurobi)
args <- commandArgs(trailingOnly = TRUE)
if (length(args) < 1) {
stop('Usage: Rscript mip2.R filename\n')
}
# Read model
cat('Reading model',args[1],'...')
model <- gurobi_read(args[1])
cat('... done\n')
# Detect set of non-continous variables
numvars <- dim(model$A)[[2]]
intvars <- which(model$vtype != 'C')
numintvars <- length(intvars)
if (numintvars < 1) {
stop('All model\'s variables are continuous, nothing to do\n')
}
# Optimize
params <- list()
params$poolsolutions <- 20
result <- gurobi(model, params)
# Capture solution information
if (result$status != 'OPTIMAL') {
cat('Optimization finished with status', result$status, '\n')
stop('Stop now\n')
}
# Iterate over the solutions
if ('pool' %in% names(result)) {
solcount <- length(result$pool)
for (k in 1:solcount) {
cat('Solution', k, 'has objective:', result$pool[[k]]$objval, '\n')
}
} else {
solcount <- 1
cat('Solution 1 has objective:', result$objval, '\n')
}
# Convert to fixed model
for (j in 1:numvars) {
if (model$vtype[j] != 'C') {
t <- floor(result$x[j]+0.5)
model$lb[j] <- t
model$ub[j] <- t
}
}
# Solve the fixed model
result2 <- gurobi(model, params)
if (result2$status != 'OPTIMAL') {
stop('Error: fixed model isn\'t optimal\n')
}
if (abs(result$objval - result2$objval) > 1e-6 * (1 + abs(result$objval))) {
stop('Error: Objective values differ\n')
}
# Print values of non-zero variables
for (j in 1:numvars) {
if (abs(result2$x[j]) < 1e-6) next
varnames <- ''
if ('varnames' %in% names(model)) {
varnames <- model$varnames[j]
} else {
varnames <- sprintf('X%d', j)
}
cat(format(varnames, justify='left', width=10),':',
format(result2$x[j], justify='right', digits=2, width=10), '\n')
}
# Clear space
rm(model, params, result, result2)
' Copyright 2025, Gurobi Optimization, LLC
'
' This example reads a MIP model from a file, solves it and
' prints the objective values from all feasible solutions
' generated while solving the MIP. Then it creates the fixed
' model and solves that model.
Imports System
Imports Gurobi
Class mip2_vb
Shared Sub Main(ByVal args As String())
If args.Length < 1 Then
Console.WriteLine("Usage: mip2_vb filename")
Return
End If
Try
Dim env As GRBEnv = New GRBEnv("lp1.log")
Dim model As GRBModel = New GRBModel(env, args(0))
If model.IsMIP = 0 Then
Console.WriteLine("Model is not a MIP")
Return
End If
model.Optimize()
Dim optimstatus As Integer = model.Status
If optimstatus = GRB.Status.INF_OR_UNBD Then
model.Parameters.Presolve = 0
model.Optimize()
optimstatus = model.Status
End If
Dim objval As Double
If optimstatus = GRB.Status.OPTIMAL Then
objval = model.ObjVal
Console.WriteLine("Optimal objective: " & objval)
ElseIf optimstatus = GRB.Status.INFEASIBLE Then
Console.WriteLine("Model is infeasible")
model.ComputeIIS()
model.Write("model.ilp")
Return
ElseIf optimstatus = GRB.Status.UNBOUNDED Then
Console.WriteLine("Model is unbounded")
Return
Else
Console.WriteLine("Optimization was stopped with status = " & _
optimstatus)
Return
End If
' Iterate over the solutions and compute the objectives
Console.WriteLine()
For k As Integer = 0 To model.SolCount - 1
model.Parameters.SolutionNumber = k
Dim objn As Double = model.PoolObjVal
Console.WriteLine("Solution " & k & " has objective: " & objn)
Next
Console.WriteLine()
' Solve fixed model
Dim fixedmodel As GRBModel = model.FixedModel()
fixedmodel.Parameters.Presolve = 0
fixedmodel.Optimize()
Dim foptimstatus As Integer = fixedmodel.Status
If foptimstatus <> GRB.Status.OPTIMAL Then
Console.WriteLine("Error: fixed model isn't optimal")
Return
End If
Dim fobjval As Double = fixedmodel.ObjVal
If Math.Abs(fobjval - objval) > 0.000001 * (1.0 + Math.Abs(objval)) Then
End If
Dim fvars() As GRBVar = fixedmodel.GetVars()
Dim x() As Double = fixedmodel.Get(GRB.DoubleAttr.X, fvars)
Dim vnames() As String = fixedmodel.Get(GRB.StringAttr.VarName, fvars)
For j As Integer = 0 To fvars.Length - 1
If x(j) <> 0 Then
Console.WriteLine(vnames(j) & " " & x(j))
End If
Next
' Dispose of models and env
fixedmodel.Dispose()
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class