Search code examples
pythonscipyscipy-optimize

Why am I not getting the values ​I want with scipy.optimize. (linear programming problems)


import numpy as np
from scipy.optimize import linprog

b_ub = [74, 40, 36]
b_eq = [20, 45, 30]
A = np.array([[7, 3, 6], [4, 8, 2], [1, 5, 9]])
m, n = A.shape
c = list(np.reshape(A, n * m))  # Convert matrix A to list c.
A_ub = np.zeros([m, m * n])
for i in np.arange(0, m,
                   1):  # Filling in the matrix of conditions-inequalities.
    for j in np.arange(0, n * m, 1):
        if i * n <= j <= n + i * n - 1:
            A_ub[i, j] = 1
A_eq = np.zeros([m, m * n])
for i in np.arange(0, m, 1):  # Filling in the matrix of conditions-equalities
    k = 0
    for j in np.arange(0, n * m, 1):
        if j == k * n + i:
            A_eq[i, j] = 1
            k = k + 1
print(linprog(c, A_ub, b_ub, A_eq, b_eq))

I'm getting this

enter image description here

instead of

enter image description here


Solution

  • I believe it is due to the default solver. Swapping the solver gave the solution you looked for. See the docs and evaluate the tradeoffs of using each solver to determine what you want to use.

    print(linprog(c, A_ub, b_ub, A_eq, b_eq, method='highs-ds'))
    
               con: array([0., 0., 0.])
     crossover_nit: 0
               fun: 215.0
           message: 'Optimization terminated successfully.'
               nit: 3
             slack: array([29., 10., 16.])
            status: 0
           success: True
                 x: array([ 0., 45.,  0.,  0.,  0., 30., 20.,  0.,  0.])