This section will work through a simple Python example in order to illustrate the use of the Gurobi Python interface. The example builds a model, optimizes it, and outputs the optimal objective value.
Our example optimizes the following model:
maximize | x | + | y | + | 2 z | ||
subject to | x | + | 2 y | + | 3 z | ![]() |
4 |
x | + | y | ![]() |
1 | |||
x, y, z binary |
Example mip1.py
This is the complete source code for our example (also available in <installdir>/examples/python/mip1.py)...
from gurobipy import * try: # Create a new model m = Model("mip1") # Create variables x = m.addVar(vtype=GRB.BINARY, name="x") y = m.addVar(vtype=GRB.BINARY, name="y") z = m.addVar(vtype=GRB.BINARY, name="z") # Integrate new variables m.update() # Set objective m.setObjective(x + y + 2 * z, GRB.MAXIMIZE) # Add constraint: x + 2 y + 3 z <= 4 m.addConstr(x + 2 * y + 3 * z <= 4, "c0") # Add constraint: x + y >= 1 m.addConstr(x + y >= 1, "c1") m.optimize() for v in m.getVars(): print v.varName, v.x print 'Obj:', m.objVal except GurobiError: print 'Error reported'
Example details
Let us now walk through the example, line by line, to understand how it achieves the desired result of optimizing the indicated model.
The example begins by importing the Gurobi functions and classes:
from gurobipy import *Gurobi Python applications should always start with this line.
Note that in order for this command to succeed, the Python application needs to know how to find the Gurobi functions and classes. Recall that you have two options here. The first is to use the Python files that are included with our distribution. You would run this example by typing gurobi.bat mip1.py (Windows) or gurobi.sh mip1.py (Linux and Mac). The second option is to install the Gurobi functions and classes into your own Python installation. Follow the instructions for running setup.py to do this.
Creating the model
The first step in our example is to create a model. A Gurobi model holds a single optimization problem. It consists of a set of variables, a set of constraints, and the associated attributes (variable bounds, objective coefficients, variable integrality types, constraint senses, constraint right-hand side values, etc.). We start this example with an empty model object:
m = Model("mip1")This function takes the desired model name as its argument.
Adding variables to the model
The next step in our example is to add variables to the model.
# Create variables x = m.addVar(vtype=GRB.BINARY, name="x") y = m.addVar(vtype=GRB.BINARY, name="y") z = m.addVar(vtype=GRB.BINARY, name="z")Variables are added through the addVar() method on a model object. A variable is always associated with a particular model.
Python allows you to pass arguments by position or by name. We've passed them by name here. Each variable gets a type (binary), and a name. We use the default values for the other arguments. Please refer to the online help (help(Model.addVar) in the Gurobi Shell) for further details on addVar().
Updating the model - lazy modification
Model modifications in the Gurobi optimizer are done in a lazy fashion, meaning that the effects of the modifications are not seen immediately. This approach makes it easier to perform a sequence of model modifications, since the model doesn't change while it is being modified. However, lazy modifications do require you to manually integrate model changes when needed. This is done with the update method:
# Integrate new variables m.update()
Setting the objective
The next step in the example is to set the optimization objective:
# Set objective: maximize x + y + 2 z model.setObjective(x + y + 2 * z, GRB.MAXIMIZE)
The objective is built here using overloaded operators. The Python API overloads the arithmetic operators to allow you to build linear and quadratic expression involving Gurobi variables.
The second argument indicates that the sense is maximization.
Adding constraints to the model
The next step in the example is to add the constraints. The first constraint is added here:
# Add constraint: x + 2 y + 3 z <= 4 m.addConstr(x + 2 * y + 3 * z <= 4, "c0")As with variables, constraints are always associated with a specific model. They are created using the addConstr() method on the model object.
We again use overloaded arithmetic operators to build linear expressions. The comparison operators are also overloaded to make it easy to build constraints.
The second argument to addConstr gives the (optional) constraint name.
The second constraint is created in a similar manner:
# Add constraint: x + y >= 1 m.addConstr(x + y >= 1, "c1")
Optimizing the model
Now that the model has been built, the next step is to optimize it:
# Optimize model m.optimize()This routine performs the optimization and populates several internal model attributes (including the status of the optimization, the solution, etc.).
Reporting results - attributes
Once the optimization is complete, we can query the values of the attributes. In particular, we can query the varName and x variable attributes to obtain the name and solution value for each variable:
for v in m.getVars(): print v.varName, v.x
We can also query the objVal attribute on the model to obtain the objective value for the current solution:
print 'Obj:', m.objVal
The names and types of all model, variable, and constraint attributes can be found in the online Python documentation. Type help(GRB.attr) in the Gurobi Shell for details.
Error handling
Errors in the Gurobi Python interface are handled through the Python exception mechanism. In the example, all Gurobi statements are enclosed inside a try block, and any associated errors would be caught by the except block.
Running the example
When you run the example (gurobi.bat mip1.py on Windows, or gurobi.sh mip1.py on Linux or Mac), you should see the following output:
Optimize a model with 2 rows, 3 columns and 5 nonzeros Presolve removed 2 rows and 3 columns Presolve time: 0.00s Explored 0 nodes (0 simplex iterations) in 0.00 seconds Thread count was 1 (of 4 available processors) Optimal solution found (tolerance 1.00e-04) Best objective 3.000000000000e+00, best bound 3.000000000000e+00, gap 0.0% x 1.0 y 0.0 z 1.0 Obj: 3.0