PuLP
PuLP is an LP (Linear Programming) modeler written in Python. It simplifies the creation of linear and mixed-integer programming optimization problems, allowing users to define problems using Pythonic syntax. It can generate MPS or LP files and call various open-source (like GLPK, COIN-OR CBC, HiGHS, SCIP) or proprietary (CPLEX, GUROBI, MOSEK, XPRESS) solvers to find optimal solutions. The current version is 3.3.0, and it is actively maintained with regular updates.
Warnings
- gotcha PuLP is a modeling library and relies on external solvers to find solutions. While the COIN-OR CBC solver is included by default, other more powerful solvers (like CPLEX, Gurobi, HiGHS, SCIP) require separate installation, often via specific `pip install pulp[solver_name]` commands. Some proprietary solvers also require valid licenses.
- gotcha PuLP is designed specifically for Linear Programming (LP) and Mixed-Integer Linear Programming (MILP) problems. It cannot be used to model or solve non-linear optimization problems.
- breaking PuLP requires Python 3.9 or newer. Older Python versions are not supported, and attempting to install or run PuLP with them will result in errors.
- gotcha On Linux and macOS systems, the default COIN-OR CBC solver (included with PuLP) might require executable permissions to run tests or solve problems. The documentation suggests running `sudo pulptest`.
Install
-
pip install pulp -
pip install pulp[open_py]
Imports
- LpProblem
from pulp import LpProblem
- LpVariable
from pulp import LpVariable
- LpMinimize
from pulp import LpMinimize
- LpMaximize
from pulp import LpMaximize
- lpSum
from pulp import lpSum
- *
from pulp import LpProblem, LpVariable, LpMinimize, lpSum, LpStatus, value
Quickstart
from pulp import LpProblem, LpVariable, LpMinimize, lpSum, LpStatus, value
# 1. Create the problem variable, specifying minimization or maximization
prob = LpProblem("My Production Problem", LpMinimize)
# 2. Define decision variables
x = LpVariable("Product_A", lowBound=0, cat='Integer')
y = LpVariable("Product_B", lowBound=0, cat='Integer')
# 3. Define the objective function (e.g., minimize cost)
prob += 3 * x + 2 * y, "Total Cost"
# 4. Define constraints
prob += 2 * x + y >= 10, "Minimum Production"
prob += x + y <= 12, "Max Capacity"
prob += x >= 4, "Min Product A"
# 5. Solve the problem
status = prob.solve()
# 6. Print the results
print(f"Status: {LpStatus[status]}")
if LpStatus[status] == "Optimal":
print(f"Optimal Total Cost: {value(prob.objective)}")
print(f"Units of Product A: {value(x)}")
print(f"Units of Product B: {value(y)}")
else:
print("No optimal solution found.")