Building and solving a small LP with Python

Solve a linear programming model using the CPLEX Python API.

After you have installed the CPLEX Python API on your system and opened a Python interactive session, you can actually build and solve a small LP model as a demonstration. The demonstration shows how to:

model by rows;

  • model by rows;

model by columns;

  • model by columns;

model by nonzero elements.

  • model by nonzero elements.

The code sample, lpex1.py, is one of the examples in the standard distribution of the product. It is an extension of the example presented in Getting Started with CPLEX as Problem statement. The demonstration shows three different ways to define an LP problem through the CPLEX Python API, how to solve it, and how to access the solution. Here is the model that the sample optimizes:

Maximize
x1  + 2x2 + 3x3
subject to
–x1 +  x2 + x3 <= 20
 x1 – 3x2 + x3 <= 30
with these bounds
0 <= x1 <= 40
0 <= x2 <= infinity
0 <= x3 <= infinity

First, the example checks the correctness of command-line arguments. If the command-line arguments are valid, the example creates and solves the problem within a try/except clause to handle any errors that may occur. Then, depending on the command line argument, the example calls one of the functions populatebyrow, populatebycolumn, or populatebynonzero, to fill the Cplex object with a representation of the optimization problem. These functions generate lists containing the data that define the LP problem. After the Cplex object has been populated by one of these three functions, its method solve invokes the optimizer in this sample.

If the optimizer fails to generate a solution, CPLEX raises an exception.

If a solution is found, CPLEX prints solution information to sys.stdout when a user’s application invokes print statements.