Quick Start
Solving an optimization problem using Gurobi in Python usually involves the following steps:
Create an empty model
Add variables
Set the objective function
Add constraints
Optimize the model
Retrieve the solution
Create an empty model
gb.Model()
is the most used class in Gurobi. It represents a mathematical optimization model.
In the code above, m
is an object of the class Model
. The string "NewModel"
is the name of the model.
Add variables
Class Model
has a method called addVar()
that adds a variable to the model. The method has the following signature:
The arguments are:
lb
: lower bound of the variableub
: upper bound of the variableobj
: coefficient of the variable in the objective functionvtype
: type of the variable. It can beGRB.CONTINUOUS
,GRB.BINARY
, orGRB.INTEGER
name
: name of the variable
By default, addVar(lb=0.0, ub=float('inf'), obj=0.0, vtype=GRB.CONTINUOUS, name="", column=None)
is called.
In addition to the addVar()
method, the Model
class has the addVars()
method and addMVar()
method. The addVars()
method adds multiple variables at once. The addMVar()
method adds NumPy
ndarray variables.
Set the objective function
The objective function is set using the setObjective()
method. This method has two arguments: the expression of the objective function and the sense of the optimization. The sense can be GRB.MINIMIZE
or GRB.MAXIMIZE
.
Note that setObjectiveN()
can be used for multi-objective optimization.
Add constraints
Constraints are added using the addConstr()
method. The method has two arguments: the expression of the constraint and the name of the constraint.
Optimize the model
Once we have added the variables, the objective function, and the constraints, we can optimize the model using the optimize()
method.
Retrieve the solution
After the optimization, we can retrieve the solution using the getVars()
method.
Example: Solving a mixed-integer linear programming problem
Let's solve the following mixed-integer linear programming problem:
Last updated