Lpmod Examples#
This section includes source code for all of the Gurobi lpmod examples.
The same source code can be found in the examples
directory of the
Gurobi 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"
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
int j;
int numvars, isMIP, status, minVar = 0;
double minVal = GRB_INFINITY, sol, lb;
char *varname;
double warmCount, warmTime, coldCount, coldTime;
if (argc < 2)
{
fprintf(stderr, "Usage: lpmod_c filename\n");
exit(1);
}
error = GRBloadenv(&env, "lpmod.log");
if (error) goto QUIT;
/* Read model and determine whether it is an LP */
error = GRBreadmodel(env, argv[1], &model);
if (error) goto QUIT;
error = GRBgetintattr(model, "IsMIP", &isMIP);
if (error) goto QUIT;
if (isMIP)
{
printf("The model is not a linear program\n");
goto QUIT;
}
error = GRBoptimize(model);
if (error) goto QUIT;
error = GRBgetintattr(model, "Status", &status);
if (error) goto QUIT;
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");
goto QUIT;
}
if (status != GRB_OPTIMAL)
{
printf("Optimization was stopped with status %i\n", status);
goto QUIT;
}
/* Find the smallest variable value */
error = GRBgetintattr(model, "NumVars", &numvars);
if (error) goto QUIT;
for (j = 0; j < numvars; ++j)
{
error = GRBgetdblattrelement(model, "X", j, &sol);
if (error) goto QUIT;
error = GRBgetdblattrelement(model, "LB", j, &lb);
if (error) goto QUIT;
if ((sol > 0.0001) && (sol < minVal) &&
(lb == 0.0))
{
minVal = sol;
minVar = j;
}
}
error = GRBgetstrattrelement(model, "VarName", minVar, &varname);
if (error) goto QUIT;
printf("\n*** Setting %s from %f to zero ***\n\n", varname, minVal);
error = GRBsetdblattrelement(model, "UB", minVar, 0.0);
if (error) goto QUIT;
/* Solve from this starting point */
error = GRBoptimize(model);
if (error) goto QUIT;
/* Save iteration & time info */
error = GRBgetdblattr(model, "IterCount", &warmCount);
if (error) goto QUIT;
error = GRBgetdblattr(model, "Runtime", &warmTime);
if (error) goto QUIT;
/* Reset the model and resolve */
printf("\n*** Resetting and solving ");
printf("without an advanced start ***\n\n");
error = GRBreset(model, 0);
if (error) goto QUIT;
error = GRBoptimize(model);
if (error) goto QUIT;
/* Save iteration & time info */
error = GRBgetdblattr(model, "IterCount", &coldCount);
if (error) goto QUIT;
error = GRBgetdblattr(model, "Runtime", &coldTime);
if (error) goto QUIT;
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);
return 0;
}
/* 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"
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2)
{
cout << "Usage: lpmod_c++ filename" << endl;
return 1;
}
GRBEnv* env = 0;
GRBVar* v = 0;
try
{
// Read model and determine whether it is an LP
env = new GRBEnv();
GRBModel model = GRBModel(*env, argv[1]);
if (model.get(GRB_IntAttr_IsMIP) != 0)
{
cout << "The model is not a linear program" << endl;
return 1;
}
model.optimize();
int status = 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;
return 1;
}
if (status != GRB_OPTIMAL)
{
cout << "Optimization was stopped with status " << status << endl;
return 0;
}
// Find the smallest variable value
double minVal = GRB_INFINITY;
int minVar = 0;
v = model.getVars();
for (int j = 0; j < model.get(GRB_IntAttr_NumVars); ++j)
{
double sol = 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 point
model.optimize();
// Save iteration & time info
double warmCount = model.get(GRB_DoubleAttr_IterCount);
double warmTime = model.get(GRB_DoubleAttr_Runtime);
// Reset the model and resolve
cout << "\n*** Resetting and solving "
<< "without an advanced start ***\n" << endl;
model.reset();
model.optimize();
// Save iteration & time info
double coldCount = model.get(GRB_DoubleAttr_IterCount);
double coldTime = model.get(GRB_DoubleAttr_Runtime);
cout << "\n*** Warm start: " << warmCount << " iterations, " <<
warmTime << " seconds" << endl;
cout << "*** Cold start: " << coldCount << " iterations, " <<
coldTime << " seconds" << endl;
}
catch (GRBException e)
{
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...)
{
cout << "Error during optimization" << endl;
}
delete[] v;
delete env;
return 0;
}
/* 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'). */
using System;
using Gurobi;
class lpmod_cs
{
static void Main(string[] args)
{
if (args.Length < 1) {
Console.Out.WriteLine("Usage: lpmod_cs filename");
return;
}
try {
// Read model and determine whether it is an LP
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
if (model.IsMIP != 0) {
Console.WriteLine("The model is not a linear program");
Environment.Exit(1);
}
model.Optimize();
int status = 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 value
double minVal = GRB.INFINITY;
GRBVar minVar = null;
foreach (GRBVar v in model.GetVars()) {
double sol = 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 point
model.Optimize();
// Save iteration & time info
double warmCount = model.IterCount;
double warmTime = model.Runtime;
// Reset the model and resolve
Console.WriteLine("\n*** Resetting and solving "
+ "without an advanced start ***\n");
model.Reset();
model.Optimize();
double coldCount = model.IterCount;
double coldTime = model.Runtime;
Console.WriteLine("\n*** Warm start: " + warmCount + " iterations, " +
warmTime + " seconds");
Console.WriteLine("*** Cold start: " + coldCount + " iterations, " +
coldTime + " seconds");
// Dispose of model and env
model.Dispose();
env.Dispose();
} catch (GRBException e) {
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'). */
import com.gurobi.gurobi.*;
public class Lpmod {
public static void main(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 LP
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(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();
int status = 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 value
double minVal = GRB.INFINITY;
GRBVar minVar = null;
for (GRBVar v : model.getVars()) {
double sol = 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 point
model.optimize();
// Save iteration & time info
double warmCount = model.get(GRB.DoubleAttr.IterCount);
double warmTime = model.get(GRB.DoubleAttr.Runtime);
// Reset the model and resolve
System.out.println("\n*** Resetting and solving "
+ "without an advanced start ***\n");
model.reset();
model.optimize();
double coldCount = model.get(GRB.DoubleAttr.IterCount);
double coldTime = 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 environment
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
function lpmod(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 model
fprintf('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;
end
ivars = find(model.vtype ~= 'C');
ints = length(ivars);
if ints > 0
fprintf('problem is a MIP, quit\n');
return;
end
result = gurobi(model);
if ~strcmp(result.status, 'OPTIMAL')
fprintf('This model cannot be solved because its optimization status is %s\n', result.status);
return;
end
cols = size(model.A,2);
% create lb if they do not exists, and set them to default values
if ~isfield(model, 'lb') || isempty(model.lb)
model.lb = zeros(cols, 1);
end
% Find the smallest variable value
minVal = inf;
minVar = -1;
for j = 1:cols
if result.x(j) > 0.0001 && result.x(j) < minVal && model.lb(j) == 0.0
minVal = result.x(j);
minVar = j;
end
end
fprintf('\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 point
result = gurobi(model);
% Save iteration & time info
warmCount = result.itercount;
warmTime = result.runtime;
% Remove warm start basis and resolve
model = 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.11
# 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').
import sys
import gurobipy as gp
from gurobipy import GRB
if len(sys.argv) < 2:
print("Usage: lpmod.py filename")
sys.exit(0)
# Read model and determine whether it is an LP
model = gp.read(sys.argv[1])
if model.IsMIP == 1:
print("The model is not a linear program")
sys.exit(1)
model.optimize()
status = model.Status
if status == GRB.INF_OR_UNBD or status == GRB.INFEASIBLE or status == GRB.UNBOUNDED:
print("The model cannot be solved because it is infeasible or unbounded")
sys.exit(1)
if status != GRB.OPTIMAL:
print(f"Optimization was stopped with status {status}")
sys.exit(0)
# Find the smallest variable value
minVal = GRB.INFINITY
for v in model.getVars():
if v.X > 0.0001 and v.X < minVal and v.LB == 0.0:
minVal = v.X
minVar = v
print(f"\n*** Setting {minVar.VarName} from {minVal:g} to zero ***\n")
minVar.UB = 0.0
# Solve from this starting point
model.optimize()
# Save iteration & time info
warmCount = model.IterCount
warmTime = model.Runtime
# Reset the model and resolve
print("\n*** Resetting and solving without an advanced start ***\n")
model.reset()
model.optimize()
coldCount = model.IterCount
coldTime = model.Runtime
print("")
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 model
cat('Reading model',args[1],'...')
model <- gurobi_read(args[1])
cat('... done\n')
# Determine whether it is an LP
if ('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 variables
intvars <- which(model$vtype != 'C')
numintvars <- length(intvars)
if (numintvars > 0) {
stop('problem is a MIP, nothing to do\n')
}
# Optimize
result <- 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 model
numvars <- ncol(model$A)
# Ensure bounds array is initialized
if (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 bound
x <- 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 name
varname <- ''
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 information
model$vbasis <- result$vbasis
model$cbasis <- result$cbasis
result2 <- gurobi(model)
warmCount <- result2$itercount
warmTime <- result2$runtime
# Reset-advance start information
model$vbasis <- NULL
model$cbasis <- NULL
result2 <- gurobi(model)
coldCount <- result2$itercount
coldTime <- result2$runtime
cat('\n*** Warm start:', warmCount, 'iterations,', warmTime, 'seconds\n')
cat('\n*** Cold start:', coldCount, 'iterations,', coldTime, 'seconds\n')
# Clear space
rm(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).
Imports System
Imports Gurobi
Class lpmod_vb
Shared Sub Main(ByVal args As String())
If args.Length < 1 Then
Console.WriteLine("Usage: lpmod_vb filename")
Return
End If
Try
' Read model and determine whether it is an LP
Dim env As New GRBEnv()
Dim model As New GRBModel(env, args(0))
If model.IsMIP <> 0 Then
Console.WriteLine("The model is not a linear program")
Environment.Exit(1)
End If
model.Optimize()
Dim status As Integer = model.Status
If (status = GRB.Status.INF_OR_UNBD) OrElse _
(status = GRB.Status.INFEASIBLE) OrElse _
(status = GRB.Status.UNBOUNDED) Then
Console.WriteLine("The model cannot be solved because it is " & _
"infeasible or unbounded")
Environment.Exit(1)
End If
If status <> GRB.Status.OPTIMAL Then
Console.WriteLine("Optimization was stopped with status " & status)
Environment.Exit(0)
End If
' Find the smallest variable value
Dim minVal As Double = GRB.INFINITY
Dim minVar As GRBVar = Nothing
For Each v As GRBVar In model.GetVars()
Dim sol As Double = v.X
If (sol > 0.0001) AndAlso _
(sol < minVal) AndAlso _
(v.LB = 0.0) Then
minVal = sol
minVar = v
End If
Next
Console.WriteLine(vbLf & "*** Setting " & _
minVar.VarName & " from " & minVal & " to zero ***" & vbLf)
minVar.UB = 0
' Solve from this starting point
model.Optimize()
' Save iteration & time info
Dim warmCount As Double = model.IterCount
Dim warmTime As Double = model.Runtime
' Reset the model and resolve
Console.WriteLine(vbLf & "*** Resetting and solving " & _
"without an advanced start ***" & vbLf)
model.Reset()
model.Optimize()
Dim coldCount As Double = model.IterCount
Dim coldTime As Double = model.Runtime
Console.WriteLine(vbLf & "*** Warm start: " & warmCount & _
" iterations, " & warmTime & " seconds")
Console.WriteLine("*** Cold start: " & coldCount & " iterations, " & _
coldTime & " seconds")
' Dispose of model and env
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class