uday
uday

Reputation: 6713

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?

Upvotes: 3

Views: 8241

Answers (2)

Addy Roy
Addy Roy

Reputation: 17

One of the key mistakes is your assumption that CVX accepts int, which is incorrect. CVX accepts only double. So, the right way of doing it maybe:

import cvxopt as cp
if not isinstance(q, np.double): 
  q.astype(np.double)
cvx_q = cp.matrix(q) 

Upvotes: 0

Chris
Chris

Reputation: 967

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.

Upvotes: 7

Related Questions