Python Reference Manual
This section documents the Gurobi Python interface. It begins with an overview of the global functions, which can be called without referencing any Python objects. It then discusses the different types of objects that are available in the interface, and the most important methods on those objects. Finally, it gives a comprehensive presentation of all of the available classes and methods.
Global Functions
The Gurobi shell contains a set of Global Functions that can be called without referring to any Gurobi objects. The most important of these functions is probably the read function, which allows you to read a model from a file. Other useful global functions are system, which allows you to issue shell commands from within the Gurobi shell, and models, which gives you a list of the currently loaded models. Other global functions allow you to read, modify, or write Gurobi parameters (readParams, setParam, and writeParams).
Models
Most actions in the Gurobi Python interface are performed by calling methods on Gurobi objects. The most commonly used object is the Model. A model consists of a set of decision variables (objects of class Var), and a set of linear constraints (objects of class Constr) or SOS constraints (objects of class SOS) on these variables. Each variable has an associated lower bound, upper bound, objective coefficient, and type (continuous, binary, etc.). Each linear constraint has an associated sense (less-than-or-equal, greater-than-or-equal, or equal), and right-hand side value.
An optimization model may be specified all at once, by loading the model from a file (using the previously mentioned read function), or it may be built incrementally, by first constructing an empty object of class Model and then subsequently calling Model.addVar to add additional variables, and Model.addConstr to add additional constraints. Constraints are specified by building linear expressions (objects of class LinExpr), and then specifying relationships between these expressions (for example, requiring that one expression be equal to another).
Models are dynamic entities; you can always add or remove variables or constraints.
Solving a Model
Once you have built a model, you can call Model.optimize to compute a solution. By default, optimize will use the dual simplex algorithm to solve continuous models, and the branch-and-cut algorithm to solve mixed integer models. The solution is stored in a set of attributes of the model, which can be subsequently queried (we will return to this topic shortly).
The Gurobi algorithms keep careful track of the state of the model, so calls to Model.optimize will only perform further optimization if relevant data has changed since the model was last optimized. If you would like to discard previously computed solution information and restart the optimization from scratch without changing the model, you can call Model.reset.
If a model is found to be infeasible, you can call Model.computeIIS to compute an Irreducible Inconsistent Subsystem (IIS) for the model. This method can be used for both continuous and MIP models, but you should be aware that the MIP version can be quite expensive. This method populates a set of IIS attributes.
After a MIP model has been solved, you can call Model.fixed to compute the associated fixed model. This model is identical to the input model, except that all integer variables are fixed to their values in the MIP solution. In some applications, it is useful to compute information on this continuous version of the MIP model (e.g., dual variables, sensitivity information, etc.).
Querying and Modifying Attributes
Most of the information associated with a Gurobi model is stored in a set of attributes. Some attributes are associated with the variables of the model, some with the constraints of the model, and some with the model itself. To give a simple example, solving an optimization model causes the X variable attribute to be populated. Attributes such as X that are computed by the Gurobi engine cannot be modified directly by the user, while others, such as the variable lower bound (the LB attribute) can.
Attributes can be accessed in two ways in the Python interface. The first is to use the getAttr() and setAttr() methods, which are available on variables (Var.getAttr/ Var.setAttr), constraints (Constr.getAttr/ Constr.setAttr), and SOSs (SOS.getAttr), and models (Model.getAttr/ Model.setAttr). These are called with the attribute name as the first argument (e.g., var.getAttr("X") or constr.setAttr("RHS", 0.0)). The full list of available attributes can be found in the Attributes section of this manual.
Attributes can also be accessed more directly: you can follow an object name by a period, followed by the name of an attribute of that object. Note that upper/lower case is ignored when referring to attributes. Thus, b = constr.rhs is equivalent to b = constr.getAttr("RHS"), and constr.rhs = 0.0 is equivalent to constr.setAttr("RHS", 0.0),
Additional Model Modification Information
Most modifications to an existing model are done through the attribute interface (e.g., changes to variable bounds, objective coefficients, constraint right-hand sides, etc.). The main exception is modification of the constraint matrix. The constraint matrix can be modified in a few ways. The first is to call the Model.chgCoeff method. This method can be used to modify the value of an existing non-zero, to set an existing non-zero to zero, or to create a new non-zero. Another way to modify the non-zeros in an existing constraint matrix is to remove a variable or constraint (through the Model.remove method). The non-zero values associated with the deleted constraint or variable are removed along with the constraint or variable itself.
One very important item to note about model modifications in the Gurobi optimizer is that they are performed in a lazy fashion, meaning that they don't actually affect the model until the next call to optimize or update on that model object. This approach provides the advantage that the model remains unchanged while you are in the process of making multiple modifications. The downside, of course, is that you have to remember to call update in order to see the effect of your changes.
Managing Parameters
The Gurobi optimizer provides a set of parameters to allow you to control many of the details of the optimization process. Factors like feasibility and optimality tolerances, choices of algorithms, strategies for exploring the MIP search tree, etc., can be controlled by modifying Gurobi parameters before beginning the optimization. Parameters are set using method Model.setParam. Current values may also be retrieved with Model.getParamInfo. You can also access parameters more directly through the Model.Params class. To set the MIPGap parameter to 0.0 for model m, for example, you can do either m.setParam('MIPGap', 0) or m.Params.MIPGap = 0.
You can read a set of parameter settings from a file using Model.read, or write the set of changed parameters using Model.write.
One thing we should note is that changing a parameter for one model has no effect on the parameter value for other models. Use the global setParam method to set a parameter for all loaded models.
The full list of Gurobi parameters can be found in the Parameters section.
Monitoring Progress - Logging and Callbacks
Progress of the optimization can be monitored through Gurobi logging. By default, Gurobi will send output to the screen. A few simple controls are available for modifying the default logging behavior. You can set the LogfileName parameter if you wish to also direct the Gurobi log to a file. The frequency of logging output can be controlled with the DisplayInterval parameter, and logging can be turned off entirely with the OutputFlag parameter.
More detailed progress monitoring can be done through a callback function. If you pass a function taking two arguments, model and where, to Model.optimize, your function will be called periodically from within the optimization. Your callback can then call Model.cbGet to retrieve additional information on the state of the optimization. You can refer to the Callback class for additional information.
Modifying Solver Behavior - Callbacks
Callbacks can also be used to modify the behavior of the Gurobi optimizer. The simplest control callback is Model.terminate, which asks the optimizer to terminate at the earliest convenient point. Method Model.cbSetSolution allows you to inject a feasible solution (or partial solution) during the solution of a MIP model. Method Model.cbCut allows you to add a cutting plane during a MIP optimization.
Error Handling
All of the methods in the Gurobi Python library can throw an exception of type GurobiError. When an exception occurs, additional information on the error can be obtained by retrieving the errno or message members of the GurobiError object. A list of possible values for the errno field can be found in the Error Code section.
Subsections
- Global Functions
- Model
- Model()
- Model.addConstr()
- Model.addRange()
- Model.addSOS()
- Model.addVar()
- Model.chgCoeff()
- Model.computeIIS()
- Model.copy()
- Model.fixed()
- Model.getAttr()
- Model.getCoeff()
- Model.getCol()
- Model.getConstrs()
- Model.getParamInfo()
- Model.getRow()
- Model.getSOS()
- Model.getVars()
- Model.optimize()
- Model.presolve()
- Model.printAttr()
- Model.printQuality()
- Model.printStats()
- Model.cbCut()
- Model.cbGet()
- Model.cbGetNodeRel()
- Model.cbGetSolution()
- Model.cbSetSolution()
- Model.read()
- Model.relax()
- Model.remove()
- Model.reset()
- Model.setAttr()
- Model.setParam()
- Model.terminate()
- Model.update()
- Model.write()
- Var
- Constr
- SOS
- LinExpr
- LinExpr()
- LinExpr.add()
- LinExpr.addConstant()
- LinExpr.addTerms()
- LinExpr.clear()
- LinExpr.copy()
- LinExpr.getConstant()
- LinExpr.getCoeff()
- LinExpr.getVar()
- LinExpr.remove()
- LinExpr.size()
- Column
- Column()
- Column.addTerms()
- Column.clear()
- Column.copy()
- Column.getCoeff()
- Column.getConstr()
- Column.remove()
- Column.size()
- Callbacks
- GurobiError
- GRB
