4

python: python3.2 cvxopt: 1.1.5 numpy: 1.6.1

I read http://abel.ee.ucla.edu/cvxopt/examples/tutorial/numpy.html

import cvxopt
import numpy as np
cvxopt.matrix(np.array([[7, 8, 9], [10, 11, 12]]))

I got

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: non-numeric element in list

By np.array(cvxopt.matrix([[7, 8, 9], [10, 11, 12]])), I got

array([[b'\x07', b'\n'],
   [b'\x08', b'\x0b'],
   [b'\t', b'\x0c']], 
  dtype='|S8')
3
  • 4
    I think it is a bug. Your code works fine with python 2.7 (as stated in the tutorial you mention). I recommend you to ask to the cvxopt discussion forum (groups.google.com/forum/?fromgroups#!forum/cvxopt).
    – Vicent
    Commented Sep 23, 2012 at 9:41
  • 2
    You could try to force a dtype=float when invoking numpy.array..
    – Pierre GM
    Commented Sep 23, 2012 at 11:51
  • @PierreGM Just tried. Didn't work :-( .
    – updogliu
    Commented Sep 24, 2012 at 0:23

3 Answers 3

4

As of cvxopt == 1.2.6 and numpy == 1.21.2:

import cvxopt
import numpy as np

matrix = cvxopt.matrix(np.array([[7, 8, 9], [10, 11, 12]]))
print(matrix)

produces the output:

[  7   8   9]
[ 10  11  12]

and print(repr(matrix)) says:

<2x3 matrix, tc='i'>

and print(type(matrix)) says:

<class 'cvxopt.base.matrix'>

The resulting matrix has integer type (the 'i') because the starting numpy array contained integers. Starting with double results in a 'd' type.

2

Check the patched dense.c that I put up on the cvxopt discussion forum (https://groups.google.com/forum/?fromgroups=#!topic/cvxopt/9jWnkbJvk54). Recompile with this, and you will be able to convert np arrays to dense matrices. I assume the same kind of edits will be necessary for sparse matrices, but as I do not need them I will leave that up to the devs.

1
  • The patched dense.c only works when converting from numpy.array to cvxopt.matrix, but not the other way around. Commented Jan 16, 2013 at 15:31
2

While it is not fixed, a simple workaround for

cvxopt.matrix(nparray)

is

cvxopt.matrix(nparray.T.tolist())

It is more tough for the opposite direction. If you expect int array,

np.vectorize(lambda x: int.from_bytes(x, 'big'))(np.array(cvxoptmat).T)

For the double array:

import struct
np.vectorize(lambda x: struct.unpack('d', x))(np.array(cvxoptmat).T)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.