You are on page 1of 16

Gurobi

IEDA 3010 Tutorial 03


Chen Yang
Quick Review
• Create model
• Add variables
• Set objective
• Add constraints
• Optimize
• Output results
• Use generator in loops
Generator
Generator allows you to
declare an object that behaves
like an iterator, i.e. it can be
used in a for loop. • Define and use a generator
function
• Create a generator and
create a list using generator
AddVars & Tupledict

Add variables with 2 indices


whose ranges are 2 and 3 Tupledict: the type of the output
• Sum
Tupledict
Traditional dict

• Select • Prod
x.prod(coeff) would contain term 2.0*var if
x[0,0] = var and coeff[0,0] = 2.0
Problem
Consider an LP problem as

where
Code of addVars

the objective here is the sum of a generator


Code of addConstrs

Equivalent code using sum()


Code and Output
Write
• How to check the model you input?

To write the formulation of the problem, use ‘*.lp’. Link to other file
format:
https://www.gurobi.com/documentation/9.5/refman/model_file_format
s.html#sec:FileFormats
Same Problem Using MVar

Results
of write()
Comparison of the Written File
Var MVar

Two indices for Var (the original definition). Only one index in MVar.
Var & MVar • Transfer Mvar to Var: tolist()

• Two parallel data types and • tolist


can not be used mutually

This code is wrong!


Var & MVar
Comparison of multiple Var and MVar
Var MVar

Create addVars addMVar

Return type Tupledict MVar

Index x[i,j], x.select(i,j) x[i,j], x[i][j]

Sum x.sum(), x.sum(i, ‘*’) x.sum(), x[i,:].sum()

Prod x.prod(coeff) None

@ operator Unavailable Available

Expression type LinExpr MLinExpr

Constraint type Constr MConstr

Transform None tolist()


Quicksum

Use it directly by

For most problems, the process


of model construction is not
costly. Using sum is already
enough.
Example of Network Optimization
An example from gurobi about
computing the network flow. You
can find the introduction to details
here

https://www.gurobi.com/documenta
tion/9.5/quickstart_windows/cs_pyt
hon.html#section:Python

This example is interesting and


challenging, so you can try to read
it and practice.

You might also like