【发布时间】:2019-06-20 06:20:28
【问题描述】:
我正在将代码从 R 转换为 Python,并且正在寻找解决线性规划问题的最简单方法的帮助。找了很久,似乎没有对最好用的模块达成共识。
在此示例中,我只想选择 5 个选项中的 3 个,最大化 obj,同时确保约束列高于 0:
obj = [np.random.uniform(0, 100) for _ in range(5)]
col1 = [1] * 5
col2 = [np.random.uniform(0, 100) for _ in range(5)]
col3 = [np.random.uniform(0, 100) for _ in range(5)]
col4 = [np.random.uniform(0, 100) for _ in range(5)]
col5 = [np.random.uniform(0, 100) for _ in range(5)]
col6 = [np.random.uniform(0, 100) for _ in range(5)]
ConstraintMatrix = pd.DataFrame(data = {'col1': col1, 'col2': col2, 'col3': col3, 'col4': col4, 'col5': col5, 'col6': col6})
ConstraintDirections = ['==', '>=', '>=', '>=', '>=', '>=']
ConstraintValues = [3, 0, 0, 0, 0, 0]
在 R 中,为了获得最大化目标的 3 个项目,我只需运行:
library(lpSolve)
sol <- lpSolve::lp("max",
objective.in = obj,
const.mat = t(ConstraintMatrix), # Transpose matrix
const.dir = ConstraintDirections,
const.rhs = ConstraintValues,
all.bin = T # decision variables are all binary
)
ConstraintMatrix$selected <- sol$solution[1:nrow(ConstraintMatrix)]
ConstraintMatrix <- ConstraintMatrix[ConstraintMatrix$selected == 1,]
显然,这个问题不需要线性规划来解决,但它说明了我正在从 Python 中寻找什么来解决我更大的问题。有没有像我的lpSolve:lp 一样接受目标、约束矩阵、方向向量和值向量并输出解决方案的 Python 函数?
【问题讨论】:
标签: python linear-programming lpsolve