Use Python to solve Linear Programming optimization problem


Let’s first define the standard format of linear programming problem,
in which we will minimize the following equation
$$
z=CX
$$
where, C is the vector of coefficients,X is the vector of variables to be optimized.
The constraints of this minimization can be written as:
$$
AX<=B
$$
where,A and B are both coefficient matrix。

Let’s see an specific example:
$$
min , z=10x_1 +15x_2+25x_3
\s.t
\-1x_1-1x_2-1x_3<=-1000
\-1x_1+2x_2-0x_3<=0
\0x_1+0x_2-1x_3<=-300
\-1x_1<=0
\-1x_2<=0
\-1x_3<=0
$$

In Python, we could call the linprog function in Scipy package to solove linear programming problem,
and here is a simple demo of coding in Python:

# Import required libraries
import numpy as np
from scipy.optimize import linprog

# Set the inequality constraints matrix
# Note: the inequality constraints must be in the form of <=
A = np.array([[-1, -1, -1], [-1, 2, 0], [0, 0, -1], [-1, 0, 0], [0, -1, 0], [0, 0, -1]])

# Set the inequality constraints vector
b = np.array([-1000, 0, -300, 0, 0, 0])

# Set the coefficients of the linear objective function vector
c = np.array([10, 15, 25])

# Solve linear programming problem
res = linprog(c, A_ub=A, b_ub=b)

# Print results
print('Optimal value:', round(res.fun, ndigits=2),
'\nx values:', res.x,
'\nNumber of iterations performed:', res.nit,
'\nStatus:', res.message)
Optimal value: 14500.0 
x values: [7.0000000e+02 7.1017063e-09 3.0000000e+02] 
Number of iterations performed: 7 
Status: Optimization terminated successfully.

Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC