Gurobi Cookbook - Linear Model (4/5)

Creating a linear programming model

We will formulate the following linear program

minimize 2 x + 3 y
subject to:
x + y >= 10
x - y <= 4
x, y >= 0
model = grb.Model()
x = model.addVar(name='x', obj=2)
y = model.addVar(name='y', obj=3)
model.update()
c0 = model.addConstr(x + y >= 10, name='c0')
c1 = model.addConstr(x - y <= 4, name='c1')
model.update()
model.optimize()
if model.solCount > 0:
    print("objective = ", model.objVal)
else:
    print("solution status = ", model.Status)
Optimize a model with 2 rows, 2 columns and 4 nonzeros
Coefficient statistics:
  Matrix range    [1e+00, 1e+00]
  Objective range [2e+00, 3e+00]
  Bounds range    [0e+00, 0e+00]
  RHS range       [4e+00, 1e+01]
Presolve time: 0.00s
Presolved: 2 rows, 2 columns, 4 nonzeros

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

Solved in 2 iterations and 0.01 seconds
Optimal objective  2.300000000e+01
objective =  23.0

commentary

We first create a fresh model object with the Model constructor. Then we create the two variables, x and y. By default, Gurobi variables are restrictred to be nonnegative. Since the variables are nonnegative in our mathematical model, we don't need to set any bounds. We do set the objective function. Before adding constraints that reference the variables, we make a call to update. Alternatively, we could have set the parameter UpdateMode to 1.