Python等价于线性规划的lpr解法

2024-04-23 06:07:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将代码从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中寻找什么。有没有一个Python函数,它接受一个目标、约束矩阵、方向向量和值向量,并像我的lpSolve:lp那样给出一个解决方案?你知道吗


Tags: inobjfornprangerandomuniformcol2