This section includes source code for all of the Gurobi lpmod examples.The same source code can be found in theexamples directory of theGurobi distribution.
/* Copyright 2025, Gurobi Optimization, LLC *//* This example reads an LP model from a file and solves it. If the model can be solved, then it finds the smallest positive variable, sets its upper bound to zero, and resolves the model two ways: first with an advanced start, then without an advanced start (i.e. 'from scratch'). */#include<stdlib.h>#include<stdio.h>#include<math.h>#include<string.h>#include"gurobi_c.h"intmain(intargc,char*argv[]){GRBenv*env=NULL;GRBmodel*model=NULL;interror=0;intj;intnumvars,isMIP,status,minVar=0;doubleminVal=GRB_INFINITY,sol,lb;char*varname;doublewarmCount,warmTime,coldCount,coldTime;if(argc<2){fprintf(stderr,"Usage: lpmod_c filename\n");exit(1);}error=GRBloadenv(&env,"lpmod.log");if(error)gotoQUIT;/* Read model and determine whether it is an LP */error=GRBreadmodel(env,argv[1],&model);if(error)gotoQUIT;error=GRBgetintattr(model,"IsMIP",&isMIP);if(error)gotoQUIT;if(isMIP){printf("The model is not a linear program\n");gotoQUIT;}error=GRBoptimize(model);if(error)gotoQUIT;error=GRBgetintattr(model,"Status",&status);if(error)gotoQUIT;if((status==GRB_INF_OR_UNBD)||(status==GRB_INFEASIBLE)||(status==GRB_UNBOUNDED)){printf("The model cannot be solved because it is ");printf("infeasible or unbounded\n");gotoQUIT;}if(status!=GRB_OPTIMAL){printf("Optimization was stopped with status %i\n",status);gotoQUIT;}/* Find the smallest variable value */error=GRBgetintattr(model,"NumVars",&numvars);if(error)gotoQUIT;for(j=0;j<numvars;++j){error=GRBgetdblattrelement(model,"X",j,&sol);if(error)gotoQUIT;error=GRBgetdblattrelement(model,"LB",j,&lb);if(error)gotoQUIT;if((sol>0.0001)&&(sol<minVal)&&(lb==0.0)){minVal=sol;minVar=j;}}error=GRBgetstrattrelement(model,"VarName",minVar,&varname);if(error)gotoQUIT;printf("\n*** Setting %s from %f to zero ***\n\n",varname,minVal);error=GRBsetdblattrelement(model,"UB",minVar,0.0);if(error)gotoQUIT;/* Solve from this starting point */error=GRBoptimize(model);if(error)gotoQUIT;/* Save iteration & time info */error=GRBgetdblattr(model,"IterCount",&warmCount);if(error)gotoQUIT;error=GRBgetdblattr(model,"Runtime",&warmTime);if(error)gotoQUIT;/* Reset the model and resolve */printf("\n*** Resetting and solving ");printf("without an advanced start ***\n\n");error=GRBreset(model,0);if(error)gotoQUIT;error=GRBoptimize(model);if(error)gotoQUIT;/* Save iteration & time info */error=GRBgetdblattr(model,"IterCount",&coldCount);if(error)gotoQUIT;error=GRBgetdblattr(model,"Runtime",&coldTime);if(error)gotoQUIT;printf("\n*** Warm start: %f iterations, %f seconds\n",warmCount,warmTime);printf("*** Cold start: %f iterations, %f seconds\n",coldCount,coldTime);QUIT:/* Error reporting */if(error){printf("ERROR: %s\n",GRBgeterrormsg(env));exit(1);}/* Free model */GRBfreemodel(model);/* Free environment */GRBfreeenv(env);return0;}
/* Copyright 2025, Gurobi Optimization, LLC *//* This example reads an LP model from a file and solves it. If the model can be solved, then it finds the smallest positive variable, sets its upper bound to zero, and resolves the model two ways: first with an advanced start, then without an advanced start (i.e. 'from scratch'). */#include"gurobi_c++.h"usingnamespacestd;intmain(intargc,char*argv[]){if(argc<2){cout<<"Usage: lpmod_c++ filename"<<endl;return1;}GRBEnv*env=0;GRBVar*v=0;try{// Read model and determine whether it is an LPenv=newGRBEnv();GRBModelmodel=GRBModel(*env,argv[1]);if(model.get(GRB_IntAttr_IsMIP)!=0){cout<<"The model is not a linear program"<<endl;return1;}model.optimize();intstatus=model.get(GRB_IntAttr_Status);if((status==GRB_INF_OR_UNBD)||(status==GRB_INFEASIBLE)||(status==GRB_UNBOUNDED)){cout<<"The model cannot be solved because it is "<<"infeasible or unbounded"<<endl;return1;}if(status!=GRB_OPTIMAL){cout<<"Optimization was stopped with status "<<status<<endl;return0;}// Find the smallest variable valuedoubleminVal=GRB_INFINITY;intminVar=0;v=model.getVars();for(intj=0;j<model.get(GRB_IntAttr_NumVars);++j){doublesol=v[j].get(GRB_DoubleAttr_X);if((sol>0.0001)&&(sol<minVal)&&(v[j].get(GRB_DoubleAttr_LB)==0.0)){minVal=sol;minVar=j;}}cout<<"\n*** Setting "<<v[minVar].get(GRB_StringAttr_VarName)<<" from "<<minVal<<" to zero ***"<<endl<<endl;v[minVar].set(GRB_DoubleAttr_UB,0.0);// Solve from this starting pointmodel.optimize();// Save iteration & time infodoublewarmCount=model.get(GRB_DoubleAttr_IterCount);doublewarmTime=model.get(GRB_DoubleAttr_Runtime);// Reset the model and resolvecout<<"\n*** Resetting and solving "<<"without an advanced start ***\n"<<endl;model.reset();model.optimize();// Save iteration & time infodoublecoldCount=model.get(GRB_DoubleAttr_IterCount);doublecoldTime=model.get(GRB_DoubleAttr_Runtime);cout<<"\n*** Warm start: "<<warmCount<<" iterations, "<<warmTime<<" seconds"<<endl;cout<<"*** Cold start: "<<coldCount<<" iterations, "<<coldTime<<" seconds"<<endl;}catch(GRBExceptione){cout<<"Error code = "<<e.getErrorCode()<<endl;cout<<e.getMessage()<<endl;}catch(...){cout<<"Error during optimization"<<endl;}delete[]v;deleteenv;return0;}
/* Copyright 2025, Gurobi Optimization, LLC *//* This example reads an LP model from a file and solves it. If the model can be solved, then it finds the smallest positive variable, sets its upper bound to zero, and resolves the model two ways: first with an advanced start, then without an advanced start (i.e. 'from scratch'). */usingSystem;usingGurobi;classlpmod_cs{staticvoidMain(string[]args){if(args.Length<1){Console.Out.WriteLine("Usage: lpmod_cs filename");return;}try{// Read model and determine whether it is an LPGRBEnvenv=newGRBEnv();GRBModelmodel=newGRBModel(env,args[0]);if(model.IsMIP!=0){Console.WriteLine("The model is not a linear program");Environment.Exit(1);}model.Optimize();intstatus=model.Status;if((status==GRB.Status.INF_OR_UNBD)||(status==GRB.Status.INFEASIBLE)||(status==GRB.Status.UNBOUNDED)){Console.WriteLine("The model cannot be solved because it is "+"infeasible or unbounded");Environment.Exit(1);}if(status!=GRB.Status.OPTIMAL){Console.WriteLine("Optimization was stopped with status "+status);Environment.Exit(0);}// Find the smallest variable valuedoubleminVal=GRB.INFINITY;GRBVarminVar=null;foreach(GRBVarvinmodel.GetVars()){doublesol=v.X;if((sol>0.0001)&&(sol<minVal)&&(v.LB==0.0)){minVal=sol;minVar=v;}}Console.WriteLine("\n*** Setting "+minVar.VarName+" from "+minVal+" to zero ***\n");minVar.UB=0.0;// Solve from this starting pointmodel.Optimize();// Save iteration & time infodoublewarmCount=model.IterCount;doublewarmTime=model.Runtime;// Reset the model and resolveConsole.WriteLine("\n*** Resetting and solving "+"without an advanced start ***\n");model.Reset();model.Optimize();doublecoldCount=model.IterCount;doublecoldTime=model.Runtime;Console.WriteLine("\n*** Warm start: "+warmCount+" iterations, "+warmTime+" seconds");Console.WriteLine("*** Cold start: "+coldCount+" iterations, "+coldTime+" seconds");// Dispose of model and envmodel.Dispose();env.Dispose();}catch(GRBExceptione){Console.WriteLine("Error code: "+e.ErrorCode+". "+e.Message);}}}
/* Copyright 2025, Gurobi Optimization, LLC *//* This example reads an LP model from a file and solves it. If the model can be solved, then it finds the smallest positive variable, sets its upper bound to zero, and resolves the model two ways: first with an advanced start, then without an advanced start (i.e. 'from scratch'). */importcom.gurobi.gurobi.*;publicclassLpmod{publicstaticvoidmain(String[]args){if(args.length<1){System.out.println("Usage: java Lpmod filename");System.exit(1);}try{// Read model and determine whether it is an LPGRBEnvenv=newGRBEnv();GRBModelmodel=newGRBModel(env,args[0]);if(model.get(GRB.IntAttr.IsMIP)!=0){System.out.println("The model is not a linear program");System.exit(1);}model.optimize();intstatus=model.get(GRB.IntAttr.Status);if(status==GRB.Status.INF_OR_UNBD||status==GRB.Status.INFEASIBLE||status==GRB.Status.UNBOUNDED){System.out.println("The model cannot be solved because it is "+"infeasible or unbounded");System.exit(1);}if(status!=GRB.Status.OPTIMAL){System.out.println("Optimization was stopped with status "+status);System.exit(0);}// Find the smallest variable valuedoubleminVal=GRB.INFINITY;GRBVarminVar=null;for(GRBVarv:model.getVars()){doublesol=v.get(GRB.DoubleAttr.X);if((sol>0.0001)&&(sol<minVal)&&(v.get(GRB.DoubleAttr.LB)==0.0)){minVal=sol;minVar=v;}}System.out.println("\n*** Setting "+minVar.get(GRB.StringAttr.VarName)+" from "+minVal+" to zero ***\n");minVar.set(GRB.DoubleAttr.UB,0.0);// Solve from this starting pointmodel.optimize();// Save iteration & time infodoublewarmCount=model.get(GRB.DoubleAttr.IterCount);doublewarmTime=model.get(GRB.DoubleAttr.Runtime);// Reset the model and resolveSystem.out.println("\n*** Resetting and solving "+"without an advanced start ***\n");model.reset();model.optimize();doublecoldCount=model.get(GRB.DoubleAttr.IterCount);doublecoldTime=model.get(GRB.DoubleAttr.Runtime);System.out.println("\n*** Warm start: "+warmCount+" iterations, "+warmTime+" seconds");System.out.println("*** Cold start: "+coldCount+" iterations, "+coldTime+" seconds");// Dispose of model and environmentmodel.dispose();env.dispose();}catch(GRBExceptione){System.out.println("Error code: "+e.getErrorCode()+". "+e.getMessage());}}}
functionlpmod(filename)% Copyright 2025, Gurobi Optimization, LLC%% This example reads an LP model from a file and solves it.% If the model can be solved, then it finds the smallest positive variable,% sets its upper bound to zero, and resolves the model two ways:% first with an advanced start, then without an advanced start% (i.e. 'from scratch').% Read modelfprintf('Reading model %s\n',filename);model=gurobi_read(filename);if(isfield(model,'multiobj')&&~isempty(model.multiobj))||...(isfield(model,'sos')&&~isempty(model.sos))||...(isfield(model,'pwlobj')&&~isempty(model.pwlobj))||...(isfield(model,'quadcon')&&~isempty(model.quadcon))||...(isfield(model,'genconstr')&&~isempty(model.genconstr))||...isfield(model,'Q')fprintf('The model is not a linear program, quit\n');return;endivars=find(model.vtype~='C');ints=length(ivars);ifints>0fprintf('problem is a MIP, quit\n');return;endresult=gurobi(model);if~strcmp(result.status,'OPTIMAL')fprintf('This model cannot be solved because its optimization status is %s\n',result.status);return;endcols=size(model.A,2);% create lb if they do not exists, and set them to default valuesif~isfield(model,'lb')||isempty(model.lb)model.lb=zeros(cols,1);end% Find the smallest variable valueminVal=inf;minVar=-1;forj=1:colsifresult.x(j)>0.0001&&result.x(j)<minVal&&model.lb(j)==0.0minVal=result.x(j);minVar=j;endendfprintf('\n*** Setting %s from %d to zero ***\n',model.varnames{minVar},minVar);model.ub(minVar)=0;model.vbasis=result.vbasis;model.cbasis=result.cbasis;% Solve from this starting pointresult=gurobi(model);% Save iteration & time infowarmCount=result.itercount;warmTime=result.runtime;% Remove warm start basis and resolvemodel=rmfield(model,'vbasis');model=rmfield(model,'cbasis');result=gurobi(model);coldCount=result.itercount;coldTime=result.runtime;fprintf('\n');fprintf('*** Warm start: %g iterations, %g seconds\n',warmCount,warmTime);fprintf('*** Cold start: %g iterations, %g seconds\n',coldCount,coldTime);
#!/usr/bin/env python3# Copyright 2025, Gurobi Optimization, LLC# This example reads an LP model from a file and solves it.# If the model can be solved, then it finds the smallest positive variable,# sets its upper bound to zero, and resolves the model two ways:# first with an advanced start, then without an advanced start# (i.e. 'from scratch').importsysimportgurobipyasgpfromgurobipyimportGRBiflen(sys.argv)<2:print("Usage: lpmod.py filename")sys.exit(0)# Read model and determine whether it is an LPmodel=gp.read(sys.argv[1])ifmodel.IsMIP==1:print("The model is not a linear program")sys.exit(1)model.optimize()status=model.Statusifstatus==GRB.INF_OR_UNBDorstatus==GRB.INFEASIBLEorstatus==GRB.UNBOUNDED:print("The model cannot be solved because it is infeasible or unbounded")sys.exit(1)ifstatus!=GRB.OPTIMAL:print(f"Optimization was stopped with status{status}")sys.exit(0)# Find the smallest variable valueminVal=GRB.INFINITYforvinmodel.getVars():ifv.X>0.0001andv.X<minValandv.LB==0.0:minVal=v.XminVar=vprint(f"\n*** Setting{minVar.VarName} from{minVal:g} to zero ***\n")minVar.UB=0.0# Solve from this starting pointmodel.optimize()# Save iteration & time infowarmCount=model.IterCountwarmTime=model.Runtime# Reset the model and resolveprint("\n*** Resetting and solving without an advanced start ***\n")model.reset()model.optimize()coldCount=model.IterCountcoldTime=model.Runtimeprint("")print(f"*** Warm start:{warmCount:g} iterations,{warmTime:g} seconds")print(f"*** Cold start:{coldCount:g} iterations,{coldTime:g} seconds")
# Copyright 2025, Gurobi Optimization, LLC## This example reads an LP model from a file and solves it.# If the model can be solved, then it finds the smallest positive variable,# sets its upper bound to zero, and resultolves the model two ways:# first with an advanced start, then without an advanced start# (i.e. 'from scratch').library(Matrix)library(gurobi)args<-commandArgs(trailingOnly=TRUE)if(length(args)<1){stop('Usage: Rscript lpmod.R filename\n')}# Read modelcat('Reading model',args[1],'...')model<-gurobi_read(args[1])cat('... done\n')# Determine whether it is an LPif('multiobj'%in%names(model)||'sos'%in%names(model)||'pwlobj'%in%names(model)||'cones'%in%names(model)||'quadcon'%in%names(model)||'genconstr'%in%names(model)){stop('The model is not a linear program\n')}# Detect set of non-continuous variablesintvars<-which(model$vtype!='C')numintvars<-length(intvars)if(numintvars>0){stop('problem is a MIP, nothing to do\n')}# Optimizeresult<-gurobi(model)if(result$status!='OPTIMAL'){cat('This model cannot be solved because its optimization status is',result$status,'\n')stop('Stop now\n')}# Recover number of variables in modelnumvars<-ncol(model$A)# Ensure bounds array is initializedif(is.null(model$lb)){model$lb<-rep(0,numvars)}if(is.null(model$ub)){model$ub<-rep(Inf,numvars)}# Find smallest (non-zero) variable value with zero lower boundx<-replace(result$x,result$x<1e-4,Inf)x<-replace(x,model$lb>1e-6,Inf)minVar<-which.min(x)minVal<-x[minVar]# Get variable namevarname<-''if(is.null(model$varnames)){varname<-sprintf('C%d',minVar)}else{varname<-model$varnames[minVar]}cat('\n*** Setting',varname,'from',minVal,'to zero ***\n\n')model$ub[minVar]<-0# Set advance start basis informationmodel$vbasis<-result$vbasismodel$cbasis<-result$cbasisresult2<-gurobi(model)warmCount<-result2$itercountwarmTime<-result2$runtime# Reset-advance start informationmodel$vbasis<-NULLmodel$cbasis<-NULLresult2<-gurobi(model)coldCount<-result2$itercountcoldTime<-result2$runtimecat('\n*** Warm start:',warmCount,'iterations,',warmTime,'seconds\n')cat('\n*** Cold start:',coldCount,'iterations,',coldTime,'seconds\n')# Clear spacerm(model,result,result2)
' Copyright 2025, Gurobi Optimization, LLC'' This example reads an LP model from a file and solves it.' If the model can be solved, then it finds the smallest positive variable,' sets its upper bound to zero, and resolves the model two ways:' first with an advanced start, then without an advanced start' (i.e. from scratch).ImportsSystemImportsGurobiClasslpmod_vbSharedSubMain(ByValargsAsString())Ifargs.Length<1ThenConsole.WriteLine("Usage: lpmod_vb filename")ReturnEndIfTry' Read model and determine whether it is an LPDimenvAsNewGRBEnv()DimmodelAsNewGRBModel(env,args(0))Ifmodel.IsMIP<>0ThenConsole.WriteLine("The model is not a linear program")Environment.Exit(1)EndIfmodel.Optimize()DimstatusAsInteger=model.StatusIf(status=GRB.Status.INF_OR_UNBD)OrElse_(status=GRB.Status.INFEASIBLE)OrElse_(status=GRB.Status.UNBOUNDED)ThenConsole.WriteLine("The model cannot be solved because it is "&_"infeasible or unbounded")Environment.Exit(1)EndIfIfstatus<>GRB.Status.OPTIMALThenConsole.WriteLine("Optimization was stopped with status "&status)Environment.Exit(0)EndIf' Find the smallest variable valueDimminValAsDouble=GRB.INFINITYDimminVarAsGRBVar=NothingForEachvAsGRBVarInmodel.GetVars()DimsolAsDouble=v.XIf(sol>0.0001)AndAlso_(sol<minVal)AndAlso_(v.LB=0.0)ThenminVal=solminVar=vEndIfNextConsole.WriteLine(vbLf&"*** Setting "&_minVar.VarName&" from "&minVal&" to zero ***"&vbLf)minVar.UB=0' Solve from this starting pointmodel.Optimize()' Save iteration & time infoDimwarmCountAsDouble=model.IterCountDimwarmTimeAsDouble=model.Runtime' Reset the model and resolveConsole.WriteLine(vbLf&"*** Resetting and solving "&_"without an advanced start ***"&vbLf)model.Reset()model.Optimize()DimcoldCountAsDouble=model.IterCountDimcoldTimeAsDouble=model.RuntimeConsole.WriteLine(vbLf&"*** Warm start: "&warmCount&_" iterations, "&warmTime&" seconds")Console.WriteLine("*** Cold start: "&coldCount&" iterations, "&_coldTime&" seconds")' Dispose of model and envmodel.Dispose()env.Dispose()CatcheAsGRBExceptionConsole.WriteLine("Error code: "&e.ErrorCode&". "&e.Message)EndTryEndSubEndClass
Help and Feedback