Linear programming with Python and PuLP

Linear programming with Python and PuLP

What is PuLP?

From the official page:

PuLP is an LP modeler written in python. PuLP can generate MPS or LP files and call GLPK, COIN CLP/CBC, CPLEX, and GUROBI to solve linear problems.

An example

We want to give a short example of how to solve a linear programming problem with Python. Among the options we chose the PuLP module developed by Stuart Mitchell.

A mechanics company can produce 2 different products using 4 departments. The maximum annual production capacity of the 4 departments in relation to the two types of product is the following:

Dep Product_A Product_B
Moulding 25,000 35,000
Painting 33,000 17,000
Assembly A 22,500 0
Assembly B 0 15,000
Net profit per unit 300 250

This means, for example, that the moulding department has a maximum production capacity of 25,000 Product_A units if it operates exclusively on this product. The same department has a maximum capacity of 35,000 units if it only works for Product_B.

What is the annual production (production mix) that maximizes the total net profit?

Mathematical model

Variables

x = produced units of Product_A;
y = produced units of Product_B;

Objective Function

max z=300*x+250*y

Constraints

1.4*x+y ≤ 35000
0.51*x+y ≤ 17000
x ≤ 22500
y ≤ 15000
x ≥ 0
y ≥ 0

Solve with Python and PuLP

Pulp is a Python module that allows users to describe and solve linear programming problems. We found it very interesting because Pulp works entirely within the syntax and idioms of Python and provides Python objects that represent problems of optimization and decision variables also allowing constraints to be expressed in a way that is very similar to the original mathematical model.

Please refer to the documentation and examples on the use of PuLP.

from pulp import *
x = pulp.LpVariable("x", lowBound=0)
y = pulp.LpVariable("y", lowBound=0)
problem = pulp.LpProblem("A simple max problem", pulp.LpMaximize)
problem += 300*x + 250*y, "The objective function"
problem += 1.4*x + y <= 35000, "1st constraint"
problem += 0.51*x + y <= 17000, "2nd constraint"
problem += x <= 22500, "3rd constraint"
problem += y <= 15000, "4th constraint"
problem.solve()
print "Optimal Result:"
for variable in problem.variables():
    print variable.name, "=", variable.varValue
print "Total net max profit:"
print value(problem.objective)

Optimal Result:
x = 20224.719
y = 6685.3933
Total net max profit:
7738764.025
Avatar photo
About Carlo Bazzo 17 Articles
Sysadmin & network eng. @Epysoft, editor @TheTechGoggler, CTO @HDEMO. Former developer @MSFT @GOOG. Former MOps consultant @XRX @HPQ. LinkedIn: it.linkedin.com/in/carlobazzo