将 numpy 数组与 lpsolve 一起使用?

Using numpy arrays with lpsolve?

在文档中,它说您可以使用 numpy 数组:

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

当我尝试这样做时出现错误。

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

结果:

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

如果我愿意:

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

它可以工作,但会占用更多内存(在一般情况下)。

当我运行lpsolve()

结果是:

lpsolve  Python Interface version 5.5.0.9
using lpsolve version 5.5.2.0

如果您在使用 lpsolve 时遇到问题,可以使用 PyLPSolve。它是 lpsolve 的包装器,允许我使用 numpy 数组。

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