Python Interface
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. This chapter assumes that you are already familiar with the Python programming language, and that you read the preceding section on the Gurobi Interactive Shell. If you would like to learn more about the Python language, we recommend that you visit the online Python tutorial.
We should note that Gurobi has chosen not to make any assumptions about what Python components are already installed on your machine. We have therefore included a full Python environment with our distribution. You will need to use a set of scripts we provide in order to run Gurobi Python programs within our distributed Python environment. Alternatively, if you are already a Python user, we provide a setup.py script for installing the gurobipy module in your Python environment. You should refer to the instructions for building and running the example for further details.
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(0.0, 1.0, -1.0, GRB.BINARY, "x")
y = m.addVar(0.0, 1.0, -1.0, GRB.BINARY, "y")
z = m.addVar(0.0, 1.0, -2.0, GRB.BINARY, "z")
# Integrate new variables
m.update()
# Add constraint: x + 2 y + 3 z <= 4
m.addConstr(LinExpr([1.0, 2.0, 3.0], [x, y, z]), GRB.LESS_EQUAL, 4.0, "c0")
# Add constraint: x + y >= 1
m.addConstr(LinExpr([1.0, 1.0], [x, y]), GRB.GREATER_EQUAL, 1.0, "c1")
m.optimize()
for v in m.getVars():
print v.VarName, v.X
print 'Obj:', m.ObjVal
except:
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.
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(0.0, 1.0, -1.0, GRB.BINARY, "x") y = m.addVar(0.0, 1.0, -1.0, GRB.BINARY, "y") z = m.addVar(0.0, 1.0, -2.0, GRB.BINARY, "z")Variables are added through the addVar() method on a model object. A variable is always associated with a particular model.
The first and second arguments to the addVar() call are the variable lower and upper bounds, respectively. The third argument is the objective coefficient (the default objective sense is minimization, so we've negated the coefficients from our maximization objective here). The fourth argument is the variable type. Our variables are all binary in this example. The final argument is the name of the variable.
The addVar() method also takes an optional final column argument that allows you to specify a set of initial non-zero values for the new variable. Please refer to the online help ( help(Model.addVar) in the Gurobi Shell) for further details.
Updating the model - lazy modification
Model modifications in the Gurobi optimizer are done in a lazy fashion, meaning that the effect of the modification is 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 modification does require you to manually integrate model changes when needed. This is done with the following routine:
# Integrate new variables m.update()
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(LinExpr([1.0, 2.0, 3.0], [x, y, z]), GRB.LESS_EQUAL, 4.0, "c0")As with variables, constraints are always associated with a specific model. They are created using the addConstr() method on the model object. The first three arguments provide the left-hand side of the constraint, the sense, and the right-hand side. The two sides can consist of either a constant, a variable, or a linear expression (an object of type LinExpr). In our example, we created a linear expression object on the fly for the left-hand side, and used a constant (4.0) for the right-hand side.
The second constraint is created in a similar manner:
# Add constraint: x + y >= 1 m.addConstr(LinExpr([1.0, 1.0], [x, y]), GRB.GREATER_EQUAL, 1.0, "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 associated except block.
Building and running the example
Python is an interpreted language, so no explicit compilation step is required to run the examples. For Windows platforms, you can simply type the following in the Gurobi Python example directory (<installdir>/examples/python):
gurobi.bat mip1.pyFor Linux or Mac OS platforms, type:
gurobi.sh mip1.py
If you are a Python user, and wish to use Gurobi from within your own Python environment, you can install the gurobipy module directly into your environment. You do this by issuing this command from your <installdir>:
python setup.py installOn Linux or Mac OS systems, unless you are using your own private Python installation, you will need to run this command as super-user. Once gurobipy is successfully installed, you can type python mip1.py (more generally, you can type from gurobipy import * in your Python environment).
The Python example directory contains a number of examples. We encourage you to browse and modify them in order to become more familiar with the Gurobi Python interface.
