Gurobi Training
Gurobi 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
A quick
i k peek
k under
d the
h h
hood
d
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
Matrix
◦ C
Object-oriented
◦ C++, Java, Python
◦ .NET through Microsoft Solver Foundation
Interactive shell and command
command-line
line tool
Modeling systems and MATLAB
Models
◦ .LP, .MPS, .RLP, .REW
Solution information
◦ .ILP, .MST, .BAS, .SOL
Parameters
◦ .PRM
PRM
Designed
g for efficiency
y
◦ Very efficient simplex
◦ Very powerful MIP
◦ Make
M k ththe mostt off multi-processors
lti
Very
y simple
p way
y to solve a model from a file
◦ gurobi_cl [param=value]* filename
Open
p a command p
prompt
p
cd to examples\data
p subdirectory
y of
Gurobi
Cutting planes:
Gomory: 1
Example
◦ gurobi
bi cl
l heuristics=0.2
h i ti 0 2 misc07.mps
i 07
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
FeasibilityTol:
y Primal feasibility
y
IntFeasTol: Integer feasibility
MarkowitzTol: Simplex pivoting
MIPGap: Relative MIP gap
OptimalityTol: Dual feasibility
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
Getting
g Started Manual
Reference Manual
◦ APIs
◦ Parameters
◦ Attributes
Example Tour
◦ 16 examples for all supported languages
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
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
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 }
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
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")
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)
Solve misc07.mps
p
Var a variable
Constr a constraint
setParam()
()
◦ Set parameters for new models in this session
read()
◦ Create a Model object from a model file
Var.getAttr()
g ()
◦ Get attribute values
Var.setAttr()
◦ Set attribute values
E
Example:
l
x.setAttr("VarName", "TotalCost")
print x.RC
Constr.getAttr()
g ()
◦ Get attribute values
Constr.setAttr()
◦ Set attribute values
E
Example:
l
c.setAttr("Sense", "=")
print c.Slack
Solving
g
Attribute & parameter management
Summary information
Copying & Writing
Model introspection
Model modification
Callbacks
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
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.
Model.printAttr()
p ()
◦ Print nonzero attribute values
Model.printStats()
◦ Print number of constraints, variables, etc.
Model.printQuality()
◦ Print info about the solution quality
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
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
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)
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]:
C++
Java
Python
Similar in design
All are efficient
◦ Each directly works with Gurobi matrices
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
Solving
g
Attribute & parameter management
Summary information
Copying & Writing
Model introspection
Model modification
Callbacks
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()
The LinExpr
p class defines linear expressions
p
Complex
l expressions: add
dd terms
◦ z[1] + z[2] + … + z[n]:
sum = LinExpr()
for zi in z:
sum.addTerms(1.0, zi)
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 ")
x-y=0
Steps:
◦ Add the constraint
◦ Solve & print objective
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
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
Example
m = read("model1.mps")
n = read("model2.mps")
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
Python
y is not jjust an interactive shell
◦ Store programs in files
◦ Run via gurobi.sh [filename]
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
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
In Python
y
◦ Classes: Model, Var, Constr, …
◦ Methods: getAttr(), setAttr()
I JJava, C
In C++
◦ Classes: GRBModel, GRBVar, GRBConstr, …
◦ Methods: get(),
get() set()
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
Operator
p overloading
g
◦ Makes model easier to read & write
Memory management
◦ Lack of garbage collector makes C++ programming
more complicated
Python
y
m.addConstr(
LinExpr([1, 2], [x, y]), '<', 5)
C
C++
m.addConstr(x + 2*y <= 5);
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)
Prototype
yp with Interactive Shell
◦ Object model is nearly identical
◦ Interactive and easy to test things
◦ Even
E callbacks
llb k are supportedt d
Two similar
l fformats to represent rows
(constraints) and columns (variables)
maximize x + y + 2 z
subject to x + 2 y + 3 z <= 4
x + y >= 1
x, y, z binary
/* 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;
/* 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;
/* Optimize model */
error = GRBoptimize(model);
if (error) goto QUIT;
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free model */
( );
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
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);