3

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?

cel
  • 30,017
  • 18
  • 97
  • 117
uday
  • 6,453
  • 13
  • 56
  • 94
  • Related: https://stackoverflow.com/questions/12551009/python3-conversion-between-cvxopt-matrix-and-numpy-array/45933678#45933678 – 0 _ Aug 29 '17 at 07:59

2 Answers2

6

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.

Chris
  • 957
  • 5
  • 10
  • Strictly speaking it is the `cvxopt.qp` solver that requires double floats for all of its arguments. CVXOPT itself does support integer matrices (`cvxopt.matrix(np.arange(5))` will return an integer matrix with typecode `'i'`). – ali_m Oct 31 '15 at 18:03
0

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) 
Addy Roy
  • 17
  • 1
  • 5