Continuous linear optimization in PuLP (Python)

In a previous post I demonstrated how to solve a linear optimization problem in Python, using SciPy.optimize with the linprog function. In this post I want to provide a coding example in Python, using the PuLP module to solve below problem:

This problem is linear and can be solved using Pulp in Python. The modeling syntax is quite different from SciPy.optimize, as you can see from below coding example:

# importing PuLP (can be installed with pip install, e.g. in the anaconda prompt)
import pulp

# use the LpProblem function to initialize a statement of our linear optimization problem 
linearProblem = pulp.LpProblem("some title",pulp.LpMaximize) # we maximize, and thus use LpMaximize as parameter

# using the PuLP module optimization variables have to be declared with the LpVariable function
x1 = pulp.LpVariable("x1",lowBound = 0) # x1 has only lower bound, no upper bound
x2 = pulp.LpVariable("x2",lowBound = 0) # x2 has only lower bound, no upper bound

# using the += operator we can add the objective function to the problem declared
linearProblem += 2*x1 + 3*x2 

# same approach is valid for adding constraints
linearProblem += x1 + x2 <= 10
linearProblem += 2*x1 + x2 <= 15

# we can review our problem now
linearProblem
some_title:
MAXIMIZE
2*x1 + 3*x2 + 0
SUBJECT TO
_C1: x1 + x2 <= 10

_C2: 2 x1 + x2 <= 15

VARIABLES
x1 Continuous
x2 Continuous

As we can see the objective function is 2 X1 + 3 X2, as documented in the initial mathematical problem statement in scalar syntax. The constraints are marked with _C1 and _C2. They too are consistent with the mathematical problem statement at the beginning of this post. Furthermore, it is correct that X1 and X2 are continuous and not discrete optimization variables.

We can now solve the problem, using PuLP in Python:

# solve the problem, using the standard PuLP solver for continuous linear optimization problems
solution = linearProblem.solve()

# see if optimization run was successful, using LpStatus from the PuLP module
pulp.LpStatus[solution]
'Optimal'

The solution is optimal. Let us see the optimal objective function value:

# the optimal objective function value is accessed with the value function in the following way
pulp.value(linearProblem.objective)
30.0
# the optimal solution for x1 is accessed with the value function as well (but we already have x1 as handler)
pulp.value(x1)
0.0
# lastly, below I show optimal solution for x2
pulp.value(x2)
10.0

On my blog you can also find posts demonstrating linear programming in R, using lpSolve and FuzzyLP (e.g. with crispLP or FCLP.sampledBeta). Furthermore, I have provided examples of quadratic optimization with quadprog in R and cvxopt in Python. Lastly, I have solved non-linear optimization problems with gradient descent in R, using the nloptr package.

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Close

Meta