0% found this document useful (0 votes)
129 views

Gurobi Training

Uploaded by

Bin Christian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views

Gurobi Training

Uploaded by

Bin Christian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Gurobi Optimizer Training

N
November
b 1313, 2009
About the instructor

 Greg
g Glockner
◦ PhD, Industrial Engineering, Georgia Tech
◦ Trained customers worldwide in modeling and
optimization software
◦ Joined Gurobi in spring of 2009
Agenda

 Quick tour of Gurobi Optimizer


Q p

 Hands-on with Gurobi Interactive Shell

 Modeling with Gurobi Object-Oriented


Interfaces

 Working with the C Interface

 A quick
i k peek
k under
d the
h h
hood
d

18-Jun-10 © 2009 Gurobi Optimization 3


Gurobi Optimizer: A Quick
Tour

18-Jun-10 © 2009 Gurobi Optimization 4


What is Gurobi Optimizer?

 Gurobi Optimizer
p is a high-end
g system
y for
solving linear programs and mixed-integer
programs

 If this
hi is
i unfamiliar
f ili to you, it’s
i ’ going
i to be
b a
very long day!
Algorithms in Gurobi

 LP: p
primal and dual simplex
p
 MIP: parallel branch and bound with
heuristics and cutting planes
◦ Both LP & MIP include automatic presolve
 IIS for LP and MIP

 Next release: parallel LP barrier with


crossover
Interfaces to Gurobi

 Matrix
◦ C
 Object-oriented
◦ C++, Java, Python
◦ .NET through Microsoft Solver Foundation
 Interactive shell and command
command-line
line tool
 Modeling systems and MATLAB

 Other languages are possible but not


y supported
officially pp

18-Jun-10 © 2009 Gurobi Optimization 7


File format support

 Models
◦ .LP, .MPS, .RLP, .REW
 Solution information
◦ .ILP, .MST, .BAS, .SOL
 Parameters
◦ .PRM
PRM

 All support built-in


built in compression (gzip,
(gzip bzip2)

18-Jun-10 © 2009 Gurobi Optimization 8


Gurobi design

 Designed
g for efficiency
y
◦ Very efficient simplex
◦ Very powerful MIP
◦ Make
M k ththe mostt off multi-processors
lti

 Just enough customization


◦ Parameters
◦ Callbacks
◦ Some esoteric features deliberately left out to keep
Gurobi efficient

18-Jun-10 © 2009 Gurobi Optimization 9


Command-line interface

 Very
y simple
p way
y to solve a model from a file
◦ gurobi_cl [param=value]* filename

 Useful for quick tests of models & parameters


 Does not save solution values

18-Jun-10 © 2009 Gurobi Optimization 10


Try it: Command-line interface

 Open
p a command p
prompt
p

 cd to examples\data
p subdirectory
y of
Gurobi

 Solve these models:


◦ afiro.mps
◦ stein9.mps
stein9 mps
◦ misc07.mps

18-Jun-10 © 2009 Gurobi Optimization 11


Log file (LP)
Optimize a model with 27 Rows, 32 Columns and 83 NonZeros

Presolve removed 21 rows and 23 columns


Presolve time: 0.00 sec.
Presolved: 6 Rows, 9 Columns, 26 Nonzeros

Iteration Objective Primal Inf. Dual Inf. Time


0 -4.8565680e+02 1.179278e+02 0.000000e+00 0s
3 -4.6475314e+02 0.000000e+00 0.000000e+00 0s

Solved in 3 iterations and 0.00 seconds


Optimal objective -4.647531429e+02

18-Jun-10 © 2009 Gurobi Optimization 12


Log file (MIP)
Nodes | Current Node | Objective Bounds | Work
Expl
l Unexpl
l | Obj Depth
h IntInf
f | Incumbent
b BestBd
d G
Gap | It/Node
/ d Time
i

0 0 4.0000 0 6 5.0000 4.0000 20.0% - 0s


0 0 4.0000 0 8 5.0000 4.0000 20.0% - 0s
0 0 4.0000 0 8 5.0000 4.0000 20.0% - 0s
0 0 4.0000 0 8 5.0000 4.0000 20.0% - 0s

Cutting planes:
Gomory: 1

Explored 13 nodes (49 simplex iterations) in 0.00 seconds


Thread count was 2 (of 16 available processors)

Optimal solution found (tolerance 1.00e-04)


Best objective 5.0000000000e+00, best bound 5.0000000000e+00, gap 0.0%

18-Jun-10 © 2009 Gurobi Optimization 13


Try it: Parameters

 Solve the model:


◦ misc07.mps

 Try different values between 0.0 and 1.0 for


the heuristics parameter

 Example
◦ gurobi
bi cl
l heuristics=0.2
h i ti 0 2 misc07.mps
i 07

18-Jun-10 © 2009 Gurobi Optimization 14


Gurobi Parameters

 Parameters control the behavior of Gurobi


algorithms
◦ Termination criteria
◦ T l
Tolerances
◦ Simplex method
◦ MIP
◦ MIP cuts
◦ General
 All
ll parameters h
have good
dddefault
f l values
l
 Common parameters to adjust are
highlighted

18-Jun-10 © 2009 Gurobi Optimization 15


Parameters: Termination

 Cutoff: Stop
p if objective
j is worse
 IterationLimit: Limit on simplex iterations
 NodeLimit: Limit on MIP nodes
 SolutionLimit: Limit on MIP solutions
 TimeLimit: Time limit in seconds

18-Jun-10 © 2009 Gurobi Optimization 16


Parameters: Tolerances

 FeasibilityTol:
y Primal feasibility
y
 IntFeasTol: Integer feasibility
 MarkowitzTol: Simplex pivoting
 MIPGap: Relative MIP gap
 OptimalityTol: Dual feasibility

18-Jun-10 © 2009 Gurobi Optimization 17


Parameters: Simplex

 LPMethod: Whether to use p primal or dual


 NormAdjust: Different norm pricing
 ObjScale: Value to rescale the objective
 PerturbValue: Value for perturbation
 Quad: Use quad precision
 ScaleFlag: Allow model scaling
 SimplexPricing: Variable pricing strategy

18-Jun-10 © 2009 Gurobi Optimization 18


Parameters: MIP

 Heuristics: How frequently


q y to run heuristics
 NodefileDir: Directory to use for node files
 NodefileStart: When to start using node files
◦ No need to run out of memory for MIP tree
 RootMethod: LP method for root relaxation
 SubMIPNodes:
b d # nodes
d to use ffor RINS
 VarBranch: Branch variable selection

18-Jun-10 © 2009 Gurobi Optimization 19


Parameters: MIP cuts

 Cuts: Global cut g


generation control
◦ Specific cuts can be controlled individually
 CutAggPasses: Number of constraint
aggregation passes in cut generation
 GomoryPasses: Number of Gomory cut passes

18-Jun-10 © 2009 Gurobi Optimization 20


Parameters: Other

 Aggregate:
gg g Control p
presolve aggregation
gg g
 DisplayInterval: Logging frequency
 IISMethod: Tradeoff speed/size
p / in IIS
 LogfileName: Filename for logfile
 OutputFlag:
p g Whether to output
p to screen
 PreCrush: Turn on to add cut callbacks
 Presolve: Whether to use presolve
 Threads: # of threads to use for parallel

18-Jun-10 © 2009 Gurobi Optimization 21


Documentation overview

 Getting
g Started Manual
 Reference Manual
◦ APIs
◦ Parameters
◦ Attributes
 Example Tour
◦ 16 examples for all supported languages

 Available both online and on your computer

18-Jun-10 © 2009 Gurobi Optimization 22


Using Gurobi with AMPL

 Configuration
g
◦ Put Gurobi link files into AMPL directory
◦ Add AMPL directory to PATH
◦ Linux:
Li Add AMPL di directory
t tto LD
LD_LIBRARY_PATH
LIBRARY PATH

 When running, set solver to Gurobi


◦ option solver gurobi_ampl;

 Setting Gurobi parameters


◦ option gurobi_options $gurobi_options 'mipgap 0.01';

18-Jun-10 © 2009 Gurobi Optimization 23


AMPL/Gurobi details

 See AMPL/Gurobi
/ User Guide for:
◦ Installation / Configuration information
◦ Full list of parameters (options)
 Di ib
Distributed
d with
i h AMPL/G
AMPL/Gurobi
bi

 N extra
No t licenses
li needed
d d
◦ Your existing AMPL license plus a Gurobi license
will allow y
you to run Gurobi from AMPL

18-Jun-10 © 2009 Gurobi Optimization 24


Using Gurobi with GAMS

 When running,
g, set solver to Gurobi
◦ By default
 Set Gurobi as default solver during GAMS installation
◦ Manually
M ll
 Option LP = Gurobi; { or MIP or RMIP }

 Setting Gurobi parameters


◦ Via command-line flags
◦ Via options file

18-Jun-10 © 2009 Gurobi Optimization 25


GAMS/Gurobi details

 See GAMS/Gurobi
/ Guide for:
◦ Installation / Configuration information
◦ Full list of options (parameters)
 A il bl on www.gams.com
Available

 A extra
An t license
li iis required
i d
◦ Separate licenses for Gurobi and GAMS do not
enable y
you to use Gurobi from GAMS
◦ Contact GAMS to obtain this license

18-Jun-10 © 2009 Gurobi Optimization 26


Hands-on with the Gurobi
Interactive Shell

18-Jun-10 © 2009 Gurobi Optimization 27


Try it: Open the environment

 Open
p a command p
prompt
p

 Type:
◦ gurobi (Windows)
◦ gurobi.sh (Linux, Mac)

 To quit:
◦ Press Ctrl
Ctrl-Z
Z (Windows)
◦ Press Ctrl-D (Linux, Mac)
◦ Enter quit()
Try it: Solve a model from a file

 cd to examples\data
p \ subdirectory
y of
Gurobi
 Open the Gurobi interactive shell
 Read a model
◦ model = read("afiro.mps")
 S l the
Solve th model
d l
◦ model.optimize()
 Print the solution
◦ model.printAttr("X")

18-Jun-10 © 2009 Gurobi Optimization 29


Interactive Shell structure

 Interactive shell is a p
programming
g g language!
g g
◦ read() is a global function
◦ Model is an object
◦ Model.optimize() and d Model.printAttr() are
methods (functions on the Model object)

 So we can choose any name for the model:


model = read("afiro.mps") m = read("afiro.mps")
model.optimize() m.optimize()
model.printAttr("X") m.printAttr("X")

18-Jun-10 © 2009 Gurobi Optimization 30


Attributes

 Attributes describe elements of a model

 Attributes pertain to a specific element


◦ Variable
◦ Constraint
◦ the overall Model
◦ Etc.

 Note that Attributes describe the model;


Parameters control the algorithms

18-Jun-10 © 2009 Gurobi Optimization 31


Working with attributes

 Some attributes are read-onlyy ((ex: ObjVal);


j );
others are settable (ex: UB)
 Methods to access attributes
◦ getAttr(), setAttr(): use name or wildcards
◦ Directly: x.UB
 Examples:
◦ print m.getAttr("ObjVal")
◦ x.UB = 1.0

 Don't panic! Just refer to the Attributes


reference manual
18-Jun-10 © 2009 Gurobi Optimization 32
Try it: Use model attributes

 Solve misc07.mps
p

 Print the following attributes:


◦ Objective value (ObjVal)
◦ Solution count (SolCount)

 Hint: use print keyword

18-Jun-10 © 2009 Gurobi Optimization 33


Primary Gurobi classes

 Model the model

 Var a variable

 Constr a constraint

18-Jun-10 © 2009 Gurobi Optimization 34


Selected global functions

 setParam()
()
◦ Set parameters for new models in this session

 read()
◦ Create a Model object from a model file

18-Jun-10 © 2009 Gurobi Optimization 35


Variable methods

 Var.getAttr()
g ()
◦ Get attribute values
 Var.setAttr()
◦ Set attribute values

 E
Example:
l
 x.setAttr("VarName", "TotalCost")
 print x.RC

18-Jun-10 © 2009 Gurobi Optimization 36


Constraint methods

 Constr.getAttr()
g ()
◦ Get attribute values
 Constr.setAttr()
◦ Set attribute values

 E
Example:
l
 c.setAttr("Sense", "=")
 print c.Slack

18-Jun-10 © 2009 Gurobi Optimization 37


Key model methods

 Solving
g
 Attribute & parameter management
 Summary information
 Copying & Writing
 Model introspection
 Model modification
 Callbacks

18-Jun-10 © 2009 Gurobi Optimization 38


Solving methods

 Model.optimize()
p ()
◦ Solve a model
 Model.presolve()
◦ Run presolve
 Model.reset()
◦ Reset solution information so that model is solved
from scratch
 Model.computeIIS()
p
◦ Compute LP or MIP IIS to detect infeasibilities

18-Jun-10 © 2009 Gurobi Optimization 39


Management methods

 Model.getAttr()
g ()
◦ Get attribute values
 Model.setAttr()
◦ Set attribute values
 Model.setParam()
◦ Set parameter values for the model
 Model.getParamInfo()
◦ Find current parameter values
 Model.read()
◦ Read information for a model
◦ Parameter file, MIP starting values, etc.

18-Jun-10 © 2009 Gurobi Optimization 40


Summary information

 Model.printAttr()
p ()
◦ Print nonzero attribute values

 Model.printStats()
◦ Print number of constraints, variables, etc.

 Model.printQuality()
◦ Print info about the solution quality

18-Jun-10 © 2009 Gurobi Optimization 41


Copying & Writing

 Model.copy()
py()
◦ Return a copy of the model, ex: n = m.copy()
 Model.relax()
◦ Return a copy of the model where integer variables
are relaxed
 Model fixed()
Model.fixed()
◦ Create a copy of the model where integer variables
are fixed to values in the current solution

18-Jun-10 © 2009 Gurobi Optimization 42


Model introspection

 Model.getVars()
g ()
◦ Get model variables as a list of Var objects
 Model.getConstrs()
◦ Get model constraints as a list of Constr objects
 Model.getRow()
◦ Get list of variables for a given constraint
 Model.getCol()
◦ Get list of constraints for a given variable

18-Jun-10 © 2009 Gurobi Optimization 43


Model modification

 Model.remove()
()
◦ Remove an element (variable, constraint)
 Model.addVar()
◦ Return a new variable for the model
 Model.addConstr()
◦ Return a new constraint for the model
 Model.addRange()
◦ Return a new range constraint for the model
 Model.update()
◦ Process model updates (more about this later)

18-Jun-10 © 2009 Gurobi Optimization 44


Try it: Use introspection

 Solve misc07.mps p
 Print variable names and values
◦ Code hint:
for v in [get the variables]:
print [variable name],[variable value]
◦ Notes
 v contains each variable value
 Must indent body of the for-loop
 Enter
E t blank
bl k li
line tto end
d th
the ffor-loop
l
 Extra credit: Just print nonzero values
◦ Code hint: if [variable is nonzero]:

18-Jun-10 © 2009 Gurobi Optimization 45


Congratulations!

 You jjust wrote y


your first Python
y p
programs
g
using Gurobi!
◦ The Gurobi Interactive Shell is really just the Python
shell
h ll with
ith extensions
t i for
f Gurobi
G bi

 More in the next section


section…

18-Jun-10 © 2009 Gurobi Optimization 46


Modeling with Gurobi OO
Interfaces

18-Jun-10 © 2009 Gurobi Optimization 47


3 Object-Oriented interfaces

 C++
 Java
 Python

 Similar in design
 All are efficient
◦ Each directly works with Gurobi matrices

 We will start with Python


◦ It
It’s
s interpreted
What is Python?

 General p
purpose
p p
programming
g g language
g g
◦ Dynamic typing
◦ Automatic memory management
◦ Obj t
Object-oriented
i t d
◦ Uses indentation for block delimiters

 Includes a large standard library

18-Jun-10 © 2009 Gurobi Optimization 49


Review: Key model methods

 Solving
g
 Attribute & parameter management
 Summary information
 Copying & Writing
 Model introspection
 Model modification
 Callbacks

18-Jun-10 © 2009 Gurobi Optimization 50


Lazy updates

 Lazy
y updates
p make Gurobi interfaces efficient
◦ Changes are made in a batch
 Remember to call Model.update() when you
need to reference
f an updated model element
◦ Ex: After you add a variable, call Model.update()
before using the variable in a constraint
◦ Model.update() is called automatically inside
Model.optimize()

 For best performance, only call


Model update() when necessary
Model.update()

18-Jun-10 © 2009 Gurobi Optimization 51


Basic steps to build a model

 Create a Model object


j
 Create the variables
 Call Model.update() once
 Create the constraints
 Call Model.optimize()
◦ No need to call Model.update() after adding
constraints – Model.optimize() calls Model.update()
auto at ca y
automatically

18-Jun-10 © 2009 Gurobi Optimization 52


Building linear expressions

 The LinExpr
p class defines linear expressions
p

 Simple expressions: use the constructor


◦ x + 2 y: LinExpr([1.0, 2.0], [x, y])

 Complex
l expressions: add
dd terms
◦ z[1] + z[2] + … + z[n]:
sum = LinExpr()
for zi in z:
sum.addTerms(1.0, zi)

18-Jun-10 © 2009 Gurobi Optimization 53


Try it: Build a simple LP

maximize x+y
subject to x+2y≤4
x, y ≥ 0
 Steps:
◦ Create the Model object
◦ M k maximization:
Make i i i set ModelSense
M d lS attribute
ib to -1
1
◦ Create the variables
◦ Update the model
◦ Add the constraints
◦ Solve & print objective
◦ W i model
Write d l using
i M d l i ("
Model.write("test.lp")
l ")

18-Jun-10 © 2009 Gurobi Optimization 54


Try it: Add a constraint

x-y=0

 Steps:
◦ Add the constraint
◦ Solve & print objective

18-Jun-10 © 2009 Gurobi Optimization 55


Adding a variable

 Tricky
y to add it to existing
g constraints

 Two options:
◦ Change coefficients in existing constraints
◦ Create a Column() object with the list of constraints
and coefficients

18-Jun-10 © 2009 Gurobi Optimization 56


Try it: Add a new variable

maximize x+y+2z
subject to x+2y+z≤4
x–y=0
x, y, z ≥ 0
 Steps:
◦ Use Model.getConstrs()[0] to get 1st constraint
◦ Create Column() object for z constraint coefficients
◦ Add z variable
◦ Solve and print objective

18-Jun-10 © 2009 Gurobi Optimization 57


Working with multiple models

 JJust create a Model object


j for each model!

 Example
m = read("model1.mps")
n = read("model2.mps")

18-Jun-10 © 2009 Gurobi Optimization 58


Try it: Working with 2 models

 Steps:
p
◦ Read misc07.mps from examples\data subdirectory
◦ Copy it to another Model object
◦ S t solution
Set l ti limit
li it to
t 2 iin th
the first
fi t model
d l andd solve
l
◦ Save its solution as a MIP start (.MST file)
◦ Read the MIP start in the 2nd model object
j
◦ Solve it to optimality

18-Jun-10 © 2009 Gurobi Optimization 59


Programming in Python

 Python
y is not jjust an interactive shell
◦ Store programs in files
◦ Run via gurobi.sh [filename]

 More care should be taken for a real program


◦ Error checking
◦ Testing the result codes of a model
 Optimal, feasible, etc.
◦ See examples\python subdirectory

18-Jun-10 © 2009 Gurobi Optimization 60


Try it: Run a Python program

 Go to examples\python
p \py subdirectory
y
 Run some of the examples:
◦ gurobi workforce3.py
◦ gurobi diet.py
 Take a look at the source code

18-Jun-10 © 2009 Gurobi Optimization 61


What about Java and C++?

 We used Python
y for training
g
◦ Nothing additional to setup and configure
◦ It is interactive – no compiling
◦ Easy
E to
t write
it – structure
t t iis lless rigid
i id

 Gurobi interfaces are similar for C++,


C++ Java

18-Jun-10 © 2009 Gurobi Optimization 62


Naming differences

 In Python
y
◦ Classes: Model, Var, Constr, …
◦ Methods: getAttr(), setAttr()
 I JJava, C
In C++
◦ Classes: GRBModel, GRBVar, GRBConstr, …
◦ Methods: get(),
get() set()

 See Reference Manual for details

18-Jun-10 © 2009 Gurobi Optimization 63


Other general differences

 Environment
◦ In Java and C++, start with an instance of GRBEnv
 Global parameters associated with the environment
◦ Constructor for GRBModel requires a GRBEnv object
 Error handling
◦ Must catch GRBException
◦ Mandatory
M d t ffor C
C++, JJava; optional
ti l ffor P
Python
th
 Global parameters
◦ GRBModel gets its copy of parameter settings
◦ Once GRBModel is instantiated, parameter changes in
GRBEnv are not reflected in model

18-Jun-10 © 2009 Gurobi Optimization 64


Other C++ considerations

 Operator
p overloading
g
◦ Makes model easier to read & write

 Memory management
◦ Lack of garbage collector makes C++ programming
more complicated

18-Jun-10 © 2009 Gurobi Optimization 65


C++ operator overloading

 Python
y
m.addConstr(
LinExpr([1, 2], [x, y]), '<', 5)
 C
C++
m.addConstr(x + 2*y <= 5);

 Helpful for simple expressions

18-Jun-10 © 2009 Gurobi Optimization 66


C++ memory management tips

 Be careful about lifecycle


y of C++ objects
j
◦ Destructor is called when they go out of scope

 Delete pointers to C++ objects when finished


◦ Otherwise you will have a memory leak

 Gurobi creates some objects on the heap


◦ Ex: GRBModel::addVars()

 See examples\c++ for best practices

18-Jun-10 © 2009 Gurobi Optimization 67


Comparing the OO interfaces

 Python
y
obj = m.getAttr("ObjVal")
nsol = m.getAttr("SolCount")
 J
Java
double obj = m.get(GRB.DoubleAttr.ObjVal)
int nsol = m.get(GRB.IntAttr.SolCount)
m get(GRB IntAttr SolCount)
 C++
double obj
j = m.get(GRB
g DoubleAttr ObjVal)
j
int nsol = m.get(GRB_IntAttr_SolCount)

18-Jun-10 © 2009 Gurobi Optimization 68


Gurobi OO modeling tips

 Prototype
yp with Interactive Shell
◦ Object model is nearly identical
◦ Interactive and easy to test things
◦ Even
E callbacks
llb k are supportedt d

 Be careful with C++ memory management

18-Jun-10 © 2009 Gurobi Optimization 69


Working
g with the C Interface

18-Jun-10 © 2009 Gurobi Optimization 70


Matrix interface

 Gurobi C++,, JJava and Python


y interfaces
represent a model via objects

 Gurobi C interface represents a model via


matrix coefficients
Sparse matrices

 In most models,, nearly


y all entries in the A
matrix are zero

 Modern solvers like Gurobi only represent the


non-zero elements in the A matrix

 This compression is very efficient for memory


and computation but there is a learning curve

18-Jun-10 © 2009 Gurobi Optimization 72


Compressed Sparse Matrices

 List the nonzero coefficients

 List the positions of these coefficients


◦ Remember that counting starts from zero!

 Two similar
l fformats to represent rows
(constraints) and columns (variables)

18-Jun-10 © 2009 Gurobi Optimization 73


Sparse row example

18-Jun-10 © 2009 Gurobi Optimization 74


Sparse column example

18-Jun-10 © 2009 Gurobi Optimization 75


C interface functions

 Environment creation & destruction


 Model creation & modification
 Solution
 Model queries
 Input/output
 Attribute & parameter management
 Logging & callbacks
 Error handling

18-Jun-10 © 2009 Gurobi Optimization 76


An example

maximize x + y + 2 z
subject to x + 2 y + 3 z <= 4
x + y >= 1
x, y, z binary

 This is mip1 from the examples subdirectory

18-Jun-10 © 2009 Gurobi Optimization 77


Initialization

/* Create environment */
error = GRBloadenv(&env, "mip1.log");
if (error || env == NULL) {
fprintf(stderr, "Error: could not create environment\n");
exit(1);
exit(1)
}

/ Create an empty
/* p y model */
/
error = GRBnewmodel(env, &model, "mip1", 0, NULL, NULL, NULL,
NULL, NULL);
if (error) goto QUIT;

18-Jun-10 © 2009 Gurobi Optimization 78


Creating variables

/* Add variables */
obj[0] = -1; obj[1] = -1; obj[2] = -2;
vtype[0] = GRB_BINARY; vtype[1] = GRB_BINARY; vtype[2] =
GRB_BINARY;
error = GRBaddvars(model,
GRBaddvars(model 3,
3 00, NULL
NULL, NULL,
NULL NULL,
NULL obj,
obj NULL,
NULL
NULL, vtype, NULL);
if (error) goto QUIT;

/* Integrate new variables */


error = GRBupdatemodel(model);
if (error) goto QUIT;

18-Jun-10 © 2009 Gurobi Optimization 79


Adding constraints

/* First constraint: x + 2 y + 3 z <= 4 */


ind[0] = 0; ind[1] = 1; ind[2] = 2;
val[0] = 1; val[1] = 2; val[2] = 3;
error = GRBaddconstr(model, 3, ind, val, GRB_LESS_EQUAL, 4.0,
"c0");
c0 );
if (error) goto QUIT;

/* Second constraint: x + y >= 1 */


ind[0] = 0; ind[1] = 1;
val[0] = 1; val[1] = 1;
error = GRBaddconstr(model, 2, ind, val, GRB_GREATER_EQUAL, 1.0,
"c1");
"c1")
if (error) goto QUIT;

18-Jun-10 © 2009 Gurobi Optimization 80


Optimization

/* Optimize model */
error = GRBoptimize(model);
if (error) goto QUIT;

/* Capture solution information */


error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
if (error) goto QUIT;

error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);


if (error) goto QUIT;

error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, 3, sol);


if (error) goto QUIT;

18-Jun-10 © 2009 Gurobi Optimization 81


Error reporting & cleanup

/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}

/* Free model */
( );
GRBfreemodel(model);

/* Free environment */
GRBfreeenv(env);

18-Jun-10 © 2009 Gurobi Optimization 82


Comparing the interfaces

 Python
obj = m.getAttr("ObjVal")
nsol = m.getAttr("SolCount")
 Java
double obj = m.get(GRB.DoubleAttr.ObjVal)
int nsol = m.get(GRB.IntAttr.SolCount)
 C++
double obj = m.get(GRB_DoubleAttr_ObjVal)
int nsol = m.get(GRB_IntAttr_SolCount)
 C
error = GRBgetdblattr(m, GRB_DBL_ATTR_OBJVAL, &objval);
error = GRBgetintattr(m, GRB_INT_ATTR_SOLCOUNT, &nsol);

18-Jun-10 © 2009 Gurobi Optimization 83


Summary

 C interface is the matrix interface to Gurobi


◦ Direct interface to Gurobi data structures

 OO interfaces are modeling interfaces


◦ Generally easier to use

 All are very lightweight


◦ Very low overhead
◦ All support efficient “lazy updates”
◦ Use your programming needs to pick an interface

18-Jun-10 © 2009 Gurobi Optimization 84

You might also like