2018-09-17-LP_solution

Gurobi Python Interface

14 Sep 2018

The Gurobi Optimizer is a fast optimization solver for linear programming (LP), quadratic programming (QP), quadratically constrained programming (QCP), mixed integer linear programming (MILP), mixed-integer quadratic programming (MIQP), and mixed-integer quadratically constrained programming (MIQCP).

Gurobi Python Interface could enable applying gurobi optimization in the python syntax just as a package.

Set-up Procedures

  1. Register for an academic free license
    register an account with your edu email to get a free license.

  2. Download gurobi into anaconda
    use conda install to derive the gurobipy package.

  3. Activate the gurobi license
    generate the key code through website.
    store the gurobi.lic key file into the default location.

Python application demonstration

This is the complete source code for python example with gurobi.

   from gurobipy import *

   try:
       # Create a new model
       m = Model("mip1")

       # Create variables
       x = m.addVar(vtype=GRB.BINARY, name="x")
       y = m.addVar(vtype=GRB.BINARY, name="y")
       z = m.addVar(vtype=GRB.BINARY, name="z")

       # Set objective
       m.setObjective(x + y + 2 * z, GRB.MAXIMIZE)
       
       # Add constraint: x + 2 y + 3 z <= 4
       m.addConstr(x + 2 * y + 3 * z <= 4, "c0")
       # Add constraint: x + y >= 1
       m.addConstr(x + y >= 1, "c1")
       
       m.optimize() # optimization
       
       for v in m.getVars():
           print(v.varName, v.x)
       print('Obj:', m.objVal)
       
   except GurobiError:
       print('Error reported')

There are many other python examples. For more detailed instruction