Open In App

Python | Linear Programming in Pulp

Linear Programming (LP), also known as linear optimization is a mathematical programming technique to obtain the best result or outcome, like maximum profit or least cost, in a mathematical model whose requirements are represented by linear relationships. Linear programming is a special case of mathematical programming, also known as mathematical optimization.
Generally, an organization or a company has mainly two objectives, the first one is minimization and the other is maximization. Minimization means to minimize the total cost of production while maximization means to maximize their profit. So with the help of linear programming graphical method, we can find the optimum solution.

Basic terminologies of Linear Programming



Note: For a problem to be a linear programming problem, the objective function, constraints, and the non – negativity restrictions must be linear.

Example 1: Consider the following problem:



Minimize :  Z = 3x + 5y
Subject to the constraints: 
2x + 3y >= 12
-x + y <= 3
x >= 4
y <= 3
x, y >= 0

Solving the above linear programming problem in Python:
PuLP is one of many libraries in Python ecosystem for solving optimization problems. You can install PuLp in Jupyter notebook as follows:




import sys !{sys.executable} -m pip install pulp

Code : To solve the aforementioned linear programming problem in Python:




# import the library pulp as p
import pulp as p
  
# Create a LP Minimization problem
Lp_prob = p.LpProblem('Problem', p.LpMinimize) 
  
# Create problem Variables 
x = p.LpVariable("x", lowBound = 0)   # Create a variable x >= 0
y = p.LpVariable("y", lowBound = 0)   # Create a variable y >= 0
  
# Objective Function
Lp_prob += 3 * x + 5 * y   
  
# Constraints:
Lp_prob += 2 * x + 3 * y >= 12
Lp_prob += -x + y <= 3
Lp_prob += x >= 4
Lp_prob += y <= 3
  
# Display the problem
print(Lp_prob)
  
status = Lp_prob.solve()   # Solver
print(p.LpStatus[status])   # The solution status
  
# Printing the final solution
print(p.value(x), p.value(y), p.value(Lp_prob.objective))  

Explanation :

Now, let’s understand the code step by step:

Review the Output




# Display the problem
print(Lp_prob)

Output




status = Lp_prob.solve()   # Solver
print(p.LpStatus[status])   # The solution status

Output

Optimal




# Printing the final solution
print(p.value(x), p.value(y), p.value(Lp_prob.objective))

Output

6.0 0.0 18.0

The optimal value for x and y are 6.0 and 0.0 respectively. The optimised objective function value is 18.0.


Article Tags :