简体   繁体   中英

Using numpy arrays with lpsolve?

In the docs, it says you can use numpy arrays:

numpy package

In the above section Maximum usage of matrices with lpsolve the package numpy was already mentioned. See http://numpy.scipy.org/ for a brief overview. This package is the successor of the older and obsolete package Numeric. Since lp_solve is all about arrays and matrices, it is logical that the lpsolve Python driver accepts numpy arrays. This is possible from driver version 5.5.0.9. Before it was needed that numpy arrays were converted to lists. For example:

>>> from numpy import *
>>> from lpsolve55 import *
>>> lp=lpsolve('make_lp', 0, 4);
>>> c = array([1, 3, 6.24, 0.1])
>>> ret = lpsolve('set_obj_fn', lp, c)

Note that the numpy array variable c is passed directly to lpsolve. Before driver version 5.5.0.9 this gave an error since lpsolve did not know numpy arrays. They had to be converted to lists:

>>> ret = lpsolve('set_obj_fn', lp, list(c))

That is ok for small models, but for larger arrays this gives an extra memory overhead since c is now two times in memory. Once as the numpy array and once as list.

Note that all returned arrays from lpsolve are always lists.

Also note that the older package Numeric is not supported by lpsolve. So it is not possible to provide a Numeric array to lpsolve. That will give an error.

http://lpsolve.sourceforge.net/5.5/Python.htm

When I attempt to do that I get an error.

lp = lpsolve('make_lp', 0, 7)
coef = np.array([0, 0, 0, 1, 1, 1, 1])
lpsolve('set_obj_fn', lp, coef)

Results in:

lpsolve('set_obj_fn', lp, coef)
lpsolve.error: invalid vector.

If I would do:

lpsolve('set_obj_fn', lp, coef.tolist())

It works but costs much more memory (in the general case).

When I run lpsolve()

It results in:

lpsolve  Python Interface version 5.5.0.9
using lpsolve version 5.5.2.0

You can use PyLPSolve if you are having trouble with lpsolve. It is a wrapper for lpsolve that allowed me to use numpy arrays.

http://www.stat.washington.edu/~hoytak/code/pylpsolve/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM