pythonnumpycvxopt

converting numpy vector to cvxopt


This may be a very silly question, but I have been struggling with it and couldn't find it readily in the documentation.

I am trying to do a quadratic programming using the description given here. The documentation here covers only conversion of 2 dimensional numpy arrays into cvxopt arrays, not 1 dimensional numpy arrays.

My q vector of the objective function (1/2)x' P x + q' x is a numpy vector, say of size n.

I tried to convert q from numpy to cvxopt in the following ways:

import cvxopt as cvx
cvx_q = cvx.matrix(q)   # didn't work
cvx_q = cvx.matrix(q, (n, 1)) # didn't work
cvx_q = cvx.matrix(np.array([q])) # didn't work
cvx_q = cvx.matrix(np.array([q]), (1, n)) # didn't work
cvx_q = cvx.matrix(np.array([q]), (n, 1)) # didn't work

In all cases, I get an answer TypeError: buffer format not supported.

However, numpy matrices seem to work fine, e.g.

cvx_p = cvx.matrix(p)   # works fine, p is a n x n numpy matrix

If I try to run the optimization without converting the numpy vector to cvxopt format like this:

cvxs.qp(cvx_p, cvx_q, cvx_g, cvx_h, cvx_a, cvx_b)

I get an error: TypeError 'q' must be a 'd' matrix with one column.

What could be the correct way to convert a numpy vector into a cvxopt matrix with one column?


Solution

  • You have not included any sample data, but when I encountered this error, it was because of the dtype.

    try:

    q = q.astype(np.double)
    cvx_q = matrix(q)
    

    CVX only accepts doubles, not ints.