3. From the model to Python/Gurobi
Lecture notes (PDF) · Slides (PDF)
Class: implementation · Script: python/cap06_gurobi.py
Prerequisites
-
From this module, Chapter 1 «What is a MIP model»: the classes of variables and the structure of a model.
-
From this module, Chapter 2 «Relaxations, duality and bounds»: the LP relaxation, its dual and the solver attributes
ObjValandObjBound.
Objectives
At the end of this chapter you will be able to:
-
write a model in
gurobipy, one family of variables and constraints per block; -
declare the four classes of variables, remembering the default bounds;
-
read the results in the right order:
Status,SolCount,ObjValandObjBound; -
use tolerances correctly when reading integer values;
-
solve the LP relaxation with
relax()and read its duals.
The course uses one solver only, Gurobi from Python. The chapter shows how a model is written — one family of constraints per block, with the names of the mathematical model — how the results are read, including the case where the solver has not finished, and three complete models that the heuristics chapter takes up again.
Every number on these pages comes from a single script,
python/cap06_gurobi.py, and the chapter is organised into five sections.
-
3.1 Writing a model in gurobipy
The basic gurobipy instructions, the four classes of variables and the rule of the course: one family of constraints per block.
-
3.2 Reading the results
Status,SolCount,ObjVal,ObjBound,MIPGap,NodeCount, and the three cases whereObjValcannot be read. -
3.3 Tolerances and relaxations
"Integer" within
IntFeasTol, andrelax()to obtain the relaxation of the model just written. -
3.4 Three classic models
Bin packing, makespan and travelling salesman, from the statement to the instance: the three problems the heuristics take up again.
-
3.5 The protocol, and how to run it
The sequence every problem repeats, from the data to the table of bounds, and how the script is run.
In summary
In summary
-
A
gurobipymodel is written block by block, oneaddConstrsper family, with the name of the constraint label. -
The results are read always in the same order; with
SolCount\(=0\) there is noObjValto read. -
Integer means integer within a tolerance: one tests
x.X > 0.5, neverx.X == 1. -
relax()gives the LP relaxation and its dualsPi, the numbers that the notes compare with the hand-built dual. -
Bin packing, makespan and the TSP (MTZ formulation) are the three models that the rest of the course reuses.