This section includes source code for all of the Gurobi feasopt examples.The same source code can be found in theexamples directory of theGurobi distribution.
/* Copyright 2026, 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"intmain(intargc,char*argv[]){GRBenv*env=NULL;GRBmodel*model=NULL;GRBmodel*feasmodel=NULL;double*rhspen=NULL;interror=0;inti,j;intnumvars,numconstrs;charsense;intvind[1];doublevval[1];doublefeasobj;char*cname,*vname;if(argc<2){fprintf(stderr,"Usage: feasopt_c filename\n");exit(1);}error=GRBloadenv(&env,"feasopt.log");if(error)gotoQUIT;error=GRBreadmodel(env,argv[1],&model);if(error)gotoQUIT;/* Create a copy to use FeasRelax feature later */feasmodel=GRBcopymodel(model);if(error)gotoQUIT;/* clear objective */error=GRBgetintattr(model,"NumVars",&numvars);if(error)gotoQUIT;for(j=0;j<numvars;++j){error=GRBsetdblattrelement(model,"Obj",j,0.0);if(error)gotoQUIT;}/* add slack variables */error=GRBgetintattr(model,"NumConstrs",&numconstrs);if(error)gotoQUIT;for(i=0;i<numconstrs;++i){error=GRBgetcharattrelement(model,"Sense",i,&sense);if(error)gotoQUIT;if(sense!='>'){error=GRBgetstrattrelement(model,"ConstrName",i,&cname);if(error)gotoQUIT;vname=malloc(sizeof(char)*(6+strlen(cname)));if(!vname)gotoQUIT;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)gotoQUIT;free(vname);}if(sense!='<'){error=GRBgetstrattrelement(model,"ConstrName",i,&cname);if(error)gotoQUIT;vname=malloc(sizeof(char)*(6+strlen(cname)));if(!vname)gotoQUIT;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)gotoQUIT;free(vname);}}/* Optimize modified model */error=GRBoptimize(model);if(error)gotoQUIT;error=GRBwrite(model,"feasopt.lp");if(error)gotoQUIT;/* Use FeasRelax feature */rhspen=(double*)malloc(numconstrs*sizeof(double));if(rhspen==NULL){printf("ERROR: out of memory\n");gotoQUIT;}/* 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)gotoQUIT;/* optimize FeasRelax model */error=GRBwrite(feasmodel,"feasopt1.lp");if(error)gotoQUIT;error=GRBoptimize(feasmodel);if(error)gotoQUIT;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);return0;}
/* Copyright 2026, 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"usingnamespacestd;intmain(intargc,char*argv[]){if(argc<2){cout<<"Usage: feasopt_c++ filename"<<endl;return1;}GRBEnv*env=0;GRBConstr*c=0;try{env=newGRBEnv();GRBModelfeasmodel=GRBModel(*env,argv[1]);// Create a copy to use FeasRelax feature later */GRBModelfeasmodel1=GRBModel(feasmodel);// clear objectivefeasmodel.setObjective(GRBLinExpr(0.0));// add slack variablesc=feasmodel.getConstrs();for(inti=0;i<feasmodel.get(GRB_IntAttr_NumConstrs);++i){charsense=c[i].get(GRB_CharAttr_Sense);if(sense!='>'){doublecoef=-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!='<'){doublecoef=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 modelfeasmodel.optimize();feasmodel.write("feasopt.lp");// use FeasRelax feature */feasmodel1.feasRelax(GRB_FEASRELAX_LINEAR,true,false,true);feasmodel1.write("feasopt1.lp");feasmodel1.optimize();}catch(GRBExceptione){cout<<"Error code = "<<e.getErrorCode()<<endl;cout<<e.getMessage()<<endl;}catch(...){cout<<"Error during optimization"<<endl;}delete[]c;deleteenv;return0;}
/* Copyright 2026, 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. */usingGurobi;usingSystem;classfeasopt_cs{staticvoidMain(string[]args){if(args.Length<1){Console.Out.WriteLine("Usage: feasopt_cs filename");return;}try{GRBEnvenv=newGRBEnv();GRBModelfeasmodel=newGRBModel(env,args[0]);// Create a copy to use FeasRelax feature later */GRBModelfeasmodel1=newGRBModel(feasmodel);// Clear objectivefeasmodel.SetObjective(newGRBLinExpr());// Add slack variablesGRBConstr[]c=feasmodel.GetConstrs();for(inti=0;i<c.Length;++i){charsense=c[i].Sense;if(sense!='>'){GRBConstr[]constrs=newGRBConstr[]{c[i]};double[]coeffs=newdouble[]{-1};feasmodel.AddVar(0.0,GRB.INFINITY,1.0,GRB.CONTINUOUS,constrs,coeffs,"ArtN_"+c[i].ConstrName);}if(sense!='<'){GRBConstr[]constrs=newGRBConstr[]{c[i]};double[]coeffs=newdouble[]{1};feasmodel.AddVar(0.0,GRB.INFINITY,1.0,GRB.CONTINUOUS,constrs,coeffs,"ArtP_"+c[i].ConstrName);}}// Optimize modified modelfeasmodel.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 envfeasmodel1.Dispose();feasmodel.Dispose();env.Dispose();}catch(GRBExceptione){Console.WriteLine("Error code: "+e.ErrorCode+". "+e.Message);}}}
/* Copyright 2026, 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. */importcom.gurobi.gurobi.*;publicclassFeasopt{publicstaticvoidmain(String[]args){if(args.length<1){System.out.println("Usage: java Feasopt filename");System.exit(1);}try{GRBEnvenv=newGRBEnv();GRBModelfeasmodel=newGRBModel(env,args[0]);// Create a copy to use FeasRelax feature later */GRBModelfeasmodel1=newGRBModel(feasmodel);// Clear objectivefeasmodel.setObjective(newGRBLinExpr());// Add slack variablesGRBConstr[]c=feasmodel.getConstrs();for(inti=0;i<c.length;++i){charsense=c[i].get(GRB.CharAttr.Sense);if(sense!='>'){GRBConstr[]constrs=newGRBConstr[]{c[i]};double[]coeffs=newdouble[]{-1};feasmodel.addVar(0.0,GRB.INFINITY,1.0,GRB.CONTINUOUS,constrs,coeffs,"ArtN_"+c[i].get(GRB.StringAttr.ConstrName));}if(sense!='<'){GRBConstr[]constrs=newGRBConstr[]{c[i]};double[]coeffs=newdouble[]{1};feasmodel.addVar(0.0,GRB.INFINITY,1.0,GRB.CONTINUOUS,constrs,coeffs,"ArtP_"+c[i].get(GRB.StringAttr.ConstrName));}}// Optimize modified modelfeasmodel.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 environmentfeasmodel1.dispose();feasmodel.dispose();env.dispose();}catch(GRBExceptione){System.out.println("Error code: "+e.getErrorCode()+". "+e.getMessage());}}}
functionfeasopt(filename)%% Copyright 2026, 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 modelfprintf('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 relaxedpenalties.rhs=ones(rows,1);result=gurobi_feasrelax(model,0,true,penalties,params);gurobi_write(result.model,'feasopt1.lp');% clear objectivemodel.obj=zeros(cols,1);nvar=cols;forc=1:rowsifmodel.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;endifmodel.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;endendgurobi_write(model,'feasopt2.lp');result2=gurobi(model,params);end
#!/usr/bin/env python3# Copyright 2026, 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.importsysimportgurobipyasgpiflen(sys.argv)<2:print("Usage: feasopt.py filename")sys.exit(0)feasmodel=gp.read(sys.argv[1])# create a copy to use FeasRelax feature laterfeasmodel1=feasmodel.copy()# clear objectivefeasmodel.setObjective(0.0)# add slack variablesforcinfeasmodel.getConstrs():sense=c.Senseifsense!=">":feasmodel.addVar(obj=1.0,name=f"ArtN_{c.ConstrName}",column=gp.Column([-1],[c]))ifsense!="<":feasmodel.addVar(obj=1.0,name=f"ArtP_{c.ConstrName}",column=gp.Column([1],[c]))# optimize modified modelfeasmodel.optimize()feasmodel.write("feasopt.lp")# use FeasRelax featurefeasmodel1.feasRelaxS(0,True,False,True)feasmodel1.write("feasopt1.lp")feasmodel1.optimize()
# Copyright 2026, 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 parametersparams<-list()params$logfile<-'feasopt.log'# Read modelcat('Reading model',args[1],'...')model<-gurobi_read(args[1],params)cat('... done\n')# Create penaltiespenalties<-list()penalties$lb<-Infpenalties$ub<-Infpenalties$rhs<-rep(1,length(model$rhs))result<-gurobi_feasrelax(model,0,TRUE,penalties,params=params)# Display resultsif(result$feasobj>1e-6){cat('Model',args[1],'is infeasible within variable bounds\n')}else{cat('Model',args[1],'is feasible\n')}# Clear spacerm(params,model,penalties,result)
' Copyright 2026, 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.ImportsGurobiImportsSystemClassfeasopt_vbSharedSubMain(ByValargsAsString())Ifargs.Length<1ThenConsole.WriteLine("Usage: feasopt_vb filename")ReturnEndIfTryDimenvAsNewGRBEnv()DimfeasmodelAsNewGRBModel(env,args(0))'Create a copy to use FeasRelax feature laterDimfeasmodel1AsNewGRBModel(feasmodel)' Clear objectivefeasmodel.SetObjective(NewGRBLinExpr())' Add slack variablesDimcAsGRBConstr()=feasmodel.GetConstrs()ForiAsInteger=0Toc.Length-1DimsenseAsChar=c(i).SenseIfsense<>">"cThenDimconstrsAsGRBConstr()=NewGRBConstr(){c(i)}DimcoeffsAsDouble()=NewDouble(){-1}feasmodel.AddVar(0.0,GRB.INFINITY,1.0,GRB.CONTINUOUS,_constrs,coeffs,_"ArtN_"&c(i).ConstrName)EndIfIfsense<>"<"cThenDimconstrsAsGRBConstr()=NewGRBConstr(){c(i)}DimcoeffsAsDouble()=NewDouble(){1}feasmodel.AddVar(0.0,GRB.INFINITY,1.0,GRB.CONTINUOUS,_constrs,coeffs,_"ArtP_"&c(i).ConstrName)EndIfNext' Optimize modified modelfeasmodel.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 envfeasmodel1.Dispose()feasmodel.Dispose()env.Dispose()CatcheAsGRBExceptionConsole.WriteLine("Error code: "&e.ErrorCode&". "&e.Message)EndTryEndSubEndClass
Help and Feedback