This section includes source code for all of the Gurobi mip2 examples.The same source code can be found in theexamples directory of theGurobi 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<assert.h>#include<stdlib.h>#include<stdio.h>#include<math.h>#include"gurobi_c.h"intmain(intargc,char*argv[]){GRBenv*env=NULL;GRBmodel*model=NULL;GRBmodel*fixed=NULL;interror=0;intismip;intj,k,solcount,numvars;doubleobjn;intoptimstatus,foptimstatus;doubleobjval,fobjval;char*varname;doublex;/* 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)gotoQUIT;/* Read model from file */error=GRBreadmodel(env,argv[1],&model);if(error)gotoQUIT;error=GRBgetintattr(model,"IsMIP",&ismip);if(error)gotoQUIT;if(ismip==0){printf("Model is not a MIP\n");gotoQUIT;}/* Get model environment */menv=GRBgetenv(model);assert(menv!=NULL);/* Solve model */error=GRBoptimize(model);if(error)gotoQUIT;/* Capture solution information */error=GRBgetintattr(model,GRB_INT_ATTR_STATUS,&optimstatus);if(error)gotoQUIT;printf("\nOptimization complete\n");if(optimstatus==GRB_OPTIMAL){error=GRBgetdblattr(model,GRB_DBL_ATTR_OBJVAL,&objval);if(error)gotoQUIT;printf("Optimal objective: %.4e\n\n",objval);}elseif(optimstatus==GRB_INF_OR_UNBD){printf("Model is infeasible or unbounded\n\n");gotoQUIT;}elseif(optimstatus==GRB_INFEASIBLE){printf("Model is infeasible\n\n");gotoQUIT;}elseif(optimstatus==GRB_UNBOUNDED){printf("Model is unbounded\n\n");gotoQUIT;}else{printf("Optimization was stopped with status = %d\n\n",optimstatus);gotoQUIT;}/* Iterate over the solutions and compute the objectives */error=GRBgetintattr(model,"SolCount",&solcount);if(error)gotoQUIT;printf("\n");for(k=0;k<solcount;++k){error=GRBsetintparam(menv,"SolutionNumber",k);if(error)gotoQUIT;error=GRBgetdblattr(model,GRB_DBL_ATTR_POOLNOBJVAL,&objn);if(error)gotoQUIT;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");gotoQUIT;}fenv=GRBgetenv(fixed);assert(fenv!=NULL);error=GRBsetintparam(fenv,"PRESOLVE",0);if(error)gotoQUIT;error=GRBoptimize(fixed);if(error)gotoQUIT;error=GRBgetintattr(fixed,GRB_INT_ATTR_STATUS,&foptimstatus);if(error)gotoQUIT;if(foptimstatus!=GRB_OPTIMAL){fprintf(stderr,"Error: fixed model isn't optimal\n");gotoQUIT;}error=GRBgetdblattr(fixed,GRB_DBL_ATTR_OBJVAL,&fobjval);if(error)gotoQUIT;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)gotoQUIT;/* Print values of nonzero variables */for(j=0;j<numvars;++j){error=GRBgetstrattrelement(fixed,"VarName",j,&varname);if(error)gotoQUIT;error=GRBgetdblattrelement(fixed,"X",j,&x);if(error)gotoQUIT;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);return0;}
/* 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>usingnamespacestd;intmain(intargc,char*argv[]){if(argc<2){cout<<"Usage: mip2_c++ filename"<<endl;return1;}GRBEnv*env=0;GRBVar*fvars=0;try{env=newGRBEnv();GRBModelmodel=GRBModel(*env,argv[1]);if(model.get(GRB_IntAttr_IsMIP)==0){throwGRBException("Model is not a MIP");}model.optimize();intoptimstatus=model.get(GRB_IntAttr_Status);cout<<"Optimization complete"<<endl;doubleobjval=0;if(optimstatus==GRB_OPTIMAL){objval=model.get(GRB_DoubleAttr_ObjVal);cout<<"Optimal objective: "<<objval<<endl;}elseif(optimstatus==GRB_INF_OR_UNBD){cout<<"Model is infeasible or unbounded"<<endl;return0;}elseif(optimstatus==GRB_INFEASIBLE){cout<<"Model is infeasible"<<endl;return0;}elseif(optimstatus==GRB_UNBOUNDED){cout<<"Model is unbounded"<<endl;return0;}else{cout<<"Optimization was stopped with status = "<<optimstatus<<endl;return0;}/* Iterate over the solutions and compute the objectives */cout<<endl;for(intk=0;k<model.get(GRB_IntAttr_SolCount);++k){model.set(GRB_IntParam_SolutionNumber,k);doubleobjn=model.get(GRB_DoubleAttr_PoolNObjVal);cout<<"Solution "<<k<<" has objective: "<<objn<<endl;}cout<<endl;/* Create a fixed model, turn off presolve and solve */GRBModelfixed=model.fixedModel();fixed.set(GRB_IntParam_Presolve,0);fixed.optimize();intfoptimstatus=fixed.get(GRB_IntAttr_Status);if(foptimstatus!=GRB_OPTIMAL){cerr<<"Error: fixed model isn't optimal"<<endl;return0;}doublefobjval=fixed.get(GRB_DoubleAttr_ObjVal);if(fabs(fobjval-objval)>1.0e-6*(1.0+fabs(objval))){cerr<<"Error: objective values are different"<<endl;return0;}intnumvars=model.get(GRB_IntAttr_NumVars);/* Print values of nonzero variables */fvars=fixed.getVars();for(intj=0;j<numvars;j++){GRBVarv=fvars[j];if(v.get(GRB_DoubleAttr_X)!=0.0){cout<<v.get(GRB_StringAttr_VarName)<<" "<<v.get(GRB_DoubleAttr_X)<<endl;}}}catch(GRBExceptione){cout<<"Error code = "<<e.getErrorCode()<<endl;cout<<e.getMessage()<<endl;}catch(...){cout<<"Error during optimization"<<endl;}delete[]fvars;deleteenv;return0;}
/* 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. */usingSystem;usingGurobi;classmip2_cs{staticvoidMain(string[]args){if(args.Length<1){Console.Out.WriteLine("Usage: mip2_cs filename");return;}try{GRBEnvenv=newGRBEnv();GRBModelmodel=newGRBModel(env,args[0]);if(model.IsMIP==0){Console.WriteLine("Model is not a MIP");return;}model.Optimize();intoptimstatus=model.Status;doubleobjval=0;if(optimstatus==GRB.Status.OPTIMAL){objval=model.ObjVal;Console.WriteLine("Optimal objective: "+objval);}elseif(optimstatus==GRB.Status.INF_OR_UNBD){Console.WriteLine("Model is infeasible or unbounded");return;}elseif(optimstatus==GRB.Status.INFEASIBLE){Console.WriteLine("Model is infeasible");return;}elseif(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(intk=0;k<model.SolCount;++k){model.Parameters.SolutionNumber=k;doubleobjn=model.PoolNObjVal;Console.WriteLine("Solution "+k+" has objective: "+objn);}Console.WriteLine();/* Create a fixed model, turn off presolve and solve */GRBModelfixedmodel=model.FixedModel();fixedmodel.Parameters.Presolve=0;fixedmodel.Optimize();intfoptimstatus=fixedmodel.Status;if(foptimstatus!=GRB.Status.OPTIMAL){Console.WriteLine("Error: fixed model isn't optimal");return;}doublefobjval=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(intj=0;j<fvars.Length;j++){if(x[j]!=0.0)Console.WriteLine(vnames[j]+" "+x[j]);}// Dispose of models and envfixedmodel.Dispose();model.Dispose();env.Dispose();}catch(GRBExceptione){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. */importcom.gurobi.gurobi.*;publicclassMip2{publicstaticvoidmain(String[]args){if(args.length<1){System.out.println("Usage: java Mip2 filename");System.exit(1);}try{GRBEnvenv=newGRBEnv();GRBModelmodel=newGRBModel(env,args[0]);if(model.get(GRB.IntAttr.IsMIP)==0){System.out.println("Model is not a MIP");System.exit(1);}model.optimize();intoptimstatus=model.get(GRB.IntAttr.Status);doubleobjval=0;if(optimstatus==GRB.Status.OPTIMAL){objval=model.get(GRB.DoubleAttr.ObjVal);System.out.println("Optimal objective: "+objval);}elseif(optimstatus==GRB.Status.INF_OR_UNBD){System.out.println("Model is infeasible or unbounded");return;}elseif(optimstatus==GRB.Status.INFEASIBLE){System.out.println("Model is infeasible");return;}elseif(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(intk=0;k<model.get(GRB.IntAttr.SolCount);++k){model.set(GRB.IntParam.SolutionNumber,k);doubleobjn=model.get(GRB.DoubleAttr.PoolNObjVal);System.out.println("Solution "+k+" has objective: "+objn);}System.out.println();/* Create a fixed model, turn off presolve and solve */GRBModelfixed=model.fixedModel();fixed.set(GRB.IntParam.Presolve,0);fixed.optimize();intfoptimstatus=fixed.get(GRB.IntAttr.Status);if(foptimstatus!=GRB.Status.OPTIMAL){System.err.println("Error: fixed model isn't optimal");return;}doublefobjval=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(intj=0;j<fvars.length;j++){if(x[j]!=0.0){System.out.println(vnames[j]+" "+x[j]);}}// Dispose of models and environmentfixed.dispose();model.dispose();env.dispose();}catch(GRBExceptione){System.out.println("Error code: "+e.getErrorCode()+". "+e.getMessage());}}}
functionmip2(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 modelfprintf('Reading model %s\n',filename);model=gurobi_read(filename);cols=size(model.A,2);ivars=find(model.vtype~='C');ints=length(ivars);ifints<=0fprintf('All variables of the model are continuous, nothing to do\n');return;end% Optimizeparams.poolsolutions=20;result=gurobi(model,params);% Capture solution informationif~strcmp(result.status,'OPTIMAL')fprintf('This model cannot be solved because its optimization status is %s\n',...result.status);return;end% Iterate over the solutionsifisfield(result,'pool')&&~isempty(result.pool)solcount=length(result.pool);fork=1:solcountfprintf('Solution %d has objective %g\n',k,result.pool(k).objval);endelsefprintf('Solution 1 has objective %g\n',result.objval);end% Convert to fixed modelforj=1:colsifmodel.vtype(j)~='C't=floor(result.x(j)+0.5);model.lb(j)=t;model.ub(j)=t;endend% Solve the fixed modelresult2=gurobi(model,params);if~strcmp(result.status,'OPTIMAL')fprintf('Error: fixed model is not optimal\n');return;endifabs(result.objval-result2.objval)>1e-6*(1+abs(result.objval))fprintf('Error: Objective values differ\n');end% Print values of non-zero variablesforj=1:colsifabs(result2.x(j))>1e-6fprintf('%s %g\n',model.varnames{j},result2.x(j));endend
#!/usr/bin/env python3# 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.importsysimportgurobipyasgpfromgurobipyimportGRBiflen(sys.argv)<2:print("Usage: mip2.py filename")sys.exit(0)# Read and solve modelmodel=gp.read(sys.argv[1])ifmodel.IsMIP==0:print("Model is not a MIP")sys.exit(0)model.optimize()ifmodel.Status==GRB.OPTIMAL:print(f"Optimal objective:{model.ObjVal:g}")elifmodel.Status==GRB.INF_OR_UNBD:print("Model is infeasible or unbounded")sys.exit(0)elifmodel.Status==GRB.INFEASIBLE:print("Model is infeasible")sys.exit(0)elifmodel.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 objectivesmodel.Params.OutputFlag=0print("")forkinrange(model.SolCount):model.Params.SolutionNumber=kprint(f"Solution{k} has objective{model.PoolNObjVal:g}")print("")model.Params.OutputFlag=1fixed=model.fixed()fixed.Params.Presolve=0fixed.optimize()iffixed.Status!=GRB.OPTIMAL:print("Error: fixed model isn't optimal")sys.exit(1)diff=model.ObjVal-fixed.ObjValifabs(diff)>1e-6*(1.0+abs(model.ObjVal)):print("Error: objective values are different")sys.exit(1)# Print values of nonzero variablesforvinfixed.getVars():ifv.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 modelcat('Reading model',args[1],'...')model<-gurobi_read(args[1])cat('... done\n')# Detect set of non-continous variablesnumvars<-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')}# Optimizeparams<-list()params$poolsolutions<-20result<-gurobi(model,params)# Capture solution informationif(result$status!='OPTIMAL'){cat('Optimization finished with status',result$status,'\n')stop('Stop now\n')}# Iterate over the solutionsif('pool'%in%names(result)){solcount<-length(result$pool)for(kin1:solcount){cat('Solution',k,'has objective:',result$pool[[k]]$objval,'\n')}}else{solcount<-1cat('Solution 1 has objective:',result$objval,'\n')}# Convert to fixed modelfor(jin1:numvars){if(model$vtype[j]!='C'){t<-floor(result$x[j]+0.5)model$lb[j]<-tmodel$ub[j]<-t}}# Solve the fixed modelresult2<-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 variablesfor(jin1:numvars){if(abs(result2$x[j])<1e-6)nextvarnames<-''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 spacerm(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.ImportsSystemImportsGurobiClassmip2_vbSharedSubMain(ByValargsAsString())Ifargs.Length<1ThenConsole.WriteLine("Usage: mip2_vb filename")ReturnEndIfTryDimenvAsGRBEnv=NewGRBEnv("lp1.log")DimmodelAsGRBModel=NewGRBModel(env,args(0))Ifmodel.IsMIP=0ThenConsole.WriteLine("Model is not a MIP")ReturnEndIfmodel.Optimize()DimoptimstatusAsInteger=model.StatusIfoptimstatus=GRB.Status.INF_OR_UNBDThenmodel.Parameters.Presolve=0model.Optimize()optimstatus=model.StatusEndIfDimobjvalAsDoubleIfoptimstatus=GRB.Status.OPTIMALThenobjval=model.ObjValConsole.WriteLine("Optimal objective: "&objval)ElseIfoptimstatus=GRB.Status.INFEASIBLEThenConsole.WriteLine("Model is infeasible")model.ComputeIIS()model.Write("model.ilp")ReturnElseIfoptimstatus=GRB.Status.UNBOUNDEDThenConsole.WriteLine("Model is unbounded")ReturnElseConsole.WriteLine("Optimization was stopped with status = "&_optimstatus)ReturnEndIf' Iterate over the solutions and compute the objectivesConsole.WriteLine()ForkAsInteger=0Tomodel.SolCount-1model.Parameters.SolutionNumber=kDimobjnAsDouble=model.PoolNObjValConsole.WriteLine("Solution "&k&" has objective: "&objn)NextConsole.WriteLine()' Solve fixed modelDimfixedmodelAsGRBModel=model.FixedModel()fixedmodel.Parameters.Presolve=0fixedmodel.Optimize()DimfoptimstatusAsInteger=fixedmodel.StatusIffoptimstatus<>GRB.Status.OPTIMALThenConsole.WriteLine("Error: fixed model isn't optimal")ReturnEndIfDimfobjvalAsDouble=fixedmodel.ObjValIfMath.Abs(fobjval-objval)>0.000001*(1.0+Math.Abs(objval))ThenEndIfDimfvars()AsGRBVar=fixedmodel.GetVars()Dimx()AsDouble=fixedmodel.Get(GRB.DoubleAttr.X,fvars)Dimvnames()AsString=fixedmodel.Get(GRB.StringAttr.VarName,fvars)ForjAsInteger=0Tofvars.Length-1Ifx(j)<>0ThenConsole.WriteLine(vnames(j)&" "&x(j))EndIfNext' Dispose of models and envfixedmodel.Dispose()model.Dispose()env.Dispose()CatcheAsGRBExceptionConsole.WriteLine("Error code: "&e.ErrorCode&". "&e.Message)EndTryEndSubEndClass
Help and Feedback