pythonlinear-programmingcvxpycvxopt

Simple Symbolic LP problem to Matrix form


I solved a linear programming problem and here is my symbolic form code.

import cvxpy as cp
import numpy as np

x11 = cp.Variable(nonneg=True)
x12 = cp.Variable(nonneg=True)
x21 = cp.Variable(nonneg=True)
x22 = cp.Variable(nonneg=True)
x31 = cp.Variable(nonneg=True)
x32 = cp.Variable(nonneg=True)

constraints = [x11 + x12 == 1000,
              x21 + x22 == 1500,
              x31 + x32 == 1200,
              x11 + x21 + x31 == 2300,
              x12 + x22 + x32 == 1400]

obj = cp.Minimize((80*x11 + 215*x12 + 100*x21 + 108*x22 + 102*x31 + 68*x32))

prob = cp.Problem(obj, constraints)
prob.solve()
print('status: ', prob.status)
print('optimal value: ', prob.value)
print('optimal variables: ', x11.value, x12.value, x21.value, x22.value, x31.value, x32.value)

status: optimal

optimal value: 313200.00003146095

optimal variables: 999.9999999627637 3.7235625579412695e-08 1299.99999940076 200.00000059923934 6.364774533690845e-07 1199.999999363524

But I want to change this code to matrix form. here is my another code for matrix form

x = cp.Variable((3, 2), nonneg=True)

constraints = [cp.sum(x[0,:]) == 1000,
              cp.sum(x[1,:]) == 1500,
              cp.sum(x[2,:]) == 1200,
              cp.sum(x[:, 0]) == 2300,
              cp.sum(x[:, 1]) == 1400]

coe = [[80, 215], [100, 108], [102, 68]]

t
obj = cp.Minimize(cp.sum(coe @ x))

prob = cp.Problem(obj, constraints)
prob.solve()
print('status: ', prob.status)
print('optimal value: ', prob.value)
for i in range(3):
    for j in range(2):
        print('optimal variables:x('+str(i)+','+str(j)+')', x[i,j].value)

status: optimal

optimal value: 810999.9999986519

optimal variables:x(0,0) 649.9892627159586

optimal variables:x(0,1) 350.01073728291954

optimal variables:x(1,0) 900.0113075911175

optimal variables:x(1,1) 599.9886924056102

optimal variables:x(2,0) 749.9994296884455

optimal variables:x(2,1) 450.00057030957413

I think the results should be same and the matrix form code is wrong. Could you find my mistakes?


Solution

  • You must be careful when you work on matrix multiplication especially on different libraries. I found that @ is used in matrix-matrix multiplication. And not a element-wise multiplicationin. See cvxpy's official documents.

    Somehow during @ multiplication, cvxpy misunderstands your target.

    Solution: change obj = cp.Minimize(cp.sum(coe @ x)) to

    obj = cp.Minimize(cp.sum(cp.multiply(coe, x.T))) (I'm also confused why coe is regarded as (2x3))