Demo 2 - Creating and solving your first model

$$\begin{array}{rll} \text{max} & x+y+2z \\ \text{s.t.} & x + 2y + 3z \le 4 \\ & x + y \ge 1 \\[10pt] & x,y,z \in \lbrace 0,1 \rbrace \end{array} $$

Step 1: Import functions from the gurobipy module

In [1]:
from gurobipy import *

Step 2: Create empty model

In [2]:
m = Model()

Step 3: Create activitiy variables

In [3]:
x = m.addVar(vtype=GRB.BINARY, name="x")
y = m.addVar(vtype=GRB.BINARY, name="y")
z = m.addVar(vtype=GRB.BINARY, name="z")

Step 4: Set objective function

In [4]:
m.setObjective(x + y + 2*z, GRB.MAXIMIZE)

Step 5: Add constraints

In [5]:
c1 = m.addConstr(x + 2*y + 3*z <= 4)
c2 = m.addConstr(x + y >= 1)

Step 6: Solve model

In [6]:
m.optimize()
Optimize a model with 2 rows, 3 columns and 5 nonzeros
Variable types: 0 continuous, 3 integer (3 binary)
Coefficient statistics:
  Matrix range     [1e+00, 3e+00]
  Objective range  [1e+00, 2e+00]
  Bounds range     [1e+00, 1e+00]
  RHS range        [1e+00, 4e+00]
Presolve removed 2 rows and 3 columns
Presolve time: 0.00s
Presolve: All rows and columns removed

Explored 0 nodes (0 simplex iterations) in 0.02 seconds
Thread count was 1 (of 4 available processors)

Solution count 1: 3 
Pool objective bound 3

Optimal solution found (tolerance 1.00e-04)
Best objective 3.000000000000e+00, best bound 3.000000000000e+00, gap 0.0000%

Step 8: Print variable values for optimal solution

In [7]:
m.printAttr('X')
    Variable            X 
-------------------------
           x            1 
           z            1