Linear Programming Formulation

First, you will learn how to solve the following Linear Program using Gurobi Python interface.

$$ \begin{aligned} \text{Min} \,\, 10x + 26y & \\ 11x + 3y & \ge 21 \\ 6x + 20y & \ge 39 \\ x \ge 0 ,& y \ge 0 \end{aligned} $$

The following should be the first line of any of your python + gurobi programs. This is to ensure that the program can access the gurobi functions and classes.

In [1]:
from gurobipy import *

Next we create a new gurobi model and name it lp. Note that you can change the name of the model ls as well as name of the gurobi object which in this case is m.

In [2]:
# Create a new Gurobi Model
m = Model("lp")  

Next we create two positive variables $x$ and $y$ and add it to the model.

In [3]:
# Create two new variables
x = m.addVar(lb=0, name ="x")
y = m.addVar(lb=0, name ="y")

We then add the objective function to the model. The objective function in this case is minimize. If you wanted to maximize, you would set the objective function parameter to GRB.MAXIMIZE.

In [4]:
# Set the objective function
m.setObjective(10*x + 26*y, GRB.MINIMIZE)

We then add two constraints named c0 and c1. The earlier versions of gurobi have a m.update() command which is not needed in version 7.

In [5]:
#Add Constraints
m.addConstr(11*x + 3*y >= 21, "c0")
m.addConstr(6*x + 20*y >= 39, "c1")
Out[5]:
<gurobi.Constr *Awaiting Model Update*>

Next we solve the model.

In [6]:
# Solve the model
m.optimize()
Optimize a model with 2 rows, 2 columns and 4 nonzeros
Coefficient statistics:
  Matrix range     [3e+00, 2e+01]
  Objective range  [1e+01, 3e+01]
  Bounds range     [0e+00, 0e+00]
  RHS range        [2e+01, 4e+01]
Presolve time: 0.49s
Presolved: 2 rows, 2 columns, 4 nonzeros

Iteration    Objective       Primal Inf.    Dual Inf.      Time
       0    0.0000000e+00   2.531250e+00   0.000000e+00      0s
       2    5.4000000e+01   0.000000e+00   0.000000e+00      0s

Solved in 2 iterations and 0.49 seconds
Optimal objective  5.400000000e+01

If the model was solved to optimality, we print the objective function and optimal solution. We show two ways to access the optimal solution below.

In [7]:
if m.status == GRB.Status.OPTIMAL:
    print('Obj Function:', m.objVal)
    for v in m.getVars():
        print(v.varName, v.x)
# Another way to print the variable
    print("Optimal Solution:")
    print(x.varName, x.x)
    print(y.varName, y.x)        
else:
    print(m.status)
Obj Function: 54.0
x 1.5
y 1.5
Optimal Solution:
x 1.5
y 1.5