Feasopt Examples#
This section includes source code for all of the Gurobi feasopt examples.
The same source code can be found in the examples
directory of the
Gurobi distribution.
/* Copyright 2024, Gurobi Optimization, LLC */
/* This example reads a MIP model from a file, adds artificial
variables to each constraint, and then minimizes the sum of the
artificial variables. A solution with objective zero corresponds
to a feasible solution to the input model.
We can also use FeasRelax feature to do it. In this example, we
use minrelax=1, i.e. optimizing the returned model finds a solution
that minimizes the original objective, but only from among those
solutions that minimize the sum of the artificial variables. */
#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;
GRBmodel *feasmodel = NULL;
double *rhspen = NULL;
int error = 0;
int i, j;
int numvars, numconstrs;
char sense;
int vind[1];
double vval[1];
double feasobj;
char *cname, *vname;
if (argc < 2)
{
fprintf(stderr, "Usage: feasopt_c filename\n");
exit(1);
}
error = GRBloadenv(&env, "feasopt.log");
if (error) goto QUIT;
error = GRBreadmodel(env, argv[1], &model);
if (error) goto QUIT;
/* Create a copy to use FeasRelax feature later */
feasmodel = GRBcopymodel(model);
if (error) goto QUIT;
/* clear objective */
error = GRBgetintattr(model, "NumVars", &numvars);
if (error) goto QUIT;
for (j = 0; j < numvars; ++j)
{
error = GRBsetdblattrelement(model, "Obj", j, 0.0);
if (error) goto QUIT;
}
/* add slack variables */
error = GRBgetintattr(model, "NumConstrs", &numconstrs);
if (error) goto QUIT;
for (i = 0; i < numconstrs; ++i)
{
error = GRBgetcharattrelement(model, "Sense", i, &sense);
if (error) goto QUIT;
if (sense != '>')
{
error = GRBgetstrattrelement(model, "ConstrName", i, &cname);
if (error) goto QUIT;
vname = malloc(sizeof(char) * (6 + strlen(cname)));
if (!vname) goto QUIT;
strcpy(vname, "ArtN_");
strcat(vname, cname);
vind[0] = i;
vval[0] = -1.0;
error = GRBaddvar(model, 1, vind, vval, 1.0, 0.0, GRB_INFINITY,
GRB_CONTINUOUS, vname);
if (error) goto QUIT;
free(vname);
}
if (sense != '<')
{
error = GRBgetstrattrelement(model, "ConstrName", i, &cname);
if (error) goto QUIT;
vname = malloc(sizeof(char) * (6 + strlen(cname)));
if (!vname) goto QUIT;
strcpy(vname, "ArtP_");
strcat(vname, cname);
vind[0] = i;
vval[0] = 1.0;
error = GRBaddvar(model, 1, vind, vval, 1.0, 0.0, GRB_INFINITY,
GRB_CONTINUOUS, vname);
if (error) goto QUIT;
free(vname);
}
}
/* Optimize modified model */
error = GRBoptimize(model);
if (error) goto QUIT;
error = GRBwrite(model, "feasopt.lp");
if (error) goto QUIT;
/* Use FeasRelax feature */
rhspen = (double *) malloc(numconstrs*sizeof(double));
if (rhspen == NULL) {
printf("ERROR: out of memory\n");
goto QUIT;
}
/* set penalties for artificial variables */
for (i = 0; i < numconstrs; i++) rhspen[i] = 1;
/* create a FeasRelax model with the original objective recovered
and enforcement on minimum of aretificial variables */
error = GRBfeasrelax(feasmodel, GRB_FEASRELAX_LINEAR, 1,
NULL, NULL, rhspen, &feasobj);
if (error) goto QUIT;
/* optimize FeasRelax model */
error = GRBwrite(feasmodel, "feasopt1.lp");
if (error) goto QUIT;
error = GRBoptimize(feasmodel);
if (error) goto QUIT;
QUIT:
/* Error reporting */
if (error)
{
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free models, env and etc. */
if (rhspen) free(rhspen);
GRBfreemodel(model);
GRBfreemodel(feasmodel);
GRBfreeenv(env);
return 0;
}
/* Copyright 2024, Gurobi Optimization, LLC */
/* This example reads a MIP model from a file, adds artificial
variables to each constraint, and then minimizes the sum of the
artificial variables. A solution with objective zero corresponds
to a feasible solution to the input model.
We can also use FeasRelax feature to do it. In this example, we
use minrelax=1, i.e. optimizing the returned model finds a solution
that minimizes the original objective, but only from among those
solutions that minimize the sum of the artificial variables. */
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2)
{
cout << "Usage: feasopt_c++ filename" << endl;
return 1;
}
GRBEnv* env = 0;
GRBConstr* c = 0;
try
{
env = new GRBEnv();
GRBModel feasmodel = GRBModel(*env, argv[1]);
// Create a copy to use FeasRelax feature later */
GRBModel feasmodel1 = GRBModel(feasmodel);
// clear objective
feasmodel.setObjective(GRBLinExpr(0.0));
// add slack variables
c = feasmodel.getConstrs();
for (int i = 0; i < feasmodel.get(GRB_IntAttr_NumConstrs); ++i)
{
char sense = c[i].get(GRB_CharAttr_Sense);
if (sense != '>')
{
double coef = -1.0;
feasmodel.addVar(0.0, GRB_INFINITY, 1.0, GRB_CONTINUOUS, 1,
&c[i], &coef, "ArtN_" +
c[i].get(GRB_StringAttr_ConstrName));
}
if (sense != '<')
{
double coef = 1.0;
feasmodel.addVar(0.0, GRB_INFINITY, 1.0, GRB_CONTINUOUS, 1,
&c[i], &coef, "ArtP_" +
c[i].get(GRB_StringAttr_ConstrName));
}
}
// optimize modified model
feasmodel.optimize();
feasmodel.write("feasopt.lp");
// use FeasRelax feature */
feasmodel1.feasRelax(GRB_FEASRELAX_LINEAR, true, false, true);
feasmodel1.write("feasopt1.lp");
feasmodel1.optimize();
}
catch (GRBException e)
{
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...)
{
cout << "Error during optimization" << endl;
}
delete[] c;
delete env;
return 0;
}
/* Copyright 2024, Gurobi Optimization, LLC */
/* This example reads a MIP model from a file, adds artificial
variables to each constraint, and then minimizes the sum of the
artificial variables. A solution with objective zero corresponds
to a feasible solution to the input model.
We can also use FeasRelax feature to do it. In this example, we
use minrelax=1, i.e. optimizing the returned model finds a solution
that minimizes the original objective, but only from among those
solutions that minimize the sum of the artificial variables. */
using Gurobi;
using System;
class feasopt_cs
{
static void Main(string[] args)
{
if (args.Length < 1) {
Console.Out.WriteLine("Usage: feasopt_cs filename");
return;
}
try {
GRBEnv env = new GRBEnv();
GRBModel feasmodel = new GRBModel(env, args[0]);
// Create a copy to use FeasRelax feature later */
GRBModel feasmodel1 = new GRBModel(feasmodel);
// Clear objective
feasmodel.SetObjective(new GRBLinExpr());
// Add slack variables
GRBConstr[] c = feasmodel.GetConstrs();
for (int i = 0; i < c.Length; ++i) {
char sense = c[i].Sense;
if (sense != '>') {
GRBConstr[] constrs = new GRBConstr[] { c[i] };
double[] coeffs = new double[] { -1 };
feasmodel.AddVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, constrs,
coeffs, "ArtN_" + c[i].ConstrName);
}
if (sense != '<') {
GRBConstr[] constrs = new GRBConstr[] { c[i] };
double[] coeffs = new double[] { 1 };
feasmodel.AddVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, constrs,
coeffs, "ArtP_" +
c[i].ConstrName);
}
}
// Optimize modified model
feasmodel.Optimize();
feasmodel.Write("feasopt.lp");
// Use FeasRelax feature */
feasmodel1.FeasRelax(GRB.FEASRELAX_LINEAR, true, false, true);
feasmodel1.Write("feasopt1.lp");
feasmodel1.Optimize();
// Dispose of model and env
feasmodel1.Dispose();
feasmodel.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
/* Copyright 2024, Gurobi Optimization, LLC */
/* This example reads a MIP model from a file, adds artificial
variables to each constraint, and then minimizes the sum of the
artificial variables. A solution with objective zero corresponds
to a feasible solution to the input model.
We can also use FeasRelax feature to do it. In this example, we
use minrelax=1, i.e. optimizing the returned model finds a solution
that minimizes the original objective, but only from among those
solutions that minimize the sum of the artificial variables. */
import com.gurobi.gurobi.*;
public class Feasopt {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java Feasopt filename");
System.exit(1);
}
try {
GRBEnv env = new GRBEnv();
GRBModel feasmodel = new GRBModel(env, args[0]);
// Create a copy to use FeasRelax feature later */
GRBModel feasmodel1 = new GRBModel(feasmodel);
// Clear objective
feasmodel.setObjective(new GRBLinExpr());
// Add slack variables
GRBConstr[] c = feasmodel.getConstrs();
for (int i = 0; i < c.length; ++i) {
char sense = c[i].get(GRB.CharAttr.Sense);
if (sense != '>') {
GRBConstr[] constrs = new GRBConstr[] { c[i] };
double[] coeffs = new double[] { -1 };
feasmodel.addVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, constrs,
coeffs, "ArtN_" +
c[i].get(GRB.StringAttr.ConstrName));
}
if (sense != '<') {
GRBConstr[] constrs = new GRBConstr[] { c[i] };
double[] coeffs = new double[] { 1 };
feasmodel.addVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, constrs,
coeffs, "ArtP_" +
c[i].get(GRB.StringAttr.ConstrName));
}
}
// Optimize modified model
feasmodel.optimize();
feasmodel.write("feasopt.lp");
// use FeasRelax feature */
feasmodel1.feasRelax(GRB.FEASRELAX_LINEAR, true, false, true);
feasmodel1.write("feasopt1.lp");
feasmodel1.optimize();
// Dispose of model and environment
feasmodel1.dispose();
feasmodel.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
function feasopt(filename)
%
% Copyright 2024, Gurobi Optimization, LLC
%
% This example reads a MIP model from a file, adds artificial
% variables to each constraint, and then minimizes the sum of the
% artificial variables. A solution with objective zero corresponds
% to a feasible solution to the input model.
% We can also use FeasRelax feature to do it. In this example, we
% use minrelax=1, i.e. optimizing the returned model finds a solution
% that minimizes the original objective, but only from among those
% solutions that minimize the sum of the artificial variables.
% Read model
fprintf('Reading model %s\n', filename);
model = gurobi_read(filename);
params.logfile = 'feasopt.log';
result1 = gurobi(model, params);
[rows, cols] = size(model.A);
% Create penalties, only linear constraints are allowed to be relaxed
penalties.rhs = ones(rows, 1);
result = gurobi_feasrelax(model, 0, true, penalties, params);
gurobi_write(result.model, 'feasopt1.lp');
% clear objective
model.obj = zeros(cols, 1);
nvar = cols;
for c = 1:rows
if model.sense(c) ~= '>'
nvar = nvar + 1;
model.A(c, nvar) = -1;
model.obj(nvar) = 1;
model.vtype(nvar) = 'C';
model.varnames(nvar) = strcat('ArtN_', model.constrnames(c));
model.lb(nvar) = 0;
model.ub(nvar) = inf;
end
if model.sense(c) ~= '<'
nvar = nvar + 1;
model.A(c, nvar) = 1;
model.obj(nvar) = 1;
model.vtype(nvar) = 'C';
model.varnames(nvar) = strcat('ArtP_', model.constrnames(c));
model.lb(nvar) = 0;
model.ub(nvar) = inf;
end
end
gurobi_write(model, 'feasopt2.lp');
result2 = gurobi(model, params);
end
#!/usr/bin/env python3.11
# Copyright 2024, Gurobi Optimization, LLC
# This example reads a MIP model from a file, adds artificial
# variables to each constraint, and then minimizes the sum of the
# artificial variables. A solution with objective zero corresponds
# to a feasible solution to the input model.
#
# We can also use FeasRelax feature to do it. In this example, we
# use minrelax=1, i.e. optimizing the returned model finds a solution
# that minimizes the original objective, but only from among those
# solutions that minimize the sum of the artificial variables.
import sys
import gurobipy as gp
if len(sys.argv) < 2:
print("Usage: feasopt.py filename")
sys.exit(0)
feasmodel = gp.read(sys.argv[1])
# create a copy to use FeasRelax feature later
feasmodel1 = feasmodel.copy()
# clear objective
feasmodel.setObjective(0.0)
# add slack variables
for c in feasmodel.getConstrs():
sense = c.Sense
if sense != ">":
feasmodel.addVar(
obj=1.0, name=f"ArtN_{c.ConstrName}", column=gp.Column([-1], [c])
)
if sense != "<":
feasmodel.addVar(
obj=1.0, name=f"ArtP_{c.ConstrName}", column=gp.Column([1], [c])
)
# optimize modified model
feasmodel.optimize()
feasmodel.write("feasopt.lp")
# use FeasRelax feature
feasmodel1.feasRelaxS(0, True, False, True)
feasmodel1.write("feasopt1.lp")
feasmodel1.optimize()
# Copyright 2024, Gurobi Optimization, LLC
#
# This example reads a MIP model from a file, adds artificial
# variables to each constraint, and then minimizes the sum of the
# artificial variables. A solution with objective zero corresponds
# to a feasible solution to the input model.
# We can also use FeasRelax feature to do it. In this example, we
# use minrelax=1, i.e. optimizing the returned model finds a solution
# that minimizes the original objective, but only from among those
# solutions that minimize the sum of the artificial variables.
library(Matrix)
library(gurobi)
args <- commandArgs(trailingOnly = TRUE)
if (length(args) < 1) {
stop('Usage: Rscript feasopt.R filename\n')
}
# Set up parameters
params <- list()
params$logfile <- 'feasopt.log'
# Read model
cat('Reading model',args[1],'...')
model <- gurobi_read(args[1], params)
cat('... done\n')
# Create penalties
penalties <- list()
penalties$lb <- Inf
penalties$ub <- Inf
penalties$rhs <- rep(1,length(model$rhs))
result <- gurobi_feasrelax(model, 0, TRUE, penalties, params = params)
# Display results
if (result$feasobj > 1e-6) {
cat('Model',args[1],'is infeasible within variable bounds\n')
} else {
cat('Model',args[1],'is feasible\n')
}
# Clear space
rm(params, model, penalties, result)
' Copyright 2024, Gurobi Optimization, LLC
'
' This example reads a MIP model from a file, adds artificial
' variables to each constraint, and then minimizes the sum of the
' artificial variables. A solution with objective zero corresponds
' to a feasible solution to the input model.
' We can also use FeasRelax feature to do it. In this example, we
' use minrelax=1, i.e. optimizing the returned model finds a solution
' that minimizes the original objective, but only from among those
' solutions that minimize the sum of the artificial variables.
Imports Gurobi
Imports System
Class feasopt_vb
Shared Sub Main(ByVal args As String())
If args.Length < 1 Then
Console.WriteLine("Usage: feasopt_vb filename")
Return
End If
Try
Dim env As New GRBEnv()
Dim feasmodel As New GRBModel(env, args(0))
'Create a copy to use FeasRelax feature later
Dim feasmodel1 As New GRBModel(feasmodel)
' Clear objective
feasmodel.SetObjective(New GRBLinExpr())
' Add slack variables
Dim c As GRBConstr() = feasmodel.GetConstrs()
For i As Integer = 0 To c.Length - 1
Dim sense As Char = c(i).Sense
If sense <> ">"c Then
Dim constrs As GRBConstr() = New GRBConstr() {c(i)}
Dim coeffs As Double() = New Double() {-1}
feasmodel.AddVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, _
constrs, coeffs, _
"ArtN_" & c(i).ConstrName)
End If
If sense <> "<"c Then
Dim constrs As GRBConstr() = New GRBConstr() {c(i)}
Dim coeffs As Double() = New Double() {1}
feasmodel.AddVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, _
constrs, coeffs, _
"ArtP_" & c(i).ConstrName)
End If
Next
' Optimize modified model
feasmodel.Optimize()
feasmodel.Write("feasopt.lp")
' Use FeasRelax feature */
feasmodel1.FeasRelax(GRB.FEASRELAX_LINEAR, true, false, true)
feasmodel1.Write("feasopt1.lp")
feasmodel1.Optimize()
' Dispose of model and env
feasmodel1.Dispose()
feasmodel.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
End Try
End Sub
End Class