4

I am trying to solve a linear program with CVXOPT. There are 2n variables, x_1,...,x_2n. The LP is in the form of

min x_{n+1}+...+x_{2n}

s.t. Ax \leq b

Here, A and b are fixed. It seems very straightforward from here. Since I am optimizing the sum of the second half of the variables, I create a vector of n zeroes and n ones: c = (0,...,0,1,...,1) and have the following code (assume A and b are already computed):

c = [1]*(2*k + 2)
for i in range(k + 1):
    c[i] = 0
c = matrix(c)
sol=solvers.lp(c,A,b)
print(sol['x'])

This code is straight from CVXOPT documentation. However, I get an error saying:

TypeError: 'c' must be a dense column matrix

I looked this up but it seems to me that calling matrix() should have converted c to the appropriate type. Does anyone know how to fix this?

Community
  • 1
  • 1
N. Mao
  • 499
  • 1
  • 10
  • 19
  • I didn't explain what k is, but I think that that should be irrelevant to this question. If I'm wrong, let me know. – N. Mao Aug 28 '15 at 09:54

1 Answers1

6

The problem is that the constructor of the matrix object interprets it as being of integer type, whereas it should be double. If you populate your list with explicitly double numbers it should work.

From the source code of cvxopt:

 if type(c) is not matrix or c.typecode != 'd' or c.size[1] != 1: 
     raise TypeError("'c' must be a dense column matrix") 

checking..

import cvxopt
k = 20
c = [1]*(2*k + 2)
for i in range(k + 1):
    c[i] = 0

c = cvxopt.matrix(c)
print c.typecode  # Prints 'i'

Solution:

c = [1.]*(2*k + 2)
print c.typecode  # Prints 'd'
Ioannis
  • 5,238
  • 2
  • 19
  • 31
  • Thanks! I think this is likely the answer. After making this change, however, I get an error: TypeError: 'G' must be a dense or sparse 'd' matrix with 10 columns. – N. Mao Aug 28 '15 at 12:36
  • I see that there is a stackoverflow question about this error, but I don't see many parallels between that thread and this one. Do you have any insight about this? – N. Mao Aug 28 '15 at 12:37
  • This is a different error, as it is related to the way you have defined matrix `A`. Could you check that `A` is defined as of type `d` (what we did above) and that it has the right number of dimensions? – Ioannis Aug 28 '15 at 14:33
  • A does have a typecode of 'd', and the dimensions checked out. The number of columns in A is 10, contrary to what the error seems to say. At this point, perhaps it is best to open a new thread, yes? – N. Mao Aug 30 '15 at 05:59
  • I would suggest so. Then it will have a complete description and more visibility to the community. I bet quite a few people who work with cvxopt get similar errors.. – Ioannis Aug 30 '15 at 14:23